From 0ea7866f82ad189a694e86d9f8512f7817294516 Mon Sep 17 00:00:00 2001 From: Steffen Date: Fri, 2 Oct 2026 09:22:49 +0200 Subject: [PATCH] Implement US-07 blood-pressure observation history --- .../Controllers/ObservationController.cs | 4 + .../ObservationApplicationService.cs | 14 +++ .../Application/ObservationRepository.cs | 2 + .../Controllers/ObservationController.cs | 18 +++ .../Persistence/SqlObservationRepository.cs | 6 + src/README.md | 6 +- .../ObservationHistoryTests.cs | 106 ++++++++++++++++++ 7 files changed, 155 insertions(+), 1 deletion(-) create mode 100644 tests/Observation.AcceptanceTests/ObservationHistoryTests.cs diff --git a/src/ApiGateway/Controllers/ObservationController.cs b/src/ApiGateway/Controllers/ObservationController.cs index 4872c49..614c6e4 100644 --- a/src/ApiGateway/Controllers/ObservationController.cs +++ b/src/ApiGateway/Controllers/ObservationController.cs @@ -18,6 +18,10 @@ public sealed class ObservationController(IHttpClientFactory clients) : Controll public Task GetLatest(Guid patientId, CancellationToken cancellationToken) => ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/observations/latest", cancellationToken); + [HttpGet("patients/{patientId:guid}/observations")] + public Task GetByPeriod(Guid patientId, CancellationToken cancellationToken) => + ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/observations{Request.QueryString}", cancellationToken); + private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken) { using var request = new HttpRequestMessage(method, path); diff --git a/src/ObservationService/Application/ObservationApplicationService.cs b/src/ObservationService/Application/ObservationApplicationService.cs index 5645e69..b1cfe11 100644 --- a/src/ObservationService/Application/ObservationApplicationService.cs +++ b/src/ObservationService/Application/ObservationApplicationService.cs @@ -40,4 +40,18 @@ public sealed class ObservationApplicationService(ObservationRepository reposito public Task GetLatestAsync(Guid patientId, CancellationToken cancellationToken) => repository.FindLatestByPatientIdAsync(patientId, cancellationToken); + + public Task> GetByPeriodAsync(Guid patientId, DateTime from, DateTime to, + 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); + } + + private static DateTime NormalizeTimestamp(DateTime timestamp) => + DateTime.SpecifyKind(timestamp.Kind == DateTimeKind.Unspecified ? timestamp : timestamp.ToUniversalTime(), + DateTimeKind.Unspecified); } diff --git a/src/ObservationService/Application/ObservationRepository.cs b/src/ObservationService/Application/ObservationRepository.cs index e8ab61e..b34fee3 100644 --- a/src/ObservationService/Application/ObservationRepository.cs +++ b/src/ObservationService/Application/ObservationRepository.cs @@ -7,4 +7,6 @@ public interface ObservationRepository Task SaveAsync(BloodPressureObservation observation, CancellationToken cancellationToken); Task FindByIdAsync(Guid observationId, CancellationToken cancellationToken); Task FindLatestByPatientIdAsync(Guid patientId, CancellationToken cancellationToken); + Task> FindByPatientIdAndPeriodAsync(Guid patientId, DateTime from, DateTime to, + CancellationToken cancellationToken); } diff --git a/src/ObservationService/Controllers/ObservationController.cs b/src/ObservationService/Controllers/ObservationController.cs index 50e9640..d6dbc85 100644 --- a/src/ObservationService/Controllers/ObservationController.cs +++ b/src/ObservationService/Controllers/ObservationController.cs @@ -1,4 +1,5 @@ using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.ModelBinding; using ObservationService.Application; using ObservationService.Contracts; using ObservationService.Domain; @@ -44,6 +45,23 @@ public sealed class ObservationController(ObservationApplicationService service) return observation is null ? NotFound() : Ok(ToDto(observation)); } + [HttpGet("patients/{patientId:guid}/observations")] + public async Task>> GetByPeriod(Guid patientId, + [FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to, + CancellationToken cancellationToken) + { + try + { + var observations = await service.GetByPeriodAsync(patientId, from, to, cancellationToken); + return Ok(observations.Select(ToDto).ToList()); + } + catch (ArgumentException) + { + ModelState.AddModelError(nameof(to), "The end time must not be earlier than the start time."); + return ValidationProblem(ModelState); + } + } + private static ObservationDto ToDto(BloodPressureObservation observation) => new(observation.ObservationId, observation.PatientId, observation.MeasuredAt, observation.Systolic, observation.Diastolic, observation.Pulse, observation.Context, observation.Note); diff --git a/src/ObservationService/Persistence/SqlObservationRepository.cs b/src/ObservationService/Persistence/SqlObservationRepository.cs index 60677d5..ecdc62d 100644 --- a/src/ObservationService/Persistence/SqlObservationRepository.cs +++ b/src/ObservationService/Persistence/SqlObservationRepository.cs @@ -20,4 +20,10 @@ public sealed class SqlObservationRepository(ObservationDbContext db) : Observat db.Observations.AsNoTracking().Where(o => o.PatientId == patientId) .OrderByDescending(o => o.MeasuredAt).ThenByDescending(o => o.ObservationId) .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); } diff --git a/src/README.md b/src/README.md index e0050e0..1c61640 100644 --- a/src/README.md +++ b/src/README.md @@ -1,4 +1,4 @@ -# US-01–US-06: Patient profiles and blood-pressure observations +# US-01–US-07: Patient profiles and blood-pressure observations Implemented with .NET 10 LTS (see the [official download page](https://dotnet.microsoft.com/en-us/download/dotnet/10.0)), ASP.NET Core controllers, and PostgreSQL/EF Core. The API gateway, Patient/Profile service and Observation Service are separate executables and can run on separate machines. Each domain service owns its database. @@ -52,6 +52,10 @@ The Observation Service checks patient existence by calling the gateway's patien US-06 acceptance tests cover out-of-order measurements, patient-specific selection, retrieval after restart, and no available observation even when another patient has recorded measurements. No new dependencies or schema changes are required. +`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. + Authentication and access control are defined in US-13, US-14 and `Docs/Design/authentication-and-access-control-design.md`, and remain to be implemented as separate stories, as explicitly instructed. These endpoints currently have no access restrictions. ## Automated acceptance tests diff --git a/tests/Observation.AcceptanceTests/ObservationHistoryTests.cs b/tests/Observation.AcceptanceTests/ObservationHistoryTests.cs new file mode 100644 index 0000000..397cc96 --- /dev/null +++ b/tests/Observation.AcceptanceTests/ObservationHistoryTests.cs @@ -0,0 +1,106 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using Xunit; + +namespace Observation.AcceptanceTests; + +public sealed class ObservationHistoryTests(ObservationApiFixture fixture) : IClassFixture +{ + private sealed record Profile(Guid PatientId); + private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt, + int Systolic, int Diastolic, int Pulse, string? Context, string? Note); + + private async Task CreatePatientAsync() + { + using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new + { + name = "History Example", dateOfBirth = "1980-01-01" + }); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + return (await response.Content.ReadFromJsonAsync())!.PatientId; + } + + private async Task RecordAsync(Guid patientId, string measuredAt, int systolic, int diastolic, int pulse) + { + using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new + { + measuredAt, systolic, diastolic, pulse, context = "Resting", note = "Before breakfast" + }); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + return (await response.Content.ReadFromJsonAsync())!; + } + + private Task HistoryAsync(Guid patientId, string from, string to) => + fixture.Client.GetFromJsonAsync( + $"/api/patients/{patientId}/observations?from={Uri.EscapeDataString(from)}&to={Uri.EscapeDataString(to)}"); + + [Fact] + public async Task Selected_period_returns_only_the_matching_observation_after_restart() + { + var patientId = await CreatePatientAsync(); + await RecordAsync(patientId, "2026-09-01T08:00:00", 120, 80, 60); + var expected = await RecordAsync(patientId, "2026-09-05T08:00:00", 125, 82, 65); + await RecordAsync(patientId, "2026-09-10T08:00:00", 130, 84, 70); + await RecordAsync(await CreatePatientAsync(), "2026-09-05T08:00:00", 140, 90, 75); + await fixture.RestartHostsAsync(); + + var history = await HistoryAsync(patientId, "2026-09-03T00:00:00", "2026-09-08T23:59:59"); + + Assert.Equal(expected, Assert.Single(history!)); + } + + [Fact] + public async Task Results_are_chronological_and_include_both_period_boundaries() + { + var patientId = await CreatePatientAsync(); + var last = await RecordAsync(patientId, "2026-09-10T08:00:00", 130, 84, 70); + var first = await RecordAsync(patientId, "2026-09-01T08:00:00", 120, 80, 60); + var middle = await RecordAsync(patientId, "2026-09-05T08:00:00", 125, 82, 65); + + Assert.Equal(new[] { first, middle, last }, + await HistoryAsync(patientId, "2026-09-01T08:00:00", "2026-09-10T08:00:00")); + Assert.Equal(first, Assert.Single((await HistoryAsync(patientId, + "2026-09-01T08:00:00", "2026-09-01T08:00:00"))!)); + } + + [Fact] + public async Task No_matching_observations_returns_an_empty_array() + { + var patientId = await CreatePatientAsync(); + await RecordAsync(await CreatePatientAsync(), "2026-09-05T08:00:00", 125, 82, 65); + Assert.Empty((await HistoryAsync(patientId, "2026-09-03T00:00:00", "2026-09-08T23:59:59"))!); + await RecordAsync(patientId, "2026-09-01T08:00:00", 120, 80, 60); + Assert.Empty((await HistoryAsync(patientId, "2026-09-03T00:00:00", "2026-09-08T23:59:59"))!); + } + + [Theory] + [InlineData("from=2026-09-08T00:00:00&to=2026-09-03T00:00:00")] + [InlineData("from=invalid&to=2026-09-08T00:00:00")] + [InlineData("from=2026-09-03T00:00:00&to=invalid")] + [InlineData("from=2026-09-03T00:00:00")] + [InlineData("to=2026-09-08T00:00:00")] + [InlineData("")] + public async Task Invalid_or_missing_period_is_rejected_without_changing_observations(string query) + { + var patientId = await CreatePatientAsync(); + var saved = await RecordAsync(patientId, "2026-09-05T08:00:00", 125, 82, 65); + using var response = await fixture.Client.GetAsync($"/api/patients/{patientId}/observations?{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(saved, await fixture.Client.GetFromJsonAsync($"/api/observations/{saved.ObservationId}")); + } + + [Fact] + public async Task Offset_bounds_are_normalized_consistently_with_recorded_measurements() + { + var patientId = await CreatePatientAsync(); + var saved = await RecordAsync(patientId, "2026-09-05T10:00:00+02:00", 125, 82, 65); + + Assert.Equal(saved, Assert.Single((await HistoryAsync(patientId, + "2026-09-05T10:00:00+02:00", "2026-09-05T08:00:00Z"))!)); + Assert.Empty((await HistoryAsync(patientId, "2026-09-05T08:00:01Z", "2026-09-05T11:00:00Z"))!); + } +}