Implement US-07 blood-pressure observation history

This commit is contained in:
Steffen committed 2026-10-02 09:22:49 +02:00
1 parent df47bcbbd7
commit 0ea7866f82
7 files changed
+155 -1

No files matched your search

@@ -18,6 +18,10 @@ public sealed class ObservationController(IHttpClientFactory clients) : Controll
public Task GetLatest(Guid patientId, CancellationToken cancellationToken) => public Task GetLatest(Guid patientId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/observations/latest", 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) private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken)
{ {
using var request = new HttpRequestMessage(method, path); using var request = new HttpRequestMessage(method, path);
@@ -40,4 +40,18 @@ public sealed class ObservationApplicationService(ObservationRepository reposito
public Task<BloodPressureObservation?> GetLatestAsync(Guid patientId, CancellationToken cancellationToken) => public Task<BloodPressureObservation?> GetLatestAsync(Guid patientId, CancellationToken cancellationToken) =>
repository.FindLatestByPatientIdAsync(patientId, cancellationToken); repository.FindLatestByPatientIdAsync(patientId, cancellationToken);
public Task<List<BloodPressureObservation>> 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);
} }
@@ -7,4 +7,6 @@ public interface ObservationRepository
Task<BloodPressureObservation> SaveAsync(BloodPressureObservation observation, CancellationToken cancellationToken); Task<BloodPressureObservation> SaveAsync(BloodPressureObservation observation, CancellationToken cancellationToken);
Task<BloodPressureObservation?> FindByIdAsync(Guid observationId, CancellationToken cancellationToken); Task<BloodPressureObservation?> FindByIdAsync(Guid observationId, CancellationToken cancellationToken);
Task<BloodPressureObservation?> FindLatestByPatientIdAsync(Guid patientId, CancellationToken cancellationToken); Task<BloodPressureObservation?> FindLatestByPatientIdAsync(Guid patientId, CancellationToken cancellationToken);
Task<List<BloodPressureObservation>> FindByPatientIdAndPeriodAsync(Guid patientId, DateTime from, DateTime to,
CancellationToken cancellationToken);
} }
@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using ObservationService.Application; using ObservationService.Application;
using ObservationService.Contracts; using ObservationService.Contracts;
using ObservationService.Domain; using ObservationService.Domain;
@@ -44,6 +45,23 @@ public sealed class ObservationController(ObservationApplicationService service)
return observation is null ? NotFound() : Ok(ToDto(observation)); return observation is null ? NotFound() : Ok(ToDto(observation));
} }
[HttpGet("patients/{patientId:guid}/observations")]
public async Task<ActionResult<List<ObservationDto>>> 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) => private static ObservationDto ToDto(BloodPressureObservation observation) =>
new(observation.ObservationId, observation.PatientId, observation.MeasuredAt, observation.Systolic, new(observation.ObservationId, observation.PatientId, observation.MeasuredAt, observation.Systolic,
observation.Diastolic, observation.Pulse, observation.Context, observation.Note); observation.Diastolic, observation.Pulse, observation.Context, observation.Note);
@@ -20,4 +20,10 @@ public sealed class SqlObservationRepository(ObservationDbContext db) : Observat
db.Observations.AsNoTracking().Where(o => o.PatientId == patientId) db.Observations.AsNoTracking().Where(o => o.PatientId == patientId)
.OrderByDescending(o => o.MeasuredAt).ThenByDescending(o => o.ObservationId) .OrderByDescending(o => o.MeasuredAt).ThenByDescending(o => o.ObservationId)
.FirstOrDefaultAsync(cancellationToken); .FirstOrDefaultAsync(cancellationToken);
public Task<List<BloodPressureObservation>> 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);
} }
+5 -1
View File
@@ -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. 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. 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. 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 ## Automated acceptance tests
@@ -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<ObservationApiFixture>
{
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<Guid> 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<Profile>())!.PatientId;
}
private async Task<Observation> 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<Observation>())!;
}
private Task<Observation[]?> HistoryAsync(Guid patientId, string from, string to) =>
fixture.Client.GetFromJsonAsync<Observation[]>(
$"/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<Observation>($"/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"))!);
}
}