diff --git a/src/ApiGateway/Controllers/ObservationController.cs b/src/ApiGateway/Controllers/ObservationController.cs index 022243e..6495918 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 UpdateObservation(Guid observationId, CancellationToken cancellationToken) => ForwardAsync(HttpMethod.Put, $"api/observations/{observationId}", cancellationToken); + [HttpPatch("observations/{observationId:guid}")] + public Task PatchObservation(Guid observationId, CancellationToken cancellationToken) => + ForwardAsync(HttpMethod.Patch, $"api/observations/{observationId}", cancellationToken); + [HttpGet("observations/{observationId:guid}")] public Task GetObservation(Guid observationId, CancellationToken cancellationToken) => ForwardAsync(HttpMethod.Get, $"api/observations/{observationId}", cancellationToken); @@ -33,7 +37,7 @@ public sealed class ObservationController(IHttpClientFactory clients) : Controll private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken) { using var request = new HttpRequestMessage(method, path); - if (method == HttpMethod.Post || method == HttpMethod.Put) + if (method == HttpMethod.Post || method == HttpMethod.Put || method == HttpMethod.Patch) { request.Content = new StreamContent(Request.Body); if (Request.ContentType is not null) diff --git a/src/ObservationService/Application/ObservationApplicationService.cs b/src/ObservationService/Application/ObservationApplicationService.cs index 418ee54..68fc80b 100644 --- a/src/ObservationService/Application/ObservationApplicationService.cs +++ b/src/ObservationService/Application/ObservationApplicationService.cs @@ -16,8 +16,16 @@ public sealed class ObservationApplicationService(ObservationRepository reposito if (request.Systolic is null or <= 0 || request.Diastolic is null or <= 0 || request.Pulse is null or <= 0) throw new ArgumentException("Positive measured values are required.", nameof(request)); - return repository.UpdateValuesAsync(observationId, request.Systolic.Value, request.Diastolic.Value, - request.Pulse.Value, DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified), cancellationToken); + return PatchAsync(observationId, new PatchObservationRequest { Systolic = request.Systolic, Diastolic = request.Diastolic, Pulse = request.Pulse }, cancellationToken); + } + + public Task PatchAsync(Guid observationId, PatchObservationRequest request, + CancellationToken cancellationToken) + { + Validator.ValidateObject(request, new ValidationContext(request), validateAllProperties: true); + if (request.MeasurementContext is not null) + Validator.ValidateObject(request.MeasurementContext, new ValidationContext(request.MeasurementContext), validateAllProperties: true); + return repository.UpdateAsync(observationId, request, DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified), cancellationToken); } public async Task RecordAsync(Guid patientId, RecordObservationRequest request, diff --git a/src/ObservationService/Application/ObservationRepository.cs b/src/ObservationService/Application/ObservationRepository.cs index 6ac9578..ca26874 100644 --- a/src/ObservationService/Application/ObservationRepository.cs +++ b/src/ObservationService/Application/ObservationRepository.cs @@ -1,3 +1,4 @@ +using ObservationService.Contracts; using ObservationService.Domain; namespace ObservationService.Application; @@ -5,7 +6,7 @@ namespace ObservationService.Application; public interface ObservationRepository { Task DeleteAsync(Guid observationId, CancellationToken cancellationToken); - Task UpdateValuesAsync(Guid observationId, int systolic, int diastolic, int pulse, + Task UpdateAsync(Guid observationId, PatchObservationRequest request, DateTime updatedAt, CancellationToken cancellationToken); Task SaveAsync(BloodPressureObservation observation, CancellationToken cancellationToken); Task FindByIdAsync(Guid observationId, CancellationToken cancellationToken); diff --git a/src/ObservationService/Contracts/MeasurementContextPatch.cs b/src/ObservationService/Contracts/MeasurementContextPatch.cs new file mode 100644 index 0000000..4223e7c --- /dev/null +++ b/src/ObservationService/Contracts/MeasurementContextPatch.cs @@ -0,0 +1,87 @@ +using System.ComponentModel.DataAnnotations; +using System.Text.Json.Serialization; + +namespace ObservationService.Contracts; + +[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)] +public sealed record MeasurementContextPatch +{ + private string? setting; + [AllowedValues("Home", "Clinic", "Other", "Unknown", null)] + public string? Setting + { + get => setting; + init { setting = value; SettingSpecified = true; } + } + [JsonIgnore] + public bool SettingSpecified { get; private set; } + + private string? activityCondition; + [AllowedValues("AtRest", "DuringActivity", "AfterActivity", "Unknown", null)] + public string? ActivityCondition + { + get => activityCondition; + init { activityCondition = value; ActivityConditionSpecified = true; } + } + [JsonIgnore] + public bool ActivityConditionSpecified { get; private set; } + + private decimal? restDurationMinutes; + [Range(0, double.MaxValue)] + public decimal? RestDurationMinutes + { + get => restDurationMinutes; + init { restDurationMinutes = value; RestDurationMinutesSpecified = true; } + } + [JsonIgnore] + public bool RestDurationMinutesSpecified { get; private set; } + + private string? bodyPosition; + public string? BodyPosition + { + get => bodyPosition; + init { bodyPosition = value; BodyPositionSpecified = true; } + } + [JsonIgnore] + public bool BodyPositionSpecified { get; private set; } + + private string? measuredArm; + public string? MeasuredArm + { + get => measuredArm; + init { measuredArm = value; MeasuredArmSpecified = true; } + } + [JsonIgnore] + public bool MeasuredArmSpecified { get; private set; } + + private string? deviceDetails; + public string? DeviceDetails + { + get => deviceDetails; + init { deviceDetails = value; DeviceDetailsSpecified = true; } + } + [JsonIgnore] + public bool DeviceDetailsSpecified { get; private set; } + + private string? cuffDetails; + public string? CuffDetails + { + get => cuffDetails; + init { cuffDetails = value; CuffDetailsSpecified = true; } + } + [JsonIgnore] + public bool CuffDetailsSpecified { get; private set; } + + private string? additionalCircumstances; + public string? AdditionalCircumstances + { + get => additionalCircumstances; + init { additionalCircumstances = value; AdditionalCircumstancesSpecified = true; } + } + [JsonIgnore] + public bool AdditionalCircumstancesSpecified { get; private set; } + + [JsonIgnore] + public bool HasChanges => SettingSpecified || ActivityConditionSpecified || RestDurationMinutesSpecified || + BodyPositionSpecified || MeasuredArmSpecified || DeviceDetailsSpecified || CuffDetailsSpecified || AdditionalCircumstancesSpecified; +} diff --git a/src/ObservationService/Contracts/PatchObservationRequest.cs b/src/ObservationService/Contracts/PatchObservationRequest.cs new file mode 100644 index 0000000..eecfde3 --- /dev/null +++ b/src/ObservationService/Contracts/PatchObservationRequest.cs @@ -0,0 +1,78 @@ +using System.ComponentModel.DataAnnotations; +using System.Text.Json.Serialization; + +namespace ObservationService.Contracts; + +[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)] +public sealed record PatchObservationRequest : IValidatableObject +{ + private int? systolic; + [Range(1, int.MaxValue)] + public int? Systolic + { + get => systolic; + init { systolic = value; SystolicSpecified = true; } + } + [JsonIgnore] + public bool SystolicSpecified { get; private set; } + + private int? diastolic; + [Range(1, int.MaxValue)] + public int? Diastolic + { + get => diastolic; + init { diastolic = value; DiastolicSpecified = true; } + } + [JsonIgnore] + public bool DiastolicSpecified { get; private set; } + + private int? pulse; + [Range(1, int.MaxValue)] + public int? Pulse + { + get => pulse; + init { pulse = value; PulseSpecified = true; } + } + [JsonIgnore] + public bool PulseSpecified { get; private set; } + + private MeasurementContextPatch? measurementContext; + public MeasurementContextPatch? MeasurementContext + { + get => measurementContext; + init { measurementContext = value; MeasurementContextSpecified = true; } + } + [JsonIgnore] + public bool MeasurementContextSpecified { get; private set; } + + private string? context; + public string? Context + { + get => context; + init { context = value; ContextSpecified = true; } + } + [JsonIgnore] + public bool ContextSpecified { get; private set; } + + private string? note; + public string? Note + { + get => note; + init { note = value; NoteSpecified = true; } + } + [JsonIgnore] + public bool NoteSpecified { get; private set; } + + public IEnumerable Validate(ValidationContext validationContext) + { + if (SystolicSpecified && Systolic is null) + yield return new ValidationResult("Systolic cannot be cleared.", [nameof(Systolic)]); + if (DiastolicSpecified && Diastolic is null) + yield return new ValidationResult("Diastolic cannot be cleared.", [nameof(Diastolic)]); + if (PulseSpecified && Pulse is null) + yield return new ValidationResult("Pulse cannot be cleared.", [nameof(Pulse)]); + if (!SystolicSpecified && !DiastolicSpecified && !PulseSpecified && !ContextSpecified && !NoteSpecified && + !(MeasurementContextSpecified && (MeasurementContext is null || MeasurementContext.HasChanges))) + yield return new ValidationResult("Supply at least one supported field to update."); + } +} diff --git a/src/ObservationService/Contracts/UpdateObservationRequest.cs b/src/ObservationService/Contracts/UpdateObservationRequest.cs index 4c64e5c..3cbcc49 100644 --- a/src/ObservationService/Contracts/UpdateObservationRequest.cs +++ b/src/ObservationService/Contracts/UpdateObservationRequest.cs @@ -1,7 +1,9 @@ +using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; namespace ObservationService.Contracts; +[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)] public sealed record UpdateObservationRequest { [Required, Range(1, int.MaxValue)] diff --git a/src/ObservationService/Controllers/ObservationController.cs b/src/ObservationService/Controllers/ObservationController.cs index 3fad47b..e9d3a7f 100644 --- a/src/ObservationService/Controllers/ObservationController.cs +++ b/src/ObservationService/Controllers/ObservationController.cs @@ -43,6 +43,14 @@ public sealed class ObservationController(ObservationApplicationService service) return observation is null ? NotFound() : Ok(ToDto(observation)); } + [HttpPatch("observations/{observationId:guid}")] + public async Task> PatchObservation(Guid observationId, PatchObservationRequest request, + CancellationToken cancellationToken) + { + var observation = await service.PatchAsync(observationId, request, cancellationToken); + return observation is null ? NotFound() : Ok(ToDto(observation)); + } + [HttpGet("observations/{observationId:guid}")] public async Task> GetObservation(Guid observationId, CancellationToken cancellationToken) { diff --git a/src/ObservationService/Persistence/SqlObservationRepository.cs b/src/ObservationService/Persistence/SqlObservationRepository.cs index 2d87f15..bc71283 100644 --- a/src/ObservationService/Persistence/SqlObservationRepository.cs +++ b/src/ObservationService/Persistence/SqlObservationRepository.cs @@ -1,3 +1,4 @@ +using ObservationService.Contracts; using Microsoft.EntityFrameworkCore; using ObservationService.Application; using ObservationService.Domain; @@ -10,17 +11,39 @@ public sealed class SqlObservationRepository(ObservationDbContext db) : Observat await db.Observations.Where(o => o.ObservationId == observationId) .ExecuteDeleteAsync(cancellationToken) > 0; - public async Task UpdateValuesAsync(Guid observationId, int systolic, int diastolic, - int pulse, DateTime updatedAt, CancellationToken cancellationToken) + public async Task UpdateAsync(Guid observationId, PatchObservationRequest request, + DateTime updatedAt, CancellationToken cancellationToken) { var observation = await db.Observations.SingleOrDefaultAsync(o => o.ObservationId == observationId, cancellationToken); if (observation is null) return null; - observation.Systolic = systolic; - observation.Diastolic = diastolic; - observation.Pulse = pulse; + if (request.SystolicSpecified) observation.Systolic = request.Systolic!.Value; + if (request.DiastolicSpecified) observation.Diastolic = request.Diastolic!.Value; + if (request.PulseSpecified) observation.Pulse = request.Pulse!.Value; + if (request.ContextSpecified) observation.Context = request.Context; + if (request.NoteSpecified) observation.Note = request.Note; + if (request.MeasurementContextSpecified) + { + if (request.MeasurementContext is null) observation.MeasurementContext = new(); + else + { + var patch = request.MeasurementContext; + var current = observation.MeasurementContext; + observation.MeasurementContext = current with + { + Setting = patch.SettingSpecified ? patch.Setting ?? "Unknown" : current.Setting, + ActivityCondition = patch.ActivityConditionSpecified ? patch.ActivityCondition ?? "Unknown" : current.ActivityCondition, + RestDurationMinutes = patch.RestDurationMinutesSpecified ? patch.RestDurationMinutes : current.RestDurationMinutes, + BodyPosition = patch.BodyPositionSpecified ? patch.BodyPosition : current.BodyPosition, + MeasuredArm = patch.MeasuredArmSpecified ? patch.MeasuredArm : current.MeasuredArm, + DeviceDetails = patch.DeviceDetailsSpecified ? patch.DeviceDetails : current.DeviceDetails, + CuffDetails = patch.CuffDetailsSpecified ? patch.CuffDetails : current.CuffDetails, + AdditionalCircumstances = patch.AdditionalCircumstancesSpecified ? patch.AdditionalCircumstances : current.AdditionalCircumstances + }; + } + } observation.UpdatedAt = updatedAt; await db.SaveChangesAsync(cancellationToken); return observation; diff --git a/src/README.md b/src/README.md index e87e778..e4af491 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 is implemented under US-07; context-only updates remain under US-08. +or text. Context filtering is implemented under US-07; partial context updates are implemented 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. @@ -149,7 +149,42 @@ Existing Insights requests continue to consume the unchanged unfiltered array. N `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. -US-08 tests cover the documented correction and rejection scenarios, correction of all three values, persistence after restart, preservation of other fields and creation time, modification timestamps, visibility in latest/history, unaffected other observations, and missing/malformed values. No new dependencies are introduced. +`PATCH /api/observations/{observationId}` accepts a partial JSON object. For example: + +```json +{ + "measurementContext": { + "setting": "Clinic", + "activityCondition": null, + "deviceDetails": "Corrected device" + } +} +``` + +Only supplied fields change. Within `measurementContext`, setting/activity nulls +clear the category to `Unknown`; null optional details clear them without changing +other details. An explicit `measurementContext: null` clears the whole structured +object to unknown categories and null details, while retaining legacy text and +notes. Omission of the object preserves it. Optional `context` and `note` can also +be changed or cleared with null. Optional `systolic`, `diastolic` and `pulse` support +individual positive-integer corrections; they cannot be cleared. Empty patches or +objects containing no supported changes return `400`. Creation time, measurement +time, patient association and observation identifier cannot be changed by patches. + +Successful patches return `200` with the updated observation and modification time. +Validation occurs before any changes are saved; unsupported fields/categories, negative +rest duration, non-positive/null numerical values and malformed input reject the +whole request with `400` validation details. Missing observations return `404` +without insertion. Ownership restrictions apply to the actual observation patient; +professionals cannot patch even assigned patients. The existing `PUT` endpoint +retains its complete numerical-correction contract and rejects unsupported fields +rather than silently ignoring context supplied on that route. Use `PATCH` for context +updates. Both routes use the same +Observation-owned update operation and save changes atomically. Subsequent reads, +latest observations and filtered history use current recorded context. US-11 trend +integration remains to be verified when that endpoint is implemented. + +US-08 tests cover the original full numerical corrections and rejection scenarios plus context-only/single-value patches, historical context additions, individual field corrections/clears, whole-context clearing, preservation of omitted data and creation time, persistence after restart, fresh filter membership, atomic rejection, missing observations and access restrictions. No new dependencies are introduced. `DELETE /api/observations/{observationId}` removes the observation and returns `204 No Content`. A missing or previously deleted observation returns `404`. The Observation Service deletes the row from its own database in a single statement; deleted observations disappear from specific retrieval, history, and latest selection. Other observations and the patient profile are preserved. diff --git a/tests/Observation.AcceptanceTests/PatchObservationTests.cs b/tests/Observation.AcceptanceTests/PatchObservationTests.cs new file mode 100644 index 0000000..6dc8d3f --- /dev/null +++ b/tests/Observation.AcceptanceTests/PatchObservationTests.cs @@ -0,0 +1,190 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text; +using System.Text.Json; +using HealthApp.TestSupport; +using Microsoft.EntityFrameworkCore; +using Xunit; + +namespace Observation.AcceptanceTests; + +public sealed class PatchObservationTests(ObservationApiFixture fixture) : IClassFixture +{ + private sealed record Profile(Guid PatientId); + private sealed record ContextData(string Setting, string ActivityCondition, decimal? RestDurationMinutes, + string? BodyPosition, string? MeasuredArm, string? DeviceDetails, string? CuffDetails, string? AdditionalCircumstances); + private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt, + int Systolic, int Diastolic, int Pulse, string? Context, string? Note, ContextData MeasurementContext); + + private async Task Record(bool withContext = true) + { + using var patient = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Partial correction", dateOfBirth = "1980-01-01" }); + Assert.Equal(HttpStatusCode.Created, patient.StatusCode); + var patientId = (await patient.Content.ReadFromJsonAsync())!.PatientId; + using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new + { + measuredAt = "2026-09-12T08:00:00", systolic = 182, diastolic = 82, pulse = 68, + context = "Legacy text", note = "Saved note", + measurementContext = withContext ? new { setting = "Home", activityCondition = "AtRest", restDurationMinutes = 5.5m, + bodyPosition = "Seated", measuredArm = "Left", deviceDetails = "Device", cuffDetails = "Cuff", additionalCircumstances = "Circumstances" } : null + }); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + return (await response.Content.ReadFromJsonAsync())!; + } + + private Task Patch(Guid id, object body) => fixture.Client.PatchAsJsonAsync($"/api/observations/{id}", body); + private Task Read(Guid id) => fixture.Client.GetFromJsonAsync($"/api/observations/{id}"); + private Task History(Guid patient, string selection) => fixture.Client.GetFromJsonAsync( + $"/api/patients/{patient}/observations?from=2026-09-01&to=2026-10-01&{selection}"); + + [Fact] + public async Task Context_can_be_added_to_a_historical_observation_without_changing_its_measurements() + { + var original = await Record(false); + using var response = await Patch(original.ObservationId, new { measurementContext = new { setting = "Home", activityCondition = "AtRest" } }); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var updated = (await response.Content.ReadFromJsonAsync())!; + Assert.Equal(original with { MeasurementContext = original.MeasurementContext with { Setting = "Home", ActivityCondition = "AtRest" } }, updated); + } + + [Fact] + public async Task Correcting_one_context_field_preserves_omitted_data_and_changes_selection_after_restart() + { + var original = await Record(); + await using var db = fixture.CreateObservationDbContext(); + var before = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId); + using var response = await Patch(original.ObservationId, new { measurementContext = new { setting = "Clinic" } }); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var expected = original with { MeasurementContext = original.MeasurementContext with { Setting = "Clinic" } }; + Assert.Equal(expected, await response.Content.ReadFromJsonAsync()); + await fixture.RestartHostsAsync(); + Assert.Equal(expected, await Read(original.ObservationId)); + Assert.Equal(expected, await fixture.Client.GetFromJsonAsync($"/api/patients/{original.PatientId}/observations/latest")); + Assert.Empty((await History(original.PatientId, "setting=Home"))!); + Assert.Equal(expected, Assert.Single((await History(original.PatientId, "setting=Clinic&activityCondition=AtRest"))!)); + var after = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId); + Assert.Equal(before.CreatedAt, after.CreatedAt); + Assert.True(after.UpdatedAt > before.UpdatedAt); + } + + [Fact] + public async Task Individual_optional_fields_can_be_corrected_or_cleared_without_erasing_other_context() + { + var original = await Record(); + using var corrected = await Patch(original.ObservationId, new { measurementContext = new { restDurationMinutes = 0m, + bodyPosition = "Standing", measuredArm = "Right", deviceDetails = "Corrected device", cuffDetails = "Corrected cuff", additionalCircumstances = "After walking" } }); + Assert.Equal(HttpStatusCode.OK, corrected.StatusCode); + var expected = original with { MeasurementContext = original.MeasurementContext with { RestDurationMinutes = 0, + BodyPosition = "Standing", MeasuredArm = "Right", DeviceDetails = "Corrected device", CuffDetails = "Corrected cuff", AdditionalCircumstances = "After walking" } }; + Assert.Equal(expected, await corrected.Content.ReadFromJsonAsync()); + using var clear = await Patch(original.ObservationId, new { measurementContext = new { activityCondition = (string?)null, + restDurationMinutes = (decimal?)null, bodyPosition = (string?)null, measuredArm = (string?)null, + deviceDetails = (string?)null, cuffDetails = (string?)null, additionalCircumstances = (string?)null } }); + Assert.Equal(HttpStatusCode.OK, clear.StatusCode); + expected = original with { MeasurementContext = new ContextData("Home", "Unknown", null, null, null, null, null, null) }; + Assert.Equal(expected, await Read(original.ObservationId)); + Assert.Empty((await History(original.PatientId, "activityCondition=AtRest"))!); + Assert.Equal(expected, Assert.Single((await History(original.PatientId, "activityCondition=Unknown"))!)); + using var setting = await Patch(original.ObservationId, new { measurementContext = new { setting = (string?)null } }); + Assert.Equal(HttpStatusCode.OK, setting.StatusCode); + Assert.Equal("Unknown", (await Read(original.ObservationId))!.MeasurementContext.Setting); + } + + [Fact] + public async Task Explicit_null_context_object_clears_structured_context_but_preserves_legacy_text_and_numbers() + { + var original = await Record(); + using var response = await Patch(original.ObservationId, new { measurementContext = (object?)null }); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(original with { MeasurementContext = new ContextData("Unknown", "Unknown", null, null, null, null, null, null) }, await Read(original.ObservationId)); + } + + [Fact] + public async Task Single_numerical_and_legacy_text_updates_preserve_other_values() + { + var original = await Record(); + using var correction = await Patch(original.ObservationId, new { systolic = 128 }); + Assert.Equal(HttpStatusCode.OK, correction.StatusCode); + Assert.Equal(original with { Systolic = 128 }, await Read(original.ObservationId)); + using var text = await Patch(original.ObservationId, new { context = "Corrected narrative", note = (string?)null }); + Assert.Equal(HttpStatusCode.OK, text.StatusCode); + Assert.Equal(original with { Systolic = 128, Context = "Corrected narrative", Note = null }, await Read(original.ObservationId)); + } + + [Theory] + [InlineData("{\"systolic\":128,\"measurementContext\":{\"setting\":\"Unsupported\"}}")] + [InlineData("{\"note\":\"Change\",\"measurementContext\":{\"activityCondition\":\"Unsupported\"}}")] + [InlineData("{\"measurementContext\":{\"restDurationMinutes\":-1}}")] + [InlineData("{\"systolic\":null}")] + [InlineData("{\"diastolic\":0}")] + [InlineData("{\"pulse\":-1}")] + [InlineData("{\"systolic\":\"invalid\"}")] + [InlineData("{\"systolic\":128,\"measurementContext\":{\"unsupportedField\":\"value\"}}")] + [InlineData("{}")] + [InlineData("{\"measurementContext\":{}}")] + [InlineData("{")] + public async Task Invalid_patches_reject_the_whole_update_without_changes(string json) + { + var original = await Record(); + await using var db = fixture.CreateObservationDbContext(); + var before = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId); + using var content = new StringContent(json, Encoding.UTF8, "application/json"); + using var response = await fixture.Client.PatchAsync($"/api/observations/{original.ObservationId}", content); + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + Assert.True(problem.RootElement.TryGetProperty("errors", out _)); + Assert.Equal(original, await Read(original.ObservationId)); + var after = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId); + Assert.Equal(before.UpdatedAt, after.UpdatedAt); + } + + [Fact] + public async Task Unsupported_context_in_a_legacy_put_does_not_silently_apply_its_numerical_changes() + { + var original = await Record(); + using var response = await fixture.Client.PutAsJsonAsync($"/api/observations/{original.ObservationId}", new + { + systolic = 128, diastolic = 80, pulse = 65, + measurementContext = new { setting = "Unsupported" } + }); + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Equal(original, await Read(original.ObservationId)); + } + + [Fact] + public async Task Missing_observation_is_not_created_by_a_context_patch() + { + await Record(); + await using var db = fixture.CreateObservationDbContext(); + var count = await db.Observations.CountAsync(); + using var response = await Patch(Guid.NewGuid(), new { measurementContext = new { setting = "Clinic" } }); + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.Equal(count, await db.Observations.CountAsync()); + } + + [Fact] + public async Task Other_patients_professionals_and_unauthenticated_clients_cannot_patch_context() + { + var original = await Record(); + var other = await Record(); + fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = original.PatientId.ToString(); + await fixture.RestartHostsAsync(); + var otherToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, fixture.Authentication.PatientAccounts[other.PatientId]); + var professional = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional"); + foreach (var (token, expected) in new[] + { + ((string?)null, HttpStatusCode.Unauthorized), ((string?)"invalid", HttpStatusCode.Unauthorized), + ((string?)otherToken, HttpStatusCode.NotFound), ((string?)professional, HttpStatusCode.Forbidden) + }) + { + using var request = new HttpRequestMessage(HttpMethod.Patch, $"/api/observations/{original.ObservationId}") + { Content = JsonContent.Create(new { measurementContext = new { setting = "Clinic" } }) }; + if (token is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + using var response = await fixture.RawClient.SendAsync(request); + Assert.Equal(expected, response.StatusCode); + } + Assert.Equal(original, await Read(original.ObservationId)); + Assert.Equal(other, await Read(other.ObservationId)); + } +}