Implement US-10 selected-context insights and final rounding

This commit is contained in:
Steffen committed 2026-10-05 13:26:22 +02:00
1 parent d21005b6fe
commit a0a9e2e9b9
11 files changed
+314 -18

No files matched your search

@@ -1,3 +1,4 @@
using System.ComponentModel.DataAnnotations;
using InsightsService.Clients;
using InsightsService.Domain;
@@ -6,14 +7,15 @@ namespace InsightsService.Application;
public sealed class InsightsApplicationService(ObservationServiceClient observations, InsightCalculator calculator)
{
public async Task<HealthInsight?> GetSummaryAsync(Guid patientId, DateTime from, DateTime to,
CancellationToken cancellationToken)
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));
var history = await observations.GetByPeriodAsync(patientId, from, to, cancellationToken);
return calculator.CalculateSummary(patientId, from, to, history);
Validator.ValidateObject(selection, new ValidationContext(selection), validateAllProperties: true);
var history = await observations.GetByPeriodAsync(patientId, from, to, selection, cancellationToken);
return calculator.CalculateSummary(patientId, from, to, history, selection);
}
private static DateTime NormalizeTimestamp(DateTime value) =>
@@ -1,3 +1,4 @@
using InsightsService.Domain;
using System.Globalization;
using InsightsService.Contracts;
@@ -6,11 +7,14 @@ namespace InsightsService.Clients;
public sealed class HttpObservationServiceClient(HttpClient client) : ObservationServiceClient
{
public async Task<List<ObservationDto>> GetByPeriodAsync(Guid patientId, DateTime from, DateTime to,
CancellationToken cancellationToken)
ContextSelection selection, CancellationToken cancellationToken)
{
var start = Uri.EscapeDataString(from.ToString("O", CultureInfo.InvariantCulture));
var end = Uri.EscapeDataString(to.ToString("O", CultureInfo.InvariantCulture));
using var response = await client.GetAsync($"api/patients/{patientId}/observations?from={start}&to={end}",
var filters = "";
if (selection.Setting is not null) filters += "&setting=" + Uri.EscapeDataString(selection.Setting);
if (selection.ActivityCondition is not null) filters += "&activityCondition=" + Uri.EscapeDataString(selection.ActivityCondition);
using var response = await client.GetAsync($"api/patients/{patientId}/observations?from={start}&to={end}{filters}",
HttpCompletionOption.ResponseHeadersRead, cancellationToken);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<List<ObservationDto>>(cancellationToken)
@@ -1,3 +1,4 @@
using InsightsService.Domain;
using InsightsService.Contracts;
namespace InsightsService.Clients;
@@ -5,5 +6,5 @@ namespace InsightsService.Clients;
public interface ObservationServiceClient
{
Task<List<ObservationDto>> GetByPeriodAsync(Guid patientId, DateTime from, DateTime to,
CancellationToken cancellationToken);
ContextSelection selection, CancellationToken cancellationToken);
}
@@ -1,5 +1,8 @@
using InsightsService.Domain;
namespace InsightsService.Contracts;
public sealed record HealthInsightDto(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic);
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic,
ContextSelection AppliedSelection, int ContributingCount, string ContextExplanation);
@@ -1,4 +1,8 @@
namespace InsightsService.Contracts;
public sealed record ObservationDto(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
int Systolic, int Diastolic, int Pulse);
int Systolic, int Diastolic, int Pulse, MeasurementContextDto? MeasurementContext = null,
string? Context = null, string? Note = null);
public sealed record MeasurementContextDto(string? Setting, string? ActivityCondition, decimal? RestDurationMinutes,
string? BodyPosition, string? MeasuredArm, string? DeviceDetails, string? CuffDetails, string? AdditionalCircumstances);
@@ -1,3 +1,4 @@
using InsightsService.Domain;
using InsightsService.Application;
using InsightsService.Contracts;
using Microsoft.AspNetCore.Mvc;
@@ -12,16 +13,17 @@ public sealed class InsightsController(InsightsApplicationService service) : Con
[HttpGet]
public async Task<ActionResult<HealthInsightDto>> GetSummary(Guid patientId,
[FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to,
CancellationToken cancellationToken)
[FromQuery] ContextSelection selection, CancellationToken cancellationToken)
{
try
{
var insight = await service.GetSummaryAsync(patientId, from, to, cancellationToken);
var insight = await service.GetSummaryAsync(patientId, from, to, selection, cancellationToken);
return insight is null
? Problem(statusCode: StatusCodes.Status404NotFound, title: "Insufficient observation data for calculation.")
: Ok(new HealthInsightDto(insight.PatientId, insight.PeriodStart, insight.PeriodEnd,
insight.AverageSystolic, insight.AverageDiastolic, insight.AveragePulse,
insight.MinSystolic, insight.MaxSystolic, insight.MinDiastolic, insight.MaxDiastolic));
insight.MinSystolic, insight.MaxSystolic, insight.MinDiastolic, insight.MaxDiastolic,
insight.AppliedSelection, insight.ContributingCount, insight.ContextExplanation));
}
catch (ArgumentException)
{
@@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations;
namespace InsightsService.Domain;
public sealed record ContextSelection
{
[AllowedValues("Home", "Clinic", "Other", "Unknown", null)]
public string? Setting { get; init; }
[AllowedValues("AtRest", "DuringActivity", "AfterActivity", "Unknown", null)]
public string? ActivityCondition { get; init; }
}
+2 -1
View File
@@ -2,4 +2,5 @@ namespace InsightsService.Domain;
public sealed record HealthInsight(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic);
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic,
ContextSelection AppliedSelection, int ContributingCount, string ContextExplanation);
@@ -1,3 +1,4 @@
using System.Globalization;
using InsightsService.Contracts;
namespace InsightsService.Domain;
@@ -5,13 +6,45 @@ namespace InsightsService.Domain;
public sealed class InsightCalculator
{
public HealthInsight? CalculateSummary(Guid patientId, DateTime from, DateTime to,
IReadOnlyList<ObservationDto> observations)
IReadOnlyList<ObservationDto> observations, ContextSelection selection)
{
if (observations.Count == 0)
return null;
return new HealthInsight(patientId, from, to,
observations.Average(o => (decimal)o.Systolic), observations.Average(o => (decimal)o.Diastolic),
observations.Average(o => (decimal)o.Pulse), observations.Min(o => o.Systolic),
observations.Max(o => o.Systolic), observations.Min(o => o.Diastolic), observations.Max(o => o.Diastolic));
Math.Round(observations.Average(o => (decimal)o.Systolic), 2, MidpointRounding.AwayFromZero),
Math.Round(observations.Average(o => (decimal)o.Diastolic), 2, MidpointRounding.AwayFromZero),
Math.Round(observations.Average(o => (decimal)o.Pulse), 2, MidpointRounding.AwayFromZero),
observations.Min(o => o.Systolic), observations.Max(o => o.Systolic),
observations.Min(o => o.Diastolic), observations.Max(o => o.Diastolic),
selection, observations.Count, DescribeContext(observations));
}
private static string DescribeContext(IReadOnlyList<ObservationDto> observations)
{
var settings = observations.Select(o => o.MeasurementContext?.Setting ?? "Unknown").ToArray();
var activities = observations.Select(o => o.MeasurementContext?.ActivityCondition ?? "Unknown").ToArray();
var explanation = $"Recorded settings: {Counts(settings)}. Recorded activity conditions: {Counts(activities)}.";
if (settings.Distinct().Count() > 1 || activities.Distinct().Count() > 1)
explanation += " This numerical summary pools mixed settings or activity conditions.";
if (settings.Contains("Unknown") || activities.Contains("Unknown"))
explanation += " Some setting or activity information is unknown.";
var details = new (string Name, string?[] Values)[]
{
("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()),
("additional circumstances", observations.Select(o => o.MeasurementContext?.AdditionalCircumstances).ToArray())
};
var missing = details.Where(d => d.Values.Any(string.IsNullOrWhiteSpace)).Select(d => d.Name).ToArray();
var differing = details.Where(d => d.Values.Where(v => !string.IsNullOrWhiteSpace(v)).Distinct().Count() > 1)
.Select(d => d.Name).ToArray();
if (missing.Length > 0) explanation += $" Optional details are unrecorded for some observations: {string.Join(", ", missing)}.";
if (differing.Length > 0) explanation += $" Recorded detail values differ: {string.Join(", ", differing)}.";
return explanation + " These are descriptive statistics, not a diagnostic monitoring protocol; recorded categories alone do not establish clinically comparable conditions. Legacy narrative text does not establish a category.";
}
private static string Counts(IEnumerable<string> values) => string.Join(", ", values.GroupBy(v => v)
.OrderBy(g => g.Key, StringComparer.Ordinal).Select(g => $"{g.Key} ({g.Count()})"));
}
+31 -2
View File
@@ -190,11 +190,40 @@ US-08 tests cover the original full numerical corrections and rejection scenario
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.
`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; averages retain fractional values without deliberate rounding. 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`.
The independent Insights Service follows the documented controller/application-service/calculator/client design. Its HTTP observation client retrieves history through the configured gateway; there are no production project references between services. Each request recalculates from current observations, so corrections/deletions are reflected immediately. Failed observation retrieval returns `502`, and timeouts return `504`, instead of indicating insufficient data. Gateway requests to an unavailable Insights Service likewise return `502`/`504`.
US-10 tests use all four HTTP hosts and the existing separate patient/observation test databases. They cover all five acceptance scenarios, fractional averages, patient and inclusive-period filtering, equal/offset bounds, corrections/deletions, restart, malformed/missing periods, and unavailable observation retrieval. Insights introduces no external dependencies. Trend calculation remains outside this story.
US-10 supports the same optional `setting` and `activityCondition` selections as
history, including explicit `Unknown` and combined matching. For example append
`&setting=Home&activityCondition=AtRest`. Omitted/empty selections include all
otherwise eligible observations. Unsupported categories return `400` validation
details. Selection that leaves no observations returns the existing insufficient-
data `404` response. Selection is forwarded through the gateway to the Observation
Service; no service implementation is referenced directly.
Successful insights also include `appliedSelection` (nullable `setting` and
`activityCondition` mean unrestricted), `contributingCount`, and
`contextExplanation`. The explanation reports recorded setting/activity counts,
mixed/unknown categories, missing optional context details and differences in
recorded optional details. It describes numerical aggregation without certifying
measurement technique, clinical comparability or completion of a diagnostic
monitoring protocol. Legacy narrative text is retained by the observation contract
but never used to invent categories. Preparation differences are reported as
recorded differences, not a clinical classification.
The rounding contract applies to all three means: seven readings of 120 and one
of 121 yield 120.13; 120, 120 and 121 yield 120.33. No intermediate rounding occurs.
Single-observation means equal the recorded values, and blood-pressure minimum and
maximum are equal. Numeric JSON need not retain trailing zeros. New requests always
use current observations/context after corrections, clearing and deletion.
US-10 tests use all four HTTP hosts and the existing separate patient/observation
test databases. They cover original summaries, independent/combined/unknown
selections, applied selections and counts, context explanations, one-observation
results, halfway/repeating rounding for all three metrics, patient/inclusive/equal/
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.
US-13 authentication and patient ownership are implemented as described in
[AUTHENTICATION.md](AUTHENTICATION.md). The account-to-profile association is persisted