Implement US-11 context-aware health trend assessments
This commit is contained in:
1 parent
a0a9e2e9b9
commit
cc76c9bde4
9 files changed
+802
-7
No files matched your search
@@ -10,6 +10,10 @@ public sealed class InsightsController(IHttpClientFactory clients) : ControllerB
|
|||||||
public Task GetSummary(Guid patientId, CancellationToken cancellationToken) =>
|
public Task GetSummary(Guid patientId, CancellationToken cancellationToken) =>
|
||||||
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/insights{Request.QueryString}", cancellationToken);
|
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/insights{Request.QueryString}", cancellationToken);
|
||||||
|
|
||||||
|
[HttpGet("patients/{patientId:guid}/trends")]
|
||||||
|
public Task GetTrend(Guid patientId, CancellationToken cancellationToken) =>
|
||||||
|
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/trends{Request.QueryString}", cancellationToken);
|
||||||
|
|
||||||
private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken)
|
private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
using var request = new HttpRequestMessage(method, path);
|
using var request = new HttpRequestMessage(method, path);
|
||||||
|
|||||||
@@ -18,6 +18,18 @@ public sealed class InsightsApplicationService(ObservationServiceClient observat
|
|||||||
return calculator.CalculateSummary(patientId, from, to, history, selection);
|
return calculator.CalculateSummary(patientId, from, to, history, selection);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<TrendAssessment> GetTrendAsync(Guid patientId, DateTime from, DateTime to,
|
||||||
|
ContextSelection selection, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
from = NormalizeTimestamp(from);
|
||||||
|
to = NormalizeTimestamp(to);
|
||||||
|
if (to < from)
|
||||||
|
throw new ArgumentException("The end time must not be earlier than the start time.", nameof(to));
|
||||||
|
Validator.ValidateObject(selection, new ValidationContext(selection), validateAllProperties: true);
|
||||||
|
var history = await observations.GetByPeriodAsync(patientId, from, to, selection, cancellationToken);
|
||||||
|
return calculator.CalculateTrend(patientId, from, to, history, selection);
|
||||||
|
}
|
||||||
|
|
||||||
private static DateTime NormalizeTimestamp(DateTime value) =>
|
private static DateTime NormalizeTimestamp(DateTime value) =>
|
||||||
DateTime.SpecifyKind(value.Kind == DateTimeKind.Unspecified ? value : value.ToUniversalTime(),
|
DateTime.SpecifyKind(value.Kind == DateTimeKind.Unspecified ? value : value.ToUniversalTime(),
|
||||||
DateTimeKind.Unspecified);
|
DateTimeKind.Unspecified);
|
||||||
|
|||||||
@@ -43,4 +43,32 @@ public sealed class InsightsController(InsightsApplicationService service) : Con
|
|||||||
return Problem(statusCode: StatusCodes.Status504GatewayTimeout, title: "Observation history timed out.");
|
return Problem(statusCode: StatusCodes.Status504GatewayTimeout, title: "Observation history timed out.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
[HttpGet("/api/patients/{patientId:guid}/trends")]
|
||||||
|
public async Task<ActionResult<TrendAssessment>> GetTrend(Guid patientId,
|
||||||
|
[FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to,
|
||||||
|
[FromQuery] ContextSelection selection, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return Ok(await service.GetTrendAsync(patientId, from, to, selection, cancellationToken));
|
||||||
|
}
|
||||||
|
catch (ArgumentException)
|
||||||
|
{
|
||||||
|
ModelState.AddModelError(nameof(to), "The end time must not be earlier than the start time.");
|
||||||
|
return ValidationProblem(ModelState);
|
||||||
|
}
|
||||||
|
catch (HttpRequestException)
|
||||||
|
{
|
||||||
|
return Problem(statusCode: StatusCodes.Status502BadGateway, title: "Observation history is unavailable.");
|
||||||
|
}
|
||||||
|
catch (System.Text.Json.JsonException)
|
||||||
|
{
|
||||||
|
return Problem(statusCode: StatusCodes.Status502BadGateway, title: "Observation history response is invalid.");
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
return Problem(statusCode: StatusCodes.Status504GatewayTimeout, title: "Observation history timed out.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using InsightsService.Contracts;
|
||||||
|
|
||||||
|
namespace InsightsService.Domain;
|
||||||
|
|
||||||
|
public sealed partial class InsightCalculator
|
||||||
|
{
|
||||||
|
private 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.";
|
||||||
|
|
||||||
|
public TrendAssessment CalculateTrend(Guid patientId, DateTime from, DateTime to,
|
||||||
|
IReadOnlyList<ObservationDto> observations, ContextSelection selection)
|
||||||
|
{
|
||||||
|
var comparability = AssessComparability(observations);
|
||||||
|
return new(patientId, from, to, selection, observations.Count, comparability,
|
||||||
|
AssessMeasurement("Systolic", "mmHg", observations, o => o.Systolic, comparability),
|
||||||
|
AssessMeasurement("Diastolic", "mmHg", observations, o => o.Diastolic, comparability),
|
||||||
|
AssessMeasurement("Pulse", "beats/min", observations, o => o.Pulse, comparability));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static MeasurementAssessment AssessMeasurement(string metric, string unit,
|
||||||
|
IReadOnlyList<ObservationDto> observations, Func<ObservationDto, int> value,
|
||||||
|
ComparabilityAssessment comparability)
|
||||||
|
{
|
||||||
|
if (observations.Count == 0)
|
||||||
|
return new(metric, unit, null, null, null, null, 0, "Unavailable", "Unavailable", null, 0,
|
||||||
|
null, "No matching observations; insufficient observation data for trend calculation.",
|
||||||
|
null, "Unavailable: no matching observations.", "CannotInterpret", GeneralLimits);
|
||||||
|
|
||||||
|
// Collapse timestamp ties for temporal calculations only; descriptive levels retain every observation.
|
||||||
|
var points = observations.GroupBy(o => o.MeasuredAt).OrderBy(g => g.Key)
|
||||||
|
.Select(g => (Time: g.Key, Value: g.Average(o => (decimal)value(o)))).ToArray();
|
||||||
|
var minimum = observations.Min(value);
|
||||||
|
var maximum = observations.Max(value);
|
||||||
|
var mean = observations.Average(o => (decimal)value(o));
|
||||||
|
var signs = points.Zip(points.Skip(1), (a, b) => Math.Sign(b.Value - a.Value))
|
||||||
|
.Where(s => s != 0).ToArray();
|
||||||
|
var reversals = signs.Zip(signs.Skip(1), (a, b) => a != b ? 1 : 0).Sum();
|
||||||
|
var direction = points.Length < 2 ? "Unavailable" : signs.Length == 0 ? "NoClearDirection" :
|
||||||
|
reversals > 0 ? "Mixed" : signs[0] > 0 ? "Increasing" : "Decreasing";
|
||||||
|
decimal? slope = null;
|
||||||
|
var overall = "Unavailable";
|
||||||
|
decimal? totalChange = null;
|
||||||
|
if (points.Length >= 2)
|
||||||
|
{
|
||||||
|
// Scale time to [0,1] before OLS, avoiding extreme timestamp magnitudes.
|
||||||
|
var span = (decimal)(points[^1].Time.Ticks - points[0].Time.Ticks);
|
||||||
|
var xs = points.Select(p => (p.Time.Ticks - points[0].Time.Ticks) / span).ToArray();
|
||||||
|
var xMean = xs.Average();
|
||||||
|
var yMean = points.Average(p => p.Value);
|
||||||
|
var numerator = points.Select((p, i) => (xs[i] - xMean) * (p.Value - yMean)).Sum();
|
||||||
|
var denominator = xs.Sum(x => (x - xMean) * (x - xMean));
|
||||||
|
var scaledSlope = numerator / denominator;
|
||||||
|
slope = scaledSlope / (span / TimeSpan.TicksPerDay);
|
||||||
|
overall = scaledSlope > 0 ? "Increasing" : scaledSlope < 0 ? "Decreasing" : "NoClearDirection";
|
||||||
|
totalChange = points.Zip(points.Skip(1), (a, b) => Math.Abs(b.Value - a.Value)).Sum();
|
||||||
|
}
|
||||||
|
var numerical = $"All {observations.Count} observations: mean {Format(mean)}, minimum {minimum}, maximum {maximum}, " +
|
||||||
|
$"range {maximum - minimum} {unit}. " + (points.Length < 2
|
||||||
|
? "Direction is unavailable: at least two distinct measurement timestamps are required."
|
||||||
|
: $"Temporal direction: {direction}; full-period least-squares direction: {overall}; " +
|
||||||
|
$"{reversals} reversal(s). Timestamp ties use arithmetic means. " +
|
||||||
|
$"Total successive change is {Format(totalChange!.Value)} {unit}.") +
|
||||||
|
" Range and successive change describe observed variation; no clinical stability classification is made.";
|
||||||
|
|
||||||
|
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.";
|
||||||
|
var interpretation = "CannotInterpret";
|
||||||
|
var hint = "Numerical changes alone do not establish favourable or concerning development.";
|
||||||
|
if (reference is not null)
|
||||||
|
{
|
||||||
|
var above = observations.Count(o => IsHigh(value(o), reference));
|
||||||
|
var below = observations.Count(o => IsLow(value(o), reference));
|
||||||
|
comparison = $"Descriptive mean {Format(mean)} {unit}; {above} observation(s) " +
|
||||||
|
$"{reference.UpperComparison} {Format(reference.UpperBoundary)} {unit}" +
|
||||||
|
(reference.LowerBoundary is { } lower ? $"; {below} observation(s) < {Format(lower)} {unit}." : ".") +
|
||||||
|
" This period does not establish a guideline diagnostic measurement protocol. " + reference.Limitation;
|
||||||
|
if (points.Length >= 2 && comparability.Status == "SupportedRecordedComparability")
|
||||||
|
{
|
||||||
|
var first = points[0].Value;
|
||||||
|
var last = points[^1].Value;
|
||||||
|
if (reversals > 0 && (above > 0 || below > 0))
|
||||||
|
{
|
||||||
|
interpretation = "Mixed";
|
||||||
|
hint = "Reversing movements and excursions outside the cited reference boundaries coexist; " +
|
||||||
|
"an overall slope does not establish consistent improvement or deterioration.";
|
||||||
|
}
|
||||||
|
else if (direction == "Decreasing" && IsHigh(first, reference) &&
|
||||||
|
!IsLow(last, reference) && below == 0 && (metric == "Pulse" || IsHigh(last, reference)))
|
||||||
|
{
|
||||||
|
interpretation = "PotentiallyFavourable";
|
||||||
|
hint = "Movement away from initially high levels towards the cited reference boundary may be favourable. " +
|
||||||
|
"This is a cautious inference from the source's reference comparison, not a clinical decision rule. " +
|
||||||
|
(IsHigh(last, reference) ? "The latest timestamp mean remains above or at the high boundary." :
|
||||||
|
"Reaching the reference interval does not establish an individual treatment target or good health.");
|
||||||
|
}
|
||||||
|
else if (metric == "Pulse" && direction == "Increasing" && IsLow(first, reference) &&
|
||||||
|
!IsHigh(last, reference) && above == 0)
|
||||||
|
{
|
||||||
|
interpretation = "PotentiallyFavourable";
|
||||||
|
hint = "Movement away from initially low resting pulse towards the reference interval may be favourable, " +
|
||||||
|
"but low pulse may be physiological in trained people. This is a cautious inference, not a clinical rule. " +
|
||||||
|
(IsLow(last, reference) ? "The latest timestamp mean remains below the lower boundary." :
|
||||||
|
"Being within these boundaries does not establish good health.");
|
||||||
|
}
|
||||||
|
else if (above > 0 || below > 0)
|
||||||
|
{
|
||||||
|
interpretation = "PotentiallyConcerning";
|
||||||
|
hint = "Observed levels outside the cited reference boundaries may warrant clinical review. " +
|
||||||
|
"Limited variation does not establish healthy levels, and a decrease into low resting pulse " +
|
||||||
|
"is not automatically favourable. The cause and individual significance cannot be determined here.";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
hint = "The recorded context supports this limited reference comparison, but " +
|
||||||
|
(points.Length < 2 ? "temporal direction is unavailable. " :
|
||||||
|
"missing or differing conditions limit interpretation of the combined trajectory. ") +
|
||||||
|
"An outside-reference value is not dismissed because preparation information is incomplete.";
|
||||||
|
}
|
||||||
|
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,
|
||||||
|
comparison, interpretation, hint + " " + comparability.Explanation + " " + GeneralLimits);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ClinicalReference? SelectReference(string metric, IReadOnlyList<ObservationDto> observations,
|
||||||
|
ComparabilityAssessment comparability)
|
||||||
|
{
|
||||||
|
if (comparability.Conflicts.Count > 0 ||
|
||||||
|
observations.Any(o => o.MeasurementContext?.ActivityCondition != "AtRest")) return null;
|
||||||
|
if (metric == "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.");
|
||||||
|
var settings = observations.Select(o => o.MeasurementContext?.Setting).Distinct().ToArray();
|
||||||
|
if (settings.Length != 1 || settings[0] is not ("Home" or "Clinic")) return null;
|
||||||
|
// Known inadequate rest prevents even a provisional resting-pressure comparison.
|
||||||
|
if (observations.Any(o => o.MeasurementContext?.RestDurationMinutes is < 5)) return null;
|
||||||
|
if (observations.Any(o => !string.IsNullOrWhiteSpace(o.MeasurementContext?.BodyPosition) &&
|
||||||
|
!new[] { "seated", "sitting", "siddende" }.Contains(o.MeasurementContext!.BodyPosition!.Trim(), StringComparer.OrdinalIgnoreCase)))
|
||||||
|
return null;
|
||||||
|
var threshold = metric == "Systolic" ? (settings[0] == "Home" ? 135 : 140) :
|
||||||
|
(settings[0] == "Home" ? 85 : 90);
|
||||||
|
return new($"Recorded {settings[0]} resting blood pressure", null, null, threshold, ">=",
|
||||||
|
[new("Lægehåndbogen: Højt blodtryk",
|
||||||
|
"https://www.sundhed.dk/sundhedsfaglig/laegehaandbogen/hjerte-kar/symptomer-og-tegn/hoejt-blodtryk/",
|
||||||
|
"2024-09-25", "2026-10-05")],
|
||||||
|
"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.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsHigh(decimal value, ClinicalReference reference) =>
|
||||||
|
reference.UpperComparison == ">=" ? value >= reference.UpperBoundary : value > reference.UpperBoundary;
|
||||||
|
private static bool IsLow(decimal value, ClinicalReference reference) =>
|
||||||
|
reference.LowerBoundary is { } lower && value < lower;
|
||||||
|
private static decimal Round(decimal value) => Math.Round(value, 2, MidpointRounding.AwayFromZero);
|
||||||
|
private static string Format(decimal value) => Round(value).ToString("0.##", CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
private static ComparabilityAssessment AssessComparability(IReadOnlyList<ObservationDto> observations)
|
||||||
|
{
|
||||||
|
List<string> similarities = [], differences = [], missing = [], conflicts = [];
|
||||||
|
if (observations.Count == 0)
|
||||||
|
return new("InsufficientContext", similarities, differences, missing, conflicts,
|
||||||
|
"No matching observations are available to assess comparability.");
|
||||||
|
var details = new (string Name, string?[] Values)[]
|
||||||
|
{
|
||||||
|
("setting", observations.Select(o => o.MeasurementContext?.Setting).ToArray()),
|
||||||
|
("activity condition", observations.Select(o => o.MeasurementContext?.ActivityCondition).ToArray()),
|
||||||
|
("rest duration", observations.Select(o => o.MeasurementContext?.RestDurationMinutes?.ToString("G29", CultureInfo.InvariantCulture)).ToArray()),
|
||||||
|
("body position", observations.Select(o => o.MeasurementContext?.BodyPosition).ToArray()),
|
||||||
|
("measured arm", observations.Select(o => o.MeasurementContext?.MeasuredArm).ToArray()),
|
||||||
|
("device", observations.Select(o => o.MeasurementContext?.DeviceDetails).ToArray()),
|
||||||
|
("cuff", observations.Select(o => o.MeasurementContext?.CuffDetails).ToArray())
|
||||||
|
};
|
||||||
|
foreach (var (name, values) in details)
|
||||||
|
{
|
||||||
|
var known = values.Where(v => !string.IsNullOrWhiteSpace(v) && v != "Unknown")
|
||||||
|
.Select(v => v!.Trim()).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase).ToArray();
|
||||||
|
if (values.Any(v => string.IsNullOrWhiteSpace(v) || v == "Unknown")) missing.Add(name);
|
||||||
|
if (known.Length > 1) differences.Add($"{name}: {string.Join(" / ", known)}");
|
||||||
|
else if (known.Length == 1 && !missing.Contains(name)) similarities.Add($"{name}: {known[0]}");
|
||||||
|
}
|
||||||
|
var circumstances = observations.Select(o => o.MeasurementContext?.AdditionalCircumstances)
|
||||||
|
.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s!.Trim())
|
||||||
|
.Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase).ToArray();
|
||||||
|
if (circumstances.Length > 1) differences.Add("additional circumstances differ");
|
||||||
|
if (observations.Any(o => o.MeasurementContext?.RestDurationMinutes is < 5))
|
||||||
|
differences.Add("recorded rest duration is below the five-minute blood-pressure preparation recommendation");
|
||||||
|
foreach (var observation in observations)
|
||||||
|
{
|
||||||
|
var context = observation.MeasurementContext;
|
||||||
|
var narrative = string.Join(" ", observation.Context, observation.Note, context?.AdditionalCircumstances,
|
||||||
|
context?.BodyPosition, context?.DeviceDetails, context?.CuffDetails).ToLowerInvariant();
|
||||||
|
if (context?.ActivityCondition == "AtRest" && new[]
|
||||||
|
{ "during exercise", "during activity", "after exercise", "after activity", "under motion", "under træning", "efter motion", "efter træning" }
|
||||||
|
.Any(narrative.Contains)) conflicts.Add("AtRest conflicts with an activity description in recorded text.");
|
||||||
|
if (context?.Setting == "Home" && new[] { "at clinic", "in clinic", "at the clinic", "på klinik", "hos lægen" }.Any(narrative.Contains))
|
||||||
|
conflicts.Add("Home conflicts with a clinic description in recorded text.");
|
||||||
|
if (context?.Setting == "Clinic" && new[] { "at home", "hjemme" }.Any(narrative.Contains))
|
||||||
|
conflicts.Add("Clinic conflicts with a home description in recorded text.");
|
||||||
|
}
|
||||||
|
var status = conflicts.Count > 0 ? "ConflictingContext" : differences.Count > 0 ? "KnownDifferences" :
|
||||||
|
missing.Count > 0 ? "InsufficientContext" : "SupportedRecordedComparability";
|
||||||
|
var explanation = $"Recorded comparability: {status}. " +
|
||||||
|
(missing.Count > 0 ? $"Unknown or missing: {string.Join(", ", missing)}. " : "") +
|
||||||
|
(differences.Count > 0 ? $"Known differences: {string.Join("; ", differences)}. " : "") +
|
||||||
|
(conflicts.Count > 0 ? $"Conflicts: {string.Join("; ", conflicts.Distinct())} " : "") +
|
||||||
|
"Matching recorded details support comparability only of those details; they do not certify identical " +
|
||||||
|
"conditions, validated equipment or guideline-compliant technique. Narrative conflict detection is limited " +
|
||||||
|
"to documented phrases; other text is not proof of comparability. A difference between Home and Clinic " +
|
||||||
|
"selections alone is not improvement or deterioration over time.";
|
||||||
|
return new(status, similarities, differences, missing, conflicts.Distinct().Order(StringComparer.Ordinal).ToArray(), explanation);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@ using InsightsService.Contracts;
|
|||||||
|
|
||||||
namespace InsightsService.Domain;
|
namespace InsightsService.Domain;
|
||||||
|
|
||||||
public sealed class InsightCalculator
|
public sealed partial class InsightCalculator
|
||||||
{
|
{
|
||||||
public HealthInsight? CalculateSummary(Guid patientId, DateTime from, DateTime to,
|
public HealthInsight? CalculateSummary(Guid patientId, DateTime from, DateTime to,
|
||||||
IReadOnlyList<ObservationDto> observations, ContextSelection selection)
|
IReadOnlyList<ObservationDto> observations, ContextSelection selection)
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
namespace InsightsService.Domain;
|
||||||
|
|
||||||
|
public sealed record TrendAssessment(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
|
||||||
|
ContextSelection AppliedSelection, int ContributingCount, ComparabilityAssessment Comparability,
|
||||||
|
MeasurementAssessment Systolic, MeasurementAssessment Diastolic, MeasurementAssessment Pulse);
|
||||||
|
|
||||||
|
public sealed record ComparabilityAssessment(string Status, IReadOnlyList<string> KnownSimilarities,
|
||||||
|
IReadOnlyList<string> KnownDifferences, IReadOnlyList<string> MissingDetails,
|
||||||
|
IReadOnlyList<string> Conflicts, string Explanation);
|
||||||
|
|
||||||
|
public sealed record MeasurementAssessment(string Metric, string Unit, decimal? Mean, int? Minimum,
|
||||||
|
int? Maximum, int? Range, int DistinctTimestampCount, string Direction, string OverallDirection,
|
||||||
|
decimal? SlopePerDay, int ReversalCount, decimal? TotalSuccessiveChange,
|
||||||
|
string NumericalExplanation, ClinicalReference? Reference, string ReferenceComparison,
|
||||||
|
string Interpretation, string Hint);
|
||||||
|
|
||||||
|
public sealed record ClinicalReference(string Scope, decimal? LowerBoundary, string? LowerComparison,
|
||||||
|
decimal UpperBoundary, string UpperComparison, IReadOnlyList<ReferenceSource> Sources,
|
||||||
|
string Limitation);
|
||||||
|
|
||||||
|
public sealed record ReferenceSource(string Title, string Url, string Updated, string Reviewed);
|
||||||
+13
-6
@@ -181,14 +181,13 @@ retains its complete numerical-correction contract and rejects unsupported field
|
|||||||
rather than silently ignoring context supplied on that route. Use `PATCH` for context
|
rather than silently ignoring context supplied on that route. Use `PATCH` for context
|
||||||
updates. Both routes use the same
|
updates. Both routes use the same
|
||||||
Observation-owned update operation and save changes atomically. Subsequent reads,
|
Observation-owned update operation and save changes atomically. Subsequent reads,
|
||||||
latest observations and filtered history use current recorded context. US-11 trend
|
latest observations and filtered history use current recorded context. US-11 trend assessments also use current recorded context on each request.
|
||||||
integration remains to be verified when that endpoint is implemented.
|
|
||||||
|
|
||||||
US-08 tests cover the original full numerical corrections and rejection scenarios plus context-only/single-value patches, historical context additions, individual field corrections/clears, whole-context clearing, preservation of omitted data and creation time, persistence after restart, fresh filter membership, atomic rejection, missing observations and access restrictions. No new dependencies are introduced.
|
US-08 tests cover the original full numerical corrections and rejection scenarios plus context-only/single-value patches, historical context additions, individual field corrections/clears, whole-context clearing, preservation of omitted data and creation time, persistence after restart, fresh filter membership, atomic rejection, missing observations and access restrictions. No new dependencies are introduced.
|
||||||
|
|
||||||
`DELETE /api/observations/{observationId}` removes the observation and returns `204 No Content`. A missing or previously deleted observation returns `404`. The Observation Service deletes the row from its own database in a single statement; deleted observations disappear from specific retrieval, history, and latest selection. Other observations and the patient profile are preserved.
|
`DELETE /api/observations/{observationId}` removes the observation and returns `204 No Content`. A missing or previously deleted observation returns `404`. The Observation Service deletes the row from its own database in a single statement; deleted observations disappear from specific retrieval, history, and latest selection. Other observations and the patient profile are preserved.
|
||||||
|
|
||||||
US-09 tests cover the original deletion scenarios plus structured-context removal, filtered history after restart, current numerical summaries excluding deleted values, preservation of other observations and their context, empty filtered results, repeated deletion, and rejection of unauthenticated/other-patient/professional deletion. Context is stored in the observation row, so its existing atomic deletion needs no new production operation. US-11 trend-specific deletion checks remain to be added with that endpoint. No new dependencies or schema changes are required.
|
US-09 tests cover the original deletion scenarios plus structured-context removal, filtered history after restart, current numerical summaries excluding deleted values, preservation of other observations and their context, empty filtered results, repeated deletion, and rejection of unauthenticated/other-patient/professional deletion. Context is stored in the observation row, so its existing atomic deletion needs no new production operation. US-11 tests verify fresh trends after deletion. No new dependencies or schema changes are required.
|
||||||
|
|
||||||
`GET /api/patients/{patientId}/insights?from=2026-09-03T00:00:00&to=2026-09-08T23:59:59` returns `200` with `patientId`, `periodStart`, `periodEnd`, decimal `averageSystolic`, `averageDiastolic`, `averagePulse`, and integer `minSystolic`, `maxSystolic`, `minDiastolic`, `maxDiastolic`. Period validation, inclusive bounds, and timestamp normalization follow observation history. A single observation is sufficient. Arithmetic means use decimal calculations and round only the final result to two decimal places, half-up (away from zero for the positive recorded values); extrema retain their recorded integer values. An empty period returns `404` problem details with title `Insufficient observation data for calculation.` Missing/malformed/reversed bounds return `400`.
|
`GET /api/patients/{patientId}/insights?from=2026-09-03T00:00:00&to=2026-09-08T23:59:59` returns `200` with `patientId`, `periodStart`, `periodEnd`, decimal `averageSystolic`, `averageDiastolic`, `averagePulse`, and integer `minSystolic`, `maxSystolic`, `minDiastolic`, `maxDiastolic`. Period validation, inclusive bounds, and timestamp normalization follow observation history. A single observation is sufficient. Arithmetic means use decimal calculations and round only the final result to two decimal places, half-up (away from zero for the positive recorded values); extrema retain their recorded integer values. An empty period returns `404` problem details with title `Insufficient observation data for calculation.` Missing/malformed/reversed bounds return `400`.
|
||||||
|
|
||||||
@@ -223,13 +222,21 @@ test databases. They cover original summaries, independent/combined/unknown
|
|||||||
selections, applied selections and counts, context explanations, one-observation
|
selections, applied selections and counts, context explanations, one-observation
|
||||||
results, halfway/repeating rounding for all three metrics, patient/inclusive/equal/
|
results, halfway/repeating rounding for all three metrics, patient/inclusive/equal/
|
||||||
offset bounds, context corrections/clearing/deletions, restart, invalid requests,
|
offset bounds, context corrections/clearing/deletions, restart, invalid requests,
|
||||||
professional assignments and unavailable observation retrieval. Insights introduces no external dependencies. Trend calculation remains outside this story.
|
professional assignments and unavailable observation retrieval. Insights introduces no external dependencies. US-11 adds the separate trend endpoint described in [TRENDS.md](TRENDS.md).
|
||||||
|
|
||||||
|
`GET /api/patients/{patientId}/trends?from=...&to=...` implements US-11 with independent
|
||||||
|
systolic, diastolic and pulse assessments, context selections/counts, recorded comparability,
|
||||||
|
full-period numerical direction, reversals and variation, sourced reference comparisons and
|
||||||
|
limited clinical interpretation. Empty/single/tied series report unavailable temporal direction;
|
||||||
|
numerical information remains where supported. See [TRENDS.md](TRENDS.md) for the response,
|
||||||
|
reproducible mathematical methods, reference sources and interpretation limits. Tests cover
|
||||||
|
all US-11 acceptance criteria, current corrections/context/deletion, access controls and failures.
|
||||||
|
No persistence, service boundaries, dependencies or configuration changed.
|
||||||
|
|
||||||
US-13 authentication and patient ownership are implemented as described in
|
US-13 authentication and patient ownership are implemented as described in
|
||||||
[AUTHENTICATION.md](AUTHENTICATION.md). The account-to-profile association is persisted
|
[AUTHENTICATION.md](AUTHENTICATION.md). The account-to-profile association is persisted
|
||||||
in the patient service. US-14 professional reads require predefined gateway assignments; professional
|
in the patient service. US-14 professional reads require predefined gateway assignments; professional
|
||||||
writes are rejected. Updated context, tie
|
writes are rejected. US-04 through US-11 include updated context, ordering, rounding and trend requirements.
|
||||||
and rounding requirements in other stories remain to be implemented incrementally.
|
|
||||||
|
|
||||||
## Automated acceptance tests
|
## Automated acceptance tests
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
# US-11 trend API and methods
|
||||||
|
|
||||||
|
`GET /api/patients/{patientId}/trends?from=...&to=...&setting=Home&activityCondition=AtRest`
|
||||||
|
uses the same inclusive UTC measurement-instant semantics and optional context selections as history and
|
||||||
|
numerical insight. Offset-free timestamps mean UTC. Both selected dimensions must match; `Unknown`
|
||||||
|
is an explicit category. Patient ownership or professional assignment is required. Each selection is a
|
||||||
|
separate labelled result for the same requested period. No cross-setting difference is interpreted as
|
||||||
|
improvement. Insights retrieves current observations through the gateway on every request, without persistence.
|
||||||
|
|
||||||
|
A valid request returns 200 even for an empty selection. Count zero, null descriptive values and explicit
|
||||||
|
`Unavailable` direction distinguish empty data from upstream failures (502/504). One observation or
|
||||||
|
all observations at a single instant retain descriptive values, but temporal direction is unavailable.
|
||||||
|
Invalid/missing period or unsupported selections return 400. No new configuration or dependencies are required.
|
||||||
|
|
||||||
|
## Numerical method
|
||||||
|
|
||||||
|
Each metric has its own unit, mean, minimum, maximum and range over every eligible observation. Decimal
|
||||||
|
means are rounded only for output, to two decimals with midpoint rounding away from zero. No numerical
|
||||||
|
range threshold is used to declare clinical stability or instability.
|
||||||
|
|
||||||
|
Temporal calculations group equal measurement instants using the arithmetic mean for each metric,
|
||||||
|
then order those groups by measurement instant. Identifier and storage order play no part. Direction
|
||||||
|
uses every adjacent nonzero change: all positive means Increasing, all negative Decreasing, both signs
|
||||||
|
Mixed, all zero NoClearDirection. Reversal count counts sign changes after excluding zero steps.
|
||||||
|
TotalSuccessiveChange sums absolute changes between consecutive timestamp means. This retains intermediate
|
||||||
|
excursions, while raw min/max retain differences within timestamp ties. No temporal change is assigned
|
||||||
|
between measurements at the same instant.
|
||||||
|
|
||||||
|
OverallDirection additionally reports the sign of an ordinary least-squares line over all timestamp
|
||||||
|
means. Time is scaled from zero to one over the observed span; each distinct timestamp has equal weight.
|
||||||
|
SlopePerDay converts that fitted slope to metric units per day and rounds to six decimals. Classification
|
||||||
|
uses the unrounded slope. An extremely small nonzero slope may round to zero; its sign is a mathematical
|
||||||
|
result, not evidence of clinical significance. The fit describes a linear tendency, not a prediction,
|
||||||
|
causal effect or a monotonic trajectory. Mixed direction and reversal count remain visible even when
|
||||||
|
an overall slope exists. Irregular sampling and repeated observations can affect the description;
|
||||||
|
there is no significance test, smoothing, diagnostic protocol or clinical variability classification.
|
||||||
|
|
||||||
|
## Context and interpretation
|
||||||
|
|
||||||
|
Comparability lists known similarities, differences and missing information for setting, activity,
|
||||||
|
rest duration, body position, measured arm, device and cuff. Differing recorded additional circumstances
|
||||||
|
also limit comparability. Matching complete recorded fields support comparability of recorded details
|
||||||
|
only, without certifying clinical technique or equipment. Missing optional additional circumstances do
|
||||||
|
not block a supported reference comparison. Known inadequate rest is reported separately.
|
||||||
|
|
||||||
|
Limited deterministic conflict detection recognises case-insensitive `during exercise`, `during activity`,
|
||||||
|
`after exercise`, `after activity`, `under motion`, `under træning`, `efter motion`, `efter træning` against
|
||||||
|
AtRest; `at clinic`, `in clinic`, `at the clinic`, `på klinik`, `hos lægen` against Home; and `at home`,
|
||||||
|
`hjemme` against Clinic. It examines preserved context, notes and recorded preparation text, without
|
||||||
|
recategorising observations. This is conservative phrase detection, not general language understanding;
|
||||||
|
negated phrases can still withhold interpretation. Arbitrary narrative is not proof of correct technique.
|
||||||
|
Detected conflicts withhold resting-reference interpretation while preserving numerical information.
|
||||||
|
|
||||||
|
Sources reviewed 2026-10-05:
|
||||||
|
|
||||||
|
- [Lægehåndbogen: Højt blodtryk](https://www.sundhed.dk/sundhedsfaglig/laegehaandbogen/hjerte-kar/symptomer-og-tegn/hoejt-blodtryk/)
|
||||||
|
(updated 2024-09-25): separate high-pressure boundaries of home 135/85 and clinic 140/90 mmHg,
|
||||||
|
inclusive. The reference comparison requires a single known setting and recorded AtRest; known rest
|
||||||
|
below five minutes or a non-seated recorded position prevents it. Missing optional preparation
|
||||||
|
details permit only a provisional comparison, explicitly identifying unknown technique. Arbitrary
|
||||||
|
period means do not establish the source's diagnostic protocol. No lower BP boundary is inferred.
|
||||||
|
- [Patienthåndbogen: Bradykardi](https://www.sundhed.dk/borger/patienthaandbogen/hjerte-og-blodkar/sygdomme/hjertearytmier/bradykardi-langsom-puls/)
|
||||||
|
(updated 2025-09-02) and [Hurtig puls](https://www.sundhed.dk/borger/patienthaandbogen/hjerte-og-blodkar/sygdomme/hjertearytmier/takykardier-hurtig-puls/)
|
||||||
|
(updated 2025-05-12): resting pulse below 50 or above 100 beats/min provides limited rate-reference
|
||||||
|
comparisons. Low pulse can be physiological in trained people. Rate alone does not diagnose rhythm
|
||||||
|
abnormalities; age, fitness, medicines and symptoms remain unknown. These boundaries are not a
|
||||||
|
universal healthy range or a patient-specific target.
|
||||||
|
|
||||||
|
Every metric returns its reference scope, exact comparison operators, source URLs, update/review dates,
|
||||||
|
counts outside the boundaries and limitations. Comparisons remain available despite missing preparation
|
||||||
|
information when the known context supports that limited comparison. Mixed or unknown activity,
|
||||||
|
conflicting narrative, mixed BP settings, or unsupported BP setting make the affected comparison unavailable.
|
||||||
|
|
||||||
|
Interpretation of development requires temporal separation, applicable references and supported recorded
|
||||||
|
comparability. The following are deliberately cautious inferences from the cited references, not new
|
||||||
|
clinical decision rules: a consistent fall from high BP that remains high may be PotentiallyFavourable,
|
||||||
|
while explicitly still high; resting pulse moving from outside towards the reference interval may be
|
||||||
|
PotentiallyFavourable unless any contributing observation crosses the opposite boundary, including values within timestamp ties. Excursions outside a boundary with reversals
|
||||||
|
are Mixed. Other outside-reference levels may be PotentiallyConcerning, including falling low pulse
|
||||||
|
or unchanging high BP. Remaining cases are CannotInterpret. No BP fall below the high threshold is
|
||||||
|
automatically called favourable, because an applicable lower limit or personalised goal is unavailable.
|
||||||
|
|
||||||
|
Each hint distinguishes numerical variation from clinical meaning, explains incomplete/differing context,
|
||||||
|
and disclaims diagnosis and medication advice. There is no combined good/bad classification across metrics.
|
||||||
|
Reference comparisons and hints are for review, not a replacement for individual clinical assessment.
|
||||||
@@ -0,0 +1,415 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
using HealthApp.TestSupport;
|
||||||
|
using InsightsService.Contracts;
|
||||||
|
using InsightsService.Domain;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace Observation.AcceptanceTests;
|
||||||
|
|
||||||
|
public sealed class HealthTrendCalculationTests
|
||||||
|
{
|
||||||
|
private static readonly Guid PatientId = Guid.NewGuid();
|
||||||
|
private static readonly DateTime Start = new(2026, 9, 1);
|
||||||
|
private static readonly MeasurementContextDto Prepared = new("Home", "AtRest", 5, "Seated", "Left", "Device A", "Adult cuff", null);
|
||||||
|
private static ObservationDto Observation(int day, int systolic, int diastolic = 90, int pulse = 70,
|
||||||
|
MeasurementContextDto? context = null, string? text = null) =>
|
||||||
|
new(Guid.NewGuid(), PatientId, Start.AddDays(day), systolic, diastolic, pulse, context ?? Prepared, text);
|
||||||
|
private static TrendAssessment Calculate(params ObservationDto[] observations) =>
|
||||||
|
new InsightCalculator().CalculateTrend(PatientId, Start, Start.AddDays(10), observations, new() { Setting = "Home", ActivityCondition = "AtRest" });
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(140, 150, 160, "Increasing")]
|
||||||
|
[InlineData(160, 150, 140, "Decreasing")]
|
||||||
|
[InlineData(150, 150, 150, "NoClearDirection")]
|
||||||
|
public void Full_period_direction_and_separate_units_and_levels(int first, int middle, int last, string direction)
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(0, first, 95, 65), Observation(1, middle, 90, 70), Observation(2, last, 85, 75));
|
||||||
|
Assert.Equal(direction, result.Systolic.Direction);
|
||||||
|
Assert.Equal(direction, result.Systolic.OverallDirection);
|
||||||
|
Assert.Equal("Decreasing", result.Diastolic.Direction);
|
||||||
|
Assert.Equal("Increasing", result.Pulse.Direction);
|
||||||
|
Assert.Equal("mmHg", result.Systolic.Unit);
|
||||||
|
Assert.Equal("mmHg", result.Diastolic.Unit);
|
||||||
|
Assert.Equal("beats/min", result.Pulse.Unit);
|
||||||
|
Assert.Equal(150m, result.Systolic.Mean);
|
||||||
|
Assert.Equal(90m, result.Diastolic.Mean);
|
||||||
|
Assert.Equal(70m, result.Pulse.Mean);
|
||||||
|
Assert.Equal("SupportedRecordedComparability", result.Comparability.Status);
|
||||||
|
Assert.Contains("rest duration: 5", result.Comparability.KnownSimilarities);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Equal_endpoints_do_not_hide_intermediate_excursion_or_reversal()
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(0, 140), Observation(1, 190), Observation(2, 140));
|
||||||
|
Assert.Equal("Mixed", result.Systolic.Direction);
|
||||||
|
Assert.Equal("NoClearDirection", result.Systolic.OverallDirection);
|
||||||
|
Assert.Equal(1, result.Systolic.ReversalCount);
|
||||||
|
Assert.Equal(50, result.Systolic.Range);
|
||||||
|
Assert.Equal(100m, result.Systolic.TotalSuccessiveChange);
|
||||||
|
Assert.Equal("Mixed", result.Systolic.Interpretation);
|
||||||
|
Assert.Contains("no clinical stability classification", result.Systolic.NumericalExplanation);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Overall_decrease_can_coexist_with_reversals_and_large_variation()
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(0, 180), Observation(1, 160), Observation(2, 170), Observation(3, 140));
|
||||||
|
Assert.Equal("Mixed", result.Systolic.Direction);
|
||||||
|
Assert.Equal("Decreasing", result.Systolic.OverallDirection);
|
||||||
|
Assert.Equal(2, result.Systolic.ReversalCount);
|
||||||
|
Assert.Equal(60m, result.Systolic.TotalSuccessiveChange);
|
||||||
|
Assert.True(result.Systolic.SlopePerDay < 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Low_variation_outside_reference_is_not_healthy()
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(0, 155), Observation(1, 155), Observation(2, 155));
|
||||||
|
Assert.Equal(0, result.Systolic.Range);
|
||||||
|
Assert.Equal("PotentiallyConcerning", result.Systolic.Interpretation);
|
||||||
|
Assert.Contains("3 observation(s) >= 135", result.Systolic.ReferenceComparison);
|
||||||
|
Assert.Contains("Limited variation does not establish healthy", result.Systolic.Hint);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Favourable_pressure_decrease_can_still_be_high_while_falling_pulse_is_concerning()
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(0, 160, 85, 70), Observation(1, 150, 90, 55), Observation(2, 140, 95, 40));
|
||||||
|
Assert.Equal("PotentiallyFavourable", result.Systolic.Interpretation);
|
||||||
|
Assert.Contains("remains above or at", result.Systolic.Hint);
|
||||||
|
Assert.Equal("PotentiallyConcerning", result.Diastolic.Interpretation);
|
||||||
|
Assert.Equal("PotentiallyConcerning", result.Pulse.Interpretation);
|
||||||
|
Assert.Contains("not automatically favourable", result.Pulse.Hint);
|
||||||
|
Assert.Equal(50m, result.Pulse.Reference!.LowerBoundary);
|
||||||
|
Assert.Equal(100m, result.Pulse.Reference.UpperBoundary);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Moving_low_pulse_up_or_high_pulse_down_is_not_automatically_concerning()
|
||||||
|
{
|
||||||
|
Assert.Equal("PotentiallyFavourable", Calculate(Observation(0, 120, pulse: 40), Observation(1, 120, pulse: 55)).Pulse.Interpretation);
|
||||||
|
Assert.Equal("PotentiallyFavourable", Calculate(Observation(0, 120, pulse: 120), Observation(1, 120, pulse: 105)).Pulse.Interpretation);
|
||||||
|
Assert.Equal("CannotInterpret", Calculate(Observation(0, 120), Observation(1, 110)).Systolic.Interpretation);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Opposite_pulse_excursions_within_timestamp_ties_are_not_hidden_by_their_mean()
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(0, 120, pulse: 30), Observation(0, 120, pulse: 210),
|
||||||
|
Observation(1, 120, pulse: 105));
|
||||||
|
Assert.Equal("Decreasing", result.Pulse.Direction);
|
||||||
|
Assert.Equal(180, result.Pulse.Range);
|
||||||
|
Assert.Equal("PotentiallyConcerning", result.Pulse.Interpretation);
|
||||||
|
Assert.Contains("1 observation(s) < 50", result.Pulse.ReferenceComparison);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Home", 135, 85)]
|
||||||
|
[InlineData("Clinic", 140, 90)]
|
||||||
|
public void References_are_setting_specific_sourced_and_not_treatment_targets(string setting, int systolic, int diastolic)
|
||||||
|
{
|
||||||
|
var context = Prepared with { Setting = setting };
|
||||||
|
var result = Calculate(Observation(0, 138, context: context), Observation(1, 138, context: context));
|
||||||
|
Assert.Equal(systolic, result.Systolic.Reference!.UpperBoundary);
|
||||||
|
Assert.Equal(diastolic, result.Diastolic.Reference!.UpperBoundary);
|
||||||
|
Assert.Equal(">=", result.Systolic.Reference.UpperComparison);
|
||||||
|
Assert.Contains("sundhed.dk", result.Systolic.Reference.Sources.Single().Url);
|
||||||
|
Assert.Contains("not individual treatment targets", result.Systolic.Hint);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(50, 0)]
|
||||||
|
[InlineData(100, 0)]
|
||||||
|
[InlineData(49, 2)]
|
||||||
|
[InlineData(101, 2)]
|
||||||
|
public void Pulse_reference_boundaries_are_exclusive(int pulse, int outsideCount)
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(0, 120, pulse: pulse), Observation(1, 120, pulse: pulse));
|
||||||
|
Assert.Contains($"{(pulse > 100 ? outsideCount : 0)} observation(s) > 100", result.Pulse.ReferenceComparison);
|
||||||
|
Assert.Contains($"{(pulse < 50 ? outsideCount : 0)} observation(s) < 50", result.Pulse.ReferenceComparison);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Missing_context_preserves_numerical_direction_but_not_resting_interpretation()
|
||||||
|
{
|
||||||
|
var unknown = new MeasurementContextDto("Unknown", "Unknown", null, null, null, null, null, null);
|
||||||
|
var result = Calculate(Observation(0, 150, context: unknown), Observation(1, 160, context: unknown));
|
||||||
|
Assert.Equal("Increasing", result.Systolic.Direction);
|
||||||
|
Assert.Equal(10, result.Systolic.Range);
|
||||||
|
Assert.Null(result.Systolic.Reference);
|
||||||
|
Assert.Null(result.Pulse.Reference);
|
||||||
|
Assert.Equal("CannotInterpret", result.Systolic.Interpretation);
|
||||||
|
Assert.Contains("setting", result.Comparability.MissingDetails);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Known_categories_with_missing_preparation_support_limited_reference_comparison()
|
||||||
|
{
|
||||||
|
var limited = new MeasurementContextDto("Home", "AtRest", null, null, null, null, null, null);
|
||||||
|
var result = Calculate(Observation(0, 150, context: limited), Observation(1, 160, context: limited));
|
||||||
|
Assert.Equal("InsufficientContext", result.Comparability.Status);
|
||||||
|
Assert.Contains("setting: Home", result.Comparability.KnownSimilarities);
|
||||||
|
Assert.Contains("rest duration", result.Comparability.MissingDetails);
|
||||||
|
Assert.NotNull(result.Systolic.Reference);
|
||||||
|
Assert.Contains("provisional", result.Systolic.ReferenceComparison);
|
||||||
|
Assert.Contains("limited reference comparison", result.Systolic.Hint);
|
||||||
|
Assert.Equal("CannotInterpret", result.Systolic.Interpretation);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Missing_optional_circumstances_do_not_block_supported_comparison()
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(0, 150), Observation(1, 160));
|
||||||
|
Assert.NotNull(result.Systolic.Reference);
|
||||||
|
Assert.Equal("PotentiallyConcerning", result.Systolic.Interpretation);
|
||||||
|
Assert.Equal("SupportedRecordedComparability", result.Comparability.Status);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("during exercise")]
|
||||||
|
[InlineData("after activity")]
|
||||||
|
[InlineData("under træning")]
|
||||||
|
public void Conflicting_rest_narrative_withholds_resting_interpretation(string narrative)
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(0, 150, text: narrative), Observation(1, 160));
|
||||||
|
Assert.Equal("ConflictingContext", result.Comparability.Status);
|
||||||
|
Assert.Contains(result.Comparability.Conflicts, s => s.Contains("AtRest"));
|
||||||
|
Assert.Null(result.Systolic.Reference);
|
||||||
|
Assert.Null(result.Pulse.Reference);
|
||||||
|
Assert.Equal("Increasing", result.Systolic.Direction);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Different_conditions_and_preparation_are_visible_and_limit_combined_trajectory()
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(0, 150), Observation(1, 160, context: Prepared with
|
||||||
|
{ ActivityCondition = "AfterActivity", BodyPosition = "Standing" }));
|
||||||
|
Assert.Equal("KnownDifferences", result.Comparability.Status);
|
||||||
|
Assert.Contains(result.Comparability.KnownDifferences, s => s.Contains("activity condition"));
|
||||||
|
Assert.Contains(result.Comparability.KnownDifferences, s => s.Contains("body position"));
|
||||||
|
Assert.Null(result.Systolic.Reference);
|
||||||
|
Assert.Equal("CannotInterpret", result.Systolic.Interpretation);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Known_inadequate_pressure_preparation_does_not_block_resting_pulse_reference()
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(0, 150, context: Prepared with { RestDurationMinutes = 1 }), Observation(1, 160));
|
||||||
|
Assert.Null(result.Systolic.Reference);
|
||||||
|
Assert.NotNull(result.Pulse.Reference);
|
||||||
|
Assert.Contains(result.Comparability.KnownDifferences, s => s.Contains("five-minute"));
|
||||||
|
var standing = Calculate(Observation(0, 150, context: Prepared with { BodyPosition = "Standing" }),
|
||||||
|
Observation(1, 160, context: Prepared with { BodyPosition = "Standing" }));
|
||||||
|
Assert.Null(standing.Systolic.Reference);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Timestamp_ties_do_not_manufacture_direction_or_hide_descriptive_range()
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(1, 140), Observation(1, 180));
|
||||||
|
Assert.Equal("Unavailable", result.Systolic.Direction);
|
||||||
|
Assert.Null(result.Systolic.SlopePerDay);
|
||||||
|
Assert.Equal(160m, result.Systolic.Mean);
|
||||||
|
Assert.Equal(40, result.Systolic.Range);
|
||||||
|
Assert.NotNull(result.Systolic.Reference);
|
||||||
|
Assert.Equal("CannotInterpret", result.Systolic.Interpretation);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Empty_and_single_series_report_each_unavailable_part()
|
||||||
|
{
|
||||||
|
var empty = Calculate();
|
||||||
|
Assert.Equal(0, empty.ContributingCount);
|
||||||
|
Assert.Null(empty.Systolic.Mean);
|
||||||
|
Assert.Equal("Unavailable", empty.Systolic.Direction);
|
||||||
|
Assert.Contains("No matching observations", empty.Systolic.NumericalExplanation);
|
||||||
|
var single = Calculate(Observation(0, 140));
|
||||||
|
Assert.Equal(140m, single.Systolic.Mean);
|
||||||
|
Assert.Equal("Unavailable", single.Systolic.Direction);
|
||||||
|
Assert.Equal("Unavailable", single.Systolic.OverallDirection);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Retrieval_and_identifier_order_do_not_change_results_including_ties()
|
||||||
|
{
|
||||||
|
var series = new[] { Observation(0, 140), Observation(0, 180), Observation(1, 150), Observation(2, 140) };
|
||||||
|
Assert.Equal(JsonSerializer.Serialize(Calculate(series)), JsonSerializer.Serialize(Calculate(series.Reverse()
|
||||||
|
.Select(o => o with { ObservationId = Guid.NewGuid() }).ToArray())));
|
||||||
|
Assert.Equal("Decreasing", Calculate(series).Systolic.Direction);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class HealthTrendTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||||
|
{
|
||||||
|
private sealed record Profile(Guid PatientId);
|
||||||
|
private sealed record Recorded(Guid ObservationId);
|
||||||
|
private const string Period = "from=2026-09-01T08%3A00%3A00&to=2026-09-10T08%3A00%3A00";
|
||||||
|
private static string PathFor(Guid patient, string selection = "", string period = Period) =>
|
||||||
|
$"/api/patients/{patient}/trends?{period}{selection}";
|
||||||
|
private async Task<Guid> Patient()
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Health trend", dateOfBirth = "1980-01-01" });
|
||||||
|
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||||
|
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||||
|
}
|
||||||
|
private async Task<Guid> Record(Guid patient, int systolic, string time = "2026-09-05T08:00:00",
|
||||||
|
string? setting = "Home", string? activity = "AtRest")
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patient}/observations", new
|
||||||
|
{
|
||||||
|
measuredAt = time, systolic, diastolic = 85, pulse = 70,
|
||||||
|
measurementContext = new { setting, activityCondition = activity, restDurationMinutes = 5,
|
||||||
|
bodyPosition = "Seated", measuredArm = "Left", deviceDetails = "Device A", cuffDetails = "Adult cuff" }
|
||||||
|
});
|
||||||
|
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||||
|
return (await response.Content.ReadFromJsonAsync<Recorded>())!.ObservationId;
|
||||||
|
}
|
||||||
|
private async Task<TrendAssessment> Trend(Guid patient, string selection = "", string period = Period)
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.GetAsync(PathFor(patient, selection, period));
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
return (await response.Content.ReadFromJsonAsync<TrendAssessment>())!;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Inclusive_patient_period_and_equal_offset_instants_apply_before_sufficiency()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
await Record(patient, 150, "2026-09-01T08:00:00");
|
||||||
|
await Record(patient, 160, "2026-09-10T08:00:00");
|
||||||
|
await Record(patient, 250, "2026-09-01T07:59:59");
|
||||||
|
await Record(patient, 250, "2026-09-10T08:00:01");
|
||||||
|
await Record(await Patient(), 250);
|
||||||
|
var result = await Trend(patient);
|
||||||
|
Assert.Equal(patient, result.PatientId);
|
||||||
|
Assert.Equal(new DateTime(2026, 9, 1, 8, 0, 0), result.PeriodStart);
|
||||||
|
Assert.Equal(new DateTime(2026, 9, 10, 8, 0, 0), result.PeriodEnd);
|
||||||
|
Assert.Equal(2, result.ContributingCount);
|
||||||
|
Assert.Equal(155m, result.Systolic.Mean);
|
||||||
|
Assert.Equal("Increasing", result.Systolic.Direction);
|
||||||
|
var equal = await Trend(patient, period: "from=2026-09-01T10%3A00%3A00%2B02%3A00&to=2026-09-01T08%3A00%3A00Z");
|
||||||
|
Assert.Equal(equal.PeriodStart, equal.PeriodEnd);
|
||||||
|
Assert.Equal(1, equal.ContributingCount);
|
||||||
|
Assert.Equal("Unavailable", equal.Systolic.Direction);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Labelled_home_and_clinic_selections_and_independent_dimensions_use_only_matches()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
await Record(patient, 150, "2026-09-02T08:00:00");
|
||||||
|
await Record(patient, 145, "2026-09-03T08:00:00");
|
||||||
|
await Record(patient, 160, "2026-09-02T08:00:00", "Clinic");
|
||||||
|
await Record(patient, 155, "2026-09-03T08:00:00", "Clinic");
|
||||||
|
await Record(patient, 200, activity: "AfterActivity");
|
||||||
|
var home = await Trend(patient, "&setting=Home&activityCondition=AtRest");
|
||||||
|
var clinic = await Trend(patient, "&setting=Clinic&activityCondition=AtRest");
|
||||||
|
Assert.Equal(new ContextSelection { Setting = "Home", ActivityCondition = "AtRest" }, home.AppliedSelection);
|
||||||
|
Assert.Equal(new ContextSelection { Setting = "Clinic", ActivityCondition = "AtRest" }, clinic.AppliedSelection);
|
||||||
|
Assert.Equal(2, home.ContributingCount);
|
||||||
|
Assert.Equal(2, clinic.ContributingCount);
|
||||||
|
Assert.Equal(135m, home.Systolic.Reference!.UpperBoundary);
|
||||||
|
Assert.Equal(140m, clinic.Systolic.Reference!.UpperBoundary);
|
||||||
|
Assert.Contains("alone is not improvement or deterioration", home.Comparability.Explanation);
|
||||||
|
Assert.Equal(3, (await Trend(patient, "&setting=Home")).ContributingCount);
|
||||||
|
Assert.Equal(4, (await Trend(patient, "&activityCondition=AtRest")).ContributingCount);
|
||||||
|
Assert.Equal("KnownDifferences", (await Trend(patient)).Comparability.Status);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Unknown_empty_and_one_selected_observation_do_not_borrow_excluded_data()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
await Record(patient, 150, "2026-09-02T08:00:00");
|
||||||
|
await Record(patient, 160, "2026-09-03T08:00:00");
|
||||||
|
await Record(patient, 180, setting: null, activity: null);
|
||||||
|
var unknown = await Trend(patient, "&setting=Unknown&activityCondition=Unknown");
|
||||||
|
Assert.Equal(1, unknown.ContributingCount);
|
||||||
|
Assert.Equal("Unavailable", unknown.Systolic.Direction);
|
||||||
|
Assert.Equal(180m, unknown.Systolic.Mean);
|
||||||
|
Assert.Null(unknown.Systolic.Reference);
|
||||||
|
var empty = await Trend(patient, "&setting=Clinic");
|
||||||
|
Assert.Equal(0, empty.ContributingCount);
|
||||||
|
Assert.Contains("No matching observations", empty.Pulse.NumericalExplanation);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Corrected_values_context_and_deletions_are_used_on_every_request_after_restart()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
var first = await Record(patient, 150, "2026-09-02T08:00:00");
|
||||||
|
var second = await Record(patient, 160, "2026-09-03T08:00:00");
|
||||||
|
Assert.Equal("Increasing", (await Trend(patient)).Systolic.Direction);
|
||||||
|
using var corrected = await fixture.Client.PatchAsJsonAsync($"/api/observations/{second}", new { systolic = 140 });
|
||||||
|
Assert.Equal(HttpStatusCode.OK, corrected.StatusCode);
|
||||||
|
Assert.Equal("Decreasing", (await Trend(patient)).Systolic.Direction);
|
||||||
|
using var context = await fixture.Client.PatchAsJsonAsync($"/api/observations/{second}",
|
||||||
|
new { measurementContext = new { activityCondition = "AfterActivity" } });
|
||||||
|
Assert.Equal(HttpStatusCode.OK, context.StatusCode);
|
||||||
|
var selected = await Trend(patient, "&activityCondition=AtRest");
|
||||||
|
Assert.Equal(1, selected.ContributingCount);
|
||||||
|
Assert.Equal("Unavailable", selected.Systolic.Direction);
|
||||||
|
Assert.Null((await Trend(patient)).Systolic.Reference);
|
||||||
|
using var deleted = await fixture.Client.DeleteAsync($"/api/observations/{second}");
|
||||||
|
Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
Assert.Equal(150m, (await Trend(patient)).Systolic.Mean);
|
||||||
|
using var last = await fixture.Client.DeleteAsync($"/api/observations/{first}");
|
||||||
|
Assert.Equal(HttpStatusCode.NoContent, last.StatusCode);
|
||||||
|
Assert.Equal(0, (await Trend(patient)).ContributingCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("from=2026-09-10&to=2026-09-01")]
|
||||||
|
[InlineData("from=bad&to=2026-09-10")]
|
||||||
|
[InlineData("from=2026-09-01")]
|
||||||
|
[InlineData("to=2026-09-10")]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData(Period + "&setting=Invalid")]
|
||||||
|
[InlineData(Period + "&activityCondition=Invalid")]
|
||||||
|
public async Task Invalid_period_or_selection_is_rejected_with_explanation(string period)
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.GetAsync(PathFor(await Patient(), period: period));
|
||||||
|
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||||
|
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||||
|
Assert.True(problem.RootElement.TryGetProperty("errors", out _));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Trend_access_requires_authentication_ownership_or_professional_assignment()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
await Record(patient, 150);
|
||||||
|
var other = await Patient();
|
||||||
|
fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = patient.ToString();
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
using var anonymous = await fixture.RawClient.GetAsync(PathFor(patient));
|
||||||
|
Assert.Equal(HttpStatusCode.Unauthorized, anonymous.StatusCode);
|
||||||
|
foreach (var (account, status) in new[] { ("professional", HttpStatusCode.OK),
|
||||||
|
("professional-empty", HttpStatusCode.NotFound), (fixture.Authentication.PatientAccounts[other], HttpStatusCode.NotFound) })
|
||||||
|
{
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Get, PathFor(patient));
|
||||||
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account));
|
||||||
|
using var response = await fixture.RawClient.SendAsync(request);
|
||||||
|
Assert.Equal(status, response.StatusCode);
|
||||||
|
if (status != HttpStatusCode.OK) Assert.Empty(await response.Content.ReadAsStringAsync());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Upstream_failure_is_not_misreported_as_empty_data()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
await fixture.StopObservationServiceAsync();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.GetAsync(PathFor(patient));
|
||||||
|
Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode);
|
||||||
|
}
|
||||||
|
finally { await fixture.RestartHostsAsync(); }
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user