Implement US-07 context-filtered observation history

This commit is contained in:
Steffen committed 2026-10-05 12:28:04 +02:00
1 parent ac6b42f32e
commit ce03038ce1
8 files changed
+235 -11

No files matched your search

@@ -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);
@@ -65,13 +65,14 @@ public sealed class ObservationApplicationService(ObservationRepository reposito
repository.FindLatestByPatientIdAsync(patientId, cancellationToken);
public Task<List<BloodPressureObservation>> 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) =>
@@ -11,5 +11,5 @@ public interface ObservationRepository
Task<BloodPressureObservation?> FindByIdAsync(Guid observationId, CancellationToken cancellationToken);
Task<BloodPressureObservation?> FindLatestByPatientIdAsync(Guid patientId, CancellationToken cancellationToken);
Task<List<BloodPressureObservation>> FindByPatientIdAndPeriodAsync(Guid patientId, DateTime from, DateTime to,
CancellationToken cancellationToken);
ContextSelection selection, CancellationToken cancellationToken);
}
@@ -60,11 +60,13 @@ public sealed class ObservationController(ObservationApplicationService service)
[HttpGet("patients/{patientId:guid}/observations")]
public async Task<ActionResult<List<ObservationDto>>> 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)
@@ -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; }
}
@@ -43,8 +43,14 @@ public sealed class SqlObservationRepository(ObservationDbContext db) : Observat
.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);
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);
}
}
+23 -2
View File
@@ -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.