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.Clients;
using InsightsService.Domain; using InsightsService.Domain;
@@ -6,14 +7,15 @@ namespace InsightsService.Application;
public sealed class InsightsApplicationService(ObservationServiceClient observations, InsightCalculator calculator) public sealed class InsightsApplicationService(ObservationServiceClient observations, InsightCalculator calculator)
{ {
public async Task<HealthInsight?> GetSummaryAsync(Guid patientId, DateTime from, DateTime to, public async Task<HealthInsight?> GetSummaryAsync(Guid patientId, DateTime from, DateTime to,
CancellationToken cancellationToken) ContextSelection selection, CancellationToken cancellationToken)
{ {
from = NormalizeTimestamp(from); from = NormalizeTimestamp(from);
to = NormalizeTimestamp(to); to = NormalizeTimestamp(to);
if (to < from) if (to < from)
throw new ArgumentException("The end time must not be earlier than the start time.", nameof(to)); 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); Validator.ValidateObject(selection, new ValidationContext(selection), validateAllProperties: true);
return calculator.CalculateSummary(patientId, from, to, history); var history = await observations.GetByPeriodAsync(patientId, from, to, selection, cancellationToken);
return calculator.CalculateSummary(patientId, from, to, history, selection);
} }
private static DateTime NormalizeTimestamp(DateTime value) => private static DateTime NormalizeTimestamp(DateTime value) =>
@@ -1,3 +1,4 @@
using InsightsService.Domain;
using System.Globalization; using System.Globalization;
using InsightsService.Contracts; using InsightsService.Contracts;
@@ -6,11 +7,14 @@ namespace InsightsService.Clients;
public sealed class HttpObservationServiceClient(HttpClient client) : ObservationServiceClient public sealed class HttpObservationServiceClient(HttpClient client) : ObservationServiceClient
{ {
public async Task<List<ObservationDto>> GetByPeriodAsync(Guid patientId, DateTime from, DateTime to, 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 start = Uri.EscapeDataString(from.ToString("O", CultureInfo.InvariantCulture));
var end = Uri.EscapeDataString(to.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); HttpCompletionOption.ResponseHeadersRead, cancellationToken);
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<List<ObservationDto>>(cancellationToken) return await response.Content.ReadFromJsonAsync<List<ObservationDto>>(cancellationToken)
@@ -1,3 +1,4 @@
using InsightsService.Domain;
using InsightsService.Contracts; using InsightsService.Contracts;
namespace InsightsService.Clients; namespace InsightsService.Clients;
@@ -5,5 +6,5 @@ namespace InsightsService.Clients;
public interface ObservationServiceClient public interface ObservationServiceClient
{ {
Task<List<ObservationDto>> GetByPeriodAsync(Guid patientId, DateTime from, DateTime to, 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; namespace InsightsService.Contracts;
public sealed record HealthInsightDto(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd, public sealed record HealthInsightDto(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse, 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; namespace InsightsService.Contracts;
public sealed record ObservationDto(Guid ObservationId, Guid PatientId, DateTime MeasuredAt, 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.Application;
using InsightsService.Contracts; using InsightsService.Contracts;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@@ -12,16 +13,17 @@ public sealed class InsightsController(InsightsApplicationService service) : Con
[HttpGet] [HttpGet]
public async Task<ActionResult<HealthInsightDto>> GetSummary(Guid patientId, public async Task<ActionResult<HealthInsightDto>> GetSummary(Guid patientId,
[FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to, [FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to,
CancellationToken cancellationToken) [FromQuery] ContextSelection selection, CancellationToken cancellationToken)
{ {
try try
{ {
var insight = await service.GetSummaryAsync(patientId, from, to, cancellationToken); var insight = await service.GetSummaryAsync(patientId, from, to, selection, cancellationToken);
return insight is null return insight is null
? Problem(statusCode: StatusCodes.Status404NotFound, title: "Insufficient observation data for calculation.") ? Problem(statusCode: StatusCodes.Status404NotFound, title: "Insufficient observation data for calculation.")
: Ok(new HealthInsightDto(insight.PatientId, insight.PeriodStart, insight.PeriodEnd, : Ok(new HealthInsightDto(insight.PatientId, insight.PeriodStart, insight.PeriodEnd,
insight.AverageSystolic, insight.AverageDiastolic, insight.AveragePulse, 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) 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, public sealed record HealthInsight(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse, 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; using InsightsService.Contracts;
namespace InsightsService.Domain; namespace InsightsService.Domain;
@@ -5,13 +6,45 @@ namespace InsightsService.Domain;
public sealed class InsightCalculator public sealed class InsightCalculator
{ {
public HealthInsight? CalculateSummary(Guid patientId, DateTime from, DateTime to, public HealthInsight? CalculateSummary(Guid patientId, DateTime from, DateTime to,
IReadOnlyList<ObservationDto> observations) IReadOnlyList<ObservationDto> observations, ContextSelection selection)
{ {
if (observations.Count == 0) if (observations.Count == 0)
return null; return null;
return new HealthInsight(patientId, from, to, return new HealthInsight(patientId, from, to,
observations.Average(o => (decimal)o.Systolic), observations.Average(o => (decimal)o.Diastolic), Math.Round(observations.Average(o => (decimal)o.Systolic), 2, MidpointRounding.AwayFromZero),
observations.Average(o => (decimal)o.Pulse), observations.Min(o => o.Systolic), Math.Round(observations.Average(o => (decimal)o.Diastolic), 2, MidpointRounding.AwayFromZero),
observations.Max(o => o.Systolic), observations.Min(o => o.Diastolic), observations.Max(o => o.Diastolic)); 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. 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`. 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 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
@@ -0,0 +1,205 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using HealthApp.TestSupport;
using Xunit;
namespace Observation.AcceptanceTests;
public sealed class ContextSelectedInsightTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
{
private sealed record Profile(Guid PatientId);
private sealed record Observation(Guid ObservationId);
private sealed record Selection(string? Setting, string? ActivityCondition);
private sealed record Insight(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse, int MinSystolic, int MaxSystolic,
int MinDiastolic, int MaxDiastolic, Selection AppliedSelection, int ContributingCount, string ContextExplanation);
private const string Period = "from=2026-09-01T08%3A00%3A00&to=2026-09-10T08%3A00%3A00";
private async Task<Guid> Patient()
{
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Selected insight", 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, int diastolic, int pulse, string? setting = "Home",
string? activity = "AtRest", string time = "2026-09-05T08:00:00", string? position = null)
{
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patient}/observations", new
{
measuredAt = time, systolic, diastolic, pulse, context = "Home resting?",
measurementContext = new { setting, activityCondition = activity, bodyPosition = position }
});
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Observation>())!.ObservationId;
}
private string PathFor(Guid patient, string selection = "", string period = Period) =>
$"/api/patients/{patient}/insights?{period}{selection}";
private Task<Insight?> Summary(Guid patient, string selection = "") => fixture.Client.GetFromJsonAsync<Insight>(PathFor(patient, selection));
[Theory]
[InlineData("&setting=Home&activityCondition=AtRest", "Home", "AtRest", 2, 125)]
[InlineData("&setting=Home", "Home", null, 3, 130)]
[InlineData("&activityCondition=AtRest", null, "AtRest", 3, 136.67)]
public async Task Independent_and_combined_selections_use_only_matching_observations_and_report_their_basis(
string query, string? setting, string? activity, int count, double average)
{
var patient = await Patient();
await Record(patient, 120, 80, 60);
await Record(patient, 130, 84, 70);
await Record(patient, 140, 88, 80, activity: "AfterActivity");
await Record(patient, 160, 90, 90, setting: "Clinic");
var result = (await Summary(patient, query))!;
Assert.Equal((decimal)average, result.AverageSystolic);
Assert.Equal(count, result.ContributingCount);
Assert.Equal(new Selection(setting, activity), result.AppliedSelection);
Assert.Equal(patient, result.PatientId);
if (count == 2)
{
Assert.Equal(82m, result.AverageDiastolic);
Assert.Equal(65m, result.AveragePulse);
Assert.Equal(120, result.MinSystolic);
Assert.Equal(130, result.MaxSystolic);
Assert.Equal(80, result.MinDiastolic);
Assert.Equal(84, result.MaxDiastolic);
}
}
[Fact]
public async Task Unfiltered_insight_includes_unknown_context_and_explains_mixed_and_missing_conditions()
{
var patient = await Patient();
await Record(patient, 120, 80, 60, position: "Seated");
await Record(patient, 130, 84, 70, setting: "Clinic", activity: "AfterActivity", position: "Standing");
await Record(patient, 140, 88, 80, setting: null, activity: null);
var result = (await Summary(patient))!;
Assert.Equal(130m, result.AverageSystolic);
Assert.Equal(3, result.ContributingCount);
Assert.Equal(new Selection(null, null), result.AppliedSelection);
Assert.Contains("mixed settings or activity conditions", result.ContextExplanation);
Assert.Contains("unknown", result.ContextExplanation);
Assert.Contains("Optional details are unrecorded", result.ContextExplanation);
Assert.Contains("Recorded detail values differ: body position", result.ContextExplanation);
Assert.Contains("do not establish clinically comparable conditions", result.ContextExplanation);
}
[Theory]
[InlineData("&setting=Unknown", "Unknown", null)]
[InlineData("&activityCondition=Unknown", null, "Unknown")]
[InlineData("&setting=Unknown&activityCondition=Unknown", "Unknown", "Unknown")]
public async Task Unknown_selection_is_explicit_and_legacy_narrative_does_not_create_known_membership(string query,
string? setting, string? activity)
{
var patient = await Patient();
await Record(patient, 120, 80, 60, setting: null, activity: null);
await Record(patient, 180, 100, 90);
var result = (await Summary(patient, query))!;
Assert.Equal(1, result.ContributingCount);
Assert.Equal(120m, result.AverageSystolic);
Assert.Equal(80m, result.AverageDiastolic);
Assert.Equal(60m, result.AveragePulse);
Assert.Equal(result.MinSystolic, result.MaxSystolic);
Assert.Equal(result.MinDiastolic, result.MaxDiastolic);
Assert.Equal(new Selection(setting, activity), result.AppliedSelection);
}
[Theory]
[InlineData(8, 120.13, 80.13, 60.13)]
[InlineData(3, 120.33, 80.33, 60.33)]
public async Task Means_round_only_the_final_value_to_two_decimals_with_half_up_rounding(int count,
double systolic, double diastolic, double pulse)
{
var patient = await Patient();
for (var i = 0; i < count; i++)
await Record(patient, 120 + (i == count - 1 ? 1 : 0), 80 + (i == count - 1 ? 1 : 0), 60 + (i == count - 1 ? 1 : 0));
var result = (await Summary(patient))!;
Assert.Equal((decimal)systolic, result.AverageSystolic);
Assert.Equal((decimal)diastolic, result.AverageDiastolic);
Assert.Equal((decimal)pulse, result.AveragePulse);
Assert.Equal(count, result.ContributingCount);
Assert.Equal(120, result.MinSystolic);
Assert.Equal(121, result.MaxSystolic);
}
[Fact]
public async Task Corrections_clearing_and_deletion_change_membership_and_fresh_summary_results_after_restart()
{
var patient = await Patient();
var first = await Record(patient, 120, 80, 60);
var second = await Record(patient, 130, 84, 70);
Assert.Equal(125m, (await Summary(patient, "&setting=Home"))!.AverageSystolic);
using var corrected = await fixture.Client.PatchAsJsonAsync($"/api/observations/{second}", new { measurementContext = new { setting = "Clinic" } });
Assert.Equal(HttpStatusCode.OK, corrected.StatusCode);
Assert.Equal(120m, (await Summary(patient, "&setting=Home"))!.AverageSystolic);
using var cleared = await fixture.Client.PatchAsJsonAsync($"/api/observations/{first}", new { measurementContext = new { activityCondition = (string?)null } });
Assert.Equal(HttpStatusCode.OK, cleared.StatusCode);
var selected = (await Summary(patient, "&setting=Home&activityCondition=Unknown"))!;
Assert.Equal(1, selected.ContributingCount);
using var deleted = await fixture.Client.DeleteAsync($"/api/observations/{first}");
Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
await fixture.RestartHostsAsync();
using var empty = await fixture.Client.GetAsync(PathFor(patient, "&setting=Home"));
Assert.Equal(HttpStatusCode.NotFound, empty.StatusCode);
Assert.Contains("Insufficient observation data", await empty.Content.ReadAsStringAsync());
var remaining = (await Summary(patient, "&setting=Clinic"))!;
Assert.Equal(1, remaining.ContributingCount);
Assert.Equal(130m, remaining.AverageSystolic);
}
[Fact]
public async Task Filtered_insight_preserves_patient_scope_inclusive_bounds_and_equal_instants()
{
var patient = await Patient();
await Record(patient, 120, 80, 60, time: "2026-09-01T08:00:00");
await Record(patient, 130, 84, 70, time: "2026-09-10T08:00:00");
await Record(patient, 200, 100, 90, time: "2026-09-01T07:59:59");
await Record(patient, 210, 110, 95, time: "2026-09-10T08:00:01");
await Record(await Patient(), 220, 120, 100);
var summary = (await Summary(patient, "&setting=Home&activityCondition=AtRest"))!;
Assert.Equal(2, summary.ContributingCount);
Assert.Equal(125m, summary.AverageSystolic);
using var equal = await fixture.Client.GetAsync(PathFor(patient, "&setting=Home", "from=2026-09-01T10%3A00%3A00%2B02%3A00&to=2026-09-01T08%3A00%3A00Z"));
Assert.Equal(HttpStatusCode.OK, equal.StatusCode);
Assert.Equal(120m, (await equal.Content.ReadFromJsonAsync<Insight>())!.AverageSystolic);
}
[Theory]
[InlineData("&setting=Unsupported")]
[InlineData("&activityCondition=Unsupported")]
public async Task Unsupported_selection_is_rejected_with_validation_details(string query)
{
var patient = await Patient();
await Record(patient, 120, 80, 60);
using var response = await fixture.Client.GetAsync(PathFor(patient, query));
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.True(problem.RootElement.TryGetProperty("errors", out _));
Assert.Equal(1, (await Summary(patient))!.ContributingCount);
}
[Fact]
public async Task Professional_selection_requires_assignment_and_other_patient_access_is_rejected()
{
var patient = await Patient();
await Record(patient, 120, 80, 60);
var other = await Patient();
fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = patient.ToString();
await fixture.RestartHostsAsync();
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, "&setting=Home&activityCondition=AtRest"));
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.Equal(1, (await response.Content.ReadFromJsonAsync<Insight>())!.ContributingCount);
else Assert.Empty(await response.Content.ReadAsStringAsync());
}
}
}