diff --git a/src/ApiGateway/Controllers/ObservationController.cs b/src/ApiGateway/Controllers/ObservationController.cs index b19a87a..022243e 100644 --- a/src/ApiGateway/Controllers/ObservationController.cs +++ b/src/ApiGateway/Controllers/ObservationController.cs @@ -46,6 +46,9 @@ public sealed class ObservationController(IHttpClientFactory clients) : Controll .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken); Response.StatusCode = (int)upstream.StatusCode; Response.ContentType = upstream.Content.Headers.ContentType?.ToString(); + foreach (var header in new[] { "X-Measurement-Setting", "X-Activity-Condition" }) + if (upstream.Headers.TryGetValues(header, out var values)) + Response.Headers[header] = values.ToArray(); if (upstream.Headers.Location is { } location) Response.Headers.Location = location.IsAbsoluteUri ? location.PathAndQuery : location.ToString(); await upstream.Content.CopyToAsync(Response.Body, cancellationToken); diff --git a/src/ObservationService/Application/ObservationApplicationService.cs b/src/ObservationService/Application/ObservationApplicationService.cs index 6ce5733..418ee54 100644 --- a/src/ObservationService/Application/ObservationApplicationService.cs +++ b/src/ObservationService/Application/ObservationApplicationService.cs @@ -65,13 +65,14 @@ public sealed class ObservationApplicationService(ObservationRepository reposito repository.FindLatestByPatientIdAsync(patientId, cancellationToken); public Task> GetByPeriodAsync(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)); - return repository.FindByPatientIdAndPeriodAsync(patientId, from, to, cancellationToken); + Validator.ValidateObject(selection, new ValidationContext(selection), validateAllProperties: true); + return repository.FindByPatientIdAndPeriodAsync(patientId, from, to, selection, cancellationToken); } private static DateTime NormalizeTimestamp(DateTime timestamp) => diff --git a/src/ObservationService/Application/ObservationRepository.cs b/src/ObservationService/Application/ObservationRepository.cs index 7b0067b..6ac9578 100644 --- a/src/ObservationService/Application/ObservationRepository.cs +++ b/src/ObservationService/Application/ObservationRepository.cs @@ -11,5 +11,5 @@ public interface ObservationRepository Task FindByIdAsync(Guid observationId, CancellationToken cancellationToken); Task FindLatestByPatientIdAsync(Guid patientId, CancellationToken cancellationToken); Task> FindByPatientIdAndPeriodAsync(Guid patientId, DateTime from, DateTime to, - CancellationToken cancellationToken); + ContextSelection selection, CancellationToken cancellationToken); } diff --git a/src/ObservationService/Controllers/ObservationController.cs b/src/ObservationService/Controllers/ObservationController.cs index 603e2c8..3fad47b 100644 --- a/src/ObservationService/Controllers/ObservationController.cs +++ b/src/ObservationService/Controllers/ObservationController.cs @@ -60,11 +60,13 @@ public sealed class ObservationController(ObservationApplicationService service) [HttpGet("patients/{patientId:guid}/observations")] public async Task>> GetByPeriod(Guid patientId, [FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to, - CancellationToken cancellationToken) + [FromQuery] ContextSelection selection, CancellationToken cancellationToken) { try { - var observations = await service.GetByPeriodAsync(patientId, from, to, cancellationToken); + var observations = await service.GetByPeriodAsync(patientId, from, to, selection, cancellationToken); + Response.Headers["X-Measurement-Setting"] = selection.Setting ?? "All"; + Response.Headers["X-Activity-Condition"] = selection.ActivityCondition ?? "All"; return Ok(observations.Select(ToDto).ToList()); } catch (ArgumentException) diff --git a/src/ObservationService/Domain/ContextSelection.cs b/src/ObservationService/Domain/ContextSelection.cs new file mode 100644 index 0000000..12daa4e --- /dev/null +++ b/src/ObservationService/Domain/ContextSelection.cs @@ -0,0 +1,12 @@ +using System.ComponentModel.DataAnnotations; + +namespace ObservationService.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; } +} diff --git a/src/ObservationService/Persistence/SqlObservationRepository.cs b/src/ObservationService/Persistence/SqlObservationRepository.cs index 849d86b..2d87f15 100644 --- a/src/ObservationService/Persistence/SqlObservationRepository.cs +++ b/src/ObservationService/Persistence/SqlObservationRepository.cs @@ -43,8 +43,14 @@ public sealed class SqlObservationRepository(ObservationDbContext db) : Observat .FirstOrDefaultAsync(cancellationToken); public Task> FindByPatientIdAndPeriodAsync(Guid patientId, DateTime from, DateTime to, - CancellationToken cancellationToken) => - db.Observations.AsNoTracking() - .Where(o => o.PatientId == patientId && o.MeasuredAt >= from && o.MeasuredAt <= to) - .OrderBy(o => o.MeasuredAt).ThenBy(o => o.ObservationId).ToListAsync(cancellationToken); + ContextSelection selection, CancellationToken cancellationToken) + { + var query = db.Observations.AsNoTracking() + .Where(o => o.PatientId == patientId && o.MeasuredAt >= from && o.MeasuredAt <= to); + if (selection.Setting is not null) + query = query.Where(o => o.MeasurementContext.Setting == selection.Setting); + if (selection.ActivityCondition is not null) + query = query.Where(o => o.MeasurementContext.ActivityCondition == selection.ActivityCondition); + return query.OrderBy(o => o.MeasuredAt).ThenBy(o => o.ObservationId).ToListAsync(cancellationToken); + } } diff --git a/src/README.md b/src/README.md index 75d75ed..e87e778 100644 --- a/src/README.md +++ b/src/README.md @@ -106,7 +106,7 @@ Apply the `RecordedMeasurementContext` Observation migration before starting the updated service. EF Core maps the owned value to columns in the same observation table; no new table, service or dependency is introduced. Existing rows receive unknown categories and null details without changing their measurements, timestamps -or text. Context filtering and context-only updates remain under US-07/US-08. +or text. Context filtering is implemented under US-07; context-only updates remain under US-08. US-05 context retrieval is covered independently of creation: dedicated tests seed saved observations directly and request them through the authenticated gateway. @@ -124,7 +124,28 @@ US-06 acceptance tests cover out-of-order measurements, patient-specific selecti `GET /api/patients/{patientId}/observations?from=2026-09-03T00:00:00&to=2026-09-08T23:59:59` returns `200` with a JSON array of that patient's observations within the inclusive measurement-time bounds, ordered chronologically. A valid period with no matches returns `[]`. Both timestamps are required; missing, malformed, or reversed bounds return `400` validation problem details. Equal bounds are valid. Offset timestamps are normalized to UTC consistently with recording; encode `+` as `%2B` in query parameters. Equal measurement timestamps are ordered by observation identifier. The query runs in the Observation Service's own database; no patient-profile lookup is needed. -US-07 tests cover all four acceptance scenarios, patient-specific filtering, persistence after restart, inclusive and equal bounds, offset normalization, and malformed/missing bounds without changing saved observations. No new dependencies or schema changes are required. +US-07 now accepts optional `setting` and `activityCondition` query selections using +the same case-sensitive categories as recording. For example, append +`&setting=Home&activityCondition=AtRest` to retrieve only home-resting observations. +Both supplied dimensions must match. `Unknown` explicitly selects a missing or +unknown category; omitted/empty query values apply no restriction on that dimension. +Legacy text is preserved but never establishes a known category match. + +The JSON response remains an observation array, including `measurementContext` on +each observation. Applied selections are reported on successful responses in +`X-Measurement-Setting` and `X-Activity-Condition` headers. Each contains the selected +category or `All` for an unrestricted dimension; `All` is response metadata, not an +accepted query category. The gateway forwards these two headers. Empty selections +return `[]` with the same selection metadata. Unsupported selections return `400` +validation problem details without changes to observations. Filtering is performed +in the Observation database within the original patient/inclusive-period query, +retaining chronological order and the existing equal-time identifier ordering. + +US-07 tests cover original history criteria plus independent/combined/unknown +context selections, response metadata including empty results, complete/partial/ +absent context, legacy-text preservation, patient-specific access, inclusive/equal +and offset bounds, persistence after restart, and invalid selections without writes. +Existing Insights requests continue to consume the unchanged unfiltered array. No new dependencies or schema changes are required. `PUT /api/observations/{observationId}` corrects the measured values using a JSON body containing required positive integer `systolic`, `diastolic`, and `pulse` fields. It returns `200` with the updated observation, preserving its identifier, patient, measurement time, context, note, and creation timestamp while updating the modification timestamp. Missing observations return `404` without insertion; invalid requests return `400` without changes. Corrections are visible through specific retrieval, latest retrieval, and history. The Observation Service owns the update; no patient-profile lookup or database schema change is required. diff --git a/tests/Observation.AcceptanceTests/ContextFilteredHistoryTests.cs b/tests/Observation.AcceptanceTests/ContextFilteredHistoryTests.cs new file mode 100644 index 0000000..cd43e32 --- /dev/null +++ b/tests/Observation.AcceptanceTests/ContextFilteredHistoryTests.cs @@ -0,0 +1,179 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using HealthApp.TestSupport; +using Microsoft.EntityFrameworkCore; +using Xunit; + +namespace Observation.AcceptanceTests; + +public sealed class ContextFilteredHistoryTests(ObservationApiFixture fixture) : IClassFixture +{ + private sealed record Profile(Guid PatientId); + private sealed record ContextData(string Setting, string ActivityCondition, string? DeviceDetails); + private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt, + string? Context, ContextData MeasurementContext); + private const string Period = "from=2026-09-01T08%3A00%3A00&to=2026-09-10T08%3A00%3A00"; + + private async Task Patient() + { + using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Filtered history", dateOfBirth = "1980-01-01" }); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + return (await response.Content.ReadFromJsonAsync())!.PatientId; + } + + private async Task Record(Guid patient, string time, string? setting, string? activity, string? legacy = null, bool includeContext = true, bool completeContext = false) + { + using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patient}/observations", new + { + measuredAt = time, systolic = 128, diastolic = 82, pulse = 68, context = legacy, + measurementContext = includeContext ? new + { + setting, activityCondition = activity, deviceDetails = "Saved device", + restDurationMinutes = completeContext ? (decimal?)5 : null, + bodyPosition = completeContext ? "Seated" : null, + measuredArm = completeContext ? "Left" : null, + cuffDetails = completeContext ? "Saved cuff" : null, + additionalCircumstances = completeContext ? "Usual routine" : null + } : null + }); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + return (await response.Content.ReadFromJsonAsync())!; + } + + private string PathFor(Guid patient, string selection = "", string period = Period) => + $"/api/patients/{patient}/observations?{period}{selection}"; + + [Theory] + [InlineData("&setting=Home", "Home", "All", 2)] + [InlineData("&activityCondition=AtRest", "All", "AtRest", 2)] + [InlineData("&setting=Home&activityCondition=AtRest", "Home", "AtRest", 1)] + public async Task Independent_and_combined_selections_return_matching_context_and_metadata(string selection, + string settingHeader, string activityHeader, int expectedCount) + { + var patient = await Patient(); + var homeRest = await Record(patient, "2026-09-05T08:00:00", "Home", "AtRest"); + var homeAfter = await Record(patient, "2026-09-06T08:00:00", "Home", "AfterActivity"); + var clinicRest = await Record(patient, "2026-09-07T08:00:00", "Clinic", "AtRest"); + await Record(patient, "2026-09-08T08:00:00", null, null, "Home, resting? Morning reading"); + using var response = await fixture.Client.GetAsync(PathFor(patient, selection)); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(settingHeader, Assert.Single(response.Headers.GetValues("X-Measurement-Setting"))); + Assert.Equal(activityHeader, Assert.Single(response.Headers.GetValues("X-Activity-Condition"))); + var history = (await response.Content.ReadFromJsonAsync())!; + Assert.Equal(expectedCount, history.Length); + var expected = new[] { homeRest, homeAfter, clinicRest }.Where(o => + (settingHeader == "All" || o.MeasurementContext.Setting == settingHeader) && + (activityHeader == "All" || o.MeasurementContext.ActivityCondition == activityHeader)).ToArray(); + Assert.Equal(expected, history); + Assert.All(history, o => Assert.Equal("Saved device", o.MeasurementContext.DeviceDetails)); + } + + [Theory] + [InlineData("&setting=Unknown", "Unknown", "All")] + [InlineData("&activityCondition=Unknown", "All", "Unknown")] + [InlineData("&setting=Unknown&activityCondition=Unknown", "Unknown", "Unknown")] + public async Task Unknown_selections_match_unknown_categories_without_interpreting_legacy_text(string selection, + string settingHeader, string activityHeader) + { + var patient = await Patient(); + var unknown = await Record(patient, "2026-09-05T08:00:00", null, null, "Home resting?"); + var partial = await Record(patient, "2026-09-06T08:00:00", "Clinic", null); + await Record(patient, "2026-09-07T08:00:00", "Home", "AtRest"); + using var response = await fixture.Client.GetAsync(PathFor(patient, selection)); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(settingHeader, Assert.Single(response.Headers.GetValues("X-Measurement-Setting"))); + Assert.Equal(activityHeader, Assert.Single(response.Headers.GetValues("X-Activity-Condition"))); + var result = (await response.Content.ReadFromJsonAsync())!; + Assert.Equal(activityHeader == "Unknown" && settingHeader == "All" ? new[] { unknown, partial } : new[] { unknown }, result); + Assert.Equal("Home resting?", result[0].Context); + } + + [Fact] + public async Task No_selection_retains_all_contexts_in_chronological_order_after_restart() + { + var patient = await Patient(); + var last = await Record(patient, "2026-09-07T08:00:00", null, null, includeContext: false); + var first = await Record(patient, "2026-09-05T08:00:00", "Home", "AtRest", completeContext: true); + var middle = await Record(patient, "2026-09-06T08:00:00", "Clinic", null); + await fixture.RestartHostsAsync(); + using var response = await fixture.Client.GetAsync(PathFor(patient)); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(new[] { first, middle, last }, await response.Content.ReadFromJsonAsync()); + Assert.Equal("All", Assert.Single(response.Headers.GetValues("X-Measurement-Setting"))); + Assert.Equal("All", Assert.Single(response.Headers.GetValues("X-Activity-Condition"))); + } + + [Fact] + public async Task Empty_filtered_history_is_an_empty_array_with_applied_selection_metadata() + { + var patient = await Patient(); + await Record(patient, "2026-09-05T08:00:00", "Home", "AtRest"); + using var response = await fixture.Client.GetAsync(PathFor(patient, "&setting=Other&activityCondition=AfterActivity")); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("[]", await response.Content.ReadAsStringAsync()); + Assert.Equal("Other", Assert.Single(response.Headers.GetValues("X-Measurement-Setting"))); + Assert.Equal("AfterActivity", Assert.Single(response.Headers.GetValues("X-Activity-Condition"))); + } + + [Fact] + public async Task Filtered_history_preserves_patient_scope_inclusive_boundaries_and_equal_bounds() + { + var patient = await Patient(); + var last = await Record(patient, "2026-09-10T08:00:00", "Home", "AtRest"); + var first = await Record(patient, "2026-09-01T08:00:00", "Home", "AtRest"); + await Record(patient, "2026-09-01T07:59:59", "Home", "AtRest"); + await Record(patient, "2026-09-10T08:00:01", "Home", "AtRest"); + await Record(patient, "2026-09-05T08:00:00", "Home", "AfterActivity"); + await Record(await Patient(), "2026-09-05T08:00:00", "Home", "AtRest"); + using var response = await fixture.Client.GetAsync(PathFor(patient, "&setting=Home&activityCondition=AtRest")); + Assert.Equal(new[] { first, last }, await response.Content.ReadFromJsonAsync()); + 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(first, Assert.Single((await equal.Content.ReadFromJsonAsync())!)); + } + + [Theory] + [InlineData("&setting=Unsupported")] + [InlineData("&activityCondition=Unsupported")] + [InlineData("&setting=All")] + [InlineData("&activityCondition=1")] + public async Task Unsupported_selections_are_rejected_without_changing_observations(string selection) + { + var patient = await Patient(); + var observation = await Record(patient, "2026-09-05T08:00:00", "Home", "AtRest"); + await using var db = fixture.CreateObservationDbContext(); + var before = await db.Observations.CountAsync(); + using var response = await fixture.Client.GetAsync(PathFor(patient, selection)); + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + Assert.True(problem.RootElement.TryGetProperty("errors", out _)); + Assert.Equal(before, await db.Observations.CountAsync()); + Assert.Equal(observation, await fixture.Client.GetFromJsonAsync($"/api/observations/{observation.ObservationId}")); + } + + [Fact] + public async Task Professional_reads_follow_assignments_and_other_patient_tokens_cannot_use_filters_to_gain_access() + { + var patient = await Patient(); + var expected = await Record(patient, "2026-09-05T08:00:00", "Home", "AtRest"); + 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(expected, Assert.Single((await response.Content.ReadFromJsonAsync())!)); + else Assert.Empty(await response.Content.ReadAsStringAsync()); + } + } +}