From a9633e49e1475f634f1d713fc8747b2b7a6d916d Mon Sep 17 00:00:00 2001 From: Steffen Date: Thu, 1 Oct 2026 11:29:54 +0200 Subject: [PATCH] Implement US-03 patient profile updates --- .../Controllers/PatientController.cs | 6 +- .../Application/PatientApplicationService.cs | 9 +++ .../Application/PatientRepository.cs | 1 + .../Contracts/UpdatePatientRequest.cs | 11 +++ .../Controllers/PatientController.cs | 7 ++ .../Persistence/SqlPatientRepository.cs | 11 +++ src/README.md | 12 ++-- .../UpdatePatientTests.cs | 71 +++++++++++++++++++ 8 files changed, 123 insertions(+), 5 deletions(-) create mode 100644 src/PatientProfileService/Contracts/UpdatePatientRequest.cs create mode 100644 tests/PatientProfile.AcceptanceTests/UpdatePatientTests.cs diff --git a/src/ApiGateway/Controllers/PatientController.cs b/src/ApiGateway/Controllers/PatientController.cs index c88b71c..84e5920 100644 --- a/src/ApiGateway/Controllers/PatientController.cs +++ b/src/ApiGateway/Controllers/PatientController.cs @@ -14,10 +14,14 @@ public sealed class PatientController(IHttpClientFactory clients) : ControllerBa public Task GetPatient(Guid patientId, CancellationToken cancellationToken) => ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}", cancellationToken); + [HttpPut("{patientId:guid}")] + public Task UpdatePatient(Guid patientId, CancellationToken cancellationToken) => + ForwardAsync(HttpMethod.Put, $"api/patients/{patientId}", cancellationToken); + private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken) { using var request = new HttpRequestMessage(method, path); - if (method == HttpMethod.Post) + if (method == HttpMethod.Post || method == HttpMethod.Put) { request.Content = new StreamContent(Request.Body); if (Request.ContentType is not null) diff --git a/src/PatientProfileService/Application/PatientApplicationService.cs b/src/PatientProfileService/Application/PatientApplicationService.cs index 922d5db..30593f9 100644 --- a/src/PatientProfileService/Application/PatientApplicationService.cs +++ b/src/PatientProfileService/Application/PatientApplicationService.cs @@ -26,4 +26,13 @@ public sealed class PatientApplicationService(PatientRepository repository) public Task GetPatientAsync(Guid patientId, CancellationToken cancellationToken) => repository.FindByIdAsync(patientId, cancellationToken); + + public async Task UpdatePatientAsync(Guid patientId, UpdatePatientRequest request, CancellationToken cancellationToken) + { + ArgumentException.ThrowIfNullOrWhiteSpace(request.Name); + if (!await repository.UpdateProfileAsync(patientId, request.Name, request.ContactInfo, cancellationToken)) + return null; + + return await repository.FindByIdAsync(patientId, cancellationToken); + } } diff --git a/src/PatientProfileService/Application/PatientRepository.cs b/src/PatientProfileService/Application/PatientRepository.cs index 8847caa..40f889f 100644 --- a/src/PatientProfileService/Application/PatientRepository.cs +++ b/src/PatientProfileService/Application/PatientRepository.cs @@ -6,4 +6,5 @@ public interface PatientRepository { Task SaveAsync(Patient patient, CancellationToken cancellationToken); Task FindByIdAsync(Guid patientId, CancellationToken cancellationToken); + Task UpdateProfileAsync(Guid patientId, string name, string? contactInfo, CancellationToken cancellationToken); } diff --git a/src/PatientProfileService/Contracts/UpdatePatientRequest.cs b/src/PatientProfileService/Contracts/UpdatePatientRequest.cs new file mode 100644 index 0000000..d843ee0 --- /dev/null +++ b/src/PatientProfileService/Contracts/UpdatePatientRequest.cs @@ -0,0 +1,11 @@ +using System.ComponentModel.DataAnnotations; + +namespace PatientProfileService.Contracts; + +public sealed record UpdatePatientRequest +{ + [Required] + public string? Name { get; init; } + + public string? ContactInfo { get; init; } +} diff --git a/src/PatientProfileService/Controllers/PatientController.cs b/src/PatientProfileService/Controllers/PatientController.cs index d03ebb0..1018086 100644 --- a/src/PatientProfileService/Controllers/PatientController.cs +++ b/src/PatientProfileService/Controllers/PatientController.cs @@ -23,6 +23,13 @@ public sealed class PatientController(PatientApplicationService service) : Contr return patient is null ? NotFound() : Ok(ToDto(patient)); } + [HttpPut("{patientId:guid}")] + public async Task> UpdatePatient(Guid patientId, UpdatePatientRequest request, CancellationToken cancellationToken) + { + var patient = await service.UpdatePatientAsync(patientId, request, cancellationToken); + return patient is null ? NotFound() : Ok(ToDto(patient)); + } + private static PatientDto ToDto(Patient patient) => new(patient.PatientId, patient.Name, patient.DateOfBirth, patient.ContactInfo); } diff --git a/src/PatientProfileService/Persistence/SqlPatientRepository.cs b/src/PatientProfileService/Persistence/SqlPatientRepository.cs index e2ad4a8..27641b4 100644 --- a/src/PatientProfileService/Persistence/SqlPatientRepository.cs +++ b/src/PatientProfileService/Persistence/SqlPatientRepository.cs @@ -15,4 +15,15 @@ public sealed class SqlPatientRepository(PatientDbContext db) : PatientRepositor public Task FindByIdAsync(Guid patientId, CancellationToken cancellationToken) => db.Patients.AsNoTracking().SingleOrDefaultAsync(p => p.PatientId == patientId, cancellationToken); + + public async Task UpdateProfileAsync(Guid patientId, string name, string? contactInfo, CancellationToken cancellationToken) + { + var now = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified); + var affected = await db.Patients.Where(p => p.PatientId == patientId) + .ExecuteUpdateAsync(update => update + .SetProperty(p => p.Name, name) + .SetProperty(p => p.ContactInfo, contactInfo) + .SetProperty(p => p.UpdatedAt, now), cancellationToken); + return affected != 0; + } } diff --git a/src/README.md b/src/README.md index 1644886..c5db903 100644 --- a/src/README.md +++ b/src/README.md @@ -1,8 +1,8 @@ -# US-01: Create a patient profile +# US-01–US-03: Create, view and update a patient profile -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 and Patient/Profile service are separate executables and can run on separate machines. Only the services needed for US-01 are implemented. +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 and Patient/Profile service are separate executables and can run on separate machines. Only the services needed for US-01–US-03 are implemented. -The controller calls `PatientApplicationService`, which uses `PatientRepository`, implemented by `SqlPatientRepository`. The service owns the `patient` table from the ER diagram, including creation/update timestamps stored as UTC in PostgreSQL `timestamp` columns. Update-profile functionality belongs to a later story. +The controller calls `PatientApplicationService`, which uses `PatientRepository`, implemented by `SqlPatientRepository`. The service owns the `patient` table from the ER diagram, including creation/update timestamps stored as UTC in PostgreSQL `timestamp` columns. ## Build and run @@ -37,7 +37,9 @@ curl -i http://127.0.0.1:5080/api/patients \ `GET /api/patients/{patientId}` retrieves the persisted profile, or returns `404` when absent. Retrieval is included because US-01 explicitly requires it. The gateway returns `502` for connection failures and `504` for upstream timeouts. -Authentication and authorization policy is unspecified; the gap is recorded in `suggestions/api-gateway-authentication.md`. No access policy has been invented for US-01. +`PUT /api/patients/{patientId}` updates the name and contact information and returns `200` with the updated profile. It preserves the patient identifier, date of birth and creation timestamp, and updates the modification timestamp. Names must be nonblank, consistent with profile creation; omitted or null contact information clears that optional value. A missing patient returns `404` without creating a profile. Invalid requests return `400` without changing stored information. + +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. These endpoints currently have no access restrictions. ## Automated acceptance tests @@ -50,6 +52,8 @@ TEST_POSTGRES_CONNECTION='Host=127.0.0.1;Database=postgres;Username=postgres;Pas The xUnit tests send HTTP requests to the gateway; the gateway reaches a real Kestrel Patient/Profile service over HTTP. They cover every US-01 acceptance scenario, retrieval after host restart, distinct identifiers, optional contact information, invalid JSON/dates, and rejection without database writes. Test assertions use an independent HTTP response contract. Production projects have no references to each other's implementation. +US-02 retrieval scenarios are covered by the creation tests. US-03 tests cover persisted updates after restart, preservation of identity and date of birth, missing-patient rejection without insertion, and invalid-name rejection without changing the profile. + Dependencies: Npgsql's EF Core PostgreSQL provider supplies persistence; EF Core Relational is pinned to the same patch as EF Core Design to keep runtime/tooling versions aligned; EF Core Design supports migration maintenance. xUnit, its Visual Studio runner, Microsoft.NET.Test.Sdk, and ASP.NET Core MVC Testing are used only for automated tests. The gateway uses the platform's HttpClient and has no extra package dependency. ## Linux deployment diff --git a/tests/PatientProfile.AcceptanceTests/UpdatePatientTests.cs b/tests/PatientProfile.AcceptanceTests/UpdatePatientTests.cs new file mode 100644 index 0000000..60713a8 --- /dev/null +++ b/tests/PatientProfile.AcceptanceTests/UpdatePatientTests.cs @@ -0,0 +1,71 @@ +using System.Net; +using System.Net.Http.Json; +using Microsoft.EntityFrameworkCore; +using Xunit; + +namespace PatientProfile.AcceptanceTests; + +public sealed class UpdatePatientTests(PatientApiFixture fixture) : IClassFixture +{ + private sealed record Profile(Guid PatientId, string Name, DateOnly DateOfBirth, string? ContactInfo); + + [Fact] + public async Task Updated_profile_preserves_identity_and_date_of_birth_and_survives_restart() + { + using var createdResponse = await fixture.Client.PostAsJsonAsync("/api/patients", new + { + name = "Steffen Example", dateOfBirth = "1980-01-01", contactInfo = "old@example.test" + }); + Assert.Equal(HttpStatusCode.Created, createdResponse.StatusCode); + var created = (await createdResponse.Content.ReadFromJsonAsync())!; + var path = $"/api/patients/{created.PatientId}"; + + using var response = await fixture.Client.PutAsJsonAsync(path, new + { + name = "Steffen Updated", contactInfo = "new@example.test" + }); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var expected = created with { Name = "Steffen Updated", ContactInfo = "new@example.test" }; + Assert.Equal(expected, await response.Content.ReadFromJsonAsync()); + + await fixture.RestartHostsAsync(); + Assert.Equal(expected, await fixture.Client.GetFromJsonAsync(path)); + } + + [Fact] + public async Task Updating_a_missing_patient_is_rejected_without_creating_a_profile() + { + await using var db = fixture.CreateDbContext(); + var countBefore = await db.Patients.CountAsync(); + var path = $"/api/patients/{Guid.NewGuid()}"; + using var response = await fixture.Client.PutAsJsonAsync(path, new + { + name = "Steffen Example", contactInfo = "new@example.test" + }); + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.Equal(countBefore, await db.Patients.CountAsync()); + using var retrieval = await fixture.Client.GetAsync(path); + Assert.Equal(HttpStatusCode.NotFound, retrieval.StatusCode); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public async Task Invalid_name_is_rejected_without_changing_the_profile(string? name) + { + using var createdResponse = await fixture.Client.PostAsJsonAsync("/api/patients", new + { + name = "Steffen Example", dateOfBirth = "1980-01-01", contactInfo = "old@example.test" + }); + Assert.Equal(HttpStatusCode.Created, createdResponse.StatusCode); + var created = (await createdResponse.Content.ReadFromJsonAsync())!; + var path = $"/api/patients/{created.PatientId}"; + using var response = await fixture.Client.PutAsJsonAsync(path, new + { + name, contactInfo = "new@example.test" + }); + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Equal(created, await fixture.Client.GetFromJsonAsync(path)); + } +}