Compare commits
12
Commits
ebf50827d6
...
b6342afdad
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b6342afdad | ||
|
|
076e675c81 | ||
|
|
cc76c9bde4 | ||
|
|
a0a9e2e9b9 | ||
|
|
d21005b6fe | ||
|
|
5aefe52853 | ||
|
|
ce03038ce1 | ||
|
|
ac6b42f32e | ||
|
|
3bfa7ea149 | ||
|
|
cfacaa0c24 | ||
|
|
5996481081 | ||
|
|
0ce9b2b168 |
No files matched your search
File renamed without changes.
File renamed without changes.
@@ -1,5 +1,6 @@
|
|||||||
<Solution>
|
<Solution>
|
||||||
<Folder Name="/src/">
|
<Folder Name="/src/">
|
||||||
|
<Project Path="src/HealthOverviewService/HealthOverviewService.csproj" />
|
||||||
<Project Path="src/InsightsService/InsightsService.csproj" />
|
<Project Path="src/InsightsService/InsightsService.csproj" />
|
||||||
<Project Path="src/ApiGateway/ApiGateway.csproj" />
|
<Project Path="src/ApiGateway/ApiGateway.csproj" />
|
||||||
<Project Path="src/PatientProfileService/PatientProfileService.csproj" />
|
<Project Path="src/PatientProfileService/PatientProfileService.csproj" />
|
||||||
|
|||||||
@@ -1,8 +1,33 @@
|
|||||||
ASPNETCORE_ENVIRONMENT=Production
|
ASPNETCORE_ENVIRONMENT=Production
|
||||||
Services__PatientProfile__BaseUrl=http://patient-profile.example.test:5081/
|
Services__PatientProfile__BaseUrl=https://patient-profile.example.test:5081/
|
||||||
ASPNETCORE_URLS=https://0.0.0.0:5443
|
ASPNETCORE_URLS=https://0.0.0.0:5443
|
||||||
Kestrel__Certificates__Default__Path=/etc/healthapp/gateway.pfx
|
Kestrel__Certificates__Default__Path=/etc/healthapp/gateway.pfx
|
||||||
Kestrel__Certificates__Default__Password=REPLACE_ME
|
Kestrel__Certificates__Default__Password=REPLACE_ME
|
||||||
Services__Observation__BaseUrl=http://observation.example.test:5082/
|
Services__Observation__BaseUrl=https://observation.example.test:5082/
|
||||||
|
|
||||||
Services__Insights__BaseUrl=http://insights.example.test:5083/
|
Services__Insights__BaseUrl=https://insights.example.test:5083/
|
||||||
|
|
||||||
|
Authentication__KeyDirectory=/var/lib/healthapp-api-gateway/keys
|
||||||
|
Authentication__TokenLifetimeMinutes=30
|
||||||
|
# Account identifiers support ASCII letters, digits, hyphen and underscore.
|
||||||
|
Authentication__Accounts__0__AccountId=example-patient
|
||||||
|
Authentication__Accounts__0__Role=Patient
|
||||||
|
Authentication__Accounts__0__PasswordHash=REPLACE_WITH_ASPNET_CORE_PASSWORD_HASH
|
||||||
|
# Use distinct randomly generated credentials of at least 32 characters.
|
||||||
|
Services__PatientProfile__Key=REPLACE_ME
|
||||||
|
Services__Observation__Key=REPLACE_ME
|
||||||
|
Services__Insights__Key=REPLACE_ME
|
||||||
|
InternalAccess__Observation__Key=REPLACE_ME
|
||||||
|
InternalAccess__Insights__Key=REPLACE_ME
|
||||||
|
|
||||||
|
# Pre-created professional credentials and read-only patient assignments.
|
||||||
|
Authentication__Accounts__1__AccountId=example_professional
|
||||||
|
Authentication__Accounts__1__Role=HealthcareProfessional
|
||||||
|
Authentication__Accounts__1__PasswordHash=REPLACE_WITH_ASPNET_CORE_PASSWORD_HASH
|
||||||
|
# Replace the synthetic identifier below with a created patient's identifier.
|
||||||
|
# Restart the gateway after changing assignments. Omit assignments for an empty list.
|
||||||
|
Access__ProfessionalAssignments__example_professional__0=00000000-0000-0000-0000-000000000001
|
||||||
|
|
||||||
|
Services__HealthOverview__BaseUrl=https://health-overview.example.test:5084/
|
||||||
|
Services__HealthOverview__Key=REPLACE_ME
|
||||||
|
InternalAccess__HealthOverview__Key=REPLACE_ME
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
ASPNETCORE_ENVIRONMENT=Production
|
||||||
|
ASPNETCORE_URLS=https://0.0.0.0:5084
|
||||||
|
Services__ApiGateway__BaseUrl=https://gateway.example.test:5443/
|
||||||
|
|
||||||
|
InternalAccess__GatewayKey=REPLACE_ME
|
||||||
|
Kestrel__Certificates__Default__Path=/etc/healthapp/service.pfx
|
||||||
|
Kestrel__Certificates__Default__Password=REPLACE_ME
|
||||||
|
Services__ApiGateway__Key=REPLACE_ME
|
||||||
@@ -1,3 +1,8 @@
|
|||||||
ASPNETCORE_ENVIRONMENT=Production
|
ASPNETCORE_ENVIRONMENT=Production
|
||||||
ASPNETCORE_URLS=http://0.0.0.0:5083
|
ASPNETCORE_URLS=https://0.0.0.0:5083
|
||||||
Services__ApiGateway__BaseUrl=https://gateway.example.test:5443/
|
Services__ApiGateway__BaseUrl=https://gateway.example.test:5443/
|
||||||
|
|
||||||
|
InternalAccess__GatewayKey=REPLACE_ME
|
||||||
|
Kestrel__Certificates__Default__Path=/etc/healthapp/service.pfx
|
||||||
|
Kestrel__Certificates__Default__Password=REPLACE_ME
|
||||||
|
Services__ApiGateway__Key=REPLACE_ME
|
||||||
@@ -1,4 +1,9 @@
|
|||||||
ASPNETCORE_ENVIRONMENT=Production
|
ASPNETCORE_ENVIRONMENT=Production
|
||||||
ASPNETCORE_URLS=http://0.0.0.0:5082
|
ASPNETCORE_URLS=https://0.0.0.0:5082
|
||||||
ConnectionStrings__ObservationDatabase="Host=database.example.test;Port=5432;Database=observations;Username=observations;Password=REPLACE_ME"
|
ConnectionStrings__ObservationDatabase="Host=database.example.test;Port=5432;Database=observations;Username=observations;Password=REPLACE_ME"
|
||||||
Services__ApiGateway__BaseUrl=https://gateway.example.test:5443/
|
Services__ApiGateway__BaseUrl=https://gateway.example.test:5443/
|
||||||
|
|
||||||
|
InternalAccess__GatewayKey=REPLACE_ME
|
||||||
|
Kestrel__Certificates__Default__Path=/etc/healthapp/service.pfx
|
||||||
|
Kestrel__Certificates__Default__Password=REPLACE_ME
|
||||||
|
Services__ApiGateway__Key=REPLACE_ME
|
||||||
@@ -1,3 +1,7 @@
|
|||||||
ASPNETCORE_ENVIRONMENT=Production
|
ASPNETCORE_ENVIRONMENT=Production
|
||||||
ASPNETCORE_URLS=http://0.0.0.0:5081
|
ASPNETCORE_URLS=https://0.0.0.0:5081
|
||||||
ConnectionStrings__PatientDatabase="Host=database.example.test;Port=5432;Database=patient_profile;Username=patient_profile;Password=REPLACE_ME"
|
ConnectionStrings__PatientDatabase="Host=database.example.test;Port=5432;Database=patient_profile;Username=patient_profile;Password=REPLACE_ME"
|
||||||
|
|
||||||
|
InternalAccess__GatewayKey=REPLACE_ME
|
||||||
|
Kestrel__Certificates__Default__Path=/etc/healthapp/service.pfx
|
||||||
|
Kestrel__Certificates__Default__Password=REPLACE_ME
|
||||||
@@ -4,6 +4,8 @@ Wants=network-online.target
|
|||||||
After=network-online.target
|
After=network-online.target
|
||||||
|
|
||||||
[Service]
|
[Service]
|
||||||
|
StateDirectory=healthapp-api-gateway
|
||||||
|
StateDirectoryMode=0700
|
||||||
Type=simple
|
Type=simple
|
||||||
User=healthapp
|
User=healthapp
|
||||||
Group=healthapp
|
Group=healthapp
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=HealthApp Health Overview service
|
||||||
|
Wants=network-online.target
|
||||||
|
After=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=healthapp
|
||||||
|
Group=healthapp
|
||||||
|
WorkingDirectory=/opt/healthapp/health-overview
|
||||||
|
ExecStart=/usr/bin/dotnet /opt/healthapp/health-overview/HealthOverviewService.dll
|
||||||
|
EnvironmentFile=/etc/healthapp/health-overview.env
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=5
|
||||||
|
KillSignal=SIGINT
|
||||||
|
TimeoutStopSec=30
|
||||||
|
SyslogIdentifier=healthapp-health-overview
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
# US-13 prototype authentication
|
||||||
|
|
||||||
|
The API gateway authenticates pre-created externally configured accounts. Login is
|
||||||
|
`POST /api/authentication/login` with `accountId` and `password`. A successful JSON
|
||||||
|
response contains `accessToken`, `tokenType: Bearer`, `expiresIn`, `accountId` and
|
||||||
|
trusted `role`; it contains no patient data or refresh token. Send the access token
|
||||||
|
as `Authorization: Bearer <token>` on subsequent patient-data requests. Invalid
|
||||||
|
credentials return the same `401` response for unknown accounts and wrong passwords.
|
||||||
|
Login responses cannot be cached. General measurement guidance remains public.
|
||||||
|
|
||||||
|
## Mechanism and configuration
|
||||||
|
|
||||||
|
Use ASP.NET Core's built-in bearer authentication and ticket protection, with
|
||||||
|
Data Protection's application name `HealthApp.ApiGateway` and the bearer purpose.
|
||||||
|
Tokens are opaque protected authentication tickets, not JWTs. The configured key
|
||||||
|
ring and framework purpose enforce the gateway trust boundary; only account ID,
|
||||||
|
role and authentication properties are protected inside a token. Do not share the
|
||||||
|
key ring with other applications/services. No custom cryptography, identity
|
||||||
|
microservice, account database or refresh-token mechanism is introduced.
|
||||||
|
|
||||||
|
The gateway verifies passwords with ASP.NET Core `PasswordHasher` against
|
||||||
|
`Authentication:Accounts:<index>:{AccountId,Role,PasswordHash}`. Roles are `Patient`
|
||||||
|
or `HealthcareProfessional`, from trusted configuration. IDs support ASCII letters,
|
||||||
|
digits, hyphen and underscore, up to 128 characters. This keeps the internal account
|
||||||
|
lookup contract unambiguous. Provision credentials externally; no registration or
|
||||||
|
administration API is exposed. For provisioning, `tools/PasswordHash` reads a
|
||||||
|
password from standard input and emits its ASP.NET Core hash. Supply input securely
|
||||||
|
(e.g. redirect a permission-restricted temporary file), and protect the resulting
|
||||||
|
hash/configuration; neither belongs in Git. The tool needs no NuGet dependency.
|
||||||
|
|
||||||
|
`Authentication:TokenLifetimeMinutes` defaults to 30; supported range is 1–1440.
|
||||||
|
`Authentication:KeyDirectory` is required. Keep its contents persistent through
|
||||||
|
restart/deployment and readable only by the gateway service account. The systemd
|
||||||
|
unit provides a mode-0700 state directory; example configuration points into it.
|
||||||
|
Keys are protected by filesystem permissions in this Linux prototype. Removing
|
||||||
|
keys invalidates tokens; preserve them for restart continuity. Accounts and
|
||||||
|
configuration are loaded at startup; after disabling accounts or changing roles,
|
||||||
|
old tokens can remain valid until their expiry. Immediate revocation is outside
|
||||||
|
this story. Missing/invalid/expired tokens return `401`; authenticate again after
|
||||||
|
expiry. Credential validation is not repeated for each operation.
|
||||||
|
|
||||||
|
Before thesis measurement, record the lifetime, account/role mix, key persistence,
|
||||||
|
login frequency and expiry handling. Normally obtain tokens during workload setup
|
||||||
|
and reuse them; state explicitly whether login is measured. If tokens expire,
|
||||||
|
re-authentication is required. Keep these choices identical across variants. The
|
||||||
|
automated test helper logs in using real password verification and caches tokens;
|
||||||
|
its account-per-resource setup is not a prescribed measurement workload.
|
||||||
|
|
||||||
|
## Ownership and profile creation
|
||||||
|
|
||||||
|
The patient service owns the account association as `patient.account_id` with a
|
||||||
|
unique index. It remains application access data, outside tokens. The gateway
|
||||||
|
queries its protected `GET /api/patients/by-account/{accountId}` service API on each
|
||||||
|
request; that API is not forwarded as a public account-lookup route. An account
|
||||||
|
without a profile may log in and create one; its other own-data requests return
|
||||||
|
`404`. Patient operations are subject to the standard Patient authorization policy.
|
||||||
|
|
||||||
|
`GET /api/patients/me` retrieves the caller’s own associated profile without needing
|
||||||
|
to know its generated identifier, including after a creation response was lost.
|
||||||
|
It returns `404` before profile creation.
|
||||||
|
|
||||||
|
Profile creation derives `X-Account-Id` from the authenticated principal. The
|
||||||
|
gateway overwrites client input; the service accepts it only behind its gateway
|
||||||
|
credential. The profile and association are inserted in one atomic database save,
|
||||||
|
so failure rolls both back. The unique index arbitrates concurrent creation. A
|
||||||
|
completed creation, a retry after a lost response and a competing request cannot
|
||||||
|
create another profile; later attempts receive `409`. A retry after a failed
|
||||||
|
transaction may create the first profile. Profile identity remains persistent
|
||||||
|
through restarts. US-01's authenticated creation is included because US-13 depends
|
||||||
|
on a persistent, recoverable association.
|
||||||
|
|
||||||
|
Apply the new patient migration before startup. Existing profiles retain a null
|
||||||
|
account association rather than being assigned to an arbitrary account. They are
|
||||||
|
not accessible to patient accounts until a trusted deployment operator explicitly
|
||||||
|
associates them with pre-created accounts. For synthetic experiments, provision a
|
||||||
|
fresh database via the authenticated creation flow. Do not infer ownership from
|
||||||
|
caller-supplied IDs or automatically assign historical profiles.
|
||||||
|
|
||||||
|
For observation-ID requests, the gateway reads the observation through its service
|
||||||
|
API to obtain the actual patient, then compares that owner with the account's
|
||||||
|
profile. Requests for another patient's information receive an empty `404`, the
|
||||||
|
same as missing data, without forwarding writes or revealing existence. Failed
|
||||||
|
ownership lookups fail closed with `502`/`504`. Tokens do not cache ownership.
|
||||||
|
Healthcare-professional logins establish a trusted role. US-14 now permits reads
|
||||||
|
of assigned patients and the caller’s own assignment list; all professional writes
|
||||||
|
are rejected before forwarding. Trend/overview endpoints remain unimplemented; the
|
||||||
|
gateway's default authentication policy also protects future patient endpoints,
|
||||||
|
which must retain ownership checks when added.
|
||||||
|
|
||||||
|
## Service and transport protection
|
||||||
|
|
||||||
|
Use HTTPS for client and service traffic. Outside Development, gateway and service
|
||||||
|
requests over HTTP are rejected and outgoing service endpoints must be HTTPS.
|
||||||
|
Certificates use ordinary Kestrel configuration and normal platform validation;
|
||||||
|
no insecure certificate handler is provided. Configure DNS names/certificates for
|
||||||
|
separate machines. Development permits plain HTTP for local automated tests only.
|
||||||
|
Use network firewall rules to restrict service ports to trusted hosts as an
|
||||||
|
additional deployment control; the application credential checks still enforce
|
||||||
|
protection if a client reaches a service directly.
|
||||||
|
|
||||||
|
Each service requires `InternalAccess:GatewayKey`, a random credential of at least
|
||||||
|
32 characters, matched by the gateway's `Services:<service>:Key`. Services reject
|
||||||
|
missing/wrong keys and client bearer tokens. Use distinct per-service gateway keys
|
||||||
|
in deployment. The gateway forwards only its own configured key; arbitrary client
|
||||||
|
identity headers are not propagated. Do not log these headers or tokens.
|
||||||
|
|
||||||
|
Observation and Insights each have a separate `Services:ApiGateway:Key`, matched
|
||||||
|
by the gateway's `InternalAccess:Observation:Key` or `InternalAccess:Insights:Key`.
|
||||||
|
Their `X-Service-Key` authenticates an internal principal using an ASP.NET Core
|
||||||
|
handler. The Observation principal can only GET a patient profile by patient ID;
|
||||||
|
the Insights principal can only GET observation history by patient ID. Neither
|
||||||
|
can create/update/delete profiles or observations, query account associations or
|
||||||
|
call other protected routes. Both internal read paths still pass through the
|
||||||
|
gateway. Service credentials are separate from patient tokens and token keys.
|
||||||
|
Use independent random values, restrictive configuration-file permissions and
|
||||||
|
HTTPS; placeholder values in deployment examples deliberately fail validation.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
The acceptance suite exercises real HTTP hosts and PostgreSQL migrations. It covers
|
||||||
|
US-13's login, own access, missing/invalid/expired tokens, no-profile behaviour,
|
||||||
|
cross-patient reads/writes and observation ownership. Additional checks cover
|
||||||
|
caller-supplied account spoofing, persistent tokens/associations after restart,
|
||||||
|
duplicate/concurrent creation, unavailable-service recovery, direct service bypass,
|
||||||
|
internal-credential route restrictions, professional creation rejection and public
|
||||||
|
US-15 guidance. Existing functional assertions run through real token login rather
|
||||||
|
than a production authentication bypass.
|
||||||
|
|
||||||
|
Framework reference:
|
||||||
|
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.bearertoken.bearertokenoptions?view=aspnetcore-10.0
|
||||||
|
|
||||||
|
## US-14 professional assignments
|
||||||
|
|
||||||
|
Predefine assignments in the gateway's external `Access:ProfessionalAssignments`
|
||||||
|
configuration, keyed by the stable professional account identifier. For example:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"Access": {
|
||||||
|
"ProfessionalAssignments": {
|
||||||
|
"example_professional": [
|
||||||
|
"00000000-0000-0000-0000-000000000001",
|
||||||
|
"00000000-0000-0000-0000-000000000002"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Use actual patient identifiers returned by authenticated profile creation. The
|
||||||
|
example UUIDs are placeholders. A professional can have several patients, and
|
||||||
|
several professionals can share a patient. Duplicate identifiers are treated as
|
||||||
|
one assignment. Empty identifiers are rejected at startup. An omitted account
|
||||||
|
entry means no assignments. Configure that account's role and password hash
|
||||||
|
separately under `Authentication:Accounts`; assignments never grant a role.
|
||||||
|
|
||||||
|
`GET /api/professionals/me/patients` requires the HealthcareProfessional policy and
|
||||||
|
returns an array of `{ "patientId": "..." }` entries, in deterministic identifier
|
||||||
|
order. It lists only the caller's configured assignments, without fetching patient
|
||||||
|
records. No assignments returns `[]`. Missing profiles remain assigned identifiers;
|
||||||
|
retrieving their data follows the existing missing-resource behaviour. Caller
|
||||||
|
query parameters or identity headers cannot select another professional's list.
|
||||||
|
Patient accounts cannot use this endpoint.
|
||||||
|
|
||||||
|
Professional GET requests to existing patient profiles, observations (including
|
||||||
|
recorded legacy context), history, latest observations and numerical insight
|
||||||
|
require membership in the caller's assignment set. Observation-ID requests resolve
|
||||||
|
the actual owning patient via the protected Observation API; a supplied patient ID
|
||||||
|
is not evidence of assignment. Unassigned reads return an empty `404`, preserving
|
||||||
|
the same non-disclosure convention as patient access. Assigned missing data follows
|
||||||
|
the existing retrieval contracts. All professional POST/PUT/PATCH/DELETE requests
|
||||||
|
are rejected with `403` before ownership lookups or forwarding. There is no
|
||||||
|
assignment-management API or additional database/service.
|
||||||
|
|
||||||
|
Assignments are loaded at gateway startup, outside tokens and credential
|
||||||
|
validation. Restart the gateway after changing its external configuration. Existing
|
||||||
|
valid tokens then use the new assignment data. Empty lists need no upstream service;
|
||||||
|
observation-owner lookup failures fail closed with `502`/`504`.
|
||||||
|
|
||||||
|
The US-14 tests exercise actual login, multiple and shared assignments, empty lists,
|
||||||
|
assigned/unassigned reads, preserved context, missing resources, every existing
|
||||||
|
write route, invalid and expired credentials, patient-role rejection, assignment
|
||||||
|
changes across restart and unavailable ownership lookup. Trend and overview
|
||||||
|
endpoints now have equivalent owner/assignment routing and integration tests under
|
||||||
|
US-11/US-12. Structured observation context is included in authorized reads.
|
||||||
|
|
||||||
|
## US-12 Overview service access
|
||||||
|
|
||||||
|
The gateway requires `Services:HealthOverview:BaseUrl` and `Services:HealthOverview:Key`.
|
||||||
|
The latter matches Overview's `InternalAccess:GatewayKey` and protects direct access.
|
||||||
|
Overview's outgoing `Services:ApiGateway:Key` matches `InternalAccess:HealthOverview:Key`
|
||||||
|
on the gateway. Use distinct randomly generated credentials of at least 32 characters
|
||||||
|
for each direction and service; load them externally. Production endpoints use HTTPS.
|
||||||
|
|
||||||
|
The HealthOverview service identity is restricted to GET patient profiles, GET latest
|
||||||
|
overall observations and GET numerical insights. It cannot retrieve history, trends or
|
||||||
|
another overview, or perform writes. It establishes no client identity. The gateway
|
||||||
|
checks client ownership/professional assignment before forwarding the outer request.
|
||||||
|
Internal credentials are trusted service credentials and must remain inaccessible to clients.
|
||||||
|
Overview adds no authentication framework, shared runtime library or persistence.
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using System.Security.Claims;
|
||||||
|
using ApiGateway.Security;
|
||||||
|
using Microsoft.AspNetCore.Authentication;
|
||||||
|
using Microsoft.AspNetCore.Authentication.BearerToken;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
namespace ApiGateway.Controllers;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/authentication")]
|
||||||
|
public sealed class AuthenticationController(PrototypeAccounts accounts,
|
||||||
|
IOptionsMonitor<BearerTokenOptions> options) : ControllerBase
|
||||||
|
{
|
||||||
|
[AllowAnonymous]
|
||||||
|
[HttpPost("login")]
|
||||||
|
public IActionResult Login(LoginRequest request)
|
||||||
|
{
|
||||||
|
var account = accounts.Verify(request.AccountId, request.Password);
|
||||||
|
if (account is null) return Unauthorized(new { title = "Invalid credentials." });
|
||||||
|
var principal = new ClaimsPrincipal(new ClaimsIdentity(new[]
|
||||||
|
{
|
||||||
|
new Claim(ClaimTypes.NameIdentifier, account.AccountId),
|
||||||
|
new Claim(ClaimTypes.Role, account.Role)
|
||||||
|
}, "Bearer"));
|
||||||
|
var settings = options.Get("Bearer");
|
||||||
|
var expiry = settings.TimeProvider!.GetUtcNow().Add(settings.BearerTokenExpiration);
|
||||||
|
// Use the framework's ticket protector and bearer validation. No refresh endpoint/token.
|
||||||
|
var ticket = new AuthenticationTicket(principal, new AuthenticationProperties { ExpiresUtc = expiry }, "Bearer");
|
||||||
|
Response.Headers.CacheControl = "no-store";
|
||||||
|
Response.Headers.Pragma = "no-cache";
|
||||||
|
return Ok(new { accessToken = settings.BearerTokenProtector.Protect(ticket), tokenType = "Bearer",
|
||||||
|
expiresIn = (long)settings.BearerTokenExpiration.TotalSeconds, accountId = account.AccountId, role = account.Role });
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record LoginRequest([Required] string AccountId, [Required] string Password);
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
namespace ApiGateway.Controllers;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("api")]
|
||||||
|
public sealed class HealthOverviewController(IHttpClientFactory clients) : ControllerBase
|
||||||
|
{
|
||||||
|
[HttpGet("patients/{patientId:guid}/overview")]
|
||||||
|
public Task GetOverview(Guid patientId, CancellationToken cancellationToken) =>
|
||||||
|
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/overview{Request.QueryString}", cancellationToken);
|
||||||
|
|
||||||
|
private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
using var request = new HttpRequestMessage(method, path);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var upstream = await clients.CreateClient("HealthOverview")
|
||||||
|
.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
||||||
|
Response.StatusCode = (int)upstream.StatusCode;
|
||||||
|
Response.ContentType = upstream.Content.Headers.ContentType?.ToString();
|
||||||
|
if (upstream.Headers.Location is { } location)
|
||||||
|
Response.Headers.Location = location.IsAbsoluteUri ? location.PathAndQuery : location.ToString();
|
||||||
|
await upstream.Content.CopyToAsync(Response.Body, cancellationToken);
|
||||||
|
}
|
||||||
|
catch (HttpRequestException)
|
||||||
|
{
|
||||||
|
await WriteFailureAsync(StatusCodes.Status502BadGateway);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
await WriteFailureAsync(StatusCodes.Status504GatewayTimeout);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Task WriteFailureAsync(int status)
|
||||||
|
{
|
||||||
|
if (Response.HasStarted)
|
||||||
|
{
|
||||||
|
HttpContext.Abort();
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
Response.Clear();
|
||||||
|
return Results.Problem(statusCode: status, title: "Health overview service is unavailable.")
|
||||||
|
.ExecuteAsync(HttpContext);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,10 @@ public sealed class InsightsController(IHttpClientFactory clients) : ControllerB
|
|||||||
public Task GetSummary(Guid patientId, CancellationToken cancellationToken) =>
|
public Task GetSummary(Guid patientId, CancellationToken cancellationToken) =>
|
||||||
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/insights{Request.QueryString}", cancellationToken);
|
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/insights{Request.QueryString}", cancellationToken);
|
||||||
|
|
||||||
|
[HttpGet("patients/{patientId:guid}/trends")]
|
||||||
|
public Task GetTrend(Guid patientId, CancellationToken cancellationToken) =>
|
||||||
|
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/trends{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);
|
||||||
|
|||||||
@@ -18,6 +18,10 @@ public sealed class ObservationController(IHttpClientFactory clients) : Controll
|
|||||||
public Task UpdateObservation(Guid observationId, CancellationToken cancellationToken) =>
|
public Task UpdateObservation(Guid observationId, CancellationToken cancellationToken) =>
|
||||||
ForwardAsync(HttpMethod.Put, $"api/observations/{observationId}", 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}")]
|
[HttpGet("observations/{observationId:guid}")]
|
||||||
public Task GetObservation(Guid observationId, CancellationToken cancellationToken) =>
|
public Task GetObservation(Guid observationId, CancellationToken cancellationToken) =>
|
||||||
ForwardAsync(HttpMethod.Get, $"api/observations/{observationId}", 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)
|
private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
using var request = new HttpRequestMessage(method, path);
|
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);
|
request.Content = new StreamContent(Request.Body);
|
||||||
if (Request.ContentType is not null)
|
if (Request.ContentType is not null)
|
||||||
@@ -46,6 +50,9 @@ public sealed class ObservationController(IHttpClientFactory clients) : Controll
|
|||||||
.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
||||||
Response.StatusCode = (int)upstream.StatusCode;
|
Response.StatusCode = (int)upstream.StatusCode;
|
||||||
Response.ContentType = upstream.Content.Headers.ContentType?.ToString();
|
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)
|
if (upstream.Headers.Location is { } location)
|
||||||
Response.Headers.Location = location.IsAbsoluteUri ? location.PathAndQuery : location.ToString();
|
Response.Headers.Location = location.IsAbsoluteUri ? location.PathAndQuery : location.ToString();
|
||||||
await upstream.Content.CopyToAsync(Response.Body, cancellationToken);
|
await upstream.Content.CopyToAsync(Response.Body, cancellationToken);
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using System.Security.Claims;
|
||||||
|
|
||||||
namespace ApiGateway.Controllers;
|
namespace ApiGateway.Controllers;
|
||||||
|
|
||||||
@@ -10,6 +11,10 @@ public sealed class PatientController(IHttpClientFactory clients) : ControllerBa
|
|||||||
public Task CreatePatient(CancellationToken cancellationToken) =>
|
public Task CreatePatient(CancellationToken cancellationToken) =>
|
||||||
ForwardAsync(HttpMethod.Post, "api/patients", cancellationToken);
|
ForwardAsync(HttpMethod.Post, "api/patients", cancellationToken);
|
||||||
|
|
||||||
|
[HttpGet("me")]
|
||||||
|
public Task GetOwnPatient(CancellationToken cancellationToken) =>
|
||||||
|
ForwardAsync(HttpMethod.Get, "api/patients/by-account/" + Uri.EscapeDataString(User.FindFirstValue(ClaimTypes.NameIdentifier)!), cancellationToken);
|
||||||
|
|
||||||
[HttpGet("{patientId:guid}")]
|
[HttpGet("{patientId:guid}")]
|
||||||
public Task GetPatient(Guid patientId, CancellationToken cancellationToken) =>
|
public Task GetPatient(Guid patientId, CancellationToken cancellationToken) =>
|
||||||
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}", cancellationToken);
|
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}", cancellationToken);
|
||||||
@@ -21,6 +26,8 @@ public sealed class PatientController(IHttpClientFactory clients) : ControllerBa
|
|||||||
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);
|
||||||
|
if (method == HttpMethod.Post)
|
||||||
|
request.Headers.Add("X-Account-Id", User.FindFirstValue(ClaimTypes.NameIdentifier));
|
||||||
if (method == HttpMethod.Post || method == HttpMethod.Put)
|
if (method == HttpMethod.Post || method == HttpMethod.Put)
|
||||||
{
|
{
|
||||||
request.Content = new StreamContent(Request.Body);
|
request.Content = new StreamContent(Request.Body);
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
using System.Security.Claims;
|
||||||
|
using ApiGateway.Security;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
namespace ApiGateway.Controllers;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Authorize(Policy = "HealthcareProfessional")]
|
||||||
|
[Route("api/professionals/me/patients")]
|
||||||
|
public sealed class ProfessionalController(ProfessionalAssignments assignments) : ControllerBase
|
||||||
|
{
|
||||||
|
[HttpGet]
|
||||||
|
public IActionResult GetAssignedPatients() =>
|
||||||
|
Ok(assignments.GetPatients(User.FindFirstValue(ClaimTypes.NameIdentifier)!)
|
||||||
|
.Select(patientId => new { patientId }));
|
||||||
|
}
|
||||||
@@ -1,3 +1,10 @@
|
|||||||
|
using ApiGateway.Security;
|
||||||
|
using Microsoft.AspNetCore.Authentication;
|
||||||
|
using Microsoft.AspNetCore.Authentication.BearerToken;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.DataProtection;
|
||||||
|
using Microsoft.AspNetCore.DataProtection.KeyManagement;
|
||||||
|
using Microsoft.AspNetCore.DataProtection.Repositories;
|
||||||
namespace ApiGateway;
|
namespace ApiGateway;
|
||||||
|
|
||||||
public class Program
|
public class Program
|
||||||
@@ -7,23 +14,90 @@ public class Program
|
|||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
builder.Services.AddControllers();
|
builder.Services.AddControllers();
|
||||||
builder.Services.AddProblemDetails();
|
builder.Services.AddProblemDetails();
|
||||||
|
builder.Services.AddSingleton<PrototypeAccounts>();
|
||||||
|
builder.Services.AddSingleton<ProfessionalAssignments>();
|
||||||
|
builder.Services.AddAuthentication("ClientOrService")
|
||||||
|
.AddPolicyScheme("ClientOrService", null, options => options.ForwardDefaultSelector = context =>
|
||||||
|
context.Request.Headers.ContainsKey("X-Service-Key") ? "InternalService" : "Bearer")
|
||||||
|
.AddBearerToken("Bearer", options =>
|
||||||
|
{
|
||||||
|
options.BearerTokenExpiration = TimeSpan.FromMinutes(builder.Configuration.GetValue("Authentication:TokenLifetimeMinutes", 30));
|
||||||
|
})
|
||||||
|
.AddScheme<AuthenticationSchemeOptions, InternalServiceAuthenticationHandler>("InternalService", null);
|
||||||
|
builder.Services.AddAuthorization(options =>
|
||||||
|
{
|
||||||
|
options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
|
||||||
|
options.AddPolicy("Patient", policy => policy.RequireRole("Patient").RequireClaim(System.Security.Claims.ClaimTypes.NameIdentifier));
|
||||||
|
options.AddPolicy("HealthcareProfessional", policy => policy.RequireRole("HealthcareProfessional")
|
||||||
|
.RequireClaim(System.Security.Claims.ClaimTypes.NameIdentifier));
|
||||||
|
});
|
||||||
|
builder.Services.AddDataProtection().SetApplicationName("HealthApp.ApiGateway");
|
||||||
|
builder.Services.AddOptions<KeyManagementOptions>().Configure<IConfiguration, ILoggerFactory>((options, configuration, logger) =>
|
||||||
|
{
|
||||||
|
var keyDirectory = configuration["Authentication:KeyDirectory"];
|
||||||
|
if (string.IsNullOrWhiteSpace(keyDirectory)) throw new InvalidOperationException("Authentication:KeyDirectory is required.");
|
||||||
|
options.XmlRepository = new FileSystemXmlRepository(new DirectoryInfo(keyDirectory), logger);
|
||||||
|
});
|
||||||
builder.Services.AddHttpClient("PatientProfile", (services, client) =>
|
builder.Services.AddHttpClient("PatientProfile", (services, client) =>
|
||||||
client.BaseAddress = GetBaseUri(services.GetRequiredService<IConfiguration>(), "PatientProfile"))
|
{
|
||||||
|
var configuration = services.GetRequiredService<IConfiguration>();
|
||||||
|
client.BaseAddress = GetBaseUri(configuration, "PatientProfile");
|
||||||
|
client.DefaultRequestHeaders.Add("X-Gateway-Key", configuration["Services:PatientProfile:Key"]);
|
||||||
|
})
|
||||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||||
|
|
||||||
builder.Services.AddHttpClient("Observation", (services, client) =>
|
builder.Services.AddHttpClient("Observation", (services, client) =>
|
||||||
client.BaseAddress = GetBaseUri(services.GetRequiredService<IConfiguration>(), "Observation"))
|
{
|
||||||
|
var configuration = services.GetRequiredService<IConfiguration>();
|
||||||
|
client.BaseAddress = GetBaseUri(configuration, "Observation");
|
||||||
|
client.DefaultRequestHeaders.Add("X-Gateway-Key", configuration["Services:Observation:Key"]);
|
||||||
|
})
|
||||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||||
|
|
||||||
builder.Services.AddHttpClient("Insights", (services, client) =>
|
builder.Services.AddHttpClient("Insights", (services, client) =>
|
||||||
client.BaseAddress = GetBaseUri(services.GetRequiredService<IConfiguration>(), "Insights"))
|
{
|
||||||
|
var configuration = services.GetRequiredService<IConfiguration>();
|
||||||
|
client.BaseAddress = GetBaseUri(configuration, "Insights");
|
||||||
|
client.DefaultRequestHeaders.Add("X-Gateway-Key", configuration["Services:Insights:Key"]);
|
||||||
|
})
|
||||||
|
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||||
|
|
||||||
|
builder.Services.AddHttpClient("HealthOverview", (services, client) =>
|
||||||
|
{
|
||||||
|
var configuration = services.GetRequiredService<IConfiguration>();
|
||||||
|
client.BaseAddress = GetBaseUri(configuration, "HealthOverview");
|
||||||
|
client.DefaultRequestHeaders.Add("X-Gateway-Key", configuration["Services:HealthOverview:Key"]);
|
||||||
|
})
|
||||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||||
|
|
||||||
var app = builder.Build();
|
var app = builder.Build();
|
||||||
_ = GetBaseUri(app.Configuration, "PatientProfile");
|
_ = GetBaseUri(app.Configuration, "PatientProfile");
|
||||||
_ = GetBaseUri(app.Configuration, "Observation");
|
_ = GetBaseUri(app.Configuration, "Observation");
|
||||||
_ = GetBaseUri(app.Configuration, "Insights");
|
_ = GetBaseUri(app.Configuration, "Insights");
|
||||||
|
_ = GetBaseUri(app.Configuration, "HealthOverview");
|
||||||
|
foreach (var key in new[] { "Services:PatientProfile:Key", "Services:Observation:Key", "Services:Insights:Key", "Services:HealthOverview:Key", "InternalAccess:HealthOverview:Key", "InternalAccess:Observation:Key", "InternalAccess:Insights:Key" })
|
||||||
|
if (string.IsNullOrWhiteSpace(app.Configuration[key]) || app.Configuration[key]!.Length < 32)
|
||||||
|
throw new InvalidOperationException($"{key} must contain at least 32 characters.");
|
||||||
|
if (string.IsNullOrWhiteSpace(app.Configuration["Authentication:KeyDirectory"]))
|
||||||
|
throw new InvalidOperationException("Authentication:KeyDirectory is required.");
|
||||||
|
var lifetime = app.Configuration.GetValue("Authentication:TokenLifetimeMinutes", 30);
|
||||||
|
if (lifetime <= 0 || lifetime > 1440) throw new InvalidOperationException("Token lifetime must be between 1 and 1440 minutes.");
|
||||||
|
if (!app.Environment.IsDevelopment())
|
||||||
|
foreach (var service in new[] { "PatientProfile", "Observation", "Insights", "HealthOverview" })
|
||||||
|
if (GetBaseUri(app.Configuration, service).Scheme != "https")
|
||||||
|
throw new InvalidOperationException("Production service endpoints must use HTTPS.");
|
||||||
|
_ = app.Services.GetRequiredService<PrototypeAccounts>();
|
||||||
|
_ = app.Services.GetRequiredService<ProfessionalAssignments>();
|
||||||
app.UseExceptionHandler();
|
app.UseExceptionHandler();
|
||||||
|
app.Use(async (context, next) =>
|
||||||
|
{
|
||||||
|
if (!app.Environment.IsDevelopment() && !context.Request.IsHttps) { context.Response.StatusCode = 400; return; }
|
||||||
|
await next(context);
|
||||||
|
});
|
||||||
|
app.UseRouting();
|
||||||
|
app.UseAuthentication();
|
||||||
|
app.UseAuthorization();
|
||||||
|
app.UseMiddleware<PatientAccessMiddleware>();
|
||||||
app.MapControllers();
|
app.MapControllers();
|
||||||
app.Run();
|
app.Run();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
using System.Security.Claims;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Encodings.Web;
|
||||||
|
using Microsoft.AspNetCore.Authentication;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
namespace ApiGateway.Security;
|
||||||
|
|
||||||
|
public sealed class InternalServiceAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||||
|
ILoggerFactory logger, UrlEncoder encoder, IConfiguration configuration)
|
||||||
|
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||||
|
{
|
||||||
|
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||||
|
{
|
||||||
|
var supplied = Request.Headers["X-Service-Key"].ToString();
|
||||||
|
foreach (var service in new[] { "Observation", "Insights", "HealthOverview" })
|
||||||
|
{
|
||||||
|
var expected = configuration[$"InternalAccess:{service}:Key"]!;
|
||||||
|
if (CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(supplied), Encoding.UTF8.GetBytes(expected)))
|
||||||
|
{
|
||||||
|
var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Role, "Service"),
|
||||||
|
new Claim(ClaimTypes.NameIdentifier, service) }, Scheme.Name);
|
||||||
|
return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme.Name)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Task.FromResult(AuthenticateResult.Fail("Invalid service credential."));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Security.Claims;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
|
||||||
|
namespace ApiGateway.Security;
|
||||||
|
|
||||||
|
public sealed class PatientAccessMiddleware(RequestDelegate next)
|
||||||
|
{
|
||||||
|
public async Task InvokeAsync(HttpContext context, IHttpClientFactory clients, IAuthorizationService authorization,
|
||||||
|
ProfessionalAssignments assignments)
|
||||||
|
{
|
||||||
|
if (context.GetEndpoint()?.Metadata.GetMetadata<IAllowAnonymous>() is not null)
|
||||||
|
{
|
||||||
|
await next(context);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (context.User.Identity?.IsAuthenticated != true) { context.Response.StatusCode = 401; return; }
|
||||||
|
var route = context.Request.Path.Value ?? "";
|
||||||
|
var segments = route.Trim('/').Split('/');
|
||||||
|
if (context.User.IsInRole("Service"))
|
||||||
|
{
|
||||||
|
var service = context.User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||||
|
var patientRoute = segments.Length >= 3 && segments[0] == "api" && segments[1] == "patients"
|
||||||
|
&& Guid.TryParse(segments[2], out _);
|
||||||
|
var allowed = context.Request.Method == "GET" && patientRoute && (service switch
|
||||||
|
{
|
||||||
|
"Observation" => segments.Length == 3,
|
||||||
|
"Insights" => segments.Length == 4 && segments[3] == "observations",
|
||||||
|
"HealthOverview" => segments.Length == 3 ||
|
||||||
|
(segments.Length == 4 && segments[3] == "insights") ||
|
||||||
|
(segments.Length == 5 && segments[3] == "observations" && segments[4] == "latest"),
|
||||||
|
_ => false
|
||||||
|
});
|
||||||
|
if (!allowed) { context.Response.StatusCode = 403; return; }
|
||||||
|
await next(context);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var professional = (await authorization.AuthorizeAsync(context.User, "HealthcareProfessional")).Succeeded;
|
||||||
|
if (professional)
|
||||||
|
{
|
||||||
|
if (context.Request.Method != "GET") { context.Response.StatusCode = 403; return; }
|
||||||
|
if (route.Equals("/api/professionals/me/patients", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
await next(context);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (!(await authorization.AuthorizeAsync(context.User, "Patient")).Succeeded)
|
||||||
|
{ context.Response.StatusCode = 403; return; }
|
||||||
|
if (!professional &&
|
||||||
|
((route.Equals("/api/patients", StringComparison.OrdinalIgnoreCase) && context.Request.Method == "POST")
|
||||||
|
|| (route.Equals("/api/patients/me", StringComparison.OrdinalIgnoreCase) && context.Request.Method == "GET")))
|
||||||
|
{
|
||||||
|
await next(context);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var accountId = context.User.FindFirstValue(ClaimTypes.NameIdentifier)!;
|
||||||
|
Guid? patientId = null;
|
||||||
|
if (!professional)
|
||||||
|
{
|
||||||
|
using var ownResponse = await clients.CreateClient("PatientProfile").GetAsync(
|
||||||
|
"api/patients/by-account/" + Uri.EscapeDataString(accountId), context.RequestAborted);
|
||||||
|
if (ownResponse.StatusCode == HttpStatusCode.NotFound) { context.Response.StatusCode = 404; return; }
|
||||||
|
ownResponse.EnsureSuccessStatusCode();
|
||||||
|
using var own = JsonDocument.Parse(await ownResponse.Content.ReadAsStringAsync(context.RequestAborted));
|
||||||
|
patientId = own.RootElement.GetProperty("patientId").GetGuid();
|
||||||
|
}
|
||||||
|
Guid requestedPatient;
|
||||||
|
if (segments.Length >= 3 && segments[0] == "api" && segments[1] == "patients"
|
||||||
|
&& Guid.TryParse(segments[2], out requestedPatient)) { }
|
||||||
|
else if (segments.Length == 3 && segments[0] == "api" && segments[1] == "observations"
|
||||||
|
&& Guid.TryParse(segments[2], out var observationId))
|
||||||
|
{
|
||||||
|
using var response = await clients.CreateClient("Observation").GetAsync($"api/observations/{observationId}", context.RequestAborted);
|
||||||
|
if (response.StatusCode == HttpStatusCode.NotFound) { context.Response.StatusCode = 404; return; }
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
using var observation = JsonDocument.Parse(await response.Content.ReadAsStringAsync(context.RequestAborted));
|
||||||
|
requestedPatient = observation.RootElement.GetProperty("patientId").GetGuid();
|
||||||
|
}
|
||||||
|
else { context.Response.StatusCode = 404; return; }
|
||||||
|
var permitted = professional ? assignments.IsAssigned(accountId, requestedPatient) : requestedPatient == patientId;
|
||||||
|
if (!permitted) { context.Response.StatusCode = 404; return; }
|
||||||
|
await next(context);
|
||||||
|
}
|
||||||
|
catch (HttpRequestException) { await Results.Problem(statusCode: 502, title: "Ownership lookup is unavailable.").ExecuteAsync(context); }
|
||||||
|
catch (OperationCanceledException) when (!context.RequestAborted.IsCancellationRequested)
|
||||||
|
{ await Results.Problem(statusCode: 504, title: "Ownership lookup timed out.").ExecuteAsync(context); }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
namespace ApiGateway.Security;
|
||||||
|
|
||||||
|
// Application access data, separate from credentials and token contents.
|
||||||
|
public sealed class ProfessionalAssignments
|
||||||
|
{
|
||||||
|
private readonly Dictionary<string, Guid[]> assignments;
|
||||||
|
|
||||||
|
public ProfessionalAssignments(IConfiguration configuration)
|
||||||
|
{
|
||||||
|
assignments = configuration.GetSection("Access:ProfessionalAssignments")
|
||||||
|
.Get<Dictionary<string, Guid[]>>() ?? new(StringComparer.Ordinal);
|
||||||
|
foreach (var accountId in assignments.Keys.ToArray())
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(accountId) || assignments[accountId].Any(id => id == Guid.Empty))
|
||||||
|
throw new InvalidOperationException("Professional assignments require an account identifier and nonempty patient identifiers.");
|
||||||
|
assignments[accountId] = assignments[accountId].Distinct().Order().ToArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public IReadOnlyList<Guid> GetPatients(string accountId) =>
|
||||||
|
assignments.TryGetValue(accountId, out var patients) ? Array.AsReadOnly(patients) : Array.Empty<Guid>();
|
||||||
|
|
||||||
|
public bool IsAssigned(string accountId, Guid patientId) => GetPatients(accountId).Contains(patientId);
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
using Microsoft.AspNetCore.Identity;
|
||||||
|
|
||||||
|
namespace ApiGateway.Security;
|
||||||
|
|
||||||
|
public sealed class PrototypeAccount
|
||||||
|
{
|
||||||
|
public string AccountId { get; set; } = "";
|
||||||
|
public string Role { get; set; } = "Patient";
|
||||||
|
public string PasswordHash { get; set; } = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class PrototypeAccounts
|
||||||
|
{
|
||||||
|
private readonly Dictionary<string, PrototypeAccount> accounts;
|
||||||
|
private readonly PasswordHasher<PrototypeAccount> hasher = new();
|
||||||
|
private readonly PrototypeAccount dummy = new() { AccountId = "invalid" };
|
||||||
|
|
||||||
|
public PrototypeAccounts(IConfiguration configuration)
|
||||||
|
{
|
||||||
|
var configured = configuration.GetSection("Authentication:Accounts").Get<PrototypeAccount[]>() ?? [];
|
||||||
|
if (configured.Length == 0 || configured.Any(a => string.IsNullOrWhiteSpace(a.AccountId) || a.AccountId.Length > 128 || a.AccountId.Any(c => !char.IsAsciiLetterOrDigit(c) && c is not ('-' or '_')) || string.IsNullOrWhiteSpace(a.PasswordHash)
|
||||||
|
|| a.Role is not ("Patient" or "HealthcareProfessional")))
|
||||||
|
throw new InvalidOperationException("Authentication accounts require an identifier, password hash and supported role.");
|
||||||
|
accounts = configured.ToDictionary(a => a.AccountId, StringComparer.Ordinal);
|
||||||
|
dummy.PasswordHash = hasher.HashPassword(dummy, Guid.NewGuid().ToString());
|
||||||
|
}
|
||||||
|
|
||||||
|
public PrototypeAccount? Verify(string accountId, string password)
|
||||||
|
{
|
||||||
|
var known = accounts.TryGetValue(accountId, out var account);
|
||||||
|
account ??= dummy;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = hasher.VerifyHashedPassword(account, account.PasswordHash, password);
|
||||||
|
return known && result != PasswordVerificationResult.Failed ? account : null;
|
||||||
|
}
|
||||||
|
catch (FormatException) { return null; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using HealthOverviewService.Clients;
|
||||||
|
using HealthOverviewService.Contracts;
|
||||||
|
|
||||||
|
namespace HealthOverviewService.Application;
|
||||||
|
|
||||||
|
public sealed class HealthOverviewApplicationService(PatientProfileServiceClient patients,
|
||||||
|
ObservationServiceClient observations, InsightsServiceClient insights)
|
||||||
|
{
|
||||||
|
public async Task<HealthOverviewDto?> GetOverviewAsync(Guid patientId, DateTime from, DateTime to,
|
||||||
|
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));
|
||||||
|
Validator.ValidateObject(selection, new ValidationContext(selection), validateAllProperties: true);
|
||||||
|
var patient = await patients.GetPatientAsync(patientId, cancellationToken);
|
||||||
|
if (patient is null) return null;
|
||||||
|
var latest = await observations.GetLatestAsync(patientId, cancellationToken);
|
||||||
|
var insight = await insights.GetSummaryAsync(patientId, from, to, selection, cancellationToken);
|
||||||
|
return new(patient, latest, insight, from, to, selection, insight?.ContributingCount ?? 0,
|
||||||
|
"Latest overall observation for the patient, independent of the insight period and context selections. " +
|
||||||
|
"Its recorded context applies only to that observation, not to the insight's contributing observations.",
|
||||||
|
insight is null ? "No calculated insight is available: no observations match the requested period and insight selection." :
|
||||||
|
"The insight uses the requested period and context selection only. " + insight.ContextExplanation);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DateTime NormalizeTimestamp(DateTime value) => DateTime.SpecifyKind(
|
||||||
|
value.Kind == DateTimeKind.Unspecified ? value : value.ToUniversalTime(), DateTimeKind.Unspecified);
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Net;
|
||||||
|
using System.Text.Json;
|
||||||
|
using HealthOverviewService.Contracts;
|
||||||
|
|
||||||
|
namespace HealthOverviewService.Clients;
|
||||||
|
|
||||||
|
public abstract class InsightsServiceClient
|
||||||
|
{
|
||||||
|
public abstract Task<HealthInsightDto?> GetSummaryAsync(Guid patientId, DateTime from, DateTime to, ContextSelection selection, CancellationToken cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class HttpInsightsServiceClient(HttpClient client) : InsightsServiceClient
|
||||||
|
{
|
||||||
|
public override async Task<HealthInsightDto?> GetSummaryAsync(Guid patientId, DateTime from, DateTime to, ContextSelection selection, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var path = $"api/patients/{patientId}/insights";
|
||||||
|
path += $"?from={Uri.EscapeDataString(from.ToString("O", CultureInfo.InvariantCulture))}&to={Uri.EscapeDataString(to.ToString("O", CultureInfo.InvariantCulture))}";
|
||||||
|
if (selection.Setting is not null) path += "&setting=" + Uri.EscapeDataString(selection.Setting);
|
||||||
|
if (selection.ActivityCondition is not null) path += "&activityCondition=" + Uri.EscapeDataString(selection.ActivityCondition);
|
||||||
|
|
||||||
|
using var response = await client.GetAsync(path, cancellationToken);
|
||||||
|
if (response.StatusCode == HttpStatusCode.NotFound) return null;
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
return await response.Content.ReadFromJsonAsync<HealthInsightDto>(cancellationToken)
|
||||||
|
?? throw new JsonException("Empty upstream response.");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Net;
|
||||||
|
using System.Text.Json;
|
||||||
|
using HealthOverviewService.Contracts;
|
||||||
|
|
||||||
|
namespace HealthOverviewService.Clients;
|
||||||
|
|
||||||
|
public abstract class ObservationServiceClient
|
||||||
|
{
|
||||||
|
public abstract Task<ObservationDto?> GetLatestAsync(Guid patientId, CancellationToken cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class HttpObservationServiceClient(HttpClient client) : ObservationServiceClient
|
||||||
|
{
|
||||||
|
public override async Task<ObservationDto?> GetLatestAsync(Guid patientId, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var path = $"api/patients/{patientId}/observations/latest";
|
||||||
|
using var response = await client.GetAsync(path, cancellationToken);
|
||||||
|
if (response.StatusCode == HttpStatusCode.NotFound) return null;
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
return await response.Content.ReadFromJsonAsync<ObservationDto>(cancellationToken)
|
||||||
|
?? throw new JsonException("Empty upstream response.");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Net;
|
||||||
|
using System.Text.Json;
|
||||||
|
using HealthOverviewService.Contracts;
|
||||||
|
|
||||||
|
namespace HealthOverviewService.Clients;
|
||||||
|
|
||||||
|
public abstract class PatientProfileServiceClient
|
||||||
|
{
|
||||||
|
public abstract Task<PatientDto?> GetPatientAsync(Guid patientId, CancellationToken cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class HttpPatientProfileServiceClient(HttpClient client) : PatientProfileServiceClient
|
||||||
|
{
|
||||||
|
public override async Task<PatientDto?> GetPatientAsync(Guid patientId, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var path = $"api/patients/{patientId}";
|
||||||
|
using var response = await client.GetAsync(path, cancellationToken);
|
||||||
|
if (response.StatusCode == HttpStatusCode.NotFound) return null;
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
return await response.Content.ReadFromJsonAsync<PatientDto>(cancellationToken)
|
||||||
|
?? throw new JsonException("Empty upstream response.");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace HealthOverviewService.Contracts;
|
||||||
|
|
||||||
|
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; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record PatientDto(Guid PatientId, string Name, DateOnly DateOfBirth, string? ContactInfo);
|
||||||
|
public sealed record MeasurementContextDto(string Setting, string ActivityCondition, decimal? RestDurationMinutes,
|
||||||
|
string? BodyPosition, string? MeasuredArm, string? DeviceDetails, string? CuffDetails, string? AdditionalCircumstances);
|
||||||
|
public sealed record ObservationDto(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||||
|
int Systolic, int Diastolic, int Pulse, string? Context, string? Note, MeasurementContextDto MeasurementContext);
|
||||||
|
public sealed record HealthInsightDto(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
|
||||||
|
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
|
||||||
|
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic,
|
||||||
|
ContextSelection AppliedSelection, int ContributingCount, string ContextExplanation);
|
||||||
|
public sealed record HealthOverviewDto(PatientDto Patient, ObservationDto? LatestObservation, HealthInsightDto? Insight,
|
||||||
|
DateTime PeriodStart, DateTime PeriodEnd, ContextSelection InsightSelection, int InsightContributingCount,
|
||||||
|
string LatestObservationBasis, string InsightExplanation);
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
using HealthOverviewService.Application;
|
||||||
|
using HealthOverviewService.Contracts;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||||
|
|
||||||
|
namespace HealthOverviewService.Controllers;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/patients/{patientId:guid}/overview")]
|
||||||
|
public sealed class HealthOverviewController(HealthOverviewApplicationService service) : ControllerBase
|
||||||
|
{
|
||||||
|
[HttpGet]
|
||||||
|
public async Task<ActionResult<HealthOverviewDto>> GetOverview(Guid patientId,
|
||||||
|
[FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to,
|
||||||
|
[FromQuery] ContextSelection selection, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await service.GetOverviewAsync(patientId, from, to, selection, cancellationToken);
|
||||||
|
return result is null ? Problem(statusCode: 404, title: "Patient does not exist.") : Ok(result);
|
||||||
|
}
|
||||||
|
catch (ArgumentException)
|
||||||
|
{
|
||||||
|
ModelState.AddModelError(nameof(to), "The end time must not be earlier than the start time.");
|
||||||
|
return ValidationProblem(ModelState);
|
||||||
|
}
|
||||||
|
catch (HttpRequestException)
|
||||||
|
{ return Problem(statusCode: 502, title: "Overview source service is unavailable."); }
|
||||||
|
catch (System.Text.Json.JsonException)
|
||||||
|
{ return Problem(statusCode: 502, title: "Overview source response is invalid."); }
|
||||||
|
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||||
|
{ return Problem(statusCode: 504, title: "Overview source request timed out."); }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
</PropertyGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using HealthOverviewService.Application;
|
||||||
|
using HealthOverviewService.Clients;
|
||||||
|
|
||||||
|
namespace HealthOverviewService;
|
||||||
|
|
||||||
|
public class Program
|
||||||
|
{
|
||||||
|
public static void Main(string[] args)
|
||||||
|
{
|
||||||
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
builder.Services.AddControllers();
|
||||||
|
builder.Services.AddProblemDetails();
|
||||||
|
builder.Services.AddScoped<HealthOverviewApplicationService>();
|
||||||
|
builder.Services.AddHttpClient<PatientProfileServiceClient, HttpPatientProfileServiceClient>((services, client) =>
|
||||||
|
{
|
||||||
|
var configuration = services.GetRequiredService<IConfiguration>();
|
||||||
|
client.BaseAddress = GetGatewayUri(configuration);
|
||||||
|
var serviceKey = configuration["Services:ApiGateway:Key"];
|
||||||
|
if (string.IsNullOrWhiteSpace(serviceKey) || serviceKey.Length < 32)
|
||||||
|
throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters.");
|
||||||
|
client.DefaultRequestHeaders.Add("X-Service-Key", serviceKey);
|
||||||
|
})
|
||||||
|
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||||
|
builder.Services.AddHttpClient<ObservationServiceClient, HttpObservationServiceClient>((services, client) =>
|
||||||
|
{
|
||||||
|
var configuration = services.GetRequiredService<IConfiguration>();
|
||||||
|
client.BaseAddress = GetGatewayUri(configuration);
|
||||||
|
var serviceKey = configuration["Services:ApiGateway:Key"];
|
||||||
|
if (string.IsNullOrWhiteSpace(serviceKey) || serviceKey.Length < 32)
|
||||||
|
throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters.");
|
||||||
|
client.DefaultRequestHeaders.Add("X-Service-Key", serviceKey);
|
||||||
|
})
|
||||||
|
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||||
|
builder.Services.AddHttpClient<InsightsServiceClient, HttpInsightsServiceClient>((services, client) =>
|
||||||
|
{
|
||||||
|
var configuration = services.GetRequiredService<IConfiguration>();
|
||||||
|
client.BaseAddress = GetGatewayUri(configuration);
|
||||||
|
var serviceKey = configuration["Services:ApiGateway:Key"];
|
||||||
|
if (string.IsNullOrWhiteSpace(serviceKey) || serviceKey.Length < 32)
|
||||||
|
throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters.");
|
||||||
|
client.DefaultRequestHeaders.Add("X-Service-Key", serviceKey);
|
||||||
|
})
|
||||||
|
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||||
|
var app = builder.Build();
|
||||||
|
if (!app.Environment.IsDevelopment() && GetGatewayUri(app.Configuration).Scheme != "https")
|
||||||
|
throw new InvalidOperationException("Production gateway endpoints must use HTTPS.");
|
||||||
|
_ = GetGatewayUri(app.Configuration);
|
||||||
|
var outgoingKey = app.Configuration["Services:ApiGateway:Key"];
|
||||||
|
if (string.IsNullOrWhiteSpace(outgoingKey) || outgoingKey.Length < 32)
|
||||||
|
throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters.");
|
||||||
|
var gatewayKey = app.Configuration["InternalAccess:GatewayKey"];
|
||||||
|
if (string.IsNullOrWhiteSpace(gatewayKey) || gatewayKey.Length < 32)
|
||||||
|
throw new InvalidOperationException("InternalAccess:GatewayKey must contain at least 32 characters.");
|
||||||
|
app.UseExceptionHandler();
|
||||||
|
app.Use(async (context, next) =>
|
||||||
|
{
|
||||||
|
var supplied = context.Request.Headers["X-Gateway-Key"].ToString();
|
||||||
|
if ((!app.Environment.IsDevelopment() && !context.Request.IsHttps) ||
|
||||||
|
!CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(supplied), Encoding.UTF8.GetBytes(gatewayKey)))
|
||||||
|
{ context.Response.StatusCode = 401; return; }
|
||||||
|
await next(context);
|
||||||
|
});
|
||||||
|
app.MapControllers();
|
||||||
|
app.Run();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Uri GetGatewayUri(IConfiguration configuration)
|
||||||
|
{
|
||||||
|
var endpoint = configuration["Services:ApiGateway:BaseUrl"];
|
||||||
|
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) ||
|
||||||
|
(uri.Scheme != "http" && uri.Scheme != "https") || uri.AbsolutePath != "/" ||
|
||||||
|
!string.IsNullOrEmpty(uri.Query) || !string.IsNullOrEmpty(uri.Fragment) || !string.IsNullOrEmpty(uri.UserInfo))
|
||||||
|
throw new InvalidOperationException("Services:ApiGateway:BaseUrl must be an HTTP(S) origin URL.");
|
||||||
|
return uri;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"Logging": {
|
||||||
|
"LogLevel": {
|
||||||
|
"Default": "Information",
|
||||||
|
"Microsoft.AspNetCore": "Warning"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
using InsightsService.Clients;
|
using InsightsService.Clients;
|
||||||
using InsightsService.Domain;
|
using InsightsService.Domain;
|
||||||
|
|
||||||
@@ -6,14 +7,27 @@ namespace InsightsService.Application;
|
|||||||
public sealed class InsightsApplicationService(ObservationServiceClient observations, InsightCalculator calculator)
|
public sealed class InsightsApplicationService(ObservationServiceClient observations, InsightCalculator calculator)
|
||||||
{
|
{
|
||||||
public async Task<HealthInsight?> GetSummaryAsync(Guid patientId, DateTime from, DateTime to,
|
public async Task<HealthInsight?> GetSummaryAsync(Guid patientId, DateTime from, DateTime to,
|
||||||
CancellationToken cancellationToken)
|
ContextSelection selection, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
from = NormalizeTimestamp(from);
|
from = NormalizeTimestamp(from);
|
||||||
to = NormalizeTimestamp(to);
|
to = NormalizeTimestamp(to);
|
||||||
if (to < from)
|
if (to < from)
|
||||||
throw new ArgumentException("The end time must not be earlier than the start time.", nameof(to));
|
throw new ArgumentException("The end time must not be earlier than the start time.", nameof(to));
|
||||||
var history = await observations.GetByPeriodAsync(patientId, from, to, cancellationToken);
|
Validator.ValidateObject(selection, new ValidationContext(selection), validateAllProperties: true);
|
||||||
return calculator.CalculateSummary(patientId, from, to, history);
|
var history = await observations.GetByPeriodAsync(patientId, from, to, selection, cancellationToken);
|
||||||
|
return calculator.CalculateSummary(patientId, from, to, history, selection);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<TrendAssessment> GetTrendAsync(Guid patientId, DateTime from, DateTime to,
|
||||||
|
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));
|
||||||
|
Validator.ValidateObject(selection, new ValidationContext(selection), validateAllProperties: true);
|
||||||
|
var history = await observations.GetByPeriodAsync(patientId, from, to, selection, cancellationToken);
|
||||||
|
return calculator.CalculateTrend(patientId, from, to, history, selection);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static DateTime NormalizeTimestamp(DateTime value) =>
|
private static DateTime NormalizeTimestamp(DateTime value) =>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using InsightsService.Domain;
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using InsightsService.Contracts;
|
using InsightsService.Contracts;
|
||||||
|
|
||||||
@@ -6,11 +7,14 @@ namespace InsightsService.Clients;
|
|||||||
public sealed class HttpObservationServiceClient(HttpClient client) : ObservationServiceClient
|
public sealed class HttpObservationServiceClient(HttpClient client) : ObservationServiceClient
|
||||||
{
|
{
|
||||||
public async Task<List<ObservationDto>> GetByPeriodAsync(Guid patientId, DateTime from, DateTime to,
|
public async Task<List<ObservationDto>> GetByPeriodAsync(Guid patientId, DateTime from, DateTime to,
|
||||||
CancellationToken cancellationToken)
|
ContextSelection selection, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var start = Uri.EscapeDataString(from.ToString("O", CultureInfo.InvariantCulture));
|
var start = Uri.EscapeDataString(from.ToString("O", CultureInfo.InvariantCulture));
|
||||||
var end = Uri.EscapeDataString(to.ToString("O", CultureInfo.InvariantCulture));
|
var end = Uri.EscapeDataString(to.ToString("O", CultureInfo.InvariantCulture));
|
||||||
using var response = await client.GetAsync($"api/patients/{patientId}/observations?from={start}&to={end}",
|
var filters = "";
|
||||||
|
if (selection.Setting is not null) filters += "&setting=" + Uri.EscapeDataString(selection.Setting);
|
||||||
|
if (selection.ActivityCondition is not null) filters += "&activityCondition=" + Uri.EscapeDataString(selection.ActivityCondition);
|
||||||
|
using var response = await client.GetAsync($"api/patients/{patientId}/observations?from={start}&to={end}{filters}",
|
||||||
HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
||||||
response.EnsureSuccessStatusCode();
|
response.EnsureSuccessStatusCode();
|
||||||
return await response.Content.ReadFromJsonAsync<List<ObservationDto>>(cancellationToken)
|
return await response.Content.ReadFromJsonAsync<List<ObservationDto>>(cancellationToken)
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using InsightsService.Domain;
|
||||||
using InsightsService.Contracts;
|
using InsightsService.Contracts;
|
||||||
|
|
||||||
namespace InsightsService.Clients;
|
namespace InsightsService.Clients;
|
||||||
@@ -5,5 +6,5 @@ namespace InsightsService.Clients;
|
|||||||
public interface ObservationServiceClient
|
public interface ObservationServiceClient
|
||||||
{
|
{
|
||||||
Task<List<ObservationDto>> GetByPeriodAsync(Guid patientId, DateTime from, DateTime to,
|
Task<List<ObservationDto>> GetByPeriodAsync(Guid patientId, DateTime from, DateTime to,
|
||||||
CancellationToken cancellationToken);
|
ContextSelection selection, CancellationToken cancellationToken);
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
|
using InsightsService.Domain;
|
||||||
|
|
||||||
namespace InsightsService.Contracts;
|
namespace InsightsService.Contracts;
|
||||||
|
|
||||||
public sealed record HealthInsightDto(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
|
public sealed record HealthInsightDto(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
|
||||||
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
|
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
|
||||||
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic);
|
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic,
|
||||||
|
ContextSelection AppliedSelection, int ContributingCount, string ContextExplanation);
|
||||||
@@ -1,4 +1,8 @@
|
|||||||
namespace InsightsService.Contracts;
|
namespace InsightsService.Contracts;
|
||||||
|
|
||||||
public sealed record ObservationDto(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
public sealed record ObservationDto(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||||
int Systolic, int Diastolic, int Pulse);
|
int Systolic, int Diastolic, int Pulse, MeasurementContextDto? MeasurementContext = null,
|
||||||
|
string? Context = null, string? Note = null);
|
||||||
|
|
||||||
|
public sealed record MeasurementContextDto(string? Setting, string? ActivityCondition, decimal? RestDurationMinutes,
|
||||||
|
string? BodyPosition, string? MeasuredArm, string? DeviceDetails, string? CuffDetails, string? AdditionalCircumstances);
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using InsightsService.Domain;
|
||||||
using InsightsService.Application;
|
using InsightsService.Application;
|
||||||
using InsightsService.Contracts;
|
using InsightsService.Contracts;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
@@ -12,16 +13,17 @@ public sealed class InsightsController(InsightsApplicationService service) : Con
|
|||||||
[HttpGet]
|
[HttpGet]
|
||||||
public async Task<ActionResult<HealthInsightDto>> GetSummary(Guid patientId,
|
public async Task<ActionResult<HealthInsightDto>> GetSummary(Guid patientId,
|
||||||
[FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to,
|
[FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to,
|
||||||
CancellationToken cancellationToken)
|
[FromQuery] ContextSelection selection, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var insight = await service.GetSummaryAsync(patientId, from, to, cancellationToken);
|
var insight = await service.GetSummaryAsync(patientId, from, to, selection, cancellationToken);
|
||||||
return insight is null
|
return insight is null
|
||||||
? Problem(statusCode: StatusCodes.Status404NotFound, title: "Insufficient observation data for calculation.")
|
? Problem(statusCode: StatusCodes.Status404NotFound, title: "Insufficient observation data for calculation.")
|
||||||
: Ok(new HealthInsightDto(insight.PatientId, insight.PeriodStart, insight.PeriodEnd,
|
: Ok(new HealthInsightDto(insight.PatientId, insight.PeriodStart, insight.PeriodEnd,
|
||||||
insight.AverageSystolic, insight.AverageDiastolic, insight.AveragePulse,
|
insight.AverageSystolic, insight.AverageDiastolic, insight.AveragePulse,
|
||||||
insight.MinSystolic, insight.MaxSystolic, insight.MinDiastolic, insight.MaxDiastolic));
|
insight.MinSystolic, insight.MaxSystolic, insight.MinDiastolic, insight.MaxDiastolic,
|
||||||
|
insight.AppliedSelection, insight.ContributingCount, insight.ContextExplanation));
|
||||||
}
|
}
|
||||||
catch (ArgumentException)
|
catch (ArgumentException)
|
||||||
{
|
{
|
||||||
@@ -41,4 +43,32 @@ public sealed class InsightsController(InsightsApplicationService service) : Con
|
|||||||
return Problem(statusCode: StatusCodes.Status504GatewayTimeout, title: "Observation history timed out.");
|
return Problem(statusCode: StatusCodes.Status504GatewayTimeout, title: "Observation history timed out.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
[HttpGet("/api/patients/{patientId:guid}/trends")]
|
||||||
|
public async Task<ActionResult<TrendAssessment>> GetTrend(Guid patientId,
|
||||||
|
[FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to,
|
||||||
|
[FromQuery] ContextSelection selection, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return Ok(await service.GetTrendAsync(patientId, from, to, selection, cancellationToken));
|
||||||
|
}
|
||||||
|
catch (ArgumentException)
|
||||||
|
{
|
||||||
|
ModelState.AddModelError(nameof(to), "The end time must not be earlier than the start time.");
|
||||||
|
return ValidationProblem(ModelState);
|
||||||
|
}
|
||||||
|
catch (HttpRequestException)
|
||||||
|
{
|
||||||
|
return Problem(statusCode: StatusCodes.Status502BadGateway, title: "Observation history is unavailable.");
|
||||||
|
}
|
||||||
|
catch (System.Text.Json.JsonException)
|
||||||
|
{
|
||||||
|
return Problem(statusCode: StatusCodes.Status502BadGateway, title: "Observation history response is invalid.");
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
return Problem(statusCode: StatusCodes.Status504GatewayTimeout, title: "Observation history timed out.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace InsightsService.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; }
|
||||||
|
}
|
||||||
@@ -2,4 +2,5 @@ namespace InsightsService.Domain;
|
|||||||
|
|
||||||
public sealed record HealthInsight(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
|
public sealed record HealthInsight(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
|
||||||
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
|
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
|
||||||
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic);
|
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic,
|
||||||
|
ContextSelection AppliedSelection, int ContributingCount, string ContextExplanation);
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using InsightsService.Contracts;
|
||||||
|
|
||||||
|
namespace InsightsService.Domain;
|
||||||
|
|
||||||
|
public sealed partial class InsightCalculator
|
||||||
|
{
|
||||||
|
private const string GeneralLimits = "General reference thresholds are not individual treatment targets. " +
|
||||||
|
"This is a descriptive assessment, not a diagnosis or medication recommendation. " +
|
||||||
|
"Symptoms, treatment, training, risk factors and measurement technique are not established by these observations.";
|
||||||
|
|
||||||
|
public TrendAssessment CalculateTrend(Guid patientId, DateTime from, DateTime to,
|
||||||
|
IReadOnlyList<ObservationDto> observations, ContextSelection selection)
|
||||||
|
{
|
||||||
|
var comparability = AssessComparability(observations);
|
||||||
|
return new(patientId, from, to, selection, observations.Count, comparability,
|
||||||
|
AssessMeasurement("Systolic", "mmHg", observations, o => o.Systolic, comparability),
|
||||||
|
AssessMeasurement("Diastolic", "mmHg", observations, o => o.Diastolic, comparability),
|
||||||
|
AssessMeasurement("Pulse", "beats/min", observations, o => o.Pulse, comparability));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static MeasurementAssessment AssessMeasurement(string metric, string unit,
|
||||||
|
IReadOnlyList<ObservationDto> observations, Func<ObservationDto, int> value,
|
||||||
|
ComparabilityAssessment comparability)
|
||||||
|
{
|
||||||
|
if (observations.Count == 0)
|
||||||
|
return new(metric, unit, null, null, null, null, 0, "Unavailable", "Unavailable", null, 0,
|
||||||
|
null, "No matching observations; insufficient observation data for trend calculation.",
|
||||||
|
null, "Unavailable: no matching observations.", "CannotInterpret", GeneralLimits);
|
||||||
|
|
||||||
|
// Collapse timestamp ties for temporal calculations only; descriptive levels retain every observation.
|
||||||
|
var points = observations.GroupBy(o => o.MeasuredAt).OrderBy(g => g.Key)
|
||||||
|
.Select(g => (Time: g.Key, Value: g.Average(o => (decimal)value(o)))).ToArray();
|
||||||
|
var minimum = observations.Min(value);
|
||||||
|
var maximum = observations.Max(value);
|
||||||
|
var mean = observations.Average(o => (decimal)value(o));
|
||||||
|
var signs = points.Zip(points.Skip(1), (a, b) => Math.Sign(b.Value - a.Value))
|
||||||
|
.Where(s => s != 0).ToArray();
|
||||||
|
var reversals = signs.Zip(signs.Skip(1), (a, b) => a != b ? 1 : 0).Sum();
|
||||||
|
var direction = points.Length < 2 ? "Unavailable" : signs.Length == 0 ? "NoClearDirection" :
|
||||||
|
reversals > 0 ? "Mixed" : signs[0] > 0 ? "Increasing" : "Decreasing";
|
||||||
|
decimal? slope = null;
|
||||||
|
var overall = "Unavailable";
|
||||||
|
decimal? totalChange = null;
|
||||||
|
if (points.Length >= 2)
|
||||||
|
{
|
||||||
|
// Scale time to [0,1] before OLS, avoiding extreme timestamp magnitudes.
|
||||||
|
var span = (decimal)(points[^1].Time.Ticks - points[0].Time.Ticks);
|
||||||
|
var xs = points.Select(p => (p.Time.Ticks - points[0].Time.Ticks) / span).ToArray();
|
||||||
|
var xMean = xs.Average();
|
||||||
|
var yMean = points.Average(p => p.Value);
|
||||||
|
var numerator = points.Select((p, i) => (xs[i] - xMean) * (p.Value - yMean)).Sum();
|
||||||
|
var denominator = xs.Sum(x => (x - xMean) * (x - xMean));
|
||||||
|
var scaledSlope = numerator / denominator;
|
||||||
|
slope = scaledSlope / (span / TimeSpan.TicksPerDay);
|
||||||
|
overall = scaledSlope > 0 ? "Increasing" : scaledSlope < 0 ? "Decreasing" : "NoClearDirection";
|
||||||
|
totalChange = points.Zip(points.Skip(1), (a, b) => Math.Abs(b.Value - a.Value)).Sum();
|
||||||
|
}
|
||||||
|
var numerical = $"All {observations.Count} observations: mean {Format(mean)}, minimum {minimum}, maximum {maximum}, " +
|
||||||
|
$"range {maximum - minimum} {unit}. " + (points.Length < 2
|
||||||
|
? "Direction is unavailable: at least two distinct measurement timestamps are required."
|
||||||
|
: $"Temporal direction: {direction}; full-period least-squares direction: {overall}; " +
|
||||||
|
$"{reversals} reversal(s). Timestamp ties use arithmetic means. " +
|
||||||
|
$"Total successive change is {Format(totalChange!.Value)} {unit}.") +
|
||||||
|
" Range and successive change describe observed variation; no clinical stability classification is made.";
|
||||||
|
|
||||||
|
var reference = SelectReference(metric, observations, comparability);
|
||||||
|
var comparison = "Unavailable: known, non-conflicting resting conditions" +
|
||||||
|
(metric == "Pulse" ? "" : " and a single Home or Clinic setting") + " are required; recorded inadequate preparation also limits applicability.";
|
||||||
|
var interpretation = "CannotInterpret";
|
||||||
|
var hint = "Numerical changes alone do not establish favourable or concerning development.";
|
||||||
|
if (reference is not null)
|
||||||
|
{
|
||||||
|
var above = observations.Count(o => IsHigh(value(o), reference));
|
||||||
|
var below = observations.Count(o => IsLow(value(o), reference));
|
||||||
|
comparison = $"Descriptive mean {Format(mean)} {unit}; {above} observation(s) " +
|
||||||
|
$"{reference.UpperComparison} {Format(reference.UpperBoundary)} {unit}" +
|
||||||
|
(reference.LowerBoundary is { } lower ? $"; {below} observation(s) < {Format(lower)} {unit}." : ".") +
|
||||||
|
" This period does not establish a guideline diagnostic measurement protocol. " + reference.Limitation;
|
||||||
|
if (points.Length >= 2 && comparability.Status == "SupportedRecordedComparability")
|
||||||
|
{
|
||||||
|
var first = points[0].Value;
|
||||||
|
var last = points[^1].Value;
|
||||||
|
if (reversals > 0 && (above > 0 || below > 0))
|
||||||
|
{
|
||||||
|
interpretation = "Mixed";
|
||||||
|
hint = "Reversing movements and excursions outside the cited reference boundaries coexist; " +
|
||||||
|
"an overall slope does not establish consistent improvement or deterioration.";
|
||||||
|
}
|
||||||
|
else if (direction == "Decreasing" && IsHigh(first, reference) &&
|
||||||
|
!IsLow(last, reference) && below == 0 && (metric == "Pulse" || IsHigh(last, reference)))
|
||||||
|
{
|
||||||
|
interpretation = "PotentiallyFavourable";
|
||||||
|
hint = "Movement away from initially high levels towards the cited reference boundary may be favourable. " +
|
||||||
|
"This is a cautious inference from the source's reference comparison, not a clinical decision rule. " +
|
||||||
|
(IsHigh(last, reference) ? "The latest timestamp mean remains above or at the high boundary." :
|
||||||
|
"Reaching the reference interval does not establish an individual treatment target or good health.");
|
||||||
|
}
|
||||||
|
else if (metric == "Pulse" && direction == "Increasing" && IsLow(first, reference) &&
|
||||||
|
!IsHigh(last, reference) && above == 0)
|
||||||
|
{
|
||||||
|
interpretation = "PotentiallyFavourable";
|
||||||
|
hint = "Movement away from initially low resting pulse towards the reference interval may be favourable, " +
|
||||||
|
"but low pulse may be physiological in trained people. This is a cautious inference, not a clinical rule. " +
|
||||||
|
(IsLow(last, reference) ? "The latest timestamp mean remains below the lower boundary." :
|
||||||
|
"Being within these boundaries does not establish good health.");
|
||||||
|
}
|
||||||
|
else if (above > 0 || below > 0)
|
||||||
|
{
|
||||||
|
interpretation = "PotentiallyConcerning";
|
||||||
|
hint = "Observed levels outside the cited reference boundaries may warrant clinical review. " +
|
||||||
|
"Limited variation does not establish healthy levels, and a decrease into low resting pulse " +
|
||||||
|
"is not automatically favourable. The cause and individual significance cannot be determined here.";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
hint = "The recorded context supports this limited reference comparison, but " +
|
||||||
|
(points.Length < 2 ? "temporal direction is unavailable. " :
|
||||||
|
"missing or differing conditions limit interpretation of the combined trajectory. ") +
|
||||||
|
"An outside-reference value is not dismissed because preparation information is incomplete.";
|
||||||
|
}
|
||||||
|
return new(metric, unit, Round(mean), minimum, maximum, maximum - minimum, points.Length,
|
||||||
|
direction, overall, slope is { } s ? Math.Round(s, 6, MidpointRounding.AwayFromZero) : null,
|
||||||
|
reversals, totalChange is { } change ? Round(change) : null, numerical, reference,
|
||||||
|
comparison, interpretation, hint + " " + comparability.Explanation + " " + GeneralLimits);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ClinicalReference? SelectReference(string metric, IReadOnlyList<ObservationDto> observations,
|
||||||
|
ComparabilityAssessment comparability)
|
||||||
|
{
|
||||||
|
if (comparability.Conflicts.Count > 0 ||
|
||||||
|
observations.Any(o => o.MeasurementContext?.ActivityCondition != "AtRest")) return null;
|
||||||
|
if (metric == "Pulse")
|
||||||
|
return new("Recorded resting pulse", 50, "<", 100, ">",
|
||||||
|
[new("Patienthåndbogen: Bradykardi (langsom puls)",
|
||||||
|
"https://www.sundhed.dk/borger/patienthaandbogen/hjerte-og-blodkar/sygdomme/hjertearytmier/bradykardi-langsom-puls/",
|
||||||
|
"2025-09-02", "2026-10-05"),
|
||||||
|
new("Patienthåndbogen: Hurtig puls (takykardi)",
|
||||||
|
"https://www.sundhed.dk/borger/patienthaandbogen/hjerte-og-blodkar/sygdomme/hjertearytmier/takykardier-hurtig-puls/",
|
||||||
|
"2025-05-12", "2026-10-05")],
|
||||||
|
"These are resting-rate reference boundaries, not a diagnosis, a universal normal range or a treatment target. " +
|
||||||
|
"Low pulse can be physiological in trained people; age, fitness, symptoms and medicines affect applicability.");
|
||||||
|
var settings = observations.Select(o => o.MeasurementContext?.Setting).Distinct().ToArray();
|
||||||
|
if (settings.Length != 1 || settings[0] is not ("Home" or "Clinic")) return null;
|
||||||
|
// Known inadequate rest prevents even a provisional resting-pressure comparison.
|
||||||
|
if (observations.Any(o => o.MeasurementContext?.RestDurationMinutes is < 5)) return null;
|
||||||
|
if (observations.Any(o => !string.IsNullOrWhiteSpace(o.MeasurementContext?.BodyPosition) &&
|
||||||
|
!new[] { "seated", "sitting", "siddende" }.Contains(o.MeasurementContext!.BodyPosition!.Trim(), StringComparer.OrdinalIgnoreCase)))
|
||||||
|
return null;
|
||||||
|
var threshold = metric == "Systolic" ? (settings[0] == "Home" ? 135 : 140) :
|
||||||
|
(settings[0] == "Home" ? 85 : 90);
|
||||||
|
return new($"Recorded {settings[0]} resting blood pressure", null, null, threshold, ">=",
|
||||||
|
[new("Lægehåndbogen: Højt blodtryk",
|
||||||
|
"https://www.sundhed.dk/sundhedsfaglig/laegehaandbogen/hjerte-kar/symptomer-og-tegn/hoejt-blodtryk/",
|
||||||
|
"2024-09-25", "2026-10-05")],
|
||||||
|
"Setting-specific high-pressure reference threshold. Missing preparation details make this comparison provisional; " +
|
||||||
|
"five minutes of rest, appropriate technique and repeated measurements are not inferred. " +
|
||||||
|
"Being below a high-pressure threshold does not establish an appropriate lower level or a personalised goal.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsHigh(decimal value, ClinicalReference reference) =>
|
||||||
|
reference.UpperComparison == ">=" ? value >= reference.UpperBoundary : value > reference.UpperBoundary;
|
||||||
|
private static bool IsLow(decimal value, ClinicalReference reference) =>
|
||||||
|
reference.LowerBoundary is { } lower && value < lower;
|
||||||
|
private static decimal Round(decimal value) => Math.Round(value, 2, MidpointRounding.AwayFromZero);
|
||||||
|
private static string Format(decimal value) => Round(value).ToString("0.##", CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
private static ComparabilityAssessment AssessComparability(IReadOnlyList<ObservationDto> observations)
|
||||||
|
{
|
||||||
|
List<string> similarities = [], differences = [], missing = [], conflicts = [];
|
||||||
|
if (observations.Count == 0)
|
||||||
|
return new("InsufficientContext", similarities, differences, missing, conflicts,
|
||||||
|
"No matching observations are available to assess comparability.");
|
||||||
|
var details = new (string Name, string?[] Values)[]
|
||||||
|
{
|
||||||
|
("setting", observations.Select(o => o.MeasurementContext?.Setting).ToArray()),
|
||||||
|
("activity condition", observations.Select(o => o.MeasurementContext?.ActivityCondition).ToArray()),
|
||||||
|
("rest duration", observations.Select(o => o.MeasurementContext?.RestDurationMinutes?.ToString("G29", CultureInfo.InvariantCulture)).ToArray()),
|
||||||
|
("body position", observations.Select(o => o.MeasurementContext?.BodyPosition).ToArray()),
|
||||||
|
("measured arm", observations.Select(o => o.MeasurementContext?.MeasuredArm).ToArray()),
|
||||||
|
("device", observations.Select(o => o.MeasurementContext?.DeviceDetails).ToArray()),
|
||||||
|
("cuff", observations.Select(o => o.MeasurementContext?.CuffDetails).ToArray())
|
||||||
|
};
|
||||||
|
foreach (var (name, values) in details)
|
||||||
|
{
|
||||||
|
var known = values.Where(v => !string.IsNullOrWhiteSpace(v) && v != "Unknown")
|
||||||
|
.Select(v => v!.Trim()).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase).ToArray();
|
||||||
|
if (values.Any(v => string.IsNullOrWhiteSpace(v) || v == "Unknown")) missing.Add(name);
|
||||||
|
if (known.Length > 1) differences.Add($"{name}: {string.Join(" / ", known)}");
|
||||||
|
else if (known.Length == 1 && !missing.Contains(name)) similarities.Add($"{name}: {known[0]}");
|
||||||
|
}
|
||||||
|
var circumstances = observations.Select(o => o.MeasurementContext?.AdditionalCircumstances)
|
||||||
|
.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s!.Trim())
|
||||||
|
.Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase).ToArray();
|
||||||
|
if (circumstances.Length > 1) differences.Add("additional circumstances differ");
|
||||||
|
if (observations.Any(o => o.MeasurementContext?.RestDurationMinutes is < 5))
|
||||||
|
differences.Add("recorded rest duration is below the five-minute blood-pressure preparation recommendation");
|
||||||
|
foreach (var observation in observations)
|
||||||
|
{
|
||||||
|
var context = observation.MeasurementContext;
|
||||||
|
var narrative = string.Join(" ", observation.Context, observation.Note, context?.AdditionalCircumstances,
|
||||||
|
context?.BodyPosition, context?.DeviceDetails, context?.CuffDetails).ToLowerInvariant();
|
||||||
|
if (context?.ActivityCondition == "AtRest" && new[]
|
||||||
|
{ "during exercise", "during activity", "after exercise", "after activity", "under motion", "under træning", "efter motion", "efter træning" }
|
||||||
|
.Any(narrative.Contains)) conflicts.Add("AtRest conflicts with an activity description in recorded text.");
|
||||||
|
if (context?.Setting == "Home" && new[] { "at clinic", "in clinic", "at the clinic", "på klinik", "hos lægen" }.Any(narrative.Contains))
|
||||||
|
conflicts.Add("Home conflicts with a clinic description in recorded text.");
|
||||||
|
if (context?.Setting == "Clinic" && new[] { "at home", "hjemme" }.Any(narrative.Contains))
|
||||||
|
conflicts.Add("Clinic conflicts with a home description in recorded text.");
|
||||||
|
}
|
||||||
|
var status = conflicts.Count > 0 ? "ConflictingContext" : differences.Count > 0 ? "KnownDifferences" :
|
||||||
|
missing.Count > 0 ? "InsufficientContext" : "SupportedRecordedComparability";
|
||||||
|
var explanation = $"Recorded comparability: {status}. " +
|
||||||
|
(missing.Count > 0 ? $"Unknown or missing: {string.Join(", ", missing)}. " : "") +
|
||||||
|
(differences.Count > 0 ? $"Known differences: {string.Join("; ", differences)}. " : "") +
|
||||||
|
(conflicts.Count > 0 ? $"Conflicts: {string.Join("; ", conflicts.Distinct())} " : "") +
|
||||||
|
"Matching recorded details support comparability only of those details; they do not certify identical " +
|
||||||
|
"conditions, validated equipment or guideline-compliant technique. Narrative conflict detection is limited " +
|
||||||
|
"to documented phrases; other text is not proof of comparability. A difference between Home and Clinic " +
|
||||||
|
"selections alone is not improvement or deterioration over time.";
|
||||||
|
return new(status, similarities, differences, missing, conflicts.Distinct().Order(StringComparer.Ordinal).ToArray(), explanation);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,17 +1,50 @@
|
|||||||
|
using System.Globalization;
|
||||||
using InsightsService.Contracts;
|
using InsightsService.Contracts;
|
||||||
|
|
||||||
namespace InsightsService.Domain;
|
namespace InsightsService.Domain;
|
||||||
|
|
||||||
public sealed class InsightCalculator
|
public sealed partial class InsightCalculator
|
||||||
{
|
{
|
||||||
public HealthInsight? CalculateSummary(Guid patientId, DateTime from, DateTime to,
|
public HealthInsight? CalculateSummary(Guid patientId, DateTime from, DateTime to,
|
||||||
IReadOnlyList<ObservationDto> observations)
|
IReadOnlyList<ObservationDto> observations, ContextSelection selection)
|
||||||
{
|
{
|
||||||
if (observations.Count == 0)
|
if (observations.Count == 0)
|
||||||
return null;
|
return null;
|
||||||
return new HealthInsight(patientId, from, to,
|
return new HealthInsight(patientId, from, to,
|
||||||
observations.Average(o => (decimal)o.Systolic), observations.Average(o => (decimal)o.Diastolic),
|
Math.Round(observations.Average(o => (decimal)o.Systolic), 2, MidpointRounding.AwayFromZero),
|
||||||
observations.Average(o => (decimal)o.Pulse), observations.Min(o => o.Systolic),
|
Math.Round(observations.Average(o => (decimal)o.Diastolic), 2, MidpointRounding.AwayFromZero),
|
||||||
observations.Max(o => o.Systolic), observations.Min(o => o.Diastolic), observations.Max(o => o.Diastolic));
|
Math.Round(observations.Average(o => (decimal)o.Pulse), 2, MidpointRounding.AwayFromZero),
|
||||||
|
observations.Min(o => o.Systolic), observations.Max(o => o.Systolic),
|
||||||
|
observations.Min(o => o.Diastolic), observations.Max(o => o.Diastolic),
|
||||||
|
selection, observations.Count, DescribeContext(observations));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static string DescribeContext(IReadOnlyList<ObservationDto> observations)
|
||||||
|
{
|
||||||
|
var settings = observations.Select(o => o.MeasurementContext?.Setting ?? "Unknown").ToArray();
|
||||||
|
var activities = observations.Select(o => o.MeasurementContext?.ActivityCondition ?? "Unknown").ToArray();
|
||||||
|
var explanation = $"Recorded settings: {Counts(settings)}. Recorded activity conditions: {Counts(activities)}.";
|
||||||
|
if (settings.Distinct().Count() > 1 || activities.Distinct().Count() > 1)
|
||||||
|
explanation += " This numerical summary pools mixed settings or activity conditions.";
|
||||||
|
if (settings.Contains("Unknown") || activities.Contains("Unknown"))
|
||||||
|
explanation += " Some setting or activity information is unknown.";
|
||||||
|
var details = new (string Name, string?[] Values)[]
|
||||||
|
{
|
||||||
|
("rest duration", observations.Select(o => o.MeasurementContext?.RestDurationMinutes?.ToString("G29", CultureInfo.InvariantCulture)).ToArray()),
|
||||||
|
("body position", observations.Select(o => o.MeasurementContext?.BodyPosition).ToArray()),
|
||||||
|
("measured arm", observations.Select(o => o.MeasurementContext?.MeasuredArm).ToArray()),
|
||||||
|
("device", observations.Select(o => o.MeasurementContext?.DeviceDetails).ToArray()),
|
||||||
|
("cuff", observations.Select(o => o.MeasurementContext?.CuffDetails).ToArray()),
|
||||||
|
("additional circumstances", observations.Select(o => o.MeasurementContext?.AdditionalCircumstances).ToArray())
|
||||||
|
};
|
||||||
|
var missing = details.Where(d => d.Values.Any(string.IsNullOrWhiteSpace)).Select(d => d.Name).ToArray();
|
||||||
|
var differing = details.Where(d => d.Values.Where(v => !string.IsNullOrWhiteSpace(v)).Distinct().Count() > 1)
|
||||||
|
.Select(d => d.Name).ToArray();
|
||||||
|
if (missing.Length > 0) explanation += $" Optional details are unrecorded for some observations: {string.Join(", ", missing)}.";
|
||||||
|
if (differing.Length > 0) explanation += $" Recorded detail values differ: {string.Join(", ", differing)}.";
|
||||||
|
return explanation + " These are descriptive statistics, not a diagnostic monitoring protocol; recorded categories alone do not establish clinically comparable conditions. Legacy narrative text does not establish a category.";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Counts(IEnumerable<string> values) => string.Join(", ", values.GroupBy(v => v)
|
||||||
|
.OrderBy(g => g.Key, StringComparer.Ordinal).Select(g => $"{g.Key} ({g.Count()})"));
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
namespace InsightsService.Domain;
|
||||||
|
|
||||||
|
public sealed record TrendAssessment(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
|
||||||
|
ContextSelection AppliedSelection, int ContributingCount, ComparabilityAssessment Comparability,
|
||||||
|
MeasurementAssessment Systolic, MeasurementAssessment Diastolic, MeasurementAssessment Pulse);
|
||||||
|
|
||||||
|
public sealed record ComparabilityAssessment(string Status, IReadOnlyList<string> KnownSimilarities,
|
||||||
|
IReadOnlyList<string> KnownDifferences, IReadOnlyList<string> MissingDetails,
|
||||||
|
IReadOnlyList<string> Conflicts, string Explanation);
|
||||||
|
|
||||||
|
public sealed record MeasurementAssessment(string Metric, string Unit, decimal? Mean, int? Minimum,
|
||||||
|
int? Maximum, int? Range, int DistinctTimestampCount, string Direction, string OverallDirection,
|
||||||
|
decimal? SlopePerDay, int ReversalCount, decimal? TotalSuccessiveChange,
|
||||||
|
string NumericalExplanation, ClinicalReference? Reference, string ReferenceComparison,
|
||||||
|
string Interpretation, string Hint);
|
||||||
|
|
||||||
|
public sealed record ClinicalReference(string Scope, decimal? LowerBoundary, string? LowerComparison,
|
||||||
|
decimal UpperBoundary, string UpperComparison, IReadOnlyList<ReferenceSource> Sources,
|
||||||
|
string Limitation);
|
||||||
|
|
||||||
|
public sealed record ReferenceSource(string Title, string Url, string Updated, string Reviewed);
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
using InsightsService.Application;
|
using InsightsService.Application;
|
||||||
using InsightsService.Clients;
|
using InsightsService.Clients;
|
||||||
using InsightsService.Domain;
|
using InsightsService.Domain;
|
||||||
@@ -14,11 +16,34 @@ public class Program
|
|||||||
builder.Services.AddScoped<InsightsApplicationService>();
|
builder.Services.AddScoped<InsightsApplicationService>();
|
||||||
builder.Services.AddSingleton<InsightCalculator>();
|
builder.Services.AddSingleton<InsightCalculator>();
|
||||||
builder.Services.AddHttpClient<ObservationServiceClient, HttpObservationServiceClient>((services, client) =>
|
builder.Services.AddHttpClient<ObservationServiceClient, HttpObservationServiceClient>((services, client) =>
|
||||||
client.BaseAddress = GetGatewayUri(services.GetRequiredService<IConfiguration>()))
|
{
|
||||||
|
var configuration = services.GetRequiredService<IConfiguration>();
|
||||||
|
client.BaseAddress = GetGatewayUri(configuration);
|
||||||
|
var serviceKey = configuration["Services:ApiGateway:Key"];
|
||||||
|
if (string.IsNullOrWhiteSpace(serviceKey) || serviceKey.Length < 32)
|
||||||
|
throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters.");
|
||||||
|
client.DefaultRequestHeaders.Add("X-Service-Key", serviceKey);
|
||||||
|
})
|
||||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||||
var app = builder.Build();
|
var app = builder.Build();
|
||||||
|
if (!app.Environment.IsDevelopment() && GetGatewayUri(app.Configuration).Scheme != "https")
|
||||||
|
throw new InvalidOperationException("Production gateway endpoints must use HTTPS.");
|
||||||
_ = GetGatewayUri(app.Configuration);
|
_ = GetGatewayUri(app.Configuration);
|
||||||
|
var outgoingKey = app.Configuration["Services:ApiGateway:Key"];
|
||||||
|
if (string.IsNullOrWhiteSpace(outgoingKey) || outgoingKey.Length < 32)
|
||||||
|
throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters.");
|
||||||
|
var gatewayKey = app.Configuration["InternalAccess:GatewayKey"];
|
||||||
|
if (string.IsNullOrWhiteSpace(gatewayKey) || gatewayKey.Length < 32)
|
||||||
|
throw new InvalidOperationException("InternalAccess:GatewayKey must contain at least 32 characters.");
|
||||||
app.UseExceptionHandler();
|
app.UseExceptionHandler();
|
||||||
|
app.Use(async (context, next) =>
|
||||||
|
{
|
||||||
|
var supplied = context.Request.Headers["X-Gateway-Key"].ToString();
|
||||||
|
if ((!app.Environment.IsDevelopment() && !context.Request.IsHttps) ||
|
||||||
|
!CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(supplied), Encoding.UTF8.GetBytes(gatewayKey)))
|
||||||
|
{ context.Response.StatusCode = 401; return; }
|
||||||
|
await next(context);
|
||||||
|
});
|
||||||
app.MapControllers();
|
app.MapControllers();
|
||||||
app.Run();
|
app.Run();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
# US-12 health overview
|
||||||
|
|
||||||
|
`GET /api/patients/{patientId}/overview?from=...&to=...&setting=Home&activityCondition=AtRest`
|
||||||
|
requires the patient's authenticated account or an assigned read-only professional.
|
||||||
|
Dates use the existing inclusive measurement-instant convention. Offset-free timestamps
|
||||||
|
mean UTC; equivalent offsets identify the same instant. From and to are required,
|
||||||
|
equal bounds are valid, reversed/malformed/missing bounds return 400. Both selected
|
||||||
|
context dimensions must match for insight; `Unknown` is an explicit selectable category.
|
||||||
|
Omitted dimensions are unrestricted. Unsupported selections return 400 validation details.
|
||||||
|
|
||||||
|
The independent ASP.NET Core Health Overview Service loads the profile, latest overall
|
||||||
|
observation and US-10 numerical insight through three HTTP clients routed through the
|
||||||
|
gateway. It has no production project references to another service, database, stored
|
||||||
|
aggregate or cache. The renamed Overview ER illustration explicitly denotes data needed
|
||||||
|
from other services rather than overview persistence; the current class model governs.
|
||||||
|
|
||||||
|
## Response
|
||||||
|
|
||||||
|
A successful request returns 200 with:
|
||||||
|
|
||||||
|
- `patient`: the current profile, including ID, name, birth date and contact information.
|
||||||
|
- `latestObservation`: latest overall reading, including original text, note and all recorded
|
||||||
|
structured context, or null when no observations exist. Latest retains US-06 timestamp,
|
||||||
|
original recording-time and deterministic ID ordering. The insight period and filters
|
||||||
|
never limit latest-observation selection.
|
||||||
|
- `insight`: the existing US-10 response or null when no observations match the insight
|
||||||
|
period/context. Its rounded means, extrema, selection, contributing count and context
|
||||||
|
explanation are preserved. No trend component is added.
|
||||||
|
- `periodStart`, `periodEnd`, `insightSelection`, `insightContributingCount`: explicit insight
|
||||||
|
basis even when insight is absent (count zero).
|
||||||
|
- `latestObservationBasis`: explains that latest context belongs to that reading only.
|
||||||
|
- `insightExplanation`: preserves the insight's context limitations or explains why no
|
||||||
|
selected-period insight is available. Empty insight does not remove profile/latest.
|
||||||
|
|
||||||
|
An authorized missing patient returns 404 with `Patient does not exist.` Access rejection
|
||||||
|
retains the gateway's non-disclosing empty 404 convention; unauthenticated clients get 401.
|
||||||
|
Professional writes remain forbidden. Upstream connection/status/invalid-JSON failures
|
||||||
|
return 502; local upstream timeouts return 504. These are not reported as absent data.
|
||||||
|
Only upstream 404 responses on the appropriate profile/latest/insight routes represent
|
||||||
|
missing data. Requests are cancelled on client disconnect.
|
||||||
|
|
||||||
|
Every overview request fetches current source data, including profile updates, corrected
|
||||||
|
measurement/context, and deletions. Reads occur separately across services, so concurrent
|
||||||
|
writes may occur between them; the overview does not promise a cross-service snapshot.
|
||||||
|
There is no extra transaction, refresh mechanism, synchronisation process or persisted
|
||||||
|
copy to invalidate.
|
||||||
|
|
||||||
|
## Deployment and verification
|
||||||
|
|
||||||
|
The service builds/publishes independently with .NET 10 and starts from external
|
||||||
|
configuration. See `deploy/health-overview.env.example`, the independent systemd unit,
|
||||||
|
[README.md](README.md) and [AUTHENTICATION.md](AUTHENTICATION.md). It requires only the
|
||||||
|
gateway origin and incoming/outgoing service credentials; no database configuration or
|
||||||
|
migration is needed. Production uses HTTPS; local HTTP is limited to Development.
|
||||||
|
Addresses, network binding, credentials and certificates are configurable for separate
|
||||||
|
machines. Standard stdout/stderr logging, graceful shutdown and restart follow the other
|
||||||
|
service units. No new package dependencies are introduced.
|
||||||
|
|
||||||
|
US-12 acceptance tests run five actual HTTP hosts against separate patient/observation
|
||||||
|
PostgreSQL databases. They cover all story scenarios, boundaries/offsets, patient scope,
|
||||||
|
latest tie rules, context preservation, independent filters, unknown/mixed context,
|
||||||
|
empty selected insight, corrections/deletions/restart, profile updates, missing patients,
|
||||||
|
validation, owner/assignment enforcement, direct bypass rejection, restricted internal
|
||||||
|
service reads and unavailable upstream/Overview services.
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
using System.Net;
|
using System.Net;
|
||||||
using ObservationService.Contracts;
|
using ObservationService.Contracts;
|
||||||
using ObservationService.Domain;
|
using ObservationService.Domain;
|
||||||
@@ -15,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)
|
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));
|
throw new ArgumentException("Positive measured values are required.", nameof(request));
|
||||||
|
|
||||||
return repository.UpdateValuesAsync(observationId, request.Systolic.Value, request.Diastolic.Value,
|
return PatchAsync(observationId, new PatchObservationRequest { Systolic = request.Systolic, Diastolic = request.Diastolic, Pulse = request.Pulse }, cancellationToken);
|
||||||
request.Pulse.Value, DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified), cancellationToken);
|
}
|
||||||
|
|
||||||
|
public Task<BloodPressureObservation?> 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<BloodPressureObservation?> RecordAsync(Guid patientId, RecordObservationRequest request,
|
public async Task<BloodPressureObservation?> RecordAsync(Guid patientId, RecordObservationRequest request,
|
||||||
@@ -26,6 +35,14 @@ public sealed class ObservationApplicationService(ObservationRepository reposito
|
|||||||
request.Diastolic is null or <= 0 || request.Pulse is null or <= 0)
|
request.Diastolic is null or <= 0 || request.Pulse is null or <= 0)
|
||||||
throw new ArgumentException("A timestamp and positive measured values are required.", nameof(request));
|
throw new ArgumentException("A timestamp and positive measured values are required.", nameof(request));
|
||||||
|
|
||||||
|
var suppliedContext = request.MeasurementContext ?? new MeasurementContext();
|
||||||
|
var measurementContext = suppliedContext with
|
||||||
|
{
|
||||||
|
Setting = suppliedContext.Setting ?? "Unknown",
|
||||||
|
ActivityCondition = suppliedContext.ActivityCondition ?? "Unknown"
|
||||||
|
};
|
||||||
|
Validator.ValidateObject(measurementContext, new ValidationContext(measurementContext), validateAllProperties: true);
|
||||||
|
|
||||||
using var patient = await clients.CreateClient("ApiGateway").GetAsync($"api/patients/{patientId}",
|
using var patient = await clients.CreateClient("ApiGateway").GetAsync($"api/patients/{patientId}",
|
||||||
HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
||||||
if (patient.StatusCode == HttpStatusCode.NotFound)
|
if (patient.StatusCode == HttpStatusCode.NotFound)
|
||||||
@@ -44,6 +61,7 @@ public sealed class ObservationApplicationService(ObservationRepository reposito
|
|||||||
MeasuredAt = DateTime.SpecifyKind(measuredAt, DateTimeKind.Unspecified),
|
MeasuredAt = DateTime.SpecifyKind(measuredAt, DateTimeKind.Unspecified),
|
||||||
Systolic = request.Systolic.Value, Diastolic = request.Diastolic.Value,
|
Systolic = request.Systolic.Value, Diastolic = request.Diastolic.Value,
|
||||||
Pulse = request.Pulse.Value, Context = request.Context, Note = request.Note,
|
Pulse = request.Pulse.Value, Context = request.Context, Note = request.Note,
|
||||||
|
MeasurementContext = measurementContext,
|
||||||
CreatedAt = now, UpdatedAt = now
|
CreatedAt = now, UpdatedAt = now
|
||||||
}, cancellationToken);
|
}, cancellationToken);
|
||||||
}
|
}
|
||||||
@@ -55,13 +73,14 @@ public sealed class ObservationApplicationService(ObservationRepository reposito
|
|||||||
repository.FindLatestByPatientIdAsync(patientId, cancellationToken);
|
repository.FindLatestByPatientIdAsync(patientId, cancellationToken);
|
||||||
|
|
||||||
public Task<List<BloodPressureObservation>> GetByPeriodAsync(Guid patientId, DateTime from, DateTime to,
|
public Task<List<BloodPressureObservation>> GetByPeriodAsync(Guid patientId, DateTime from, DateTime to,
|
||||||
CancellationToken cancellationToken)
|
ContextSelection selection, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
from = NormalizeTimestamp(from);
|
from = NormalizeTimestamp(from);
|
||||||
to = NormalizeTimestamp(to);
|
to = NormalizeTimestamp(to);
|
||||||
if (to < from)
|
if (to < from)
|
||||||
throw new ArgumentException("The end time must not be earlier than the start time.", nameof(to));
|
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) =>
|
private static DateTime NormalizeTimestamp(DateTime timestamp) =>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using ObservationService.Contracts;
|
||||||
using ObservationService.Domain;
|
using ObservationService.Domain;
|
||||||
|
|
||||||
namespace ObservationService.Application;
|
namespace ObservationService.Application;
|
||||||
@@ -5,11 +6,11 @@ namespace ObservationService.Application;
|
|||||||
public interface ObservationRepository
|
public interface ObservationRepository
|
||||||
{
|
{
|
||||||
Task<bool> DeleteAsync(Guid observationId, CancellationToken cancellationToken);
|
Task<bool> DeleteAsync(Guid observationId, CancellationToken cancellationToken);
|
||||||
Task<BloodPressureObservation?> UpdateValuesAsync(Guid observationId, int systolic, int diastolic, int pulse,
|
Task<BloodPressureObservation?> UpdateAsync(Guid observationId, PatchObservationRequest request,
|
||||||
DateTime updatedAt, CancellationToken cancellationToken);
|
DateTime updatedAt, CancellationToken cancellationToken);
|
||||||
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,
|
Task<List<BloodPressureObservation>> FindByPatientIdAndPeriodAsync(Guid patientId, DateTime from, DateTime to,
|
||||||
CancellationToken cancellationToken);
|
ContextSelection selection, CancellationToken cancellationToken);
|
||||||
}
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
|
using ObservationService.Domain;
|
||||||
|
|
||||||
namespace ObservationService.Contracts;
|
namespace ObservationService.Contracts;
|
||||||
|
|
||||||
public sealed record ObservationDto(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
public sealed record ObservationDto(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||||
int Systolic, int Diastolic, int Pulse, string? Context, string? Note);
|
int Systolic, int Diastolic, int Pulse, string? Context, string? Note, MeasurementContext MeasurementContext);
|
||||||
@@ -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<ValidationResult> 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.");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
using System.ComponentModel.DataAnnotations;
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using ObservationService.Domain;
|
||||||
|
|
||||||
namespace ObservationService.Contracts;
|
namespace ObservationService.Contracts;
|
||||||
|
|
||||||
@@ -16,6 +17,8 @@ public sealed record RecordObservationRequest
|
|||||||
[Required, Range(1, int.MaxValue)]
|
[Required, Range(1, int.MaxValue)]
|
||||||
public int? Pulse { get; init; }
|
public int? Pulse { get; init; }
|
||||||
|
|
||||||
|
public MeasurementContext? MeasurementContext { get; init; }
|
||||||
|
|
||||||
public string? Context { get; init; }
|
public string? Context { get; init; }
|
||||||
public string? Note { get; init; }
|
public string? Note { get; init; }
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,9 @@
|
|||||||
|
using System.Text.Json.Serialization;
|
||||||
using System.ComponentModel.DataAnnotations;
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
namespace ObservationService.Contracts;
|
namespace ObservationService.Contracts;
|
||||||
|
|
||||||
|
[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)]
|
||||||
public sealed record UpdateObservationRequest
|
public sealed record UpdateObservationRequest
|
||||||
{
|
{
|
||||||
[Required, Range(1, int.MaxValue)]
|
[Required, Range(1, int.MaxValue)]
|
||||||
|
|||||||
@@ -43,6 +43,14 @@ public sealed class ObservationController(ObservationApplicationService service)
|
|||||||
return observation is null ? NotFound() : Ok(ToDto(observation));
|
return observation is null ? NotFound() : Ok(ToDto(observation));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[HttpPatch("observations/{observationId:guid}")]
|
||||||
|
public async Task<ActionResult<ObservationDto>> 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}")]
|
[HttpGet("observations/{observationId:guid}")]
|
||||||
public async Task<ActionResult<ObservationDto>> GetObservation(Guid observationId, CancellationToken cancellationToken)
|
public async Task<ActionResult<ObservationDto>> GetObservation(Guid observationId, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
@@ -60,11 +68,13 @@ public sealed class ObservationController(ObservationApplicationService service)
|
|||||||
[HttpGet("patients/{patientId:guid}/observations")]
|
[HttpGet("patients/{patientId:guid}/observations")]
|
||||||
public async Task<ActionResult<List<ObservationDto>>> GetByPeriod(Guid patientId,
|
public async Task<ActionResult<List<ObservationDto>>> GetByPeriod(Guid patientId,
|
||||||
[FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to,
|
[FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to,
|
||||||
CancellationToken cancellationToken)
|
[FromQuery] ContextSelection selection, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
try
|
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());
|
return Ok(observations.Select(ToDto).ToList());
|
||||||
}
|
}
|
||||||
catch (ArgumentException)
|
catch (ArgumentException)
|
||||||
@@ -76,5 +86,5 @@ public sealed class ObservationController(ObservationApplicationService service)
|
|||||||
|
|
||||||
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, observation.MeasurementContext);
|
||||||
}
|
}
|
||||||
@@ -8,6 +8,7 @@ public sealed class BloodPressureObservation
|
|||||||
public int Systolic { get; set; }
|
public int Systolic { get; set; }
|
||||||
public int Diastolic { get; set; }
|
public int Diastolic { get; set; }
|
||||||
public int Pulse { get; set; }
|
public int Pulse { get; set; }
|
||||||
|
public MeasurementContext MeasurementContext { get; set; } = new();
|
||||||
public string? Context { get; set; }
|
public string? Context { get; set; }
|
||||||
public string? Note { get; set; }
|
public string? Note { get; set; }
|
||||||
public DateTime CreatedAt { get; set; }
|
public DateTime CreatedAt { get; set; }
|
||||||
|
|||||||
@@ -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; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace ObservationService.Domain;
|
||||||
|
|
||||||
|
public sealed record MeasurementContext
|
||||||
|
{
|
||||||
|
[AllowedValues("Home", "Clinic", "Other", "Unknown", null)]
|
||||||
|
public string? Setting { get; init; } = "Unknown";
|
||||||
|
|
||||||
|
[AllowedValues("AtRest", "DuringActivity", "AfterActivity", "Unknown", null)]
|
||||||
|
public string? ActivityCondition { get; init; } = "Unknown";
|
||||||
|
|
||||||
|
[Range(0, double.MaxValue)]
|
||||||
|
public decimal? RestDurationMinutes { get; init; }
|
||||||
|
|
||||||
|
public string? BodyPosition { get; init; }
|
||||||
|
public string? MeasuredArm { get; init; }
|
||||||
|
public string? DeviceDetails { get; init; }
|
||||||
|
public string? CuffDetails { get; init; }
|
||||||
|
public string? AdditionalCircumstances { get; init; }
|
||||||
|
}
|
||||||
Generated
+134
@@ -0,0 +1,134 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
|
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||||
|
using ObservationService.Persistence;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace ObservationService.Persistence.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(ObservationDbContext))]
|
||||||
|
[Migration("20261005094632_RecordedMeasurementContext")]
|
||||||
|
partial class RecordedMeasurementContext
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
#pragma warning disable 612, 618
|
||||||
|
modelBuilder
|
||||||
|
.HasAnnotation("ProductVersion", "10.0.12")
|
||||||
|
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||||
|
|
||||||
|
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||||
|
|
||||||
|
modelBuilder.Entity("ObservationService.Domain.BloodPressureObservation", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("ObservationId")
|
||||||
|
.HasColumnType("uuid")
|
||||||
|
.HasColumnName("observation_id");
|
||||||
|
|
||||||
|
b.Property<string>("Context")
|
||||||
|
.HasColumnType("character varying")
|
||||||
|
.HasColumnName("context");
|
||||||
|
|
||||||
|
b.Property<DateTime>("CreatedAt")
|
||||||
|
.HasColumnType("timestamp without time zone")
|
||||||
|
.HasColumnName("created_at");
|
||||||
|
|
||||||
|
b.Property<int>("Diastolic")
|
||||||
|
.HasColumnType("integer")
|
||||||
|
.HasColumnName("diastolic");
|
||||||
|
|
||||||
|
b.Property<DateTime>("MeasuredAt")
|
||||||
|
.HasColumnType("timestamp without time zone")
|
||||||
|
.HasColumnName("measured_at");
|
||||||
|
|
||||||
|
b.Property<string>("Note")
|
||||||
|
.HasColumnType("character varying")
|
||||||
|
.HasColumnName("note");
|
||||||
|
|
||||||
|
b.Property<Guid>("PatientId")
|
||||||
|
.HasColumnType("uuid")
|
||||||
|
.HasColumnName("patient_id");
|
||||||
|
|
||||||
|
b.Property<int>("Pulse")
|
||||||
|
.HasColumnType("integer")
|
||||||
|
.HasColumnName("pulse");
|
||||||
|
|
||||||
|
b.Property<int>("Systolic")
|
||||||
|
.HasColumnType("integer")
|
||||||
|
.HasColumnName("systolic");
|
||||||
|
|
||||||
|
b.Property<DateTime>("UpdatedAt")
|
||||||
|
.HasColumnType("timestamp without time zone")
|
||||||
|
.HasColumnName("updated_at");
|
||||||
|
|
||||||
|
b.HasKey("ObservationId");
|
||||||
|
|
||||||
|
b.ToTable("blood_pressure_observation", (string)null);
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("ObservationService.Domain.BloodPressureObservation", b =>
|
||||||
|
{
|
||||||
|
b.OwnsOne("ObservationService.Domain.MeasurementContext", "MeasurementContext", b1 =>
|
||||||
|
{
|
||||||
|
b1.Property<Guid>("BloodPressureObservationObservationId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b1.Property<string>("ActivityCondition")
|
||||||
|
.IsRequired()
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("text")
|
||||||
|
.HasDefaultValue("Unknown")
|
||||||
|
.HasColumnName("activity_condition");
|
||||||
|
|
||||||
|
b1.Property<string>("AdditionalCircumstances")
|
||||||
|
.HasColumnType("text")
|
||||||
|
.HasColumnName("additional_circumstances");
|
||||||
|
|
||||||
|
b1.Property<string>("BodyPosition")
|
||||||
|
.HasColumnType("text")
|
||||||
|
.HasColumnName("body_position");
|
||||||
|
|
||||||
|
b1.Property<string>("CuffDetails")
|
||||||
|
.HasColumnType("text")
|
||||||
|
.HasColumnName("cuff_details");
|
||||||
|
|
||||||
|
b1.Property<string>("DeviceDetails")
|
||||||
|
.HasColumnType("text")
|
||||||
|
.HasColumnName("device_details");
|
||||||
|
|
||||||
|
b1.Property<string>("MeasuredArm")
|
||||||
|
.HasColumnType("text")
|
||||||
|
.HasColumnName("measured_arm");
|
||||||
|
|
||||||
|
b1.Property<decimal?>("RestDurationMinutes")
|
||||||
|
.HasColumnType("numeric")
|
||||||
|
.HasColumnName("rest_duration_minutes");
|
||||||
|
|
||||||
|
b1.Property<string>("Setting")
|
||||||
|
.IsRequired()
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("text")
|
||||||
|
.HasDefaultValue("Unknown")
|
||||||
|
.HasColumnName("setting");
|
||||||
|
|
||||||
|
b1.HasKey("BloodPressureObservationObservationId");
|
||||||
|
|
||||||
|
b1.ToTable("blood_pressure_observation");
|
||||||
|
|
||||||
|
b1.WithOwner()
|
||||||
|
.HasForeignKey("BloodPressureObservationObservationId");
|
||||||
|
});
|
||||||
|
|
||||||
|
b.Navigation("MeasurementContext")
|
||||||
|
.IsRequired();
|
||||||
|
});
|
||||||
|
#pragma warning restore 612, 618
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+100
@@ -0,0 +1,100 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace ObservationService.Persistence.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class RecordedMeasurementContext : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "activity_condition",
|
||||||
|
table: "blood_pressure_observation",
|
||||||
|
type: "text",
|
||||||
|
nullable: false,
|
||||||
|
defaultValue: "Unknown");
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "additional_circumstances",
|
||||||
|
table: "blood_pressure_observation",
|
||||||
|
type: "text",
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "body_position",
|
||||||
|
table: "blood_pressure_observation",
|
||||||
|
type: "text",
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "cuff_details",
|
||||||
|
table: "blood_pressure_observation",
|
||||||
|
type: "text",
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "device_details",
|
||||||
|
table: "blood_pressure_observation",
|
||||||
|
type: "text",
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "measured_arm",
|
||||||
|
table: "blood_pressure_observation",
|
||||||
|
type: "text",
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<decimal>(
|
||||||
|
name: "rest_duration_minutes",
|
||||||
|
table: "blood_pressure_observation",
|
||||||
|
type: "numeric",
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "setting",
|
||||||
|
table: "blood_pressure_observation",
|
||||||
|
type: "text",
|
||||||
|
nullable: false,
|
||||||
|
defaultValue: "Unknown");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "activity_condition",
|
||||||
|
table: "blood_pressure_observation");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "additional_circumstances",
|
||||||
|
table: "blood_pressure_observation");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "body_position",
|
||||||
|
table: "blood_pressure_observation");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "cuff_details",
|
||||||
|
table: "blood_pressure_observation");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "device_details",
|
||||||
|
table: "blood_pressure_observation");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "measured_arm",
|
||||||
|
table: "blood_pressure_observation");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "rest_duration_minutes",
|
||||||
|
table: "blood_pressure_observation");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "setting",
|
||||||
|
table: "blood_pressure_observation");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -68,6 +68,63 @@ namespace ObservationService.Persistence.Migrations
|
|||||||
|
|
||||||
b.ToTable("blood_pressure_observation", (string)null);
|
b.ToTable("blood_pressure_observation", (string)null);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("ObservationService.Domain.BloodPressureObservation", b =>
|
||||||
|
{
|
||||||
|
b.OwnsOne("ObservationService.Domain.MeasurementContext", "MeasurementContext", b1 =>
|
||||||
|
{
|
||||||
|
b1.Property<Guid>("BloodPressureObservationObservationId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b1.Property<string>("ActivityCondition")
|
||||||
|
.IsRequired()
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("text")
|
||||||
|
.HasDefaultValue("Unknown")
|
||||||
|
.HasColumnName("activity_condition");
|
||||||
|
|
||||||
|
b1.Property<string>("AdditionalCircumstances")
|
||||||
|
.HasColumnType("text")
|
||||||
|
.HasColumnName("additional_circumstances");
|
||||||
|
|
||||||
|
b1.Property<string>("BodyPosition")
|
||||||
|
.HasColumnType("text")
|
||||||
|
.HasColumnName("body_position");
|
||||||
|
|
||||||
|
b1.Property<string>("CuffDetails")
|
||||||
|
.HasColumnType("text")
|
||||||
|
.HasColumnName("cuff_details");
|
||||||
|
|
||||||
|
b1.Property<string>("DeviceDetails")
|
||||||
|
.HasColumnType("text")
|
||||||
|
.HasColumnName("device_details");
|
||||||
|
|
||||||
|
b1.Property<string>("MeasuredArm")
|
||||||
|
.HasColumnType("text")
|
||||||
|
.HasColumnName("measured_arm");
|
||||||
|
|
||||||
|
b1.Property<decimal?>("RestDurationMinutes")
|
||||||
|
.HasColumnType("numeric")
|
||||||
|
.HasColumnName("rest_duration_minutes");
|
||||||
|
|
||||||
|
b1.Property<string>("Setting")
|
||||||
|
.IsRequired()
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("text")
|
||||||
|
.HasDefaultValue("Unknown")
|
||||||
|
.HasColumnName("setting");
|
||||||
|
|
||||||
|
b1.HasKey("BloodPressureObservationObservationId");
|
||||||
|
|
||||||
|
b1.ToTable("blood_pressure_observation");
|
||||||
|
|
||||||
|
b1.WithOwner()
|
||||||
|
.HasForeignKey("BloodPressureObservationObservationId");
|
||||||
|
});
|
||||||
|
|
||||||
|
b.Navigation("MeasurementContext")
|
||||||
|
.IsRequired();
|
||||||
|
});
|
||||||
#pragma warning restore 612, 618
|
#pragma warning restore 612, 618
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,18 @@ public sealed class ObservationDbContext(DbContextOptions<ObservationDbContext>
|
|||||||
observation.Property(o => o.Pulse).HasColumnName("pulse");
|
observation.Property(o => o.Pulse).HasColumnName("pulse");
|
||||||
observation.Property(o => o.Context).HasColumnName("context").HasColumnType("character varying");
|
observation.Property(o => o.Context).HasColumnName("context").HasColumnType("character varying");
|
||||||
observation.Property(o => o.Note).HasColumnName("note").HasColumnType("character varying");
|
observation.Property(o => o.Note).HasColumnName("note").HasColumnType("character varying");
|
||||||
|
observation.OwnsOne(o => o.MeasurementContext, context =>
|
||||||
|
{
|
||||||
|
context.Property(c => c.Setting).HasColumnName("setting").HasDefaultValue("Unknown").IsRequired();
|
||||||
|
context.Property(c => c.ActivityCondition).HasColumnName("activity_condition").HasDefaultValue("Unknown").IsRequired();
|
||||||
|
context.Property(c => c.RestDurationMinutes).HasColumnName("rest_duration_minutes");
|
||||||
|
context.Property(c => c.BodyPosition).HasColumnName("body_position");
|
||||||
|
context.Property(c => c.MeasuredArm).HasColumnName("measured_arm");
|
||||||
|
context.Property(c => c.DeviceDetails).HasColumnName("device_details");
|
||||||
|
context.Property(c => c.CuffDetails).HasColumnName("cuff_details");
|
||||||
|
context.Property(c => c.AdditionalCircumstances).HasColumnName("additional_circumstances");
|
||||||
|
});
|
||||||
|
observation.Navigation(o => o.MeasurementContext).IsRequired();
|
||||||
observation.Property(o => o.CreatedAt).HasColumnName("created_at").HasColumnType("timestamp without time zone");
|
observation.Property(o => o.CreatedAt).HasColumnName("created_at").HasColumnType("timestamp without time zone");
|
||||||
observation.Property(o => o.UpdatedAt).HasColumnName("updated_at").HasColumnType("timestamp without time zone");
|
observation.Property(o => o.UpdatedAt).HasColumnName("updated_at").HasColumnType("timestamp without time zone");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using ObservationService.Contracts;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using ObservationService.Application;
|
using ObservationService.Application;
|
||||||
using ObservationService.Domain;
|
using ObservationService.Domain;
|
||||||
@@ -10,17 +11,39 @@ public sealed class SqlObservationRepository(ObservationDbContext db) : Observat
|
|||||||
await db.Observations.Where(o => o.ObservationId == observationId)
|
await db.Observations.Where(o => o.ObservationId == observationId)
|
||||||
.ExecuteDeleteAsync(cancellationToken) > 0;
|
.ExecuteDeleteAsync(cancellationToken) > 0;
|
||||||
|
|
||||||
public async Task<BloodPressureObservation?> UpdateValuesAsync(Guid observationId, int systolic, int diastolic,
|
public async Task<BloodPressureObservation?> UpdateAsync(Guid observationId, PatchObservationRequest request,
|
||||||
int pulse, DateTime updatedAt, CancellationToken cancellationToken)
|
DateTime updatedAt, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var observation = await db.Observations.SingleOrDefaultAsync(o => o.ObservationId == observationId,
|
var observation = await db.Observations.SingleOrDefaultAsync(o => o.ObservationId == observationId,
|
||||||
cancellationToken);
|
cancellationToken);
|
||||||
if (observation is null)
|
if (observation is null)
|
||||||
return null;
|
return null;
|
||||||
|
|
||||||
observation.Systolic = systolic;
|
if (request.SystolicSpecified) observation.Systolic = request.Systolic!.Value;
|
||||||
observation.Diastolic = diastolic;
|
if (request.DiastolicSpecified) observation.Diastolic = request.Diastolic!.Value;
|
||||||
observation.Pulse = pulse;
|
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;
|
observation.UpdatedAt = updatedAt;
|
||||||
await db.SaveChangesAsync(cancellationToken);
|
await db.SaveChangesAsync(cancellationToken);
|
||||||
return observation;
|
return observation;
|
||||||
@@ -38,12 +61,19 @@ public sealed class SqlObservationRepository(ObservationDbContext db) : Observat
|
|||||||
|
|
||||||
public Task<BloodPressureObservation?> FindLatestByPatientIdAsync(Guid patientId, CancellationToken cancellationToken) =>
|
public Task<BloodPressureObservation?> FindLatestByPatientIdAsync(Guid patientId, CancellationToken cancellationToken) =>
|
||||||
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.CreatedAt)
|
||||||
|
.ThenByDescending(o => o.ObservationId)
|
||||||
.FirstOrDefaultAsync(cancellationToken);
|
.FirstOrDefaultAsync(cancellationToken);
|
||||||
|
|
||||||
public Task<List<BloodPressureObservation>> FindByPatientIdAndPeriodAsync(Guid patientId, DateTime from, DateTime to,
|
public Task<List<BloodPressureObservation>> FindByPatientIdAndPeriodAsync(Guid patientId, DateTime from, DateTime to,
|
||||||
CancellationToken cancellationToken) =>
|
ContextSelection selection, CancellationToken cancellationToken)
|
||||||
db.Observations.AsNoTracking()
|
{
|
||||||
.Where(o => o.PatientId == patientId && o.MeasuredAt >= from && o.MeasuredAt <= to)
|
var query = db.Observations.AsNoTracking()
|
||||||
.OrderBy(o => o.MeasuredAt).ThenBy(o => o.ObservationId).ToListAsync(cancellationToken);
|
.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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using ObservationService.Application;
|
using ObservationService.Application;
|
||||||
using ObservationService.Persistence;
|
using ObservationService.Persistence;
|
||||||
@@ -16,7 +18,14 @@ public class Program
|
|||||||
builder.Services.AddScoped<ObservationRepository, SqlObservationRepository>();
|
builder.Services.AddScoped<ObservationRepository, SqlObservationRepository>();
|
||||||
builder.Services.AddScoped<ObservationApplicationService>();
|
builder.Services.AddScoped<ObservationApplicationService>();
|
||||||
builder.Services.AddHttpClient("ApiGateway", (services, client) =>
|
builder.Services.AddHttpClient("ApiGateway", (services, client) =>
|
||||||
client.BaseAddress = GetGatewayUri(services.GetRequiredService<IConfiguration>()))
|
{
|
||||||
|
var configuration = services.GetRequiredService<IConfiguration>();
|
||||||
|
client.BaseAddress = GetGatewayUri(configuration);
|
||||||
|
var serviceKey = configuration["Services:ApiGateway:Key"];
|
||||||
|
if (string.IsNullOrWhiteSpace(serviceKey) || serviceKey.Length < 32)
|
||||||
|
throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters.");
|
||||||
|
client.DefaultRequestHeaders.Add("X-Service-Key", serviceKey);
|
||||||
|
})
|
||||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||||
|
|
||||||
var app = builder.Build();
|
var app = builder.Build();
|
||||||
@@ -30,8 +39,24 @@ public class Program
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!app.Environment.IsDevelopment() && GetGatewayUri(app.Configuration).Scheme != "https")
|
||||||
|
throw new InvalidOperationException("Production gateway endpoints must use HTTPS.");
|
||||||
_ = GetGatewayUri(app.Configuration);
|
_ = GetGatewayUri(app.Configuration);
|
||||||
|
var outgoingKey = app.Configuration["Services:ApiGateway:Key"];
|
||||||
|
if (string.IsNullOrWhiteSpace(outgoingKey) || outgoingKey.Length < 32)
|
||||||
|
throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters.");
|
||||||
|
var gatewayKey = app.Configuration["InternalAccess:GatewayKey"];
|
||||||
|
if (string.IsNullOrWhiteSpace(gatewayKey) || gatewayKey.Length < 32)
|
||||||
|
throw new InvalidOperationException("InternalAccess:GatewayKey must contain at least 32 characters.");
|
||||||
app.UseExceptionHandler();
|
app.UseExceptionHandler();
|
||||||
|
app.Use(async (context, next) =>
|
||||||
|
{
|
||||||
|
var supplied = context.Request.Headers["X-Gateway-Key"].ToString();
|
||||||
|
if ((!app.Environment.IsDevelopment() && !context.Request.IsHttps) ||
|
||||||
|
!CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(supplied), Encoding.UTF8.GetBytes(gatewayKey)))
|
||||||
|
{ context.Response.StatusCode = 401; return; }
|
||||||
|
await next(context);
|
||||||
|
});
|
||||||
app.MapControllers();
|
app.MapControllers();
|
||||||
await app.RunAsync();
|
await app.RunAsync();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,17 +5,21 @@ namespace PatientProfileService.Application;
|
|||||||
|
|
||||||
public sealed class PatientApplicationService(PatientRepository repository)
|
public sealed class PatientApplicationService(PatientRepository repository)
|
||||||
{
|
{
|
||||||
public Task<Patient> CreatePatientAsync(CreatePatientRequest request, CancellationToken cancellationToken)
|
public async Task<Patient> CreatePatientAsync(CreatePatientRequest request, string accountId, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
ArgumentException.ThrowIfNullOrWhiteSpace(request.Name);
|
ArgumentException.ThrowIfNullOrWhiteSpace(request.Name);
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(accountId);
|
||||||
|
if (await repository.FindByAccountIdAsync(accountId, cancellationToken) is not null)
|
||||||
|
throw new ProfileAlreadyExistsException();
|
||||||
if (request.DateOfBirth is null)
|
if (request.DateOfBirth is null)
|
||||||
throw new ArgumentException("A date of birth is required.", nameof(request));
|
throw new ArgumentException("A date of birth is required.", nameof(request));
|
||||||
|
|
||||||
// The documented TIMESTAMP columns store UTC without a time-zone component.
|
// The documented TIMESTAMP columns store UTC without a time-zone component.
|
||||||
var now = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);
|
var now = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);
|
||||||
return repository.SaveAsync(new Patient
|
return await repository.SaveAsync(new Patient
|
||||||
{
|
{
|
||||||
PatientId = Guid.NewGuid(),
|
PatientId = Guid.NewGuid(),
|
||||||
|
AccountId = accountId,
|
||||||
Name = request.Name,
|
Name = request.Name,
|
||||||
DateOfBirth = request.DateOfBirth.Value,
|
DateOfBirth = request.DateOfBirth.Value,
|
||||||
ContactInfo = request.ContactInfo,
|
ContactInfo = request.ContactInfo,
|
||||||
@@ -24,6 +28,9 @@ public sealed class PatientApplicationService(PatientRepository repository)
|
|||||||
}, cancellationToken);
|
}, cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Task<Patient?> GetByAccountAsync(string accountId, CancellationToken cancellationToken) =>
|
||||||
|
repository.FindByAccountIdAsync(accountId, cancellationToken);
|
||||||
|
|
||||||
public Task<Patient?> GetPatientAsync(Guid patientId, CancellationToken cancellationToken) =>
|
public Task<Patient?> GetPatientAsync(Guid patientId, CancellationToken cancellationToken) =>
|
||||||
repository.FindByIdAsync(patientId, cancellationToken);
|
repository.FindByIdAsync(patientId, cancellationToken);
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ namespace PatientProfileService.Application;
|
|||||||
|
|
||||||
public interface PatientRepository
|
public interface PatientRepository
|
||||||
{
|
{
|
||||||
|
Task<Patient?> FindByAccountIdAsync(string accountId, CancellationToken cancellationToken);
|
||||||
Task<Patient> SaveAsync(Patient patient, CancellationToken cancellationToken);
|
Task<Patient> SaveAsync(Patient patient, CancellationToken cancellationToken);
|
||||||
Task<Patient?> FindByIdAsync(Guid patientId, CancellationToken cancellationToken);
|
Task<Patient?> FindByIdAsync(Guid patientId, CancellationToken cancellationToken);
|
||||||
Task<bool> UpdateProfileAsync(Guid patientId, string name, string? contactInfo, CancellationToken cancellationToken);
|
Task<bool> UpdateProfileAsync(Guid patientId, string name, string? contactInfo, CancellationToken cancellationToken);
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
namespace PatientProfileService.Application;
|
||||||
|
|
||||||
|
public sealed class ProfileAlreadyExistsException : Exception
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -12,8 +12,24 @@ public sealed class PatientController(PatientApplicationService service) : Contr
|
|||||||
[HttpPost]
|
[HttpPost]
|
||||||
public async Task<ActionResult<PatientDto>> CreatePatient(CreatePatientRequest request, CancellationToken cancellationToken)
|
public async Task<ActionResult<PatientDto>> CreatePatient(CreatePatientRequest request, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var patient = await service.CreatePatientAsync(request, cancellationToken);
|
var accountId = Request.Headers["X-Account-Id"].ToString();
|
||||||
return CreatedAtAction(nameof(GetPatient), new { patientId = patient.PatientId }, ToDto(patient));
|
if (string.IsNullOrWhiteSpace(accountId)) return BadRequest();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var patient = await service.CreatePatientAsync(request, accountId, cancellationToken);
|
||||||
|
return CreatedAtAction(nameof(GetPatient), new { patientId = patient.PatientId }, ToDto(patient));
|
||||||
|
}
|
||||||
|
catch (ProfileAlreadyExistsException)
|
||||||
|
{
|
||||||
|
return Conflict(new { title = "A profile already exists for this account." });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("by-account/{accountId}")]
|
||||||
|
public async Task<ActionResult<PatientDto>> GetByAccount(string accountId, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var patient = await service.GetByAccountAsync(accountId, cancellationToken);
|
||||||
|
return patient is null ? NotFound() : Ok(ToDto(patient));
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet("{patientId:guid}")]
|
[HttpGet("{patientId:guid}")]
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ namespace PatientProfileService.Domain;
|
|||||||
|
|
||||||
public sealed class Patient
|
public sealed class Patient
|
||||||
{
|
{
|
||||||
|
public string? AccountId { get; set; }
|
||||||
public Guid PatientId { get; set; }
|
public Guid PatientId { get; set; }
|
||||||
public string Name { get; set; } = "";
|
public string Name { get; set; } = "";
|
||||||
public DateOnly DateOfBirth { get; set; }
|
public DateOnly DateOfBirth { get; set; }
|
||||||
|
|||||||
+69
@@ -0,0 +1,69 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
|
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||||
|
using PatientProfileService.Persistence;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace PatientProfileService.Persistence.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(PatientDbContext))]
|
||||||
|
[Migration("20261005082209_AccountProfileAssociation")]
|
||||||
|
partial class AccountProfileAssociation
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
#pragma warning disable 612, 618
|
||||||
|
modelBuilder
|
||||||
|
.HasAnnotation("ProductVersion", "10.0.12")
|
||||||
|
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||||
|
|
||||||
|
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||||
|
|
||||||
|
modelBuilder.Entity("PatientProfileService.Domain.Patient", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("PatientId")
|
||||||
|
.HasColumnType("uuid")
|
||||||
|
.HasColumnName("patient_id");
|
||||||
|
|
||||||
|
b.Property<string>("AccountId")
|
||||||
|
.HasColumnType("text")
|
||||||
|
.HasColumnName("account_id");
|
||||||
|
|
||||||
|
b.Property<string>("ContactInfo")
|
||||||
|
.HasColumnType("character varying")
|
||||||
|
.HasColumnName("contact_info");
|
||||||
|
|
||||||
|
b.Property<DateTime>("CreatedAt")
|
||||||
|
.HasColumnType("timestamp without time zone")
|
||||||
|
.HasColumnName("created_at");
|
||||||
|
|
||||||
|
b.Property<DateOnly>("DateOfBirth")
|
||||||
|
.HasColumnType("date")
|
||||||
|
.HasColumnName("date_of_birth");
|
||||||
|
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("character varying")
|
||||||
|
.HasColumnName("name");
|
||||||
|
|
||||||
|
b.Property<DateTime>("UpdatedAt")
|
||||||
|
.HasColumnType("timestamp without time zone")
|
||||||
|
.HasColumnName("updated_at");
|
||||||
|
|
||||||
|
b.HasKey("PatientId");
|
||||||
|
|
||||||
|
b.HasIndex("AccountId")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.ToTable("patient", (string)null);
|
||||||
|
});
|
||||||
|
#pragma warning restore 612, 618
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+38
@@ -0,0 +1,38 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace PatientProfileService.Persistence.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class AccountProfileAssociation : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "account_id",
|
||||||
|
table: "patient",
|
||||||
|
type: "text",
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_patient_account_id",
|
||||||
|
table: "patient",
|
||||||
|
column: "account_id",
|
||||||
|
unique: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropIndex(
|
||||||
|
name: "IX_patient_account_id",
|
||||||
|
table: "patient");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "account_id",
|
||||||
|
table: "patient");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -28,6 +28,10 @@ namespace PatientProfileService.Persistence.Migrations
|
|||||||
.HasColumnType("uuid")
|
.HasColumnType("uuid")
|
||||||
.HasColumnName("patient_id");
|
.HasColumnName("patient_id");
|
||||||
|
|
||||||
|
b.Property<string>("AccountId")
|
||||||
|
.HasColumnType("text")
|
||||||
|
.HasColumnName("account_id");
|
||||||
|
|
||||||
b.Property<string>("ContactInfo")
|
b.Property<string>("ContactInfo")
|
||||||
.HasColumnType("character varying")
|
.HasColumnType("character varying")
|
||||||
.HasColumnName("contact_info");
|
.HasColumnName("contact_info");
|
||||||
@@ -51,6 +55,9 @@ namespace PatientProfileService.Persistence.Migrations
|
|||||||
|
|
||||||
b.HasKey("PatientId");
|
b.HasKey("PatientId");
|
||||||
|
|
||||||
|
b.HasIndex("AccountId")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
b.ToTable("patient", (string)null);
|
b.ToTable("patient", (string)null);
|
||||||
});
|
});
|
||||||
#pragma warning restore 612, 618
|
#pragma warning restore 612, 618
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ public sealed class PatientDbContext(DbContextOptions<PatientDbContext> options)
|
|||||||
var patient = modelBuilder.Entity<Patient>();
|
var patient = modelBuilder.Entity<Patient>();
|
||||||
patient.ToTable("patient");
|
patient.ToTable("patient");
|
||||||
patient.HasKey(p => p.PatientId);
|
patient.HasKey(p => p.PatientId);
|
||||||
|
patient.Property(p => p.AccountId).HasColumnName("account_id");
|
||||||
|
patient.HasIndex(p => p.AccountId).IsUnique();
|
||||||
patient.Property(p => p.PatientId).HasColumnName("patient_id").ValueGeneratedNever();
|
patient.Property(p => p.PatientId).HasColumnName("patient_id").ValueGeneratedNever();
|
||||||
patient.Property(p => p.Name).HasColumnName("name").HasColumnType("character varying").IsRequired();
|
patient.Property(p => p.Name).HasColumnName("name").HasColumnType("character varying").IsRequired();
|
||||||
patient.Property(p => p.DateOfBirth).HasColumnName("date_of_birth").HasColumnType("date");
|
patient.Property(p => p.DateOfBirth).HasColumnName("date_of_birth").HasColumnType("date");
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Npgsql;
|
||||||
using PatientProfileService.Application;
|
using PatientProfileService.Application;
|
||||||
using PatientProfileService.Domain;
|
using PatientProfileService.Domain;
|
||||||
|
|
||||||
@@ -9,10 +10,17 @@ public sealed class SqlPatientRepository(PatientDbContext db) : PatientRepositor
|
|||||||
public async Task<Patient> SaveAsync(Patient patient, CancellationToken cancellationToken)
|
public async Task<Patient> SaveAsync(Patient patient, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
db.Patients.Add(patient);
|
db.Patients.Add(patient);
|
||||||
await db.SaveChangesAsync(cancellationToken);
|
try { await db.SaveChangesAsync(cancellationToken); }
|
||||||
|
catch (DbUpdateException e) when (e.InnerException is PostgresException { SqlState: "23505", ConstraintName: "IX_patient_account_id" })
|
||||||
|
{
|
||||||
|
throw new ProfileAlreadyExistsException();
|
||||||
|
}
|
||||||
return patient;
|
return patient;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Task<Patient?> FindByAccountIdAsync(string accountId, CancellationToken cancellationToken) =>
|
||||||
|
db.Patients.AsNoTracking().SingleOrDefaultAsync(p => p.AccountId == accountId, cancellationToken);
|
||||||
|
|
||||||
public Task<Patient?> FindByIdAsync(Guid patientId, CancellationToken cancellationToken) =>
|
public Task<Patient?> FindByIdAsync(Guid patientId, CancellationToken cancellationToken) =>
|
||||||
db.Patients.AsNoTracking().SingleOrDefaultAsync(p => p.PatientId == patientId, cancellationToken);
|
db.Patients.AsNoTracking().SingleOrDefaultAsync(p => p.PatientId == patientId, cancellationToken);
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using PatientProfileService.Application;
|
using PatientProfileService.Application;
|
||||||
using PatientProfileService.Persistence;
|
using PatientProfileService.Persistence;
|
||||||
@@ -27,7 +29,18 @@ public class Program
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var gatewayKey = app.Configuration["InternalAccess:GatewayKey"];
|
||||||
|
if (string.IsNullOrWhiteSpace(gatewayKey) || gatewayKey.Length < 32)
|
||||||
|
throw new InvalidOperationException("InternalAccess:GatewayKey must contain at least 32 characters.");
|
||||||
app.UseExceptionHandler();
|
app.UseExceptionHandler();
|
||||||
|
app.Use(async (context, next) =>
|
||||||
|
{
|
||||||
|
var supplied = context.Request.Headers["X-Gateway-Key"].ToString();
|
||||||
|
if ((!app.Environment.IsDevelopment() && !context.Request.IsHttps) ||
|
||||||
|
!CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(supplied), Encoding.UTF8.GetBytes(gatewayKey)))
|
||||||
|
{ context.Response.StatusCode = 401; return; }
|
||||||
|
await next(context);
|
||||||
|
});
|
||||||
app.MapControllers();
|
app.MapControllers();
|
||||||
await app.RunAsync();
|
await app.RunAsync();
|
||||||
}
|
}
|
||||||
|
|||||||
+196
-14
@@ -1,11 +1,21 @@
|
|||||||
# US-01–US-10: Patient profiles and blood-pressure observations
|
# Patient profiles, observations, insights, overview and authentication
|
||||||
|
|
||||||
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, Observation Service, and Insights Service are separate executables and can run on separate machines. Patient/Profile and Observation each own a database. Insights calculates on demand without persistence, following `Docs/Requirements/US_10_Correction` and `Docs/Architecture/us10-insights-correction.md`.
|
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, Observation Service, Insights Service, and Health Overview Service are separate executables and can run on separate machines. Patient/Profile and Observation each own a database. Insights calculates on demand without persistence, following `Docs/Architecture/us10-insights-correction.md`.
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
|
US-13 now protects the patient-data APIs. Read [AUTHENTICATION.md](AUTHENTICATION.md)
|
||||||
|
for login, persistent profile ownership, deployment credentials and token settings.
|
||||||
|
Configure the required keys/accounts before startup. The revised US-01 creation
|
||||||
|
lifecycle is included. US-14 now permits read-only access to assigned patients.
|
||||||
|
|
||||||
## Build and run
|
## Build and run
|
||||||
|
|
||||||
|
Load external service configuration using the updated `deploy/*.env.example` templates.
|
||||||
|
Use HTTPS certificates for all production endpoints. For local HTTP development
|
||||||
|
only, set `ASPNETCORE_ENVIRONMENT=Development` on each process; all credentials and
|
||||||
|
the gateway key directory are still required.
|
||||||
|
|
||||||
Install a .NET 10 SDK and provision an empty PostgreSQL database owned by the Patient/Profile service's database user. From the repository root:
|
Install a .NET 10 SDK and provision an empty PostgreSQL database owned by the Patient/Profile service's database user. From the repository root:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -18,7 +28,7 @@ dotnet run --project src/PatientProfileService -c Release --no-build -- --migrat
|
|||||||
ASPNETCORE_URLS=http://127.0.0.1:5081 dotnet run --project src/PatientProfileService -c Release --no-build
|
ASPNETCORE_URLS=http://127.0.0.1:5081 dotnet run --project src/PatientProfileService -c Release --no-build
|
||||||
|
|
||||||
# In a separate gateway terminal.
|
# In a separate gateway terminal.
|
||||||
Services__PatientProfile__BaseUrl=http://127.0.0.1:5081/ Services__Observation__BaseUrl=http://127.0.0.1:5082/ Services__Insights__BaseUrl=http://127.0.0.1:5083/ ASPNETCORE_URLS=http://127.0.0.1:5080 dotnet run --project src/ApiGateway -c Release --no-build
|
Services__PatientProfile__BaseUrl=http://127.0.0.1:5081/ Services__Observation__BaseUrl=http://127.0.0.1:5082/ Services__Insights__BaseUrl=http://127.0.0.1:5083/ Services__HealthOverview__BaseUrl=http://127.0.0.1:5084/ ASPNETCORE_URLS=http://127.0.0.1:5080 dotnet run --project src/ApiGateway -c Release --no-build
|
||||||
|
|
||||||
# In a separate observation terminal, with its own provisioned database.
|
# In a separate observation terminal, with its own provisioned database.
|
||||||
export ConnectionStrings__ObservationDatabase='Host=127.0.0.1;Database=observations;Username=observations;Password=YOUR_LOCAL_PASSWORD'
|
export ConnectionStrings__ObservationDatabase='Host=127.0.0.1;Database=observations;Username=observations;Password=YOUR_LOCAL_PASSWORD'
|
||||||
@@ -27,6 +37,9 @@ Services__ApiGateway__BaseUrl=http://127.0.0.1:5080/ ASPNETCORE_URLS=http://127.
|
|||||||
|
|
||||||
# In a separate insights terminal; no database or migration is required.
|
# In a separate insights terminal; no database or migration is required.
|
||||||
Services__ApiGateway__BaseUrl=http://127.0.0.1:5080/ ASPNETCORE_URLS=http://127.0.0.1:5083 dotnet run --project src/InsightsService -c Release --no-build
|
Services__ApiGateway__BaseUrl=http://127.0.0.1:5080/ ASPNETCORE_URLS=http://127.0.0.1:5083 dotnet run --project src/InsightsService -c Release --no-build
|
||||||
|
|
||||||
|
# In a separate overview terminal; no database or migration is required.
|
||||||
|
Services__ApiGateway__BaseUrl=http://127.0.0.1:5080/ ASPNETCORE_URLS=http://127.0.0.1:5084 dotnet run --project src/HealthOverviewService -c Release --no-build
|
||||||
```
|
```
|
||||||
|
|
||||||
`--migrate` applies committed EF Core migrations and exits. Apply migrations as a deployment step before starting the service; normal startup does not modify the schema. Both services fail startup with a clear message if required configuration is absent. Configuration uses standard .NET JSON files, environment variables, and command-line arguments. Service endpoints and database hosts may be remote.
|
`--migrate` applies committed EF Core migrations and exits. Apply migrations as a deployment step before starting the service; normal startup does not modify the schema. Both services fail startup with a clear message if required configuration is absent. Configuration uses standard .NET JSON files, environment variables, and command-line arguments. Service endpoints and database hosts may be remote.
|
||||||
@@ -38,42 +51,203 @@ Send requests to the gateway:
|
|||||||
```bash
|
```bash
|
||||||
curl -i http://127.0.0.1:5080/api/patients \
|
curl -i http://127.0.0.1:5080/api/patients \
|
||||||
-H 'Content-Type: application/json' \
|
-H 'Content-Type: application/json' \
|
||||||
|
-H 'Authorization: Bearer YOUR_LOGIN_TOKEN' \
|
||||||
-d '{"name":"Steffen Example","dateOfBirth":"1980-01-01","contactInfo":"steffen@example.test"}'
|
-d '{"name":"Steffen Example","dateOfBirth":"1980-01-01","contactInfo":"steffen@example.test"}'
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`POST /api/authentication/login` accepts `accountId` and `password` and returns a
|
||||||
|
protected access token. Include `Authorization: Bearer YOUR_LOGIN_TOKEN` on each
|
||||||
|
patient-data request below. Initial profile creation is permitted once per patient
|
||||||
|
account; repeated/concurrent attempts report `409`. `GET /api/patients/me` retrieves
|
||||||
|
the account’s profile when its generated identifier is not yet known.
|
||||||
|
|
||||||
`POST /api/patients` returns `201 Created`, a relative `Location: /api/patients/{patientId}` header, and a JSON profile containing `patientId`, `name`, `dateOfBirth`, and `contactInfo`. Identifiers are generated UUIDs and the database primary key enforces uniqueness. Names must be nonblank; dates of birth must be supplied as valid `YYYY-MM-DD` dates. Invalid requests return `400` validation problem details and do not create profiles. Contact information is optional because US-01 does not require it.
|
`POST /api/patients` returns `201 Created`, a relative `Location: /api/patients/{patientId}` header, and a JSON profile containing `patientId`, `name`, `dateOfBirth`, and `contactInfo`. Identifiers are generated UUIDs and the database primary key enforces uniqueness. Names must be nonblank; dates of birth must be supplied as valid `YYYY-MM-DD` dates. Invalid requests return `400` validation problem details and do not create profiles. Contact information is optional because US-01 does not require it.
|
||||||
|
|
||||||
`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.
|
`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.
|
||||||
|
|
||||||
`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.
|
`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.
|
||||||
|
|
||||||
`POST /api/patients/{patientId}/observations` records a blood-pressure observation. Supply `measuredAt`, positive integer `systolic`, `diastolic` and `pulse`, plus optional `context` and `note`. It returns `201`, the saved observation including its generated `observationId` and `patientId`, and `Location: /api/observations/{observationId}`. `GET` at that location retrieves the persisted observation, or returns `404` if absent. Retrieval is included to satisfy US-04's requirement that a recorded observation can be retrieved later.
|
`POST /api/patients/{patientId}/observations` records a blood-pressure observation. Supply `measuredAt`, positive integer `systolic`, `diastolic` and `pulse`, plus optional `measurementContext`, legacy `context` and `note`. It returns `201`, the saved observation including its generated `observationId` and `patientId`, and `Location: /api/observations/{observationId}`. `GET` at that location retrieves the persisted observation, or returns `404` if absent. Retrieval is included to satisfy US-04's requirement that a recorded observation can be retrieved later.
|
||||||
|
|
||||||
The Observation Service checks patient existence by calling the gateway's patient retrieval API over HTTP before saving. It has no reference to Patient/Profile implementation code and no access to that service's database. Missing patients return `404`; validation failures return `400`. Patient lookup failures return `502` or `504` and do not save an observation. Measurement timestamps without an offset are stored as supplied; timestamps with an offset are normalized to UTC. PostgreSQL uses the diagram's `timestamp` columns without a time-zone component.
|
US-04 now supports structured context independently of legacy free text:
|
||||||
|
|
||||||
`GET /api/patients/{patientId}/observations/latest` returns `200` with that patient's observation having the greatest measurement timestamp, regardless of recording order. It returns `404` when no observation is available. Equal measurement timestamps are resolved consistently by observation identifier; US-06 does not prescribe which tied observation to return. Selection happens in the Observation Service's own database through the documented controller/application-service/repository layers.
|
```json
|
||||||
|
{
|
||||||
|
"measuredAt": "2026-09-12T08:00:00Z",
|
||||||
|
"systolic": 128,
|
||||||
|
"diastolic": 82,
|
||||||
|
"pulse": 68,
|
||||||
|
"measurementContext": {
|
||||||
|
"setting": "Home",
|
||||||
|
"activityCondition": "AtRest",
|
||||||
|
"restDurationMinutes": 5.5,
|
||||||
|
"bodyPosition": "Seated",
|
||||||
|
"measuredArm": "Left",
|
||||||
|
"deviceDetails": "Example upper-arm device",
|
||||||
|
"cuffDetails": "Example cuff",
|
||||||
|
"additionalCircumstances": "Recent stress"
|
||||||
|
},
|
||||||
|
"context": "Before breakfast",
|
||||||
|
"note": "Actual reading"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
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.
|
Supported `setting` values are `Home`, `Clinic`, `Other`, and `Unknown`;
|
||||||
|
`activityCondition` values are `AtRest`, `DuringActivity`, `AfterActivity`, and
|
||||||
|
`Unknown`. Category names are case-sensitive. Omitted/null categories, or an
|
||||||
|
omitted/null object, become `Unknown`; other omitted details stay null. Unsupported
|
||||||
|
categories and malformed fields return `400` validation details without saving.
|
||||||
|
Rest duration is optional, in minutes, and may be zero or any nonnegative decimal.
|
||||||
|
There is no minimum rest duration or posture requirement for accepting a reading.
|
||||||
|
The remaining optional details are narrative text, not technique certification.
|
||||||
|
Legacy context and notes are retained verbatim, including conflicts with categories;
|
||||||
|
no category is inferred from free text. Interpretation of conflicts belongs to
|
||||||
|
US-11. The structured object is included on observation reads and numeric-update
|
||||||
|
responses, including latest/history through their existing observation DTO.
|
||||||
|
|
||||||
|
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; 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.
|
||||||
|
They verify complete context with its measurements/timestamp after restart, partial
|
||||||
|
and unknown context, preservation of historical free text, missing-observation
|
||||||
|
behaviour, rejected unauthorised reads, and identical context for an assigned
|
||||||
|
professional and the owner. This uses the existing retrieval endpoint and DTO added
|
||||||
|
with US-04; no further production code or migration is needed for US-05.
|
||||||
|
|
||||||
|
The Observation Service checks patient existence by calling the gateway's patient retrieval API over HTTP before saving. It has no reference to Patient/Profile implementation code and no access to that service's database. Missing patients return `404`; validation failures return `400`. Patient lookup failures return `502` or `504` and do not save an observation. Measurement timestamps without an offset represent UTC clock values and are stored as supplied, independently of the host time zone; timestamps with an offset are normalized to UTC. PostgreSQL uses the diagram's `timestamp` columns without a time-zone component.
|
||||||
|
|
||||||
|
`GET /api/patients/{patientId}/observations/latest` returns `200` with that patient's observation having the greatest measurement timestamp, regardless of recording order. It returns `404` when no observation is available. Equal measurement timestamps are resolved by greatest original recording timestamp (`created_at`), then greatest observation UUID under PostgreSQL UUID ordering if recording times also tie. Edits preserve original recording time and do not affect tie selection. Context completeness does not affect selection; the returned observation includes its own saved context. Selection happens in the Observation Service's own database through the documented controller/application-service/repository layers.
|
||||||
|
|
||||||
|
US-06 acceptance tests cover out-of-order measurements, patient-specific selection, context independent of suitability/completeness, recording-time ties, later edits, reproducible complete ties across 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.
|
`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.
|
`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 assessments also use current recorded context on each request.
|
||||||
|
|
||||||
|
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.
|
`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.
|
||||||
|
|
||||||
US-09 tests cover both acceptance scenarios, persistence of deletion after restart, remaining/latest observations, deletion of the only observation, repeated deletion, and preservation of other patients' observations. No new dependencies or schema changes are required.
|
US-09 tests cover the original deletion scenarios plus structured-context removal, filtered history after restart, current numerical summaries excluding deleted values, preservation of other observations and their context, empty filtered results, repeated deletion, and rejection of unauthenticated/other-patient/professional deletion. Context is stored in the observation row, so its existing atomic deletion needs no new production operation. US-11 tests verify fresh trends after deletion. No new dependencies or schema changes are required.
|
||||||
|
|
||||||
`GET /api/patients/{patientId}/insights?from=2026-09-03T00:00:00&to=2026-09-08T23:59:59` returns `200` with `patientId`, `periodStart`, `periodEnd`, decimal `averageSystolic`, `averageDiastolic`, `averagePulse`, and integer `minSystolic`, `maxSystolic`, `minDiastolic`, `maxDiastolic`. Period validation, inclusive bounds, and timestamp normalization follow observation history. A single observation is sufficient; averages retain fractional values without deliberate rounding. An empty period returns `404` problem details with title `Insufficient observation data for calculation.` Missing/malformed/reversed bounds return `400`.
|
`GET /api/patients/{patientId}/insights?from=2026-09-03T00:00:00&to=2026-09-08T23:59:59` returns `200` with `patientId`, `periodStart`, `periodEnd`, decimal `averageSystolic`, `averageDiastolic`, `averagePulse`, and integer `minSystolic`, `maxSystolic`, `minDiastolic`, `maxDiastolic`. Period validation, inclusive bounds, and timestamp normalization follow observation history. A single observation is sufficient. Arithmetic means use decimal calculations and round only the final result to two decimal places, half-up (away from zero for the positive recorded values); extrema retain their recorded integer values. An empty period returns `404` problem details with title `Insufficient observation data for calculation.` Missing/malformed/reversed bounds return `400`.
|
||||||
|
|
||||||
The independent Insights Service follows the documented controller/application-service/calculator/client design. Its HTTP observation client retrieves history through the configured gateway; there are no production project references between services. Each request recalculates from current observations, so corrections/deletions are reflected immediately. Failed observation retrieval returns `502`, and timeouts return `504`, instead of indicating insufficient data. Gateway requests to an unavailable Insights Service likewise return `502`/`504`.
|
The independent Insights Service follows the documented controller/application-service/calculator/client design. Its HTTP observation client retrieves history through the configured gateway; there are no production project references between services. Each request recalculates from current observations, so corrections/deletions are reflected immediately. Failed observation retrieval returns `502`, and timeouts return `504`, instead of indicating insufficient data. Gateway requests to an unavailable Insights Service likewise return `502`/`504`.
|
||||||
|
|
||||||
US-10 tests use all four HTTP hosts and the existing separate patient/observation test databases. They cover all five acceptance scenarios, fractional averages, patient and inclusive-period filtering, equal/offset bounds, corrections/deletions, restart, malformed/missing periods, and unavailable observation retrieval. Insights introduces no external dependencies. Trend calculation remains outside this story.
|
US-10 supports the same optional `setting` and `activityCondition` selections as
|
||||||
|
history, including explicit `Unknown` and combined matching. For example append
|
||||||
|
`&setting=Home&activityCondition=AtRest`. Omitted/empty selections include all
|
||||||
|
otherwise eligible observations. Unsupported categories return `400` validation
|
||||||
|
details. Selection that leaves no observations returns the existing insufficient-
|
||||||
|
data `404` response. Selection is forwarded through the gateway to the Observation
|
||||||
|
Service; no service implementation is referenced directly.
|
||||||
|
|
||||||
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.
|
Successful insights also include `appliedSelection` (nullable `setting` and
|
||||||
|
`activityCondition` mean unrestricted), `contributingCount`, and
|
||||||
|
`contextExplanation`. The explanation reports recorded setting/activity counts,
|
||||||
|
mixed/unknown categories, missing optional context details and differences in
|
||||||
|
recorded optional details. It describes numerical aggregation without certifying
|
||||||
|
measurement technique, clinical comparability or completion of a diagnostic
|
||||||
|
monitoring protocol. Legacy narrative text is retained by the observation contract
|
||||||
|
but never used to invent categories. Preparation differences are reported as
|
||||||
|
recorded differences, not a clinical classification.
|
||||||
|
|
||||||
|
The rounding contract applies to all three means: seven readings of 120 and one
|
||||||
|
of 121 yield 120.13; 120, 120 and 121 yield 120.33. No intermediate rounding occurs.
|
||||||
|
Single-observation means equal the recorded values, and blood-pressure minimum and
|
||||||
|
maximum are equal. Numeric JSON need not retain trailing zeros. New requests always
|
||||||
|
use current observations/context after corrections, clearing and deletion.
|
||||||
|
|
||||||
|
US-10 tests use all four HTTP hosts and the existing separate patient/observation
|
||||||
|
test databases. They cover original summaries, independent/combined/unknown
|
||||||
|
selections, applied selections and counts, context explanations, one-observation
|
||||||
|
results, halfway/repeating rounding for all three metrics, patient/inclusive/equal/
|
||||||
|
offset bounds, context corrections/clearing/deletions, restart, invalid requests,
|
||||||
|
professional assignments and unavailable observation retrieval. Insights introduces no external dependencies. US-11 adds the separate trend endpoint described in [TRENDS.md](TRENDS.md).
|
||||||
|
|
||||||
|
`GET /api/patients/{patientId}/trends?from=...&to=...` implements US-11 with independent
|
||||||
|
systolic, diastolic and pulse assessments, context selections/counts, recorded comparability,
|
||||||
|
full-period numerical direction, reversals and variation, sourced reference comparisons and
|
||||||
|
limited clinical interpretation. Empty/single/tied series report unavailable temporal direction;
|
||||||
|
numerical information remains where supported. See [TRENDS.md](TRENDS.md) for the response,
|
||||||
|
reproducible mathematical methods, reference sources and interpretation limits. Tests cover
|
||||||
|
all US-11 acceptance criteria, current corrections/context/deletion, access controls and failures.
|
||||||
|
No persistence, service boundaries, dependencies or configuration changed.
|
||||||
|
|
||||||
|
`GET /api/patients/{patientId}/overview?from=...&to=...` implements US-12 in the
|
||||||
|
independently deployable Health Overview Service. It returns the current profile,
|
||||||
|
latest overall observation with its own recorded context, and selected-period numerical
|
||||||
|
insight. Setting/activity filters apply to insight only. Empty insight selections keep
|
||||||
|
the profile and latest reading and explain the missing insight. Context limitations,
|
||||||
|
applied selections and counts remain visible. See [OVERVIEW.md](OVERVIEW.md) for
|
||||||
|
response semantics, service credentials, deployment and consistency limits.
|
||||||
|
|
||||||
|
US-13 authentication and patient ownership are implemented as described in
|
||||||
|
[AUTHENTICATION.md](AUTHENTICATION.md). The account-to-profile association is persisted
|
||||||
|
in the patient service. US-14 professional reads require predefined gateway assignments; professional
|
||||||
|
writes are rejected. US-04 through US-11 include updated context, ordering, rounding and trend requirements.
|
||||||
|
|
||||||
## Automated acceptance tests
|
## Automated acceptance tests
|
||||||
|
|
||||||
@@ -117,7 +291,7 @@ The xUnit tests send HTTP requests to the gateway; the gateway reaches a real Ke
|
|||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
US-04 tests use real HTTP between all three hosts and separate temporary patient and observation databases. They cover every recording acceptance scenario, retrieval after restart, optional fields, distinct identifiers, malformed/missing fields, missing observations, and patient-lookup failure without database writes. Both services' committed migrations are applied twice to verify idempotence. The Observation Service uses the same EF Core PostgreSQL dependencies as Patient/Profile for its independent persistence; no new library types are introduced.
|
US-04 tests use real HTTP between the hosts and separate temporary patient and observation databases. They cover every recording acceptance scenario, retrieval after restart, optional fields, distinct identifiers, malformed/missing fields, missing observations, and patient-lookup failure without database writes. Both services' committed migrations are applied twice to verify idempotence. Context tests also verify complete/partial/absent context, departures from guidance, validation without writes, authorised professional reads, restart persistence, numeric-update preservation, and upgrading historical observations without deriving categories from free text. The Observation Service uses the same EF Core PostgreSQL dependencies as Patient/Profile for its independent persistence; no new library types are introduced.
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
@@ -130,6 +304,7 @@ dotnet publish src/PatientProfileService -c Release -o /tmp/healthapp-publish/pa
|
|||||||
dotnet publish src/ApiGateway -c Release -o /tmp/healthapp-publish/api-gateway
|
dotnet publish src/ApiGateway -c Release -o /tmp/healthapp-publish/api-gateway
|
||||||
dotnet publish src/ObservationService -c Release -o /tmp/healthapp-publish/observation
|
dotnet publish src/ObservationService -c Release -o /tmp/healthapp-publish/observation
|
||||||
dotnet publish src/InsightsService -c Release -o /tmp/healthapp-publish/insights
|
dotnet publish src/InsightsService -c Release -o /tmp/healthapp-publish/insights
|
||||||
|
dotnet publish src/HealthOverviewService -c Release -o /tmp/healthapp-publish/health-overview
|
||||||
```
|
```
|
||||||
|
|
||||||
Copy each output to its corresponding `/opt/healthapp/` directory on the intended host, install the ASP.NET Core 10 runtime, and create a `healthapp` service user/group. Adjust the paths/user in `deploy/systemd/*.service` for the host. Copy the environment examples to `/etc/healthapp/patient-profile.env` and `/etc/healthapp/api-gateway.env`, replace example values, and restrict their permissions to protect credentials. Configure the gateway certificate for the HTTPS client entry point. Its example uses a PFX certificate; standard Kestrel configuration also supports other certificate formats.
|
Copy each output to its corresponding `/opt/healthapp/` directory on the intended host, install the ASP.NET Core 10 runtime, and create a `healthapp` service user/group. Adjust the paths/user in `deploy/systemd/*.service` for the host. Copy the environment examples to `/etc/healthapp/patient-profile.env` and `/etc/healthapp/api-gateway.env`, replace example values, and restrict their permissions to protect credentials. Configure the gateway certificate for the HTTPS client entry point. Its example uses a PFX certificate; standard Kestrel configuration also supports other certificate formats.
|
||||||
@@ -146,3 +321,10 @@ Install the corresponding unit on each host and enable/start it with systemd. Th
|
|||||||
The Observation Service has its own `healthapp-observation.service` unit and environment example. Configure its `Services__ApiGateway__BaseUrl` and the gateway's `Services__Observation__BaseUrl` for the deployed hosts. Apply its migration with its own database configuration. Services need not be started in a fixed order; requests needing an unavailable upstream fail without saving observations.
|
The Observation Service has its own `healthapp-observation.service` unit and environment example. Configure its `Services__ApiGateway__BaseUrl` and the gateway's `Services__Observation__BaseUrl` for the deployed hosts. Apply its migration with its own database configuration. Services need not be started in a fixed order; requests needing an unavailable upstream fail without saving observations.
|
||||||
|
|
||||||
The Insights Service has an independent `healthapp-insights.service` systemd unit and `deploy/insights.env.example`. Install its published output under `/opt/healthapp/insights`, configure `/etc/healthapp/insights.env`, and set `Services__ApiGateway__BaseUrl` to the deployed gateway. Configure the gateway's required `Services__Insights__BaseUrl` for the deployed Insights host. URLs may refer to separate machines. Insights requires no database, migration, startup ordering, or shared process state. Standard stdout/stderr logging, graceful shutdown, and restart follow the other service units.
|
The Insights Service has an independent `healthapp-insights.service` systemd unit and `deploy/insights.env.example`. Install its published output under `/opt/healthapp/insights`, configure `/etc/healthapp/insights.env`, and set `Services__ApiGateway__BaseUrl` to the deployed gateway. Configure the gateway's required `Services__Insights__BaseUrl` for the deployed Insights host. URLs may refer to separate machines. Insights requires no database, migration, startup ordering, or shared process state. Standard stdout/stderr logging, graceful shutdown, and restart follow the other service units.
|
||||||
|
|
||||||
|
The Health Overview Service has its own `healthapp-health-overview.service` unit and
|
||||||
|
`deploy/health-overview.env.example`. Publish to `/opt/healthapp/health-overview` and
|
||||||
|
configure `/etc/healthapp/health-overview.env`. Set its `Services__ApiGateway__BaseUrl`
|
||||||
|
and the gateway's `Services__HealthOverview__BaseUrl` to the deployed hosts. The
|
||||||
|
gateway now requires the Overview endpoint and both directions of service credentials.
|
||||||
|
Overview owns no database and requires no migrations or fixed startup order.
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
# US-11 trend API and methods
|
||||||
|
|
||||||
|
`GET /api/patients/{patientId}/trends?from=...&to=...&setting=Home&activityCondition=AtRest`
|
||||||
|
uses the same inclusive UTC measurement-instant semantics and optional context selections as history and
|
||||||
|
numerical insight. Offset-free timestamps mean UTC. Both selected dimensions must match; `Unknown`
|
||||||
|
is an explicit category. Patient ownership or professional assignment is required. Each selection is a
|
||||||
|
separate labelled result for the same requested period. No cross-setting difference is interpreted as
|
||||||
|
improvement. Insights retrieves current observations through the gateway on every request, without persistence.
|
||||||
|
|
||||||
|
A valid request returns 200 even for an empty selection. Count zero, null descriptive values and explicit
|
||||||
|
`Unavailable` direction distinguish empty data from upstream failures (502/504). One observation or
|
||||||
|
all observations at a single instant retain descriptive values, but temporal direction is unavailable.
|
||||||
|
Invalid/missing period or unsupported selections return 400. No new configuration or dependencies are required.
|
||||||
|
|
||||||
|
## Numerical method
|
||||||
|
|
||||||
|
Each metric has its own unit, mean, minimum, maximum and range over every eligible observation. Decimal
|
||||||
|
means are rounded only for output, to two decimals with midpoint rounding away from zero. No numerical
|
||||||
|
range threshold is used to declare clinical stability or instability.
|
||||||
|
|
||||||
|
Temporal calculations group equal measurement instants using the arithmetic mean for each metric,
|
||||||
|
then order those groups by measurement instant. Identifier and storage order play no part. Direction
|
||||||
|
uses every adjacent nonzero change: all positive means Increasing, all negative Decreasing, both signs
|
||||||
|
Mixed, all zero NoClearDirection. Reversal count counts sign changes after excluding zero steps.
|
||||||
|
TotalSuccessiveChange sums absolute changes between consecutive timestamp means. This retains intermediate
|
||||||
|
excursions, while raw min/max retain differences within timestamp ties. No temporal change is assigned
|
||||||
|
between measurements at the same instant.
|
||||||
|
|
||||||
|
OverallDirection additionally reports the sign of an ordinary least-squares line over all timestamp
|
||||||
|
means. Time is scaled from zero to one over the observed span; each distinct timestamp has equal weight.
|
||||||
|
SlopePerDay converts that fitted slope to metric units per day and rounds to six decimals. Classification
|
||||||
|
uses the unrounded slope. An extremely small nonzero slope may round to zero; its sign is a mathematical
|
||||||
|
result, not evidence of clinical significance. The fit describes a linear tendency, not a prediction,
|
||||||
|
causal effect or a monotonic trajectory. Mixed direction and reversal count remain visible even when
|
||||||
|
an overall slope exists. Irregular sampling and repeated observations can affect the description;
|
||||||
|
there is no significance test, smoothing, diagnostic protocol or clinical variability classification.
|
||||||
|
|
||||||
|
## Context and interpretation
|
||||||
|
|
||||||
|
Comparability lists known similarities, differences and missing information for setting, activity,
|
||||||
|
rest duration, body position, measured arm, device and cuff. Differing recorded additional circumstances
|
||||||
|
also limit comparability. Matching complete recorded fields support comparability of recorded details
|
||||||
|
only, without certifying clinical technique or equipment. Missing optional additional circumstances do
|
||||||
|
not block a supported reference comparison. Known inadequate rest is reported separately.
|
||||||
|
|
||||||
|
Limited deterministic conflict detection recognises case-insensitive `during exercise`, `during activity`,
|
||||||
|
`after exercise`, `after activity`, `under motion`, `under træning`, `efter motion`, `efter træning` against
|
||||||
|
AtRest; `at clinic`, `in clinic`, `at the clinic`, `på klinik`, `hos lægen` against Home; and `at home`,
|
||||||
|
`hjemme` against Clinic. It examines preserved context, notes and recorded preparation text, without
|
||||||
|
recategorising observations. This is conservative phrase detection, not general language understanding;
|
||||||
|
negated phrases can still withhold interpretation. Arbitrary narrative is not proof of correct technique.
|
||||||
|
Detected conflicts withhold resting-reference interpretation while preserving numerical information.
|
||||||
|
|
||||||
|
Sources reviewed 2026-10-05:
|
||||||
|
|
||||||
|
- [Lægehåndbogen: Højt blodtryk](https://www.sundhed.dk/sundhedsfaglig/laegehaandbogen/hjerte-kar/symptomer-og-tegn/hoejt-blodtryk/)
|
||||||
|
(updated 2024-09-25): separate high-pressure boundaries of home 135/85 and clinic 140/90 mmHg,
|
||||||
|
inclusive. The reference comparison requires a single known setting and recorded AtRest; known rest
|
||||||
|
below five minutes or a non-seated recorded position prevents it. Missing optional preparation
|
||||||
|
details permit only a provisional comparison, explicitly identifying unknown technique. Arbitrary
|
||||||
|
period means do not establish the source's diagnostic protocol. No lower BP boundary is inferred.
|
||||||
|
- [Patienthåndbogen: Bradykardi](https://www.sundhed.dk/borger/patienthaandbogen/hjerte-og-blodkar/sygdomme/hjertearytmier/bradykardi-langsom-puls/)
|
||||||
|
(updated 2025-09-02) and [Hurtig puls](https://www.sundhed.dk/borger/patienthaandbogen/hjerte-og-blodkar/sygdomme/hjertearytmier/takykardier-hurtig-puls/)
|
||||||
|
(updated 2025-05-12): resting pulse below 50 or above 100 beats/min provides limited rate-reference
|
||||||
|
comparisons. Low pulse can be physiological in trained people. Rate alone does not diagnose rhythm
|
||||||
|
abnormalities; age, fitness, medicines and symptoms remain unknown. These boundaries are not a
|
||||||
|
universal healthy range or a patient-specific target.
|
||||||
|
|
||||||
|
Every metric returns its reference scope, exact comparison operators, source URLs, update/review dates,
|
||||||
|
counts outside the boundaries and limitations. Comparisons remain available despite missing preparation
|
||||||
|
information when the known context supports that limited comparison. Mixed or unknown activity,
|
||||||
|
conflicting narrative, mixed BP settings, or unsupported BP setting make the affected comparison unavailable.
|
||||||
|
|
||||||
|
Interpretation of development requires temporal separation, applicable references and supported recorded
|
||||||
|
comparability. The following are deliberately cautious inferences from the cited references, not new
|
||||||
|
clinical decision rules: a consistent fall from high BP that remains high may be PotentiallyFavourable,
|
||||||
|
while explicitly still high; resting pulse moving from outside towards the reference interval may be
|
||||||
|
PotentiallyFavourable unless any contributing observation crosses the opposite boundary, including values within timestamp ties. Excursions outside a boundary with reversals
|
||||||
|
are Mixed. Other outside-reference levels may be PotentiallyConcerning, including falling low pulse
|
||||||
|
or unchanging high BP. Remaining cases are CannotInterpret. No BP fall below the high threshold is
|
||||||
|
automatically called favourable, because an applicable lower limit or personalised goal is unavailable.
|
||||||
|
|
||||||
|
Each hint distinguishes numerical variation from clinical meaning, explains incomplete/differing context,
|
||||||
|
and disclaims diagnosis and medication advice. There is no combined good/bad classification across metrics.
|
||||||
|
Reference comparisons and hints are for review, not a replacement for individual clinical assessment.
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
# Current requirements versus implementation
|
||||||
|
|
||||||
|
Reviewed on 2026-10-05 against commit `0ce9b2b`, all current US-01–US-15 files and the common requirements. This is an implementation coverage review, not a proposed replacement of requirements. No implementation or authoritative documentation was changed.
|
||||||
|
|
||||||
|
The latest implementation validation passed 111 tests. Those tests were not rerun for this static review: the implementation has not changed. Passing the existing suite does not establish coverage of the new context, professional-access, trend and overview criteria.
|
||||||
|
|
||||||
|
## Story coverage
|
||||||
|
|
||||||
|
| Story | Current coverage | Remaining work |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| US-01 Create profile | Implemented for patients | None identified in the story-specific creation behaviour. Authentication, persistent association, duplicate/concurrent creation, retry/recovery and restart are implemented and tested. |
|
||||||
|
| US-02 View profile | Implemented for patients | Assigned professional reads depend on US-14's common access requirements. |
|
||||||
|
| US-03 Update profile | Implemented for patients | Extend professional-write rejection tests across this operation under US-14. The gateway already rejects professionals by default. |
|
||||||
|
| US-04 Record observation | Original numerical behaviour implemented; revised story partial | Add independently recordable setting and activity, optional preparation/device/cuff/circumstance details, persistence and migration, category validation, and context response coverage. Preserve optional/legacy text and do not invent missing categories. |
|
||||||
|
| US-05 View observation | Numerical values and legacy text returned with patient ownership checks; revised story partial | Return structured saved context and distinguish unknown values; test partial context and historical free text alongside new context. |
|
||||||
|
| US-06 Latest observation | Greatest measurement timestamp implemented; revised story partial | Return structured context. Change ties to original recording time before the deterministic identifier rule; verify edits do not affect recording time. |
|
||||||
|
| US-07 Observation history | Patient/period filtering, chronology and inclusive bounds implemented; revised story partial | Setting/activity/combined/unknown selections; selection metadata; structured context in every observation; invalid category rejection and matching-boundary tests. |
|
||||||
|
| US-08 Update observation | Numerical correction implemented; revised story partial | Add, correct and clear individual context values without erasing omitted values. Current request requires all three numerical fields, so context-only updates are impossible. Verify atomic invalid-category rejection and fresh selection/assessment membership. |
|
||||||
|
| US-09 Delete observation | Core deletion implemented | It already removes the entire row, including legacy context, and recalculated summaries exclude deleted observations. New structured-context, filtered-history and trend assertions depend on US-04/07/11; verify those integrations before treating all new criteria as covered. No separate context lifecycle is needed. |
|
||||||
|
| US-10 Numerical insight | Original summaries implemented; revised story partial | Two-decimal half-up final rounding, context selections, contributing count, applied-selection metadata and mixed/unknown-context explanation. Retain single-observation behaviour, extrema, bounds and freshness. |
|
||||||
|
| US-11 Health trend | Not implemented | Add the endpoint and separate metric assessment results; reproducible documented full-period methods; direction, reversals, variation, sufficiency, reference comparisons, clinical limitations, context selection/comparability and fresh results. Evidence-based clinical interpretation must satisfy the current story rather than the obsolete endpoint-only suggestion. |
|
||||||
|
| US-12 Health overview | Not implemented | Build the independent Health Overview service and HTTP clients through the gateway, with its controller/contracts/configuration/systemd deployment. Aggregate profile, latest overall observation and selected-period insight, retaining metadata and explanations. No trend component is required. |
|
||||||
|
| US-13 Patient authentication | Implemented for existing APIs | Login, hashed credentials, expiry/tampering rejection, ownership, no-profile state, service protection and public guidance are covered. Add equivalent access tests as trend/overview endpoints appear. US-14's professional permissions are separate unfinished work. |
|
||||||
|
| US-14 Professional access | Trusted professional login and default rejection exist; story partial | Predefined assignments; own assignment-list endpoint; empty-list behaviour; assigned-patient read policy; resource-ID ownership/assignment checks; unassigned access and write rejection tests for every relevant API. Current middleware denies all professional patient-data operations. |
|
||||||
|
| US-15 Measurement guidance | Implemented | Public ordered home instructions, source/review metadata, unknown setting, activity/pulse limitations, optionality, no patient-service calls and explicit unavailable guidance are covered. Keep the recorded source review current when content changes. |
|
||||||
|
|
||||||
|
All patient-specific reads remain subject to the common US-14 rule for assigned professionals. Consequently, implementation of a patient's own operation does not mean the complete system-wide role matrix is finished.
|
||||||
|
|
||||||
|
## Concrete code mismatches
|
||||||
|
|
||||||
|
1. **US-06 recording-time tie rule:** `src/ObservationService/Persistence/SqlObservationRepository.cs` orders latest results by `MeasuredAt`, then `ObservationId`. It does not use the persisted `CreatedAt` as the second criterion. Two equally timed observations can therefore return the older recorded observation, contrary to the new acceptance scenario.
|
||||||
|
2. **US-10 rounding:** `src/InsightsService/Domain/InsightCalculator.cs` returns unrounded decimal arithmetic means. For the new eight-value fixture it calculates `120.125`, while the required result is `120.13`; for 120, 120, 121 it returns a repeating decimal representation rather than `120.33`. Existing fractional tests use `.5`, which does not expose this mismatch.
|
||||||
|
3. **Context is only free text:** `RecordObservationRequest`, `ObservationDto` and `BloodPressureObservation` currently expose legacy `Context` and `Note`; there is no independently selectable setting/activity/preparation model. New properties submitted by a client are not implemented or persisted. The API must not be considered compliant just because a submission returns success.
|
||||||
|
4. **Context-only update rejection:** `UpdateObservationRequest` requires systolic, diastolic and pulse and contains no context properties. The new context-only requests cannot fulfil US-08.
|
||||||
|
5. **No context filters or result metadata:** observation history and insight endpoints bind only the period, with no setting/activity selections. The insight DTO has no contributing count or context explanation. Supplying a filter query does not produce the required filtered result.
|
||||||
|
6. **Professional access denied wholesale:** `PatientAccessMiddleware` explicitly permits the Patient policy and denies other non-service roles. This is safe interim behaviour, but does not satisfy assigned professional reads.
|
||||||
|
7. **Trend and overview absent:** there is no trend calculation/route or Health Overview project. Authentication fallback is not a substitute for implementing those stories or testing their access.
|
||||||
|
|
||||||
|
## Architecture and implementation boundaries
|
||||||
|
|
||||||
|
The updated draw.io models already authorise structured observation context and separate assessment results. Implement those changes inside the existing Observation/Insights services; shared production libraries or new context services are unnecessary. The documented Health Overview boundary does require its own independently runnable service. Continue gateway-routed HTTP access, service-owned databases and on-demand Insights calculation without generated-result persistence.
|
||||||
|
|
||||||
|
US-13's existing transport/credential design must extend to the Overview service when it is introduced. Its internal reads need explicit scoped service access; the current internal authentication handler recognises only Observation and Insights. Preserve patient authentication and ownership for both new public endpoints.
|
||||||
|
|
||||||
|
Document the exact interpretation of offset-free timestamps explicitly when updating implementation notes. Current code preserves their clock values and normalises offset-bearing input to UTC; the common requirements require a machine-independent documented instant interpretation. This is a documentation clarification, not a reason to invent a new time-zone feature.
|
||||||
|
|
||||||
|
## Recommended work order
|
||||||
|
|
||||||
|
1. Complete US-14 for existing APIs and retain access tests for future endpoints.
|
||||||
|
2. Complete structured context recording under US-04, including retrieval necessary to prove saved data.
|
||||||
|
3. Update US-05 and US-06, then US-07 and US-08, one logical story commit at a time.
|
||||||
|
4. Verify US-09 with context and filtering, and complete US-10 including its rounding fixtures.
|
||||||
|
5. Implement US-11 and US-12 independently using their documented dependencies. US-12 depends on numerical insight, not on US-11's trend output.
|
||||||
|
6. Verify the complete role/context/period acceptance suite across all services before claiming full specification coverage or using it for architectural comparison.
|
||||||
|
|
||||||
|
No new contradictory requirements were identified in this review. The findings are unfinished implementation and missing acceptance coverage.
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# US-12 — Overview persistence clarification resolved
|
||||||
|
|
||||||
|
Status: resolved by the user's authoritative diagram rename on 2026-10-05.
|
||||||
|
The Overview ER illustration is now named
|
||||||
|
`10_er_health_overview_service-overruled no persistence here to give an idea of what data is needed to be able to use from other services or calculate.jpg`.
|
||||||
|
This explicitly identifies its fields as a non-persisted data illustration. Follow
|
||||||
|
`06_class_health_overview_service.drawio`: aggregate current source-service data
|
||||||
|
without own persistence. No architecture or requirements documents were edited by the agent.
|
||||||
|
|
||||||
|
The original conflict and recommendation are retained below as review history;
|
||||||
|
the approval request and draft status below are superseded by this resolution.
|
||||||
|
|
||||||
|
## Original proposal
|
||||||
|
|
||||||
|
## Conflicting authoritative material
|
||||||
|
|
||||||
|
- `Docs/Architecture/06_class_health_overview_service.drawio` explicitly says the
|
||||||
|
application service loads profile, latest overall observation and selected-period
|
||||||
|
numerical insight and aggregates **without own persistence**.
|
||||||
|
- `Docs/Architecture/10_er_health_overview_service.jpg` shows a `HealthOverview`
|
||||||
|
table with a `patient_id` primary key, copied patient/latest/average fields and
|
||||||
|
`updated_at`.
|
||||||
|
- `Docs/Architecture/README.md` supersedes only listed same-stem JPEGs; the Overview
|
||||||
|
ER diagram is unlisted and remains supplied. Unlike Insights, there is no explicit
|
||||||
|
correction retiring the Overview ER table or identifying it as a non-persisted projection.
|
||||||
|
|
||||||
|
The ER diagram's database-shaped representation is ambiguous against the explicit
|
||||||
|
no-persistence class model. Implementation must not silently decide that it requires
|
||||||
|
storage or silently retire it.
|
||||||
|
|
||||||
|
## Recommended clarification (requires approval)
|
||||||
|
|
||||||
|
Follow the current class model: the independent Health Overview service calculates
|
||||||
|
on demand through gateway-routed HTTP clients and owns no database, cache or stored
|
||||||
|
aggregate. Treat the retained Overview ER diagram as a historical/logical projection,
|
||||||
|
not a persistence requirement. The user can incorporate that clarification into the
|
||||||
|
authoritative Architecture documentation; no Docs files have been edited.
|
||||||
|
|
||||||
|
This keeps current profile, latest context and selected numerical insight visible
|
||||||
|
without an unspecified synchronisation/update mechanism or additional persistence.
|
||||||
|
It matches US-12 and the explicit current Overview application-service responsibility.
|
||||||
|
|
||||||
|
If persistence is intended instead, clarify ownership, refresh/invalidation, period
|
||||||
|
and selection keys, consistency after edits/deletion, and storage schema before that
|
||||||
|
implementation proceeds. A patient-id-only table cannot represent arbitrary selected
|
||||||
|
periods and context selections without additional decisions.
|
||||||
|
|
||||||
|
## Prepared implementation
|
||||||
|
|
||||||
|
A working draft independent service, clients, protected gateway route, configuration,
|
||||||
|
systemd template and acceptance tests are present in the working tree. They implement
|
||||||
|
the recommended on-demand option and remain uncommitted pending this clarification.
|
||||||
|
No authoritative documentation or existing review file was changed. The draft does
|
||||||
|
not constitute an approved resolution of the conflict or a completed US-12 commit.
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
using HealthApp.TestSupport;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace Observation.AcceptanceTests;
|
||||||
|
|
||||||
|
public sealed class ContextFilteredHistoryTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||||
|
{
|
||||||
|
private sealed record Profile(Guid PatientId);
|
||||||
|
private sealed record ContextData(string Setting, string ActivityCondition, string? DeviceDetails);
|
||||||
|
private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||||
|
string? Context, ContextData MeasurementContext);
|
||||||
|
private const string Period = "from=2026-09-01T08%3A00%3A00&to=2026-09-10T08%3A00%3A00";
|
||||||
|
|
||||||
|
private async Task<Guid> Patient()
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Filtered history", dateOfBirth = "1980-01-01" });
|
||||||
|
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||||
|
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<Observation> Record(Guid patient, string time, string? setting, string? activity, string? legacy = null, bool includeContext = true, bool completeContext = false)
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patient}/observations", new
|
||||||
|
{
|
||||||
|
measuredAt = time, systolic = 128, diastolic = 82, pulse = 68, context = legacy,
|
||||||
|
measurementContext = includeContext ? new
|
||||||
|
{
|
||||||
|
setting, activityCondition = activity, deviceDetails = "Saved device",
|
||||||
|
restDurationMinutes = completeContext ? (decimal?)5 : null,
|
||||||
|
bodyPosition = completeContext ? "Seated" : null,
|
||||||
|
measuredArm = completeContext ? "Left" : null,
|
||||||
|
cuffDetails = completeContext ? "Saved cuff" : null,
|
||||||
|
additionalCircumstances = completeContext ? "Usual routine" : null
|
||||||
|
} : null
|
||||||
|
});
|
||||||
|
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||||
|
return (await response.Content.ReadFromJsonAsync<Observation>())!;
|
||||||
|
}
|
||||||
|
|
||||||
|
private string PathFor(Guid patient, string selection = "", string period = Period) =>
|
||||||
|
$"/api/patients/{patient}/observations?{period}{selection}";
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("&setting=Home", "Home", "All", 2)]
|
||||||
|
[InlineData("&activityCondition=AtRest", "All", "AtRest", 2)]
|
||||||
|
[InlineData("&setting=Home&activityCondition=AtRest", "Home", "AtRest", 1)]
|
||||||
|
public async Task Independent_and_combined_selections_return_matching_context_and_metadata(string selection,
|
||||||
|
string settingHeader, string activityHeader, int expectedCount)
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
var homeRest = await Record(patient, "2026-09-05T08:00:00", "Home", "AtRest");
|
||||||
|
var homeAfter = await Record(patient, "2026-09-06T08:00:00", "Home", "AfterActivity");
|
||||||
|
var clinicRest = await Record(patient, "2026-09-07T08:00:00", "Clinic", "AtRest");
|
||||||
|
await Record(patient, "2026-09-08T08:00:00", null, null, "Home, resting? Morning reading");
|
||||||
|
using var response = await fixture.Client.GetAsync(PathFor(patient, selection));
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
Assert.Equal(settingHeader, Assert.Single(response.Headers.GetValues("X-Measurement-Setting")));
|
||||||
|
Assert.Equal(activityHeader, Assert.Single(response.Headers.GetValues("X-Activity-Condition")));
|
||||||
|
var history = (await response.Content.ReadFromJsonAsync<Observation[]>())!;
|
||||||
|
Assert.Equal(expectedCount, history.Length);
|
||||||
|
var expected = new[] { homeRest, homeAfter, clinicRest }.Where(o =>
|
||||||
|
(settingHeader == "All" || o.MeasurementContext.Setting == settingHeader) &&
|
||||||
|
(activityHeader == "All" || o.MeasurementContext.ActivityCondition == activityHeader)).ToArray();
|
||||||
|
Assert.Equal(expected, history);
|
||||||
|
Assert.All(history, o => Assert.Equal("Saved device", o.MeasurementContext.DeviceDetails));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("&setting=Unknown", "Unknown", "All")]
|
||||||
|
[InlineData("&activityCondition=Unknown", "All", "Unknown")]
|
||||||
|
[InlineData("&setting=Unknown&activityCondition=Unknown", "Unknown", "Unknown")]
|
||||||
|
public async Task Unknown_selections_match_unknown_categories_without_interpreting_legacy_text(string selection,
|
||||||
|
string settingHeader, string activityHeader)
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
var unknown = await Record(patient, "2026-09-05T08:00:00", null, null, "Home resting?");
|
||||||
|
var partial = await Record(patient, "2026-09-06T08:00:00", "Clinic", null);
|
||||||
|
await Record(patient, "2026-09-07T08:00:00", "Home", "AtRest");
|
||||||
|
using var response = await fixture.Client.GetAsync(PathFor(patient, selection));
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
Assert.Equal(settingHeader, Assert.Single(response.Headers.GetValues("X-Measurement-Setting")));
|
||||||
|
Assert.Equal(activityHeader, Assert.Single(response.Headers.GetValues("X-Activity-Condition")));
|
||||||
|
var result = (await response.Content.ReadFromJsonAsync<Observation[]>())!;
|
||||||
|
Assert.Equal(activityHeader == "Unknown" && settingHeader == "All" ? new[] { unknown, partial } : new[] { unknown }, result);
|
||||||
|
Assert.Equal("Home resting?", result[0].Context);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task No_selection_retains_all_contexts_in_chronological_order_after_restart()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
var last = await Record(patient, "2026-09-07T08:00:00", null, null, includeContext: false);
|
||||||
|
var first = await Record(patient, "2026-09-05T08:00:00", "Home", "AtRest", completeContext: true);
|
||||||
|
var middle = await Record(patient, "2026-09-06T08:00:00", "Clinic", null);
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
using var response = await fixture.Client.GetAsync(PathFor(patient));
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
Assert.Equal(new[] { first, middle, last }, await response.Content.ReadFromJsonAsync<Observation[]>());
|
||||||
|
Assert.Equal("All", Assert.Single(response.Headers.GetValues("X-Measurement-Setting")));
|
||||||
|
Assert.Equal("All", Assert.Single(response.Headers.GetValues("X-Activity-Condition")));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Empty_filtered_history_is_an_empty_array_with_applied_selection_metadata()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
await Record(patient, "2026-09-05T08:00:00", "Home", "AtRest");
|
||||||
|
using var response = await fixture.Client.GetAsync(PathFor(patient, "&setting=Other&activityCondition=AfterActivity"));
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
Assert.Equal("[]", await response.Content.ReadAsStringAsync());
|
||||||
|
Assert.Equal("Other", Assert.Single(response.Headers.GetValues("X-Measurement-Setting")));
|
||||||
|
Assert.Equal("AfterActivity", Assert.Single(response.Headers.GetValues("X-Activity-Condition")));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Filtered_history_preserves_patient_scope_inclusive_boundaries_and_equal_bounds()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
var last = await Record(patient, "2026-09-10T08:00:00", "Home", "AtRest");
|
||||||
|
var first = await Record(patient, "2026-09-01T08:00:00", "Home", "AtRest");
|
||||||
|
await Record(patient, "2026-09-01T07:59:59", "Home", "AtRest");
|
||||||
|
await Record(patient, "2026-09-10T08:00:01", "Home", "AtRest");
|
||||||
|
await Record(patient, "2026-09-05T08:00:00", "Home", "AfterActivity");
|
||||||
|
await Record(await Patient(), "2026-09-05T08:00:00", "Home", "AtRest");
|
||||||
|
using var response = await fixture.Client.GetAsync(PathFor(patient, "&setting=Home&activityCondition=AtRest"));
|
||||||
|
Assert.Equal(new[] { first, last }, await response.Content.ReadFromJsonAsync<Observation[]>());
|
||||||
|
using var equal = await fixture.Client.GetAsync(PathFor(patient, "&setting=Home", "from=2026-09-01T10%3A00%3A00%2B02%3A00&to=2026-09-01T08%3A00%3A00Z"));
|
||||||
|
Assert.Equal(HttpStatusCode.OK, equal.StatusCode);
|
||||||
|
Assert.Equal(first, Assert.Single((await equal.Content.ReadFromJsonAsync<Observation[]>())!));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("&setting=Unsupported")]
|
||||||
|
[InlineData("&activityCondition=Unsupported")]
|
||||||
|
[InlineData("&setting=All")]
|
||||||
|
[InlineData("&activityCondition=1")]
|
||||||
|
public async Task Unsupported_selections_are_rejected_without_changing_observations(string selection)
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
var observation = await Record(patient, "2026-09-05T08:00:00", "Home", "AtRest");
|
||||||
|
await using var db = fixture.CreateObservationDbContext();
|
||||||
|
var before = await db.Observations.CountAsync();
|
||||||
|
using var response = await fixture.Client.GetAsync(PathFor(patient, selection));
|
||||||
|
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||||
|
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||||
|
Assert.True(problem.RootElement.TryGetProperty("errors", out _));
|
||||||
|
Assert.Equal(before, await db.Observations.CountAsync());
|
||||||
|
Assert.Equal(observation, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{observation.ObservationId}"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Professional_reads_follow_assignments_and_other_patient_tokens_cannot_use_filters_to_gain_access()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
var expected = await Record(patient, "2026-09-05T08:00:00", "Home", "AtRest");
|
||||||
|
var other = await Patient();
|
||||||
|
fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = patient.ToString();
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
foreach (var (account, status) in new[]
|
||||||
|
{
|
||||||
|
("professional", HttpStatusCode.OK), ("professional-empty", HttpStatusCode.NotFound),
|
||||||
|
(fixture.Authentication.PatientAccounts[other], HttpStatusCode.NotFound)
|
||||||
|
})
|
||||||
|
{
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Get, PathFor(patient, "&setting=Home&activityCondition=AtRest"));
|
||||||
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account));
|
||||||
|
using var response = await fixture.RawClient.SendAsync(request);
|
||||||
|
Assert.Equal(status, response.StatusCode);
|
||||||
|
if (status == HttpStatusCode.OK)
|
||||||
|
Assert.Equal(expected, Assert.Single((await response.Content.ReadFromJsonAsync<Observation[]>())!));
|
||||||
|
else Assert.Empty(await response.Content.ReadAsStringAsync());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
using HealthApp.TestSupport;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace Observation.AcceptanceTests;
|
||||||
|
|
||||||
|
public sealed class ContextSelectedInsightTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||||
|
{
|
||||||
|
private sealed record Profile(Guid PatientId);
|
||||||
|
private sealed record Observation(Guid ObservationId);
|
||||||
|
private sealed record Selection(string? Setting, string? ActivityCondition);
|
||||||
|
private sealed record Insight(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
|
||||||
|
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse, int MinSystolic, int MaxSystolic,
|
||||||
|
int MinDiastolic, int MaxDiastolic, Selection AppliedSelection, int ContributingCount, string ContextExplanation);
|
||||||
|
private const string Period = "from=2026-09-01T08%3A00%3A00&to=2026-09-10T08%3A00%3A00";
|
||||||
|
|
||||||
|
private async Task<Guid> Patient()
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Selected insight", dateOfBirth = "1980-01-01" });
|
||||||
|
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||||
|
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<Guid> Record(Guid patient, int systolic, int diastolic, int pulse, string? setting = "Home",
|
||||||
|
string? activity = "AtRest", string time = "2026-09-05T08:00:00", string? position = null)
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patient}/observations", new
|
||||||
|
{
|
||||||
|
measuredAt = time, systolic, diastolic, pulse, context = "Home resting?",
|
||||||
|
measurementContext = new { setting, activityCondition = activity, bodyPosition = position }
|
||||||
|
});
|
||||||
|
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||||
|
return (await response.Content.ReadFromJsonAsync<Observation>())!.ObservationId;
|
||||||
|
}
|
||||||
|
|
||||||
|
private string PathFor(Guid patient, string selection = "", string period = Period) =>
|
||||||
|
$"/api/patients/{patient}/insights?{period}{selection}";
|
||||||
|
private Task<Insight?> Summary(Guid patient, string selection = "") => fixture.Client.GetFromJsonAsync<Insight>(PathFor(patient, selection));
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("&setting=Home&activityCondition=AtRest", "Home", "AtRest", 2, 125)]
|
||||||
|
[InlineData("&setting=Home", "Home", null, 3, 130)]
|
||||||
|
[InlineData("&activityCondition=AtRest", null, "AtRest", 3, 136.67)]
|
||||||
|
public async Task Independent_and_combined_selections_use_only_matching_observations_and_report_their_basis(
|
||||||
|
string query, string? setting, string? activity, int count, double average)
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
await Record(patient, 120, 80, 60);
|
||||||
|
await Record(patient, 130, 84, 70);
|
||||||
|
await Record(patient, 140, 88, 80, activity: "AfterActivity");
|
||||||
|
await Record(patient, 160, 90, 90, setting: "Clinic");
|
||||||
|
var result = (await Summary(patient, query))!;
|
||||||
|
Assert.Equal((decimal)average, result.AverageSystolic);
|
||||||
|
Assert.Equal(count, result.ContributingCount);
|
||||||
|
Assert.Equal(new Selection(setting, activity), result.AppliedSelection);
|
||||||
|
Assert.Equal(patient, result.PatientId);
|
||||||
|
if (count == 2)
|
||||||
|
{
|
||||||
|
Assert.Equal(82m, result.AverageDiastolic);
|
||||||
|
Assert.Equal(65m, result.AveragePulse);
|
||||||
|
Assert.Equal(120, result.MinSystolic);
|
||||||
|
Assert.Equal(130, result.MaxSystolic);
|
||||||
|
Assert.Equal(80, result.MinDiastolic);
|
||||||
|
Assert.Equal(84, result.MaxDiastolic);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Unfiltered_insight_includes_unknown_context_and_explains_mixed_and_missing_conditions()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
await Record(patient, 120, 80, 60, position: "Seated");
|
||||||
|
await Record(patient, 130, 84, 70, setting: "Clinic", activity: "AfterActivity", position: "Standing");
|
||||||
|
await Record(patient, 140, 88, 80, setting: null, activity: null);
|
||||||
|
var result = (await Summary(patient))!;
|
||||||
|
Assert.Equal(130m, result.AverageSystolic);
|
||||||
|
Assert.Equal(3, result.ContributingCount);
|
||||||
|
Assert.Equal(new Selection(null, null), result.AppliedSelection);
|
||||||
|
Assert.Contains("mixed settings or activity conditions", result.ContextExplanation);
|
||||||
|
Assert.Contains("unknown", result.ContextExplanation);
|
||||||
|
Assert.Contains("Optional details are unrecorded", result.ContextExplanation);
|
||||||
|
Assert.Contains("Recorded detail values differ: body position", result.ContextExplanation);
|
||||||
|
Assert.Contains("do not establish clinically comparable conditions", result.ContextExplanation);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("&setting=Unknown", "Unknown", null)]
|
||||||
|
[InlineData("&activityCondition=Unknown", null, "Unknown")]
|
||||||
|
[InlineData("&setting=Unknown&activityCondition=Unknown", "Unknown", "Unknown")]
|
||||||
|
public async Task Unknown_selection_is_explicit_and_legacy_narrative_does_not_create_known_membership(string query,
|
||||||
|
string? setting, string? activity)
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
await Record(patient, 120, 80, 60, setting: null, activity: null);
|
||||||
|
await Record(patient, 180, 100, 90);
|
||||||
|
var result = (await Summary(patient, query))!;
|
||||||
|
Assert.Equal(1, result.ContributingCount);
|
||||||
|
Assert.Equal(120m, result.AverageSystolic);
|
||||||
|
Assert.Equal(80m, result.AverageDiastolic);
|
||||||
|
Assert.Equal(60m, result.AveragePulse);
|
||||||
|
Assert.Equal(result.MinSystolic, result.MaxSystolic);
|
||||||
|
Assert.Equal(result.MinDiastolic, result.MaxDiastolic);
|
||||||
|
Assert.Equal(new Selection(setting, activity), result.AppliedSelection);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(8, 120.13, 80.13, 60.13)]
|
||||||
|
[InlineData(3, 120.33, 80.33, 60.33)]
|
||||||
|
public async Task Means_round_only_the_final_value_to_two_decimals_with_half_up_rounding(int count,
|
||||||
|
double systolic, double diastolic, double pulse)
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
for (var i = 0; i < count; i++)
|
||||||
|
await Record(patient, 120 + (i == count - 1 ? 1 : 0), 80 + (i == count - 1 ? 1 : 0), 60 + (i == count - 1 ? 1 : 0));
|
||||||
|
var result = (await Summary(patient))!;
|
||||||
|
Assert.Equal((decimal)systolic, result.AverageSystolic);
|
||||||
|
Assert.Equal((decimal)diastolic, result.AverageDiastolic);
|
||||||
|
Assert.Equal((decimal)pulse, result.AveragePulse);
|
||||||
|
Assert.Equal(count, result.ContributingCount);
|
||||||
|
Assert.Equal(120, result.MinSystolic);
|
||||||
|
Assert.Equal(121, result.MaxSystolic);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Corrections_clearing_and_deletion_change_membership_and_fresh_summary_results_after_restart()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
var first = await Record(patient, 120, 80, 60);
|
||||||
|
var second = await Record(patient, 130, 84, 70);
|
||||||
|
Assert.Equal(125m, (await Summary(patient, "&setting=Home"))!.AverageSystolic);
|
||||||
|
using var corrected = await fixture.Client.PatchAsJsonAsync($"/api/observations/{second}", new { measurementContext = new { setting = "Clinic" } });
|
||||||
|
Assert.Equal(HttpStatusCode.OK, corrected.StatusCode);
|
||||||
|
Assert.Equal(120m, (await Summary(patient, "&setting=Home"))!.AverageSystolic);
|
||||||
|
using var cleared = await fixture.Client.PatchAsJsonAsync($"/api/observations/{first}", new { measurementContext = new { activityCondition = (string?)null } });
|
||||||
|
Assert.Equal(HttpStatusCode.OK, cleared.StatusCode);
|
||||||
|
var selected = (await Summary(patient, "&setting=Home&activityCondition=Unknown"))!;
|
||||||
|
Assert.Equal(1, selected.ContributingCount);
|
||||||
|
using var deleted = await fixture.Client.DeleteAsync($"/api/observations/{first}");
|
||||||
|
Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
using var empty = await fixture.Client.GetAsync(PathFor(patient, "&setting=Home"));
|
||||||
|
Assert.Equal(HttpStatusCode.NotFound, empty.StatusCode);
|
||||||
|
Assert.Contains("Insufficient observation data", await empty.Content.ReadAsStringAsync());
|
||||||
|
var remaining = (await Summary(patient, "&setting=Clinic"))!;
|
||||||
|
Assert.Equal(1, remaining.ContributingCount);
|
||||||
|
Assert.Equal(130m, remaining.AverageSystolic);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Filtered_insight_preserves_patient_scope_inclusive_bounds_and_equal_instants()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
await Record(patient, 120, 80, 60, time: "2026-09-01T08:00:00");
|
||||||
|
await Record(patient, 130, 84, 70, time: "2026-09-10T08:00:00");
|
||||||
|
await Record(patient, 200, 100, 90, time: "2026-09-01T07:59:59");
|
||||||
|
await Record(patient, 210, 110, 95, time: "2026-09-10T08:00:01");
|
||||||
|
await Record(await Patient(), 220, 120, 100);
|
||||||
|
var summary = (await Summary(patient, "&setting=Home&activityCondition=AtRest"))!;
|
||||||
|
Assert.Equal(2, summary.ContributingCount);
|
||||||
|
Assert.Equal(125m, summary.AverageSystolic);
|
||||||
|
using var equal = await fixture.Client.GetAsync(PathFor(patient, "&setting=Home", "from=2026-09-01T10%3A00%3A00%2B02%3A00&to=2026-09-01T08%3A00%3A00Z"));
|
||||||
|
Assert.Equal(HttpStatusCode.OK, equal.StatusCode);
|
||||||
|
Assert.Equal(120m, (await equal.Content.ReadFromJsonAsync<Insight>())!.AverageSystolic);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("&setting=Unsupported")]
|
||||||
|
[InlineData("&activityCondition=Unsupported")]
|
||||||
|
public async Task Unsupported_selection_is_rejected_with_validation_details(string query)
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
await Record(patient, 120, 80, 60);
|
||||||
|
using var response = await fixture.Client.GetAsync(PathFor(patient, 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(1, (await Summary(patient))!.ContributingCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Professional_selection_requires_assignment_and_other_patient_access_is_rejected()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
await Record(patient, 120, 80, 60);
|
||||||
|
var other = await Patient();
|
||||||
|
fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = patient.ToString();
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
foreach (var (account, status) in new[]
|
||||||
|
{
|
||||||
|
("professional", HttpStatusCode.OK), ("professional-empty", HttpStatusCode.NotFound),
|
||||||
|
(fixture.Authentication.PatientAccounts[other], HttpStatusCode.NotFound)
|
||||||
|
})
|
||||||
|
{
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Get, PathFor(patient, "&setting=Home&activityCondition=AtRest"));
|
||||||
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account));
|
||||||
|
using var response = await fixture.RawClient.SendAsync(request);
|
||||||
|
Assert.Equal(status, response.StatusCode);
|
||||||
|
if (status == HttpStatusCode.OK) Assert.Equal(1, (await response.Content.ReadFromJsonAsync<Insight>())!.ContributingCount);
|
||||||
|
else Assert.Empty(await response.Content.ReadAsStringAsync());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using HealthApp.TestSupport;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace Observation.AcceptanceTests;
|
||||||
|
|
||||||
|
public sealed class DeleteContextualisedObservationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||||
|
{
|
||||||
|
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 sealed record Insight(decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
|
||||||
|
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic);
|
||||||
|
private const string Period = "from=2026-09-01&to=2026-10-01";
|
||||||
|
|
||||||
|
private async Task<Guid> Patient()
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Context deletion", dateOfBirth = "1980-01-01" });
|
||||||
|
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||||
|
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<Observation> Record(Guid patient, string time, int systolic, int diastolic, int pulse)
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patient}/observations", new
|
||||||
|
{
|
||||||
|
measuredAt = time, systolic, diastolic, pulse, context = "Original context", note = "Original note",
|
||||||
|
measurementContext = new { setting = "Home", activityCondition = "AtRest", restDurationMinutes = 5.5m,
|
||||||
|
bodyPosition = "Seated", measuredArm = "Left", deviceDetails = "Device", cuffDetails = "Cuff", additionalCircumstances = "Actual circumstances" }
|
||||||
|
});
|
||||||
|
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||||
|
return (await response.Content.ReadFromJsonAsync<Observation>())!;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Task<Observation[]?> History(Guid patient) => fixture.Client.GetFromJsonAsync<Observation[]>(
|
||||||
|
$"/api/patients/{patient}/observations?{Period}&setting=Home&activityCondition=AtRest");
|
||||||
|
private Task<Insight?> Summary(Guid patient) => fixture.Client.GetFromJsonAsync<Insight>($"/api/patients/{patient}/insights?{Period}");
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Deleted_context_stays_absent_from_retrieval_filtered_history_and_latest_after_restart()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
var retained = await Record(patient, "2026-09-10T08:00:00", 120, 80, 60);
|
||||||
|
var deleted = await Record(patient, "2026-09-12T08:00:00", 200, 110, 100);
|
||||||
|
var other = await Record(await Patient(), "2026-09-13T08:00:00", 130, 84, 70);
|
||||||
|
using var response = await fixture.Client.DeleteAsync($"/api/observations/{deleted.ObservationId}");
|
||||||
|
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
|
||||||
|
Assert.Empty(await response.Content.ReadAsStringAsync());
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
using var missing = await fixture.Client.GetAsync($"/api/observations/{deleted.ObservationId}");
|
||||||
|
Assert.Equal(HttpStatusCode.NotFound, missing.StatusCode);
|
||||||
|
Assert.Empty(await missing.Content.ReadAsStringAsync());
|
||||||
|
Assert.Equal(retained, Assert.Single((await History(patient))!));
|
||||||
|
Assert.Equal(retained, await fixture.Client.GetFromJsonAsync<Observation>($"/api/patients/{patient}/observations/latest"));
|
||||||
|
Assert.Equal(other, Assert.Single((await History(other.PatientId))!));
|
||||||
|
Assert.Equal(other, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{other.ObservationId}"));
|
||||||
|
await using var db = fixture.CreateObservationDbContext();
|
||||||
|
Assert.False(await db.Observations.AnyAsync(o => o.ObservationId == deleted.ObservationId));
|
||||||
|
Assert.Equal("Device", (await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == retained.ObservationId)).MeasurementContext.DeviceDetails);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task New_numerical_summary_excludes_deleted_values_and_retains_current_remaining_observations()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
var first = await Record(patient, "2026-09-10T08:00:00", 120, 80, 60);
|
||||||
|
var second = await Record(patient, "2026-09-11T08:00:00", 130, 84, 70);
|
||||||
|
var outlier = await Record(patient, "2026-09-12T08:00:00", 200, 110, 100);
|
||||||
|
Assert.Equal(150m, (await Summary(patient))!.AverageSystolic);
|
||||||
|
using var deleted = await fixture.Client.DeleteAsync($"/api/observations/{outlier.ObservationId}");
|
||||||
|
Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
|
||||||
|
var expected = new Insight(125m, 82m, 65m, 120, 130, 80, 84);
|
||||||
|
Assert.Equal(expected, await Summary(patient));
|
||||||
|
Assert.Equal(new[] { first, second }, await History(patient));
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
Assert.Equal(expected, await Summary(patient));
|
||||||
|
Assert.Equal(new[] { first, second }, await History(patient));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Deleting_only_contextualised_observation_leaves_empty_filtered_history_and_no_summary()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
var observation = await Record(patient, "2026-09-12T08:00:00", 128, 82, 68);
|
||||||
|
using var deleted = await fixture.Client.DeleteAsync($"/api/observations/{observation.ObservationId}");
|
||||||
|
Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
|
||||||
|
using var history = await fixture.Client.GetAsync($"/api/patients/{patient}/observations?{Period}&setting=Home&activityCondition=AtRest");
|
||||||
|
Assert.Equal(HttpStatusCode.OK, history.StatusCode);
|
||||||
|
Assert.Equal("[]", await history.Content.ReadAsStringAsync());
|
||||||
|
Assert.Equal("Home", Assert.Single(history.Headers.GetValues("X-Measurement-Setting")));
|
||||||
|
Assert.Equal("AtRest", Assert.Single(history.Headers.GetValues("X-Activity-Condition")));
|
||||||
|
using var latest = await fixture.Client.GetAsync($"/api/patients/{patient}/observations/latest");
|
||||||
|
using var summary = await fixture.Client.GetAsync($"/api/patients/{patient}/insights?{Period}");
|
||||||
|
using var repeated = await fixture.Client.DeleteAsync($"/api/observations/{observation.ObservationId}");
|
||||||
|
Assert.Equal(HttpStatusCode.NotFound, latest.StatusCode);
|
||||||
|
Assert.Equal(HttpStatusCode.NotFound, summary.StatusCode);
|
||||||
|
Assert.Equal(HttpStatusCode.NotFound, repeated.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Unauthorised_deletions_preserve_the_observation_and_all_context()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
var original = await Record(patient, "2026-09-12T08:00:00", 128, 82, 68);
|
||||||
|
var otherPatient = await Patient();
|
||||||
|
fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = patient.ToString();
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
var otherToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, fixture.Authentication.PatientAccounts[otherPatient]);
|
||||||
|
var professional = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
|
||||||
|
foreach (var (token, status) in new[]
|
||||||
|
{
|
||||||
|
((string?)null, HttpStatusCode.Unauthorized), ((string?)"invalid", HttpStatusCode.Unauthorized),
|
||||||
|
((string?)otherToken, HttpStatusCode.NotFound), ((string?)professional, HttpStatusCode.Forbidden)
|
||||||
|
})
|
||||||
|
{
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Delete, $"/api/observations/{original.ObservationId}");
|
||||||
|
if (token is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||||
|
using var rejected = await fixture.RawClient.SendAsync(request);
|
||||||
|
Assert.Equal(status, rejected.StatusCode);
|
||||||
|
Assert.Equal(original, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{original.ObservationId}"));
|
||||||
|
}
|
||||||
|
Assert.Equal(original, Assert.Single((await History(patient))!));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
using HealthApp.TestSupport;
|
||||||
|
using HealthOverviewService.Contracts;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace Observation.AcceptanceTests;
|
||||||
|
|
||||||
|
public sealed class HealthOverviewTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||||
|
{
|
||||||
|
private sealed record Recorded(Guid ObservationId);
|
||||||
|
private const string Period = "from=2026-09-01T08%3A00%3A00&to=2026-09-10T08%3A00%3A00";
|
||||||
|
private static string PathFor(Guid patient, string query = Period) => $"/api/patients/{patient}/overview?{query}";
|
||||||
|
private async Task<Guid> Patient()
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new
|
||||||
|
{ name = "Overview patient", dateOfBirth = "1980-01-01", contactInfo = "Synthetic contact" });
|
||||||
|
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||||
|
return (await response.Content.ReadFromJsonAsync<PatientDto>())!.PatientId;
|
||||||
|
}
|
||||||
|
private async Task<Guid> Record(Guid patient, string time, int systolic = 120,
|
||||||
|
string? setting = "Home", string? activity = "AtRest")
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patient}/observations", new
|
||||||
|
{
|
||||||
|
measuredAt = time, systolic, diastolic = 80, pulse = 65, context = "Preserved original context", note = "Preserved note",
|
||||||
|
measurementContext = new { setting, activityCondition = activity, restDurationMinutes = 5,
|
||||||
|
bodyPosition = "Seated", measuredArm = "Left", deviceDetails = "Device", cuffDetails = "Cuff", additionalCircumstances = "Morning" }
|
||||||
|
});
|
||||||
|
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||||
|
return (await response.Content.ReadFromJsonAsync<Recorded>())!.ObservationId;
|
||||||
|
}
|
||||||
|
private async Task<HealthOverviewDto> Overview(Guid patient, string query = Period)
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.GetAsync(PathFor(patient, query));
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
return (await response.Content.ReadFromJsonAsync<HealthOverviewDto>())!;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Overview_preserves_profile_latest_context_and_selected_insight_with_different_bases()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
await Record(patient, "2026-09-01T08:00:00", 120);
|
||||||
|
await Record(patient, "2026-09-10T08:00:00", 130);
|
||||||
|
await Record(patient, "2026-09-01T07:59:59", 200);
|
||||||
|
var latest = await Record(patient, "2026-09-11T08:00:00", 210, "Clinic", "AfterActivity");
|
||||||
|
await Record(await Patient(), "2026-09-05T08:00:00", 250);
|
||||||
|
var result = await Overview(patient, Period + "&setting=Home&activityCondition=AtRest");
|
||||||
|
Assert.Equal(patient, result.Patient.PatientId);
|
||||||
|
Assert.Equal("Overview patient", result.Patient.Name);
|
||||||
|
Assert.Equal(new DateOnly(1980, 1, 1), result.Patient.DateOfBirth);
|
||||||
|
Assert.Equal("Synthetic contact", result.Patient.ContactInfo);
|
||||||
|
Assert.Equal(latest, result.LatestObservation!.ObservationId);
|
||||||
|
Assert.Equal("AfterActivity", result.LatestObservation.MeasurementContext.ActivityCondition);
|
||||||
|
Assert.Equal("Clinic", result.LatestObservation.MeasurementContext.Setting);
|
||||||
|
Assert.Equal("Seated", result.LatestObservation.MeasurementContext.BodyPosition);
|
||||||
|
Assert.Equal("Left", result.LatestObservation.MeasurementContext.MeasuredArm);
|
||||||
|
Assert.Equal("Device", result.LatestObservation.MeasurementContext.DeviceDetails);
|
||||||
|
Assert.Equal("Cuff", result.LatestObservation.MeasurementContext.CuffDetails);
|
||||||
|
Assert.Equal(5m, result.LatestObservation.MeasurementContext.RestDurationMinutes);
|
||||||
|
Assert.Equal("Morning", result.LatestObservation.MeasurementContext.AdditionalCircumstances);
|
||||||
|
Assert.Equal("Preserved original context", result.LatestObservation.Context);
|
||||||
|
Assert.Equal("Preserved note", result.LatestObservation.Note);
|
||||||
|
Assert.Equal(125m, result.Insight!.AverageSystolic);
|
||||||
|
Assert.Equal(2, result.InsightContributingCount);
|
||||||
|
Assert.Equal(result.InsightSelection, result.Insight.AppliedSelection);
|
||||||
|
Assert.Equal("Home", result.InsightSelection.Setting);
|
||||||
|
Assert.Equal("AtRest", result.InsightSelection.ActivityCondition);
|
||||||
|
Assert.Equal(new DateTime(2026, 9, 1, 8, 0, 0), result.PeriodStart);
|
||||||
|
Assert.Equal(new DateTime(2026, 9, 10, 8, 0, 0), result.PeriodEnd);
|
||||||
|
Assert.Contains("independent of the insight period and context selections", result.LatestObservationBasis);
|
||||||
|
Assert.Contains("not to the insight", result.LatestObservationBasis);
|
||||||
|
using var raw = await fixture.Client.GetAsync(PathFor(patient));
|
||||||
|
using var json = JsonDocument.Parse(await raw.Content.ReadAsStringAsync());
|
||||||
|
Assert.False(json.RootElement.TryGetProperty("trend", out _));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task No_observations_returns_profile_and_explicit_insight_absence()
|
||||||
|
{
|
||||||
|
var result = await Overview(await Patient());
|
||||||
|
Assert.NotNull(result.Patient);
|
||||||
|
Assert.Null(result.LatestObservation);
|
||||||
|
Assert.Null(result.Insight);
|
||||||
|
Assert.Equal(0, result.InsightContributingCount);
|
||||||
|
Assert.Contains("No calculated insight is available", result.InsightExplanation);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("&setting=Clinic")]
|
||||||
|
[InlineData("&activityCondition=AfterActivity")]
|
||||||
|
[InlineData("&setting=Unknown&activityCondition=Unknown")]
|
||||||
|
public async Task Empty_selected_insight_preserves_profile_latest_and_applied_selection(string selection)
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
var latest = await Record(patient, "2026-09-05T08:00:00");
|
||||||
|
var result = await Overview(patient, Period + selection);
|
||||||
|
Assert.Equal(patient, result.Patient.PatientId);
|
||||||
|
Assert.Equal(latest, result.LatestObservation!.ObservationId);
|
||||||
|
Assert.Null(result.Insight);
|
||||||
|
Assert.Equal(0, result.InsightContributingCount);
|
||||||
|
Assert.Contains("no observations match", result.InsightExplanation);
|
||||||
|
Assert.True(result.InsightSelection.Setting is not null || result.InsightSelection.ActivityCondition is not null);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Unfiltered_pooled_insight_preserves_mixed_and_unknown_context_explanations()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
await Record(patient, "2026-09-02T08:00:00", 120);
|
||||||
|
await Record(patient, "2026-09-03T08:00:00", 130, "Clinic", "AfterActivity");
|
||||||
|
var latest = await Record(patient, "2026-09-04T08:00:00", 140, null, null);
|
||||||
|
var result = await Overview(patient);
|
||||||
|
Assert.Equal(latest, result.LatestObservation!.ObservationId);
|
||||||
|
Assert.Equal("Unknown", result.LatestObservation.MeasurementContext.Setting);
|
||||||
|
Assert.Equal("Unknown", result.LatestObservation.MeasurementContext.ActivityCondition);
|
||||||
|
Assert.Null(result.InsightSelection.Setting);
|
||||||
|
Assert.Null(result.InsightSelection.ActivityCondition);
|
||||||
|
Assert.Equal(3, result.InsightContributingCount);
|
||||||
|
Assert.Equal(130m, result.Insight!.AverageSystolic);
|
||||||
|
Assert.Contains("mixed settings or activity conditions", result.Insight.ContextExplanation);
|
||||||
|
Assert.Contains("unknown", result.InsightExplanation);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Equal_offset_instants_are_valid_and_single_observation_insight_is_sufficient()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
await Record(patient, "2026-09-05T10:00:00+02:00", 121);
|
||||||
|
var result = await Overview(patient,
|
||||||
|
"from=2026-09-05T10%3A00%3A00%2B02%3A00&to=2026-09-05T08%3A00%3A00Z&setting=Home");
|
||||||
|
Assert.Equal(result.PeriodStart, result.PeriodEnd);
|
||||||
|
Assert.Equal(1, result.InsightContributingCount);
|
||||||
|
Assert.Equal(121m, result.Insight!.AverageSystolic);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Latest_tie_rules_and_current_corrections_deletions_and_profile_edits_survive_restart()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
var first = await Record(patient, "2026-09-05T08:00:00", 120);
|
||||||
|
var second = await Record(patient, "2026-09-05T08:00:00", 130, "Clinic", "AfterActivity");
|
||||||
|
Assert.Equal(second, (await Overview(patient)).LatestObservation!.ObservationId);
|
||||||
|
using var patched = await fixture.Client.PatchAsJsonAsync($"/api/observations/{first}",
|
||||||
|
new { systolic = 140, measurementContext = new { setting = "Clinic" } });
|
||||||
|
Assert.Equal(HttpStatusCode.OK, patched.StatusCode);
|
||||||
|
Assert.Null((await Overview(patient, Period + "&setting=Home")).Insight);
|
||||||
|
Assert.Equal(second, (await Overview(patient)).LatestObservation!.ObservationId);
|
||||||
|
using var edited = await fixture.Client.PutAsJsonAsync($"/api/patients/{patient}",
|
||||||
|
new { name = "Updated overview", dateOfBirth = "1980-01-01", contactInfo = "Updated contact" });
|
||||||
|
Assert.Equal(HttpStatusCode.OK, edited.StatusCode);
|
||||||
|
using var deleted = await fixture.Client.DeleteAsync($"/api/observations/{second}");
|
||||||
|
Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
var result = await Overview(patient);
|
||||||
|
Assert.Equal("Updated overview", result.Patient.Name);
|
||||||
|
Assert.Equal(first, result.LatestObservation!.ObservationId);
|
||||||
|
Assert.Equal(140m, result.Insight!.AverageSystolic);
|
||||||
|
Assert.Equal(1, result.InsightContributingCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("from=2026-09-10&to=2026-09-01")]
|
||||||
|
[InlineData("from=bad&to=2026-09-10")]
|
||||||
|
[InlineData("from=2026-09-01&to=bad")]
|
||||||
|
[InlineData("from=2026-09-01")]
|
||||||
|
[InlineData("to=2026-09-10")]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData(Period + "&setting=Invalid")]
|
||||||
|
[InlineData(Period + "&activityCondition=Invalid")]
|
||||||
|
public async Task Invalid_period_or_context_is_rejected_with_details(string query)
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.GetAsync(PathFor(await Patient(), query));
|
||||||
|
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||||
|
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||||
|
Assert.True(problem.RootElement.TryGetProperty("errors", out _));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Assigned_missing_patient_reports_absence_without_exposing_other_patients()
|
||||||
|
{
|
||||||
|
var missing = Guid.NewGuid();
|
||||||
|
fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = missing.ToString();
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Get, PathFor(missing));
|
||||||
|
request.Headers.Authorization = new("Bearer", await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional"));
|
||||||
|
using var response = await fixture.RawClient.SendAsync(request);
|
||||||
|
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||||
|
Assert.Contains("Patient does not exist", await response.Content.ReadAsStringAsync());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Overview_requires_owner_or_assigned_professional_and_blocks_direct_bypass()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
await Record(patient, "2026-09-05T08:00:00");
|
||||||
|
var other = await Patient();
|
||||||
|
fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = patient.ToString();
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
using var anonymous = await fixture.RawClient.GetAsync(PathFor(patient));
|
||||||
|
Assert.Equal(HttpStatusCode.Unauthorized, anonymous.StatusCode);
|
||||||
|
foreach (var (account, status) in new[] { ("professional", HttpStatusCode.OK),
|
||||||
|
("professional-empty", HttpStatusCode.NotFound), (fixture.Authentication.PatientAccounts[other], HttpStatusCode.NotFound) })
|
||||||
|
{
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Get, PathFor(patient));
|
||||||
|
request.Headers.Authorization = new("Bearer", await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account));
|
||||||
|
using var response = await fixture.RawClient.SendAsync(request);
|
||||||
|
Assert.Equal(status, response.StatusCode);
|
||||||
|
if (status != HttpStatusCode.OK) Assert.Empty(await response.Content.ReadAsStringAsync());
|
||||||
|
}
|
||||||
|
using var direct = fixture.CreateDirectOverviewClient();
|
||||||
|
using var bypass = await direct.GetAsync(PathFor(patient));
|
||||||
|
Assert.Equal(HttpStatusCode.Unauthorized, bypass.StatusCode);
|
||||||
|
Assert.Empty(await bypass.Content.ReadAsStringAsync());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("overview")]
|
||||||
|
[InlineData("trends")]
|
||||||
|
[InlineData("observations")]
|
||||||
|
public async Task Overview_service_credential_is_restricted_to_required_reads(string route)
|
||||||
|
{
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Get, $"/api/patients/{await Patient()}/{route}?{Period}");
|
||||||
|
request.Headers.Add("X-Service-Key", fixture.Authentication.OverviewServiceKey);
|
||||||
|
using var response = await fixture.RawClient.SendAsync(request);
|
||||||
|
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Observation")]
|
||||||
|
[InlineData("Insights")]
|
||||||
|
[InlineData("Overview")]
|
||||||
|
public async Task Unavailable_source_or_overview_is_a_failure_not_absent_insight(string service)
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
if (service == "Observation") await fixture.StopObservationServiceAsync();
|
||||||
|
if (service == "Insights") await fixture.StopInsightsServiceAsync();
|
||||||
|
if (service == "Overview") await fixture.StopOverviewServiceAsync();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.GetAsync(PathFor(patient));
|
||||||
|
Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode);
|
||||||
|
}
|
||||||
|
finally { await fixture.RestartHostsAsync(); }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,415 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
using HealthApp.TestSupport;
|
||||||
|
using InsightsService.Contracts;
|
||||||
|
using InsightsService.Domain;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace Observation.AcceptanceTests;
|
||||||
|
|
||||||
|
public sealed class HealthTrendCalculationTests
|
||||||
|
{
|
||||||
|
private static readonly Guid PatientId = Guid.NewGuid();
|
||||||
|
private static readonly DateTime Start = new(2026, 9, 1);
|
||||||
|
private static readonly MeasurementContextDto Prepared = new("Home", "AtRest", 5, "Seated", "Left", "Device A", "Adult cuff", null);
|
||||||
|
private static ObservationDto Observation(int day, int systolic, int diastolic = 90, int pulse = 70,
|
||||||
|
MeasurementContextDto? context = null, string? text = null) =>
|
||||||
|
new(Guid.NewGuid(), PatientId, Start.AddDays(day), systolic, diastolic, pulse, context ?? Prepared, text);
|
||||||
|
private static TrendAssessment Calculate(params ObservationDto[] observations) =>
|
||||||
|
new InsightCalculator().CalculateTrend(PatientId, Start, Start.AddDays(10), observations, new() { Setting = "Home", ActivityCondition = "AtRest" });
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(140, 150, 160, "Increasing")]
|
||||||
|
[InlineData(160, 150, 140, "Decreasing")]
|
||||||
|
[InlineData(150, 150, 150, "NoClearDirection")]
|
||||||
|
public void Full_period_direction_and_separate_units_and_levels(int first, int middle, int last, string direction)
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(0, first, 95, 65), Observation(1, middle, 90, 70), Observation(2, last, 85, 75));
|
||||||
|
Assert.Equal(direction, result.Systolic.Direction);
|
||||||
|
Assert.Equal(direction, result.Systolic.OverallDirection);
|
||||||
|
Assert.Equal("Decreasing", result.Diastolic.Direction);
|
||||||
|
Assert.Equal("Increasing", result.Pulse.Direction);
|
||||||
|
Assert.Equal("mmHg", result.Systolic.Unit);
|
||||||
|
Assert.Equal("mmHg", result.Diastolic.Unit);
|
||||||
|
Assert.Equal("beats/min", result.Pulse.Unit);
|
||||||
|
Assert.Equal(150m, result.Systolic.Mean);
|
||||||
|
Assert.Equal(90m, result.Diastolic.Mean);
|
||||||
|
Assert.Equal(70m, result.Pulse.Mean);
|
||||||
|
Assert.Equal("SupportedRecordedComparability", result.Comparability.Status);
|
||||||
|
Assert.Contains("rest duration: 5", result.Comparability.KnownSimilarities);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Equal_endpoints_do_not_hide_intermediate_excursion_or_reversal()
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(0, 140), Observation(1, 190), Observation(2, 140));
|
||||||
|
Assert.Equal("Mixed", result.Systolic.Direction);
|
||||||
|
Assert.Equal("NoClearDirection", result.Systolic.OverallDirection);
|
||||||
|
Assert.Equal(1, result.Systolic.ReversalCount);
|
||||||
|
Assert.Equal(50, result.Systolic.Range);
|
||||||
|
Assert.Equal(100m, result.Systolic.TotalSuccessiveChange);
|
||||||
|
Assert.Equal("Mixed", result.Systolic.Interpretation);
|
||||||
|
Assert.Contains("no clinical stability classification", result.Systolic.NumericalExplanation);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Overall_decrease_can_coexist_with_reversals_and_large_variation()
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(0, 180), Observation(1, 160), Observation(2, 170), Observation(3, 140));
|
||||||
|
Assert.Equal("Mixed", result.Systolic.Direction);
|
||||||
|
Assert.Equal("Decreasing", result.Systolic.OverallDirection);
|
||||||
|
Assert.Equal(2, result.Systolic.ReversalCount);
|
||||||
|
Assert.Equal(60m, result.Systolic.TotalSuccessiveChange);
|
||||||
|
Assert.True(result.Systolic.SlopePerDay < 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Low_variation_outside_reference_is_not_healthy()
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(0, 155), Observation(1, 155), Observation(2, 155));
|
||||||
|
Assert.Equal(0, result.Systolic.Range);
|
||||||
|
Assert.Equal("PotentiallyConcerning", result.Systolic.Interpretation);
|
||||||
|
Assert.Contains("3 observation(s) >= 135", result.Systolic.ReferenceComparison);
|
||||||
|
Assert.Contains("Limited variation does not establish healthy", result.Systolic.Hint);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Favourable_pressure_decrease_can_still_be_high_while_falling_pulse_is_concerning()
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(0, 160, 85, 70), Observation(1, 150, 90, 55), Observation(2, 140, 95, 40));
|
||||||
|
Assert.Equal("PotentiallyFavourable", result.Systolic.Interpretation);
|
||||||
|
Assert.Contains("remains above or at", result.Systolic.Hint);
|
||||||
|
Assert.Equal("PotentiallyConcerning", result.Diastolic.Interpretation);
|
||||||
|
Assert.Equal("PotentiallyConcerning", result.Pulse.Interpretation);
|
||||||
|
Assert.Contains("not automatically favourable", result.Pulse.Hint);
|
||||||
|
Assert.Equal(50m, result.Pulse.Reference!.LowerBoundary);
|
||||||
|
Assert.Equal(100m, result.Pulse.Reference.UpperBoundary);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Moving_low_pulse_up_or_high_pulse_down_is_not_automatically_concerning()
|
||||||
|
{
|
||||||
|
Assert.Equal("PotentiallyFavourable", Calculate(Observation(0, 120, pulse: 40), Observation(1, 120, pulse: 55)).Pulse.Interpretation);
|
||||||
|
Assert.Equal("PotentiallyFavourable", Calculate(Observation(0, 120, pulse: 120), Observation(1, 120, pulse: 105)).Pulse.Interpretation);
|
||||||
|
Assert.Equal("CannotInterpret", Calculate(Observation(0, 120), Observation(1, 110)).Systolic.Interpretation);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Opposite_pulse_excursions_within_timestamp_ties_are_not_hidden_by_their_mean()
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(0, 120, pulse: 30), Observation(0, 120, pulse: 210),
|
||||||
|
Observation(1, 120, pulse: 105));
|
||||||
|
Assert.Equal("Decreasing", result.Pulse.Direction);
|
||||||
|
Assert.Equal(180, result.Pulse.Range);
|
||||||
|
Assert.Equal("PotentiallyConcerning", result.Pulse.Interpretation);
|
||||||
|
Assert.Contains("1 observation(s) < 50", result.Pulse.ReferenceComparison);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Home", 135, 85)]
|
||||||
|
[InlineData("Clinic", 140, 90)]
|
||||||
|
public void References_are_setting_specific_sourced_and_not_treatment_targets(string setting, int systolic, int diastolic)
|
||||||
|
{
|
||||||
|
var context = Prepared with { Setting = setting };
|
||||||
|
var result = Calculate(Observation(0, 138, context: context), Observation(1, 138, context: context));
|
||||||
|
Assert.Equal(systolic, result.Systolic.Reference!.UpperBoundary);
|
||||||
|
Assert.Equal(diastolic, result.Diastolic.Reference!.UpperBoundary);
|
||||||
|
Assert.Equal(">=", result.Systolic.Reference.UpperComparison);
|
||||||
|
Assert.Contains("sundhed.dk", result.Systolic.Reference.Sources.Single().Url);
|
||||||
|
Assert.Contains("not individual treatment targets", result.Systolic.Hint);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(50, 0)]
|
||||||
|
[InlineData(100, 0)]
|
||||||
|
[InlineData(49, 2)]
|
||||||
|
[InlineData(101, 2)]
|
||||||
|
public void Pulse_reference_boundaries_are_exclusive(int pulse, int outsideCount)
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(0, 120, pulse: pulse), Observation(1, 120, pulse: pulse));
|
||||||
|
Assert.Contains($"{(pulse > 100 ? outsideCount : 0)} observation(s) > 100", result.Pulse.ReferenceComparison);
|
||||||
|
Assert.Contains($"{(pulse < 50 ? outsideCount : 0)} observation(s) < 50", result.Pulse.ReferenceComparison);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Missing_context_preserves_numerical_direction_but_not_resting_interpretation()
|
||||||
|
{
|
||||||
|
var unknown = new MeasurementContextDto("Unknown", "Unknown", null, null, null, null, null, null);
|
||||||
|
var result = Calculate(Observation(0, 150, context: unknown), Observation(1, 160, context: unknown));
|
||||||
|
Assert.Equal("Increasing", result.Systolic.Direction);
|
||||||
|
Assert.Equal(10, result.Systolic.Range);
|
||||||
|
Assert.Null(result.Systolic.Reference);
|
||||||
|
Assert.Null(result.Pulse.Reference);
|
||||||
|
Assert.Equal("CannotInterpret", result.Systolic.Interpretation);
|
||||||
|
Assert.Contains("setting", result.Comparability.MissingDetails);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Known_categories_with_missing_preparation_support_limited_reference_comparison()
|
||||||
|
{
|
||||||
|
var limited = new MeasurementContextDto("Home", "AtRest", null, null, null, null, null, null);
|
||||||
|
var result = Calculate(Observation(0, 150, context: limited), Observation(1, 160, context: limited));
|
||||||
|
Assert.Equal("InsufficientContext", result.Comparability.Status);
|
||||||
|
Assert.Contains("setting: Home", result.Comparability.KnownSimilarities);
|
||||||
|
Assert.Contains("rest duration", result.Comparability.MissingDetails);
|
||||||
|
Assert.NotNull(result.Systolic.Reference);
|
||||||
|
Assert.Contains("provisional", result.Systolic.ReferenceComparison);
|
||||||
|
Assert.Contains("limited reference comparison", result.Systolic.Hint);
|
||||||
|
Assert.Equal("CannotInterpret", result.Systolic.Interpretation);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Missing_optional_circumstances_do_not_block_supported_comparison()
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(0, 150), Observation(1, 160));
|
||||||
|
Assert.NotNull(result.Systolic.Reference);
|
||||||
|
Assert.Equal("PotentiallyConcerning", result.Systolic.Interpretation);
|
||||||
|
Assert.Equal("SupportedRecordedComparability", result.Comparability.Status);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("during exercise")]
|
||||||
|
[InlineData("after activity")]
|
||||||
|
[InlineData("under træning")]
|
||||||
|
public void Conflicting_rest_narrative_withholds_resting_interpretation(string narrative)
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(0, 150, text: narrative), Observation(1, 160));
|
||||||
|
Assert.Equal("ConflictingContext", result.Comparability.Status);
|
||||||
|
Assert.Contains(result.Comparability.Conflicts, s => s.Contains("AtRest"));
|
||||||
|
Assert.Null(result.Systolic.Reference);
|
||||||
|
Assert.Null(result.Pulse.Reference);
|
||||||
|
Assert.Equal("Increasing", result.Systolic.Direction);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Different_conditions_and_preparation_are_visible_and_limit_combined_trajectory()
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(0, 150), Observation(1, 160, context: Prepared with
|
||||||
|
{ ActivityCondition = "AfterActivity", BodyPosition = "Standing" }));
|
||||||
|
Assert.Equal("KnownDifferences", result.Comparability.Status);
|
||||||
|
Assert.Contains(result.Comparability.KnownDifferences, s => s.Contains("activity condition"));
|
||||||
|
Assert.Contains(result.Comparability.KnownDifferences, s => s.Contains("body position"));
|
||||||
|
Assert.Null(result.Systolic.Reference);
|
||||||
|
Assert.Equal("CannotInterpret", result.Systolic.Interpretation);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Known_inadequate_pressure_preparation_does_not_block_resting_pulse_reference()
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(0, 150, context: Prepared with { RestDurationMinutes = 1 }), Observation(1, 160));
|
||||||
|
Assert.Null(result.Systolic.Reference);
|
||||||
|
Assert.NotNull(result.Pulse.Reference);
|
||||||
|
Assert.Contains(result.Comparability.KnownDifferences, s => s.Contains("five-minute"));
|
||||||
|
var standing = Calculate(Observation(0, 150, context: Prepared with { BodyPosition = "Standing" }),
|
||||||
|
Observation(1, 160, context: Prepared with { BodyPosition = "Standing" }));
|
||||||
|
Assert.Null(standing.Systolic.Reference);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Timestamp_ties_do_not_manufacture_direction_or_hide_descriptive_range()
|
||||||
|
{
|
||||||
|
var result = Calculate(Observation(1, 140), Observation(1, 180));
|
||||||
|
Assert.Equal("Unavailable", result.Systolic.Direction);
|
||||||
|
Assert.Null(result.Systolic.SlopePerDay);
|
||||||
|
Assert.Equal(160m, result.Systolic.Mean);
|
||||||
|
Assert.Equal(40, result.Systolic.Range);
|
||||||
|
Assert.NotNull(result.Systolic.Reference);
|
||||||
|
Assert.Equal("CannotInterpret", result.Systolic.Interpretation);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Empty_and_single_series_report_each_unavailable_part()
|
||||||
|
{
|
||||||
|
var empty = Calculate();
|
||||||
|
Assert.Equal(0, empty.ContributingCount);
|
||||||
|
Assert.Null(empty.Systolic.Mean);
|
||||||
|
Assert.Equal("Unavailable", empty.Systolic.Direction);
|
||||||
|
Assert.Contains("No matching observations", empty.Systolic.NumericalExplanation);
|
||||||
|
var single = Calculate(Observation(0, 140));
|
||||||
|
Assert.Equal(140m, single.Systolic.Mean);
|
||||||
|
Assert.Equal("Unavailable", single.Systolic.Direction);
|
||||||
|
Assert.Equal("Unavailable", single.Systolic.OverallDirection);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Retrieval_and_identifier_order_do_not_change_results_including_ties()
|
||||||
|
{
|
||||||
|
var series = new[] { Observation(0, 140), Observation(0, 180), Observation(1, 150), Observation(2, 140) };
|
||||||
|
Assert.Equal(JsonSerializer.Serialize(Calculate(series)), JsonSerializer.Serialize(Calculate(series.Reverse()
|
||||||
|
.Select(o => o with { ObservationId = Guid.NewGuid() }).ToArray())));
|
||||||
|
Assert.Equal("Decreasing", Calculate(series).Systolic.Direction);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class HealthTrendTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||||
|
{
|
||||||
|
private sealed record Profile(Guid PatientId);
|
||||||
|
private sealed record Recorded(Guid ObservationId);
|
||||||
|
private const string Period = "from=2026-09-01T08%3A00%3A00&to=2026-09-10T08%3A00%3A00";
|
||||||
|
private static string PathFor(Guid patient, string selection = "", string period = Period) =>
|
||||||
|
$"/api/patients/{patient}/trends?{period}{selection}";
|
||||||
|
private async Task<Guid> Patient()
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Health trend", dateOfBirth = "1980-01-01" });
|
||||||
|
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||||
|
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||||
|
}
|
||||||
|
private async Task<Guid> Record(Guid patient, int systolic, string time = "2026-09-05T08:00:00",
|
||||||
|
string? setting = "Home", string? activity = "AtRest")
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patient}/observations", new
|
||||||
|
{
|
||||||
|
measuredAt = time, systolic, diastolic = 85, pulse = 70,
|
||||||
|
measurementContext = new { setting, activityCondition = activity, restDurationMinutes = 5,
|
||||||
|
bodyPosition = "Seated", measuredArm = "Left", deviceDetails = "Device A", cuffDetails = "Adult cuff" }
|
||||||
|
});
|
||||||
|
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||||
|
return (await response.Content.ReadFromJsonAsync<Recorded>())!.ObservationId;
|
||||||
|
}
|
||||||
|
private async Task<TrendAssessment> Trend(Guid patient, string selection = "", string period = Period)
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.GetAsync(PathFor(patient, selection, period));
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
return (await response.Content.ReadFromJsonAsync<TrendAssessment>())!;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Inclusive_patient_period_and_equal_offset_instants_apply_before_sufficiency()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
await Record(patient, 150, "2026-09-01T08:00:00");
|
||||||
|
await Record(patient, 160, "2026-09-10T08:00:00");
|
||||||
|
await Record(patient, 250, "2026-09-01T07:59:59");
|
||||||
|
await Record(patient, 250, "2026-09-10T08:00:01");
|
||||||
|
await Record(await Patient(), 250);
|
||||||
|
var result = await Trend(patient);
|
||||||
|
Assert.Equal(patient, result.PatientId);
|
||||||
|
Assert.Equal(new DateTime(2026, 9, 1, 8, 0, 0), result.PeriodStart);
|
||||||
|
Assert.Equal(new DateTime(2026, 9, 10, 8, 0, 0), result.PeriodEnd);
|
||||||
|
Assert.Equal(2, result.ContributingCount);
|
||||||
|
Assert.Equal(155m, result.Systolic.Mean);
|
||||||
|
Assert.Equal("Increasing", result.Systolic.Direction);
|
||||||
|
var equal = await Trend(patient, period: "from=2026-09-01T10%3A00%3A00%2B02%3A00&to=2026-09-01T08%3A00%3A00Z");
|
||||||
|
Assert.Equal(equal.PeriodStart, equal.PeriodEnd);
|
||||||
|
Assert.Equal(1, equal.ContributingCount);
|
||||||
|
Assert.Equal("Unavailable", equal.Systolic.Direction);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Labelled_home_and_clinic_selections_and_independent_dimensions_use_only_matches()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
await Record(patient, 150, "2026-09-02T08:00:00");
|
||||||
|
await Record(patient, 145, "2026-09-03T08:00:00");
|
||||||
|
await Record(patient, 160, "2026-09-02T08:00:00", "Clinic");
|
||||||
|
await Record(patient, 155, "2026-09-03T08:00:00", "Clinic");
|
||||||
|
await Record(patient, 200, activity: "AfterActivity");
|
||||||
|
var home = await Trend(patient, "&setting=Home&activityCondition=AtRest");
|
||||||
|
var clinic = await Trend(patient, "&setting=Clinic&activityCondition=AtRest");
|
||||||
|
Assert.Equal(new ContextSelection { Setting = "Home", ActivityCondition = "AtRest" }, home.AppliedSelection);
|
||||||
|
Assert.Equal(new ContextSelection { Setting = "Clinic", ActivityCondition = "AtRest" }, clinic.AppliedSelection);
|
||||||
|
Assert.Equal(2, home.ContributingCount);
|
||||||
|
Assert.Equal(2, clinic.ContributingCount);
|
||||||
|
Assert.Equal(135m, home.Systolic.Reference!.UpperBoundary);
|
||||||
|
Assert.Equal(140m, clinic.Systolic.Reference!.UpperBoundary);
|
||||||
|
Assert.Contains("alone is not improvement or deterioration", home.Comparability.Explanation);
|
||||||
|
Assert.Equal(3, (await Trend(patient, "&setting=Home")).ContributingCount);
|
||||||
|
Assert.Equal(4, (await Trend(patient, "&activityCondition=AtRest")).ContributingCount);
|
||||||
|
Assert.Equal("KnownDifferences", (await Trend(patient)).Comparability.Status);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Unknown_empty_and_one_selected_observation_do_not_borrow_excluded_data()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
await Record(patient, 150, "2026-09-02T08:00:00");
|
||||||
|
await Record(patient, 160, "2026-09-03T08:00:00");
|
||||||
|
await Record(patient, 180, setting: null, activity: null);
|
||||||
|
var unknown = await Trend(patient, "&setting=Unknown&activityCondition=Unknown");
|
||||||
|
Assert.Equal(1, unknown.ContributingCount);
|
||||||
|
Assert.Equal("Unavailable", unknown.Systolic.Direction);
|
||||||
|
Assert.Equal(180m, unknown.Systolic.Mean);
|
||||||
|
Assert.Null(unknown.Systolic.Reference);
|
||||||
|
var empty = await Trend(patient, "&setting=Clinic");
|
||||||
|
Assert.Equal(0, empty.ContributingCount);
|
||||||
|
Assert.Contains("No matching observations", empty.Pulse.NumericalExplanation);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Corrected_values_context_and_deletions_are_used_on_every_request_after_restart()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
var first = await Record(patient, 150, "2026-09-02T08:00:00");
|
||||||
|
var second = await Record(patient, 160, "2026-09-03T08:00:00");
|
||||||
|
Assert.Equal("Increasing", (await Trend(patient)).Systolic.Direction);
|
||||||
|
using var corrected = await fixture.Client.PatchAsJsonAsync($"/api/observations/{second}", new { systolic = 140 });
|
||||||
|
Assert.Equal(HttpStatusCode.OK, corrected.StatusCode);
|
||||||
|
Assert.Equal("Decreasing", (await Trend(patient)).Systolic.Direction);
|
||||||
|
using var context = await fixture.Client.PatchAsJsonAsync($"/api/observations/{second}",
|
||||||
|
new { measurementContext = new { activityCondition = "AfterActivity" } });
|
||||||
|
Assert.Equal(HttpStatusCode.OK, context.StatusCode);
|
||||||
|
var selected = await Trend(patient, "&activityCondition=AtRest");
|
||||||
|
Assert.Equal(1, selected.ContributingCount);
|
||||||
|
Assert.Equal("Unavailable", selected.Systolic.Direction);
|
||||||
|
Assert.Null((await Trend(patient)).Systolic.Reference);
|
||||||
|
using var deleted = await fixture.Client.DeleteAsync($"/api/observations/{second}");
|
||||||
|
Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
Assert.Equal(150m, (await Trend(patient)).Systolic.Mean);
|
||||||
|
using var last = await fixture.Client.DeleteAsync($"/api/observations/{first}");
|
||||||
|
Assert.Equal(HttpStatusCode.NoContent, last.StatusCode);
|
||||||
|
Assert.Equal(0, (await Trend(patient)).ContributingCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("from=2026-09-10&to=2026-09-01")]
|
||||||
|
[InlineData("from=bad&to=2026-09-10")]
|
||||||
|
[InlineData("from=2026-09-01")]
|
||||||
|
[InlineData("to=2026-09-10")]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData(Period + "&setting=Invalid")]
|
||||||
|
[InlineData(Period + "&activityCondition=Invalid")]
|
||||||
|
public async Task Invalid_period_or_selection_is_rejected_with_explanation(string period)
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.GetAsync(PathFor(await Patient(), period: period));
|
||||||
|
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||||
|
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||||
|
Assert.True(problem.RootElement.TryGetProperty("errors", out _));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Trend_access_requires_authentication_ownership_or_professional_assignment()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
await Record(patient, 150);
|
||||||
|
var other = await Patient();
|
||||||
|
fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = patient.ToString();
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
using var anonymous = await fixture.RawClient.GetAsync(PathFor(patient));
|
||||||
|
Assert.Equal(HttpStatusCode.Unauthorized, anonymous.StatusCode);
|
||||||
|
foreach (var (account, status) in new[] { ("professional", HttpStatusCode.OK),
|
||||||
|
("professional-empty", HttpStatusCode.NotFound), (fixture.Authentication.PatientAccounts[other], HttpStatusCode.NotFound) })
|
||||||
|
{
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Get, PathFor(patient));
|
||||||
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account));
|
||||||
|
using var response = await fixture.RawClient.SendAsync(request);
|
||||||
|
Assert.Equal(status, response.StatusCode);
|
||||||
|
if (status != HttpStatusCode.OK) Assert.Empty(await response.Content.ReadAsStringAsync());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Upstream_failure_is_not_misreported_as_empty_data()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
await fixture.StopObservationServiceAsync();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.GetAsync(PathFor(patient));
|
||||||
|
Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode);
|
||||||
|
}
|
||||||
|
finally { await fixture.RestartHostsAsync(); }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
using System.Net;
|
using System.Net;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using ObservationService.Domain;
|
||||||
using System.Net.Http.Json;
|
using System.Net.Http.Json;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
@@ -7,8 +9,9 @@ namespace Observation.AcceptanceTests;
|
|||||||
public sealed class LatestObservationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
public sealed class LatestObservationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||||
{
|
{
|
||||||
private sealed record Profile(Guid PatientId);
|
private sealed record Profile(Guid PatientId);
|
||||||
|
private sealed record ContextData(string Setting, string ActivityCondition, decimal? RestDurationMinutes, string? BodyPosition);
|
||||||
private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||||
int Systolic, int Diastolic, int Pulse, string? Context, string? Note);
|
int Systolic, int Diastolic, int Pulse, string? Context, string? Note, ContextData MeasurementContext);
|
||||||
|
|
||||||
private async Task<Guid> CreatePatientAsync()
|
private async Task<Guid> CreatePatientAsync()
|
||||||
{
|
{
|
||||||
@@ -59,4 +62,96 @@ public sealed class LatestObservationTests(ObservationApiFixture fixture) : ICla
|
|||||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||||
Assert.DoesNotContain("observationId", await response.Content.ReadAsStringAsync());
|
Assert.DoesNotContain("observationId", await response.Content.ReadAsStringAsync());
|
||||||
}
|
}
|
||||||
|
private async Task<(Guid OlderId, Guid NewerId)> SeedPair(Guid patientId, DateTime olderMeasured,
|
||||||
|
DateTime newerMeasured, DateTime olderRecorded, DateTime newerRecorded,
|
||||||
|
MeasurementContext olderContext, MeasurementContext newerContext)
|
||||||
|
{
|
||||||
|
// Make the older observation's identifier greater, so it cannot mask the recording-time rule.
|
||||||
|
var prefix = Guid.NewGuid().ToString("N")[..24];
|
||||||
|
var olderId = Guid.ParseExact(prefix + "ffffffff", "N");
|
||||||
|
var newerId = Guid.ParseExact(prefix + "00000001", "N");
|
||||||
|
await using var db = fixture.CreateObservationDbContext();
|
||||||
|
db.Observations.AddRange(
|
||||||
|
new BloodPressureObservation
|
||||||
|
{
|
||||||
|
ObservationId = newerId, PatientId = patientId, MeasuredAt = newerMeasured,
|
||||||
|
Systolic = 126, Diastolic = 80, Pulse = 66, MeasurementContext = newerContext,
|
||||||
|
CreatedAt = newerRecorded, UpdatedAt = newerRecorded
|
||||||
|
},
|
||||||
|
new BloodPressureObservation
|
||||||
|
{
|
||||||
|
ObservationId = olderId, PatientId = patientId, MeasuredAt = olderMeasured,
|
||||||
|
Systolic = 130, Diastolic = 84, Pulse = 70, MeasurementContext = olderContext,
|
||||||
|
CreatedAt = olderRecorded, UpdatedAt = olderRecorded
|
||||||
|
});
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
return (olderId, newerId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Task<Observation?> Latest(Guid patientId) =>
|
||||||
|
fixture.Client.GetFromJsonAsync<Observation>($"/api/patients/{patientId}/observations/latest");
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Newer_after_activity_observation_is_returned_with_its_own_context()
|
||||||
|
{
|
||||||
|
var patient = await CreatePatientAsync();
|
||||||
|
var time = new DateTime(2026, 9, 12, 8, 0, 0);
|
||||||
|
var pair = await SeedPair(patient, time.AddDays(-1), time, time.AddHours(2), time.AddHours(1),
|
||||||
|
new MeasurementContext { Setting = "Home", ActivityCondition = "AtRest", RestDurationMinutes = 5 },
|
||||||
|
new MeasurementContext { Setting = "Clinic", ActivityCondition = "AfterActivity", BodyPosition = "Standing" });
|
||||||
|
var latest = (await Latest(patient))!;
|
||||||
|
Assert.Equal(pair.NewerId, latest.ObservationId);
|
||||||
|
Assert.Equal(new ContextData("Clinic", "AfterActivity", null, "Standing"), latest.MeasurementContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Missing_context_does_not_replace_latest_with_an_older_complete_observation()
|
||||||
|
{
|
||||||
|
var patient = await CreatePatientAsync();
|
||||||
|
var time = new DateTime(2026, 9, 12, 8, 0, 0);
|
||||||
|
var pair = await SeedPair(patient, time.AddDays(-1), time, time, time.AddHours(1),
|
||||||
|
new MeasurementContext { Setting = "Home", ActivityCondition = "AtRest", RestDurationMinutes = 5,
|
||||||
|
BodyPosition = "Seated", MeasuredArm = "Left", DeviceDetails = "Recorded device", CuffDetails = "Recorded cuff" },
|
||||||
|
new MeasurementContext());
|
||||||
|
var latest = (await Latest(patient))!;
|
||||||
|
Assert.Equal(pair.NewerId, latest.ObservationId);
|
||||||
|
Assert.Equal(new ContextData("Unknown", "Unknown", null, null), latest.MeasurementContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Measurement_timestamp_ties_use_original_recording_time_and_ignore_later_edits()
|
||||||
|
{
|
||||||
|
var patient = await CreatePatientAsync();
|
||||||
|
var time = new DateTime(2026, 9, 12, 8, 0, 0);
|
||||||
|
var pair = await SeedPair(patient, time, time, time.AddHours(1), time.AddHours(2),
|
||||||
|
new MeasurementContext { Setting = "Home", ActivityCondition = "AtRest" },
|
||||||
|
new MeasurementContext { Setting = "Clinic", ActivityCondition = "AfterActivity" });
|
||||||
|
Assert.Equal(pair.NewerId, (await Latest(patient))!.ObservationId);
|
||||||
|
using var correction = await fixture.Client.PutAsJsonAsync($"/api/observations/{pair.OlderId}",
|
||||||
|
new { systolic = 125, diastolic = 80, pulse = 65 });
|
||||||
|
Assert.Equal(HttpStatusCode.OK, correction.StatusCode);
|
||||||
|
await using var db = fixture.CreateObservationDbContext();
|
||||||
|
var corrected = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == pair.OlderId);
|
||||||
|
Assert.Equal(time.AddHours(1), corrected.CreatedAt);
|
||||||
|
Assert.True(corrected.UpdatedAt > time.AddHours(2));
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
var latest = (await Latest(patient))!;
|
||||||
|
Assert.Equal(pair.NewerId, latest.ObservationId);
|
||||||
|
Assert.Equal("Clinic", latest.MeasurementContext.Setting);
|
||||||
|
Assert.Equal("AfterActivity", latest.MeasurementContext.ActivityCondition);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Complete_timestamp_ties_choose_greatest_identifier_reproducibly_across_restart()
|
||||||
|
{
|
||||||
|
var patient = await CreatePatientAsync();
|
||||||
|
var time = new DateTime(2026, 9, 12, 8, 0, 0);
|
||||||
|
var pair = await SeedPair(patient, time, time, time.AddHours(1), time.AddHours(1),
|
||||||
|
new MeasurementContext { Setting = "Home" }, new MeasurementContext { Setting = "Clinic" });
|
||||||
|
for (var i = 0; i < 3; i++)
|
||||||
|
Assert.Equal(pair.OlderId, (await Latest(patient))!.ObservationId);
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
Assert.Equal(pair.OlderId, (await Latest(patient))!.ObservationId);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
using Npgsql;
|
||||||
|
using ObservationService.Persistence;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace Observation.AcceptanceTests;
|
||||||
|
|
||||||
|
public sealed class MeasurementContextMigrationTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task Upgrading_an_existing_observation_retains_values_and_text_without_inventing_context()
|
||||||
|
{
|
||||||
|
var admin = Environment.GetEnvironmentVariable("TEST_POSTGRES_CONNECTION")
|
||||||
|
?? throw new InvalidOperationException("TEST_POSTGRES_CONNECTION is required.");
|
||||||
|
var database = "us04_context_upgrade_" + Guid.NewGuid().ToString("N");
|
||||||
|
await using var connection = new NpgsqlConnection(admin);
|
||||||
|
await connection.OpenAsync();
|
||||||
|
await using (var create = new NpgsqlCommand($"CREATE DATABASE {database}", connection))
|
||||||
|
await create.ExecuteNonQueryAsync();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var options = new DbContextOptionsBuilder<ObservationDbContext>().UseNpgsql(
|
||||||
|
new NpgsqlConnectionStringBuilder(admin) { Database = database }.ConnectionString).Options;
|
||||||
|
await using var db = new ObservationDbContext(options);
|
||||||
|
await db.GetService<IMigrator>().MigrateAsync("20261001095222_InitialObservationSchema");
|
||||||
|
var observation = Guid.NewGuid();
|
||||||
|
var patient = Guid.NewGuid();
|
||||||
|
await db.Database.ExecuteSqlInterpolatedAsync($"""
|
||||||
|
INSERT INTO blood_pressure_observation
|
||||||
|
(observation_id, patient_id, measured_at, systolic, diastolic, pulse, context, note, created_at, updated_at)
|
||||||
|
VALUES ({observation}, {patient}, '2026-09-12 08:00:00', 128, 82, 68,
|
||||||
|
'Morning reading; resting?', 'Historical note', '2026-09-12 09:00:00', '2026-09-12 09:00:00')
|
||||||
|
""");
|
||||||
|
await db.Database.MigrateAsync();
|
||||||
|
await db.Database.MigrateAsync();
|
||||||
|
var saved = await db.Observations.AsNoTracking().SingleAsync();
|
||||||
|
Assert.Equal(observation, saved.ObservationId);
|
||||||
|
Assert.Equal(patient, saved.PatientId);
|
||||||
|
Assert.Equal(new DateTime(2026, 9, 12, 8, 0, 0), saved.MeasuredAt);
|
||||||
|
Assert.Equal(128, saved.Systolic);
|
||||||
|
Assert.Equal(82, saved.Diastolic);
|
||||||
|
Assert.Equal(68, saved.Pulse);
|
||||||
|
Assert.Equal("Morning reading; resting?", saved.Context);
|
||||||
|
Assert.Equal("Historical note", saved.Note);
|
||||||
|
Assert.Equal("Unknown", saved.MeasurementContext.Setting);
|
||||||
|
Assert.Equal("Unknown", saved.MeasurementContext.ActivityCondition);
|
||||||
|
Assert.Null(saved.MeasurementContext.RestDurationMinutes);
|
||||||
|
Assert.Null(saved.MeasurementContext.BodyPosition);
|
||||||
|
Assert.Null(saved.MeasurementContext.MeasuredArm);
|
||||||
|
Assert.Null(saved.MeasurementContext.DeviceDetails);
|
||||||
|
Assert.Null(saved.MeasurementContext.CuffDetails);
|
||||||
|
Assert.Null(saved.MeasurementContext.AdditionalCircumstances);
|
||||||
|
Assert.Equal(new DateTime(2026, 9, 12, 9, 0, 0), saved.CreatedAt);
|
||||||
|
Assert.Equal(saved.CreatedAt, saved.UpdatedAt);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await using var drop = new NpgsqlCommand($"DROP DATABASE {database} WITH (FORCE)", connection);
|
||||||
|
await drop.ExecuteNonQueryAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,7 +13,11 @@
|
|||||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.12" />
|
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.12" />
|
||||||
<ProjectReference Include="../../src/PatientProfileService/PatientProfileService.csproj" />
|
<ProjectReference Include="../../src/PatientProfileService/PatientProfileService.csproj" />
|
||||||
<ProjectReference Include="../../src/ApiGateway/ApiGateway.csproj" />
|
<ProjectReference Include="../../src/ApiGateway/ApiGateway.csproj" />
|
||||||
|
<ProjectReference Include="../../src/HealthOverviewService/HealthOverviewService.csproj" />
|
||||||
<ProjectReference Include="../../src/InsightsService/InsightsService.csproj" />
|
<ProjectReference Include="../../src/InsightsService/InsightsService.csproj" />
|
||||||
<ProjectReference Include="../../src/ObservationService/ObservationService.csproj" />
|
<ProjectReference Include="../../src/ObservationService/ObservationService.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<Compile Include="../Support/AuthenticatedTestClient.cs" Link="Support/AuthenticatedTestClient.cs" />
|
||||||
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
using Microsoft.AspNetCore.Authentication.BearerToken;
|
||||||
|
using HealthApp.TestSupport;
|
||||||
using Microsoft.AspNetCore.Hosting;
|
using Microsoft.AspNetCore.Hosting;
|
||||||
using System.Net;
|
using System.Net;
|
||||||
using Microsoft.AspNetCore.Mvc.Testing;
|
using Microsoft.AspNetCore.Mvc.Testing;
|
||||||
@@ -16,12 +18,20 @@ public sealed class ObservationApiFixture : IAsyncLifetime
|
|||||||
private readonly string observationDatabaseName = "us04_observation_" + Guid.NewGuid().ToString("N");
|
private readonly string observationDatabaseName = "us04_observation_" + Guid.NewGuid().ToString("N");
|
||||||
private WebApplicationFactory<ObservationService.Program>? observation;
|
private WebApplicationFactory<ObservationService.Program>? observation;
|
||||||
private WebApplicationFactory<InsightsService.Program>? insights;
|
private WebApplicationFactory<InsightsService.Program>? insights;
|
||||||
|
private WebApplicationFactory<HealthOverviewService.Program>? overview;
|
||||||
|
public HttpClient CreateDirectOverviewClient() => overview!.CreateClient();
|
||||||
public string ObservationConnectionString { get; private set; } = "";
|
public string ObservationConnectionString { get; private set; } = "";
|
||||||
private string adminConnectionString = "";
|
private string adminConnectionString = "";
|
||||||
private WebApplicationFactory<PatientProfileService.Program>? service;
|
private WebApplicationFactory<PatientProfileService.Program>? service;
|
||||||
private WebApplicationFactory<ApiGateway.Program>? gateway;
|
private WebApplicationFactory<ApiGateway.Program>? gateway;
|
||||||
public string ConnectionString { get; private set; } = "";
|
public string ConnectionString { get; private set; } = "";
|
||||||
public HttpClient Client { get; private set; } = null!;
|
public HttpClient Client { get; private set; } = null!;
|
||||||
|
public HttpClient RawClient { get; private set; } = null!;
|
||||||
|
public HttpClient CreateDirectPatientClient() => service!.CreateClient();
|
||||||
|
public HttpClient CreateDirectObservationClient() => observation!.CreateClient();
|
||||||
|
public HttpClient CreateDirectInsightsClient() => insights!.CreateClient();
|
||||||
|
public AuthenticatedTestClient Authentication { get; } = new();
|
||||||
|
public Dictionary<string, string?> AdditionalGatewayConfiguration { get; } = new();
|
||||||
|
|
||||||
public async Task InitializeAsync()
|
public async Task InitializeAsync()
|
||||||
{
|
{
|
||||||
@@ -57,31 +67,39 @@ public sealed class ObservationApiFixture : IAsyncLifetime
|
|||||||
{
|
{
|
||||||
service = new WebApplicationFactory<PatientProfileService.Program>().WithWebHostBuilder(builder =>
|
service = new WebApplicationFactory<PatientProfileService.Program>().WithWebHostBuilder(builder =>
|
||||||
{
|
{
|
||||||
|
builder.UseEnvironment("Development");
|
||||||
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
||||||
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
||||||
new Dictionary<string, string?> { ["ConnectionStrings:PatientDatabase"] = ConnectionString }));
|
new Dictionary<string, string?> { ["ConnectionStrings:PatientDatabase"] = ConnectionString, ["InternalAccess:GatewayKey"] = Authentication.GatewayKey }));
|
||||||
});
|
});
|
||||||
service.UseKestrel(0);
|
service.UseKestrel(0);
|
||||||
using var serviceClient = service.CreateClient();
|
using var serviceClient = service.CreateClient();
|
||||||
|
|
||||||
gateway = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
|
gateway = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
|
||||||
{
|
{
|
||||||
|
builder.UseEnvironment("Development");
|
||||||
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
||||||
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(Authentication.Configuration()).AddInMemoryCollection(AdditionalGatewayConfiguration).AddInMemoryCollection(
|
||||||
new Dictionary<string, string?> { ["Services:PatientProfile:BaseUrl"] = serviceClient.BaseAddress!.ToString(),
|
new Dictionary<string, string?> { ["Services:PatientProfile:BaseUrl"] = serviceClient.BaseAddress!.ToString(),
|
||||||
["Services:Insights:BaseUrl"] = "http://127.0.0.1:1/",
|
["Services:Insights:BaseUrl"] = "http://127.0.0.1:1/",
|
||||||
["Services:Observation:BaseUrl"] = "http://127.0.0.1:1/" }));
|
["Services:Observation:BaseUrl"] = "http://127.0.0.1:1/" }));
|
||||||
});
|
});
|
||||||
|
gateway = gateway.WithWebHostBuilder(builder => builder.ConfigureServices(services =>
|
||||||
|
services.PostConfigure<BearerTokenOptions>("Bearer", options => options.TimeProvider = Authentication.Clock)));
|
||||||
gateway.UseKestrel(0);
|
gateway.UseKestrel(0);
|
||||||
Client = gateway.CreateClient();
|
RawClient = gateway.CreateClient();
|
||||||
|
Client = Authentication.Wrap(RawClient);
|
||||||
observation = new WebApplicationFactory<ObservationService.Program>().WithWebHostBuilder(builder =>
|
observation = new WebApplicationFactory<ObservationService.Program>().WithWebHostBuilder(builder =>
|
||||||
{
|
{
|
||||||
|
builder.UseEnvironment("Development");
|
||||||
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
||||||
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
||||||
new Dictionary<string, string?>
|
new Dictionary<string, string?>
|
||||||
{
|
{
|
||||||
["ConnectionStrings:ObservationDatabase"] = ObservationConnectionString,
|
["ConnectionStrings:ObservationDatabase"] = ObservationConnectionString,
|
||||||
["Services:ApiGateway:BaseUrl"] = Client.BaseAddress!.ToString()
|
["Services:ApiGateway:BaseUrl"] = Client.BaseAddress!.ToString(),
|
||||||
|
["InternalAccess:GatewayKey"] = Authentication.GatewayKey,
|
||||||
|
["Services:ApiGateway:Key"] = Authentication.ObservationServiceKey
|
||||||
}));
|
}));
|
||||||
});
|
});
|
||||||
observation.UseKestrel(0);
|
observation.UseKestrel(0);
|
||||||
@@ -89,25 +107,52 @@ public sealed class ObservationApiFixture : IAsyncLifetime
|
|||||||
gateway.Services.GetRequiredService<IConfiguration>()["Services:Observation:BaseUrl"] = observationClient.BaseAddress!.ToString();
|
gateway.Services.GetRequiredService<IConfiguration>()["Services:Observation:BaseUrl"] = observationClient.BaseAddress!.ToString();
|
||||||
insights = new WebApplicationFactory<InsightsService.Program>().WithWebHostBuilder(builder =>
|
insights = new WebApplicationFactory<InsightsService.Program>().WithWebHostBuilder(builder =>
|
||||||
{
|
{
|
||||||
|
builder.UseEnvironment("Development");
|
||||||
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
||||||
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
||||||
new Dictionary<string, string?> { ["Services:ApiGateway:BaseUrl"] = Client.BaseAddress!.ToString() }));
|
new Dictionary<string, string?> { ["Services:ApiGateway:BaseUrl"] = Client.BaseAddress!.ToString(), ["InternalAccess:GatewayKey"] = Authentication.GatewayKey, ["Services:ApiGateway:Key"] = Authentication.InsightsServiceKey }));
|
||||||
});
|
});
|
||||||
insights.UseKestrel(0);
|
insights.UseKestrel(0);
|
||||||
using var insightsClient = insights.CreateClient();
|
using var insightsClient = insights.CreateClient();
|
||||||
gateway.Services.GetRequiredService<IConfiguration>()["Services:Insights:BaseUrl"] = insightsClient.BaseAddress!.ToString();
|
gateway.Services.GetRequiredService<IConfiguration>()["Services:Insights:BaseUrl"] = insightsClient.BaseAddress!.ToString();
|
||||||
|
overview = new WebApplicationFactory<HealthOverviewService.Program>().WithWebHostBuilder(builder =>
|
||||||
|
{
|
||||||
|
builder.UseEnvironment("Development");
|
||||||
|
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
||||||
|
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
||||||
|
new Dictionary<string, string?> { ["Services:ApiGateway:BaseUrl"] = Client.BaseAddress!.ToString(),
|
||||||
|
["InternalAccess:GatewayKey"] = Authentication.GatewayKey,
|
||||||
|
["Services:ApiGateway:Key"] = Authentication.OverviewServiceKey }));
|
||||||
|
});
|
||||||
|
overview.UseKestrel(0);
|
||||||
|
using var overviewClient = overview.CreateClient();
|
||||||
|
gateway.Services.GetRequiredService<IConfiguration>()["Services:HealthOverview:BaseUrl"] = overviewClient.BaseAddress!.ToString();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task RestartHostsAsync()
|
public async Task RestartHostsAsync()
|
||||||
{
|
{
|
||||||
Client.Dispose();
|
Client.Dispose();
|
||||||
await insights!.DisposeAsync();
|
RawClient.Dispose();
|
||||||
|
if (overview is not null) await overview.DisposeAsync();
|
||||||
|
if (insights is not null) await insights.DisposeAsync();
|
||||||
if (observation is not null) await observation.DisposeAsync();
|
if (observation is not null) await observation.DisposeAsync();
|
||||||
await gateway!.DisposeAsync();
|
await gateway!.DisposeAsync();
|
||||||
if (service is not null) await service.DisposeAsync();
|
if (service is not null) await service.DisposeAsync();
|
||||||
StartHosts();
|
StartHosts();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task StopOverviewServiceAsync()
|
||||||
|
{
|
||||||
|
if (overview is not null) await overview.DisposeAsync();
|
||||||
|
overview = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task StopInsightsServiceAsync()
|
||||||
|
{
|
||||||
|
if (insights is not null) await insights.DisposeAsync();
|
||||||
|
insights = null;
|
||||||
|
}
|
||||||
|
|
||||||
public async Task StopObservationServiceAsync()
|
public async Task StopObservationServiceAsync()
|
||||||
{
|
{
|
||||||
if (observation is not null) await observation.DisposeAsync();
|
if (observation is not null) await observation.DisposeAsync();
|
||||||
@@ -123,10 +168,13 @@ public sealed class ObservationApiFixture : IAsyncLifetime
|
|||||||
public async Task DisposeAsync()
|
public async Task DisposeAsync()
|
||||||
{
|
{
|
||||||
Client?.Dispose();
|
Client?.Dispose();
|
||||||
|
RawClient?.Dispose();
|
||||||
|
if (overview is not null) await overview.DisposeAsync();
|
||||||
if (insights is not null) await insights.DisposeAsync();
|
if (insights is not null) await insights.DisposeAsync();
|
||||||
if (observation is not null) await observation.DisposeAsync();
|
if (observation is not null) await observation.DisposeAsync();
|
||||||
if (gateway is not null) await gateway.DisposeAsync();
|
if (gateway is not null) await gateway.DisposeAsync();
|
||||||
if (service is not null) await service.DisposeAsync();
|
if (service is not null) await service.DisposeAsync();
|
||||||
|
if (Directory.Exists(Authentication.KeyDirectory)) Directory.Delete(Authentication.KeyDirectory, true);
|
||||||
if (string.IsNullOrEmpty(adminConnectionString)) return;
|
if (string.IsNullOrEmpty(adminConnectionString)) return;
|
||||||
|
|
||||||
NpgsqlConnection.ClearAllPools();
|
NpgsqlConnection.ClearAllPools();
|
||||||
|
|||||||
@@ -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<ObservationApiFixture>
|
||||||
|
{
|
||||||
|
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<Observation> 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<Profile>())!.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<Observation>())!;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Task<HttpResponseMessage> Patch(Guid id, object body) => fixture.Client.PatchAsJsonAsync($"/api/observations/{id}", body);
|
||||||
|
private Task<Observation?> Read(Guid id) => fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{id}");
|
||||||
|
private Task<Observation[]?> History(Guid patient, string selection) => fixture.Client.GetFromJsonAsync<Observation[]>(
|
||||||
|
$"/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<Observation>())!;
|
||||||
|
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<Observation>());
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
Assert.Equal(expected, await Read(original.ObservationId));
|
||||||
|
Assert.Equal(expected, await fixture.Client.GetFromJsonAsync<Observation>($"/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<Observation>());
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,277 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
using HealthApp.TestSupport;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace Observation.AcceptanceTests;
|
||||||
|
|
||||||
|
public sealed class PatientAuthenticationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||||
|
{
|
||||||
|
private static int nextAccount = 150;
|
||||||
|
private sealed record Profile(Guid PatientId);
|
||||||
|
private sealed record Observation(Guid ObservationId, Guid PatientId, int Systolic);
|
||||||
|
private static object ProfileRequest => new { name = "Patient", dateOfBirth = "1980-01-01" };
|
||||||
|
private static object ObservationRequest => new { measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68 };
|
||||||
|
|
||||||
|
private async Task<HttpResponseMessage> Send(HttpMethod method, string path, string? token = null, object? body = null)
|
||||||
|
{
|
||||||
|
using var request = new HttpRequestMessage(method, path);
|
||||||
|
if (token is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||||
|
if (body is not null) request.Content = JsonContent.Create(body);
|
||||||
|
return await fixture.RawClient.SendAsync(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<(string Token, Guid PatientId, string Account)> Patient()
|
||||||
|
{
|
||||||
|
var account = "test-" + Interlocked.Increment(ref nextAccount);
|
||||||
|
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
|
||||||
|
using var response = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
|
||||||
|
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||||
|
return (token, (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId, account);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Login_without_profile_returns_normalized_identity_and_no_patient_data()
|
||||||
|
{
|
||||||
|
using var response = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login",
|
||||||
|
new { accountId = "test-0", password = AuthenticatedTestClient.Password, role = "HealthcareProfessional" });
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
Assert.Contains("no-store", response.Headers.CacheControl!.ToString());
|
||||||
|
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||||
|
Assert.Equal("test-0", json.RootElement.GetProperty("accountId").GetString());
|
||||||
|
Assert.Equal("Patient", json.RootElement.GetProperty("role").GetString());
|
||||||
|
Assert.Equal(1800, json.RootElement.GetProperty("expiresIn").GetInt32());
|
||||||
|
Assert.False(json.RootElement.TryGetProperty("patientId", out _));
|
||||||
|
Assert.False(json.RootElement.TryGetProperty("refreshToken", out _));
|
||||||
|
using var unavailable = await Send(HttpMethod.Get, $"/api/patients/{Guid.NewGuid()}", json.RootElement.GetProperty("accessToken").GetString());
|
||||||
|
Assert.Equal(HttpStatusCode.NotFound, unavailable.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Invalid_account_and_invalid_password_have_same_rejection()
|
||||||
|
{
|
||||||
|
using var unknown = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login", new { accountId = "absent", password = AuthenticatedTestClient.Password });
|
||||||
|
using var incorrect = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login", new { accountId = "test-0", password = "incorrect" });
|
||||||
|
Assert.Equal(HttpStatusCode.Unauthorized, unknown.StatusCode);
|
||||||
|
Assert.Equal(unknown.StatusCode, incorrect.StatusCode);
|
||||||
|
Assert.Equal(await unknown.Content.ReadAsStringAsync(), await incorrect.Content.ReadAsStringAsync());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("GET", "patients/00000000-0000-0000-0000-000000000001")]
|
||||||
|
[InlineData("POST", "patients")]
|
||||||
|
[InlineData("GET", "patients/me")]
|
||||||
|
[InlineData("PUT", "patients/00000000-0000-0000-0000-000000000001")]
|
||||||
|
[InlineData("GET", "observations/00000000-0000-0000-0000-000000000001")]
|
||||||
|
[InlineData("PUT", "observations/00000000-0000-0000-0000-000000000001")]
|
||||||
|
[InlineData("DELETE", "observations/00000000-0000-0000-0000-000000000001")]
|
||||||
|
[InlineData("POST", "patients/00000000-0000-0000-0000-000000000001/observations")]
|
||||||
|
[InlineData("GET", "patients/00000000-0000-0000-0000-000000000001/observations/latest")]
|
||||||
|
[InlineData("GET", "patients/00000000-0000-0000-0000-000000000001/observations")]
|
||||||
|
[InlineData("GET", "patients/00000000-0000-0000-0000-000000000001/insights")]
|
||||||
|
public async Task Missing_and_invalid_tokens_reject_every_existing_patient_operation(string method, string path)
|
||||||
|
{
|
||||||
|
await using var patients = fixture.CreateDbContext();
|
||||||
|
await using var observations = fixture.CreateObservationDbContext();
|
||||||
|
var patientCount = await patients.Patients.CountAsync();
|
||||||
|
var observationCount = await observations.Observations.CountAsync();
|
||||||
|
foreach (var token in new string?[] { null, "unverifiable" })
|
||||||
|
{
|
||||||
|
using var response = await Send(new HttpMethod(method), "/api/" + path, token, method == "GET" ? null : ProfileRequest);
|
||||||
|
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||||
|
Assert.DoesNotContain("Patient", await response.Content.ReadAsStringAsync());
|
||||||
|
}
|
||||||
|
Assert.Equal(patientCount, await patients.Patients.CountAsync());
|
||||||
|
Assert.Equal(observationCount, await observations.Observations.CountAsync());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Own_observations_and_insights_are_available_but_another_patients_reads_and_writes_are_rejected()
|
||||||
|
{
|
||||||
|
var first = await Patient();
|
||||||
|
var second = await Patient();
|
||||||
|
using var record = await Send(HttpMethod.Post, $"/api/patients/{first.PatientId}/observations", first.Token, ObservationRequest);
|
||||||
|
Assert.Equal(HttpStatusCode.Created, record.StatusCode);
|
||||||
|
var observation = (await record.Content.ReadFromJsonAsync<Observation>())!;
|
||||||
|
var paths = new[] { $"patients/{first.PatientId}", $"patients/{first.PatientId}/observations",
|
||||||
|
$"patients/{first.PatientId}/observations/latest", $"patients/{first.PatientId}/insights", $"observations/{observation.ObservationId}" };
|
||||||
|
foreach (var path in paths)
|
||||||
|
{
|
||||||
|
var query = path.EndsWith("/observations") || path.EndsWith("/insights") ? "?from=2026-09-01&to=2026-10-01" : "";
|
||||||
|
using var own = await Send(HttpMethod.Get, "/api/" + path + query, first.Token);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, own.StatusCode);
|
||||||
|
using var other = await Send(HttpMethod.Get, "/api/" + path + query, second.Token);
|
||||||
|
Assert.Equal(HttpStatusCode.NotFound, other.StatusCode);
|
||||||
|
Assert.Empty(await other.Content.ReadAsStringAsync());
|
||||||
|
}
|
||||||
|
foreach (var (method, path, body) in new[]
|
||||||
|
{
|
||||||
|
(HttpMethod.Put, $"patients/{first.PatientId}", ProfileRequest),
|
||||||
|
(HttpMethod.Post, $"patients/{first.PatientId}/observations", ObservationRequest),
|
||||||
|
(HttpMethod.Put, $"observations/{observation.ObservationId}", ObservationRequest),
|
||||||
|
(HttpMethod.Delete, $"observations/{observation.ObservationId}", (object?)null)
|
||||||
|
})
|
||||||
|
{
|
||||||
|
using var response = await Send(method, "/api/" + path, second.Token, body);
|
||||||
|
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||||
|
}
|
||||||
|
using var retained = await Send(HttpMethod.Get, $"/api/observations/{observation.ObservationId}", first.Token);
|
||||||
|
Assert.Equal(128, (await retained.Content.ReadFromJsonAsync<Observation>())!.Systolic);
|
||||||
|
await using var db = fixture.CreateObservationDbContext();
|
||||||
|
Assert.Single(await db.Observations.Where(o => o.PatientId == first.PatientId).ToListAsync());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Caller_supplied_account_identity_cannot_replace_authenticated_identity()
|
||||||
|
{
|
||||||
|
var account = "test-" + Interlocked.Increment(ref nextAccount);
|
||||||
|
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/patients") { Content = JsonContent.Create(ProfileRequest) };
|
||||||
|
request.Headers.Authorization = new("Bearer", token);
|
||||||
|
request.Headers.Add("X-Account-Id", "test-0");
|
||||||
|
using var response = await fixture.RawClient.SendAsync(request);
|
||||||
|
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||||
|
await using var db = fixture.CreateDbContext();
|
||||||
|
var id = (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||||
|
Assert.Equal(account, (await db.Patients.SingleAsync(p => p.PatientId == id)).AccountId);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Profile_creation_retries_and_concurrency_preserve_one_persistent_association()
|
||||||
|
{
|
||||||
|
var account = "test-" + Interlocked.Increment(ref nextAccount);
|
||||||
|
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
|
||||||
|
var responses = await Task.WhenAll(Send(HttpMethod.Post, "/api/patients", token, ProfileRequest), Send(HttpMethod.Post, "/api/patients", token, ProfileRequest));
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Assert.Single(responses, r => r.StatusCode == HttpStatusCode.Created);
|
||||||
|
Assert.Single(responses, r => r.StatusCode == HttpStatusCode.Conflict);
|
||||||
|
var profile = (await responses.Single(r => r.StatusCode == HttpStatusCode.Created).Content.ReadFromJsonAsync<Profile>())!;
|
||||||
|
using var retry = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
|
||||||
|
Assert.Equal(HttpStatusCode.Conflict, retry.StatusCode);
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
using var read = await Send(HttpMethod.Get, "/api/patients/me", token);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, read.StatusCode);
|
||||||
|
Assert.Equal(profile.PatientId, (await read.Content.ReadFromJsonAsync<Profile>())!.PatientId);
|
||||||
|
await using var db = fixture.CreateDbContext();
|
||||||
|
Assert.Single(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
|
||||||
|
}
|
||||||
|
finally { foreach (var response in responses) response.Dispose(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Failed_creation_can_be_retried_without_an_orphan_profile()
|
||||||
|
{
|
||||||
|
var account = "test-" + Interlocked.Increment(ref nextAccount);
|
||||||
|
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
|
||||||
|
await fixture.StopPatientServiceAsync();
|
||||||
|
using var failed = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
|
||||||
|
Assert.Equal(HttpStatusCode.BadGateway, failed.StatusCode);
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
using var retry = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
|
||||||
|
Assert.Equal(HttpStatusCode.Created, retry.StatusCode);
|
||||||
|
await using var db = fixture.CreateDbContext();
|
||||||
|
Assert.Single(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Expired_token_is_rejected_and_login_produces_a_fresh_token()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
fixture.Authentication.Clock.Advance(TimeSpan.FromMinutes(31));
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var expired = await Send(HttpMethod.Get, $"/api/patients/{patient.PatientId}", patient.Token);
|
||||||
|
Assert.Equal(HttpStatusCode.Unauthorized, expired.StatusCode);
|
||||||
|
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, patient.Account);
|
||||||
|
using var renewed = await Send(HttpMethod.Get, $"/api/patients/{patient.PatientId}", token);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, renewed.StatusCode);
|
||||||
|
}
|
||||||
|
finally { fixture.Authentication.Clock.Advance(TimeSpan.FromMinutes(-31)); }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Tampering_with_a_valid_token_is_rejected()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
var token = patient.Token.ToCharArray();
|
||||||
|
var position = token.Length / 2;
|
||||||
|
token[position] = token[position] == 'A' ? 'B' : 'A';
|
||||||
|
using var response = await Send(HttpMethod.Get, $"/api/patients/{patient.PatientId}", new string(token));
|
||||||
|
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Database_failure_rolls_back_profile_and_association_together()
|
||||||
|
{
|
||||||
|
var account = "test-" + Interlocked.Increment(ref nextAccount);
|
||||||
|
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
|
||||||
|
await using var db = fixture.CreateDbContext();
|
||||||
|
await db.Database.ExecuteSqlRawAsync("""
|
||||||
|
CREATE FUNCTION fail_profile_test() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||||
|
BEGIN
|
||||||
|
IF NEW.name = 'simulate-write-failure' THEN RAISE EXCEPTION 'test write failure'; END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END; $$;
|
||||||
|
CREATE TRIGGER fail_profile_test BEFORE INSERT ON patient FOR EACH ROW EXECUTE FUNCTION fail_profile_test();
|
||||||
|
""");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var failed = await Send(HttpMethod.Post, "/api/patients", token,
|
||||||
|
new { name = "simulate-write-failure", dateOfBirth = "1980-01-01" });
|
||||||
|
Assert.Equal(HttpStatusCode.InternalServerError, failed.StatusCode);
|
||||||
|
Assert.Empty(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
|
||||||
|
using var retry = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
|
||||||
|
Assert.Equal(HttpStatusCode.Created, retry.StatusCode);
|
||||||
|
Assert.Single(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await db.Database.ExecuteSqlRawAsync("DROP TRIGGER fail_profile_test ON patient; DROP FUNCTION fail_profile_test();");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Direct_services_reject_client_tokens_missing_keys_and_forged_keys()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
foreach (var client in new[] { fixture.CreateDirectPatientClient(), fixture.CreateDirectObservationClient(), fixture.CreateDirectInsightsClient() })
|
||||||
|
{
|
||||||
|
using (client)
|
||||||
|
{
|
||||||
|
client.DefaultRequestHeaders.Authorization = new("Bearer", patient.Token);
|
||||||
|
foreach (var key in new string?[] { null, "forged" })
|
||||||
|
{
|
||||||
|
client.DefaultRequestHeaders.Remove("X-Gateway-Key");
|
||||||
|
if (key is not null) client.DefaultRequestHeaders.Add("X-Gateway-Key", key);
|
||||||
|
using var response = await client.GetAsync($"/api/patients/{patient.PatientId}");
|
||||||
|
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Service_credentials_are_limited_to_their_documented_read_calls()
|
||||||
|
{
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/patients") { Content = JsonContent.Create(ProfileRequest) };
|
||||||
|
request.Headers.Add("X-Service-Key", fixture.Authentication.ObservationServiceKey);
|
||||||
|
using var response = await fixture.RawClient.SendAsync(request);
|
||||||
|
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||||
|
using var forbidden = new HttpRequestMessage(HttpMethod.Get, "/api/patients/by-account/test-0");
|
||||||
|
forbidden.Headers.Add("X-Service-Key", fixture.Authentication.InsightsServiceKey);
|
||||||
|
using var rejected = await fixture.RawClient.SendAsync(forbidden);
|
||||||
|
Assert.Equal(HttpStatusCode.Forbidden, rejected.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Healthcare_professional_cannot_create_profiles()
|
||||||
|
{
|
||||||
|
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
|
||||||
|
using var response = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
|
||||||
|
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,275 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
using HealthApp.TestSupport;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace Observation.AcceptanceTests;
|
||||||
|
|
||||||
|
public sealed class ProfessionalAccessTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||||
|
{
|
||||||
|
private const string AssignmentPath = "/api/professionals/me/patients";
|
||||||
|
private sealed record Profile(Guid PatientId, string Name);
|
||||||
|
private sealed record Observation(Guid ObservationId, Guid PatientId, int Systolic, string? Context, string? Note);
|
||||||
|
private sealed record AssignedPatient(Guid PatientId);
|
||||||
|
|
||||||
|
private async Task<Guid> CreatePatient()
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Assigned Patient", dateOfBirth = "1980-01-01" });
|
||||||
|
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||||
|
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<Observation> Record(Guid patientId)
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
|
||||||
|
{
|
||||||
|
measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68,
|
||||||
|
context = "Resting", note = "Actual conditions"
|
||||||
|
});
|
||||||
|
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||||
|
return (await response.Content.ReadFromJsonAsync<Observation>())!;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task Assign(Guid[] first, Guid[]? second = null)
|
||||||
|
{
|
||||||
|
fixture.AdditionalGatewayConfiguration.Clear();
|
||||||
|
for (var i = 0; i < first.Length; i++)
|
||||||
|
fixture.AdditionalGatewayConfiguration[$"Access:ProfessionalAssignments:professional:{i}"] = first[i].ToString();
|
||||||
|
for (var i = 0; i < (second?.Length ?? 0); i++)
|
||||||
|
fixture.AdditionalGatewayConfiguration[$"Access:ProfessionalAssignments:professional-second:{i}"] = second![i].ToString();
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<HttpResponseMessage> Send(HttpMethod method, string path, string? token, object? body = null)
|
||||||
|
{
|
||||||
|
using var request = new HttpRequestMessage(method, path);
|
||||||
|
if (token is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||||
|
if (body is not null) request.Content = JsonContent.Create(body);
|
||||||
|
return await fixture.RawClient.SendAsync(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Login_recognizes_professional_identity_and_does_not_put_assignments_in_the_token_response()
|
||||||
|
{
|
||||||
|
using var response = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login",
|
||||||
|
new { accountId = "professional", password = AuthenticatedTestClient.Password, role = "Patient" });
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||||
|
Assert.Equal("HealthcareProfessional", json.RootElement.GetProperty("role").GetString());
|
||||||
|
Assert.Equal("professional", json.RootElement.GetProperty("accountId").GetString());
|
||||||
|
Assert.False(json.RootElement.TryGetProperty("patientId", out _));
|
||||||
|
Assert.False(json.RootElement.TryGetProperty("assignments", out _));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Professionals_list_only_their_own_assignments_and_can_share_patients()
|
||||||
|
{
|
||||||
|
var first = await CreatePatient();
|
||||||
|
var shared = await CreatePatient();
|
||||||
|
var second = await CreatePatient();
|
||||||
|
var excluded = await CreatePatient();
|
||||||
|
await Assign([first, shared, first], [shared, second]);
|
||||||
|
foreach (var (account, expected) in new[]
|
||||||
|
{
|
||||||
|
("professional", new[] { first, shared }),
|
||||||
|
("professional-second", new[] { shared, second }),
|
||||||
|
("professional-empty", Array.Empty<Guid>())
|
||||||
|
})
|
||||||
|
{
|
||||||
|
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
|
||||||
|
using var response = await Send(HttpMethod.Get, AssignmentPath + "?accountId=professional-second", token);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
var patients = (await response.Content.ReadFromJsonAsync<AssignedPatient[]>())!;
|
||||||
|
Assert.Equal(expected.Order(), patients.Select(p => p.PatientId).Order());
|
||||||
|
Assert.DoesNotContain(patients, p => p.PatientId == excluded);
|
||||||
|
}
|
||||||
|
var sharedToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional-second");
|
||||||
|
using var read = await Send(HttpMethod.Get, $"/api/patients/{shared}", sharedToken);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, read.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Assigned_profiles_observations_context_history_latest_and_insights_are_readable()
|
||||||
|
{
|
||||||
|
var patient = await CreatePatient();
|
||||||
|
var observation = await Record(patient);
|
||||||
|
await Assign([patient]);
|
||||||
|
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
|
||||||
|
foreach (var path in new[]
|
||||||
|
{
|
||||||
|
$"/api/patients/{patient}", $"/api/observations/{observation.ObservationId}",
|
||||||
|
$"/api/patients/{patient}/observations/latest", $"/api/patients/{patient}/observations?from=2026-09-01&to=2026-10-01",
|
||||||
|
$"/api/patients/{patient}/insights?from=2026-09-01&to=2026-10-01"
|
||||||
|
})
|
||||||
|
{
|
||||||
|
using var response = await Send(HttpMethod.Get, path, token);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
using var own = await fixture.Client.GetAsync(path);
|
||||||
|
Assert.Equal(await own.Content.ReadAsStringAsync(), await response.Content.ReadAsStringAsync());
|
||||||
|
}
|
||||||
|
using var specific = await Send(HttpMethod.Get, $"/api/observations/{observation.ObservationId}", token);
|
||||||
|
Assert.Equal(observation, await specific.Content.ReadFromJsonAsync<Observation>());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Unassigned_patients_and_observations_are_rejected_even_with_a_supplied_assigned_patient_id()
|
||||||
|
{
|
||||||
|
var assigned = await CreatePatient();
|
||||||
|
var unassigned = await CreatePatient();
|
||||||
|
var observation = await Record(unassigned);
|
||||||
|
await Assign([assigned]);
|
||||||
|
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
|
||||||
|
foreach (var path in new[]
|
||||||
|
{
|
||||||
|
$"/api/patients/{unassigned}", $"/api/observations/{observation.ObservationId}?patientId={assigned}",
|
||||||
|
$"/api/patients/{unassigned}/observations/latest", $"/api/patients/{unassigned}/observations?from=2026-09-01&to=2026-10-01",
|
||||||
|
$"/api/patients/{unassigned}/insights?from=2026-09-01&to=2026-10-01"
|
||||||
|
})
|
||||||
|
{
|
||||||
|
using var response = await Send(HttpMethod.Get, path, token);
|
||||||
|
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||||
|
Assert.Empty(await response.Content.ReadAsStringAsync());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Missing_information_for_assigned_patients_follows_existing_retrieval_behaviour()
|
||||||
|
{
|
||||||
|
var patient = await CreatePatient();
|
||||||
|
var missingPatient = Guid.NewGuid();
|
||||||
|
await Assign([patient, missingPatient]);
|
||||||
|
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
|
||||||
|
foreach (var path in new[]
|
||||||
|
{
|
||||||
|
$"/api/patients/{missingPatient}", $"/api/observations/{Guid.NewGuid()}",
|
||||||
|
$"/api/patients/{patient}/observations/latest", $"/api/patients/{patient}/insights?from=2026-09-01&to=2026-10-01"
|
||||||
|
})
|
||||||
|
{
|
||||||
|
using var response = await Send(HttpMethod.Get, path, token);
|
||||||
|
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||||
|
}
|
||||||
|
using var history = await Send(HttpMethod.Get, $"/api/patients/{patient}/observations?from=2026-09-01&to=2026-10-01", token);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, history.StatusCode);
|
||||||
|
Assert.Equal("[]", await history.Content.ReadAsStringAsync());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("professional")]
|
||||||
|
[InlineData("professional-empty")]
|
||||||
|
public async Task Professionals_cannot_create_update_or_delete_any_patient_information(string account)
|
||||||
|
{
|
||||||
|
var patient = await CreatePatient();
|
||||||
|
var observation = await Record(patient);
|
||||||
|
await Assign([patient]);
|
||||||
|
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
|
||||||
|
await using var patients = fixture.CreateDbContext();
|
||||||
|
await using var observations = fixture.CreateObservationDbContext();
|
||||||
|
var before = await patients.Patients.AsNoTracking().SingleAsync(p => p.PatientId == patient);
|
||||||
|
var count = await patients.Patients.CountAsync();
|
||||||
|
foreach (var (method, path, body) in new[]
|
||||||
|
{
|
||||||
|
(HttpMethod.Post, "/api/patients", (object?)new { name = "Forbidden", dateOfBirth = "1980-01-01" }),
|
||||||
|
(HttpMethod.Put, $"/api/patients/{patient}", (object?)new { name = "Forbidden" }),
|
||||||
|
(HttpMethod.Post, $"/api/patients/{patient}/observations", (object?)new { measuredAt = "2026-09-12T08:00:00", systolic = 190, diastolic = 90, pulse = 80 }),
|
||||||
|
(HttpMethod.Put, $"/api/observations/{observation.ObservationId}", (object?)new { systolic = 190, diastolic = 90, pulse = 80 }),
|
||||||
|
(HttpMethod.Delete, $"/api/observations/{observation.ObservationId}", (object?)null)
|
||||||
|
})
|
||||||
|
{
|
||||||
|
using var response = await Send(method, path, token, body);
|
||||||
|
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||||
|
Assert.Empty(await response.Content.ReadAsStringAsync());
|
||||||
|
}
|
||||||
|
Assert.Equal(count, await patients.Patients.CountAsync());
|
||||||
|
var after = await patients.Patients.AsNoTracking().SingleAsync(p => p.PatientId == patient);
|
||||||
|
Assert.Equal(before.Name, after.Name);
|
||||||
|
Assert.Equal(before.UpdatedAt, after.UpdatedAt);
|
||||||
|
var saved = await observations.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == observation.ObservationId);
|
||||||
|
Assert.Equal(128, saved.Systolic);
|
||||||
|
Assert.Equal("Resting", saved.Context);
|
||||||
|
Assert.Equal("Actual conditions", saved.Note);
|
||||||
|
Assert.Single(await observations.Observations.Where(o => o.PatientId == patient).ToListAsync());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Missing_invalid_and_expired_tokens_do_not_disclose_assignments_or_patient_data()
|
||||||
|
{
|
||||||
|
var patient = await CreatePatient();
|
||||||
|
await Assign([patient]);
|
||||||
|
foreach (var token in new string?[] { null, "invalid" })
|
||||||
|
{
|
||||||
|
using var list = await Send(HttpMethod.Get, AssignmentPath, token);
|
||||||
|
using var read = await Send(HttpMethod.Get, $"/api/patients/{patient}", token);
|
||||||
|
Assert.Equal(HttpStatusCode.Unauthorized, list.StatusCode);
|
||||||
|
Assert.Equal(HttpStatusCode.Unauthorized, read.StatusCode);
|
||||||
|
Assert.Empty(await list.Content.ReadAsStringAsync());
|
||||||
|
Assert.Empty(await read.Content.ReadAsStringAsync());
|
||||||
|
}
|
||||||
|
var valid = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
|
||||||
|
fixture.Authentication.Clock.Advance(TimeSpan.FromMinutes(31));
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var expired = await Send(HttpMethod.Get, AssignmentPath, valid);
|
||||||
|
Assert.Equal(HttpStatusCode.Unauthorized, expired.StatusCode);
|
||||||
|
}
|
||||||
|
finally { fixture.Authentication.Clock.Advance(TimeSpan.FromMinutes(-31)); }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Incorrect_professional_secret_and_unknown_account_have_identical_login_rejections()
|
||||||
|
{
|
||||||
|
using var incorrect = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login", new { accountId = "professional", password = "wrong" });
|
||||||
|
using var unknown = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login", new { accountId = "unknown-professional", password = AuthenticatedTestClient.Password });
|
||||||
|
Assert.Equal(HttpStatusCode.Unauthorized, incorrect.StatusCode);
|
||||||
|
Assert.Equal(incorrect.StatusCode, unknown.StatusCode);
|
||||||
|
Assert.Equal(await incorrect.Content.ReadAsStringAsync(), await unknown.Content.ReadAsStringAsync());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Patient_cannot_list_professional_assignments_and_retains_own_access()
|
||||||
|
{
|
||||||
|
var patient = await CreatePatient();
|
||||||
|
await Assign([patient]);
|
||||||
|
var account = fixture.Authentication.PatientAccounts[patient];
|
||||||
|
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
|
||||||
|
using var rejected = await Send(HttpMethod.Get, AssignmentPath, token);
|
||||||
|
Assert.Equal(HttpStatusCode.Forbidden, rejected.StatusCode);
|
||||||
|
using var own = await Send(HttpMethod.Get, $"/api/patients/{patient}", token);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, own.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Assignment_removal_is_used_after_restart_even_with_an_existing_token()
|
||||||
|
{
|
||||||
|
var patient = await CreatePatient();
|
||||||
|
await Assign([patient]);
|
||||||
|
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
|
||||||
|
using var allowed = await Send(HttpMethod.Get, $"/api/patients/{patient}", token);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, allowed.StatusCode);
|
||||||
|
await Assign([]);
|
||||||
|
using var rejected = await Send(HttpMethod.Get, $"/api/patients/{patient}", token);
|
||||||
|
Assert.Equal(HttpStatusCode.NotFound, rejected.StatusCode);
|
||||||
|
using var list = await Send(HttpMethod.Get, AssignmentPath, token);
|
||||||
|
Assert.Equal("[]", await list.Content.ReadAsStringAsync());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Observation_ownership_lookup_failure_fails_closed_while_assignment_list_remains_available()
|
||||||
|
{
|
||||||
|
var patient = await CreatePatient();
|
||||||
|
var observation = await Record(patient);
|
||||||
|
await Assign([patient]);
|
||||||
|
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
|
||||||
|
await fixture.StopObservationServiceAsync();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var read = await Send(HttpMethod.Get, $"/api/observations/{observation.ObservationId}", token);
|
||||||
|
Assert.Equal(HttpStatusCode.BadGateway, read.StatusCode);
|
||||||
|
using var list = await Send(HttpMethod.Get, AssignmentPath, token);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, list.StatusCode);
|
||||||
|
}
|
||||||
|
finally { await fixture.RestartHostsAsync(); }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
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 RecordMeasurementContextTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||||
|
{
|
||||||
|
private sealed record Profile(Guid PatientId);
|
||||||
|
private sealed record Context(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, Context MeasurementContext);
|
||||||
|
|
||||||
|
private async Task<Guid> Patient()
|
||||||
|
{
|
||||||
|
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Context patient", dateOfBirth = "1980-01-01" });
|
||||||
|
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||||
|
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Task<HttpResponseMessage> Record(Guid patientId, object? measurementContext, string? context = null, string? note = null) =>
|
||||||
|
fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
|
||||||
|
{
|
||||||
|
measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68,
|
||||||
|
measurementContext, context, note
|
||||||
|
});
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Complete_context_is_saved_with_the_correct_values_and_retrievable_after_restart()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
var expected = new Context("Home", "AtRest", 5.5m, "Seated", "Left", "Example upper-arm device",
|
||||||
|
"Example cuff", "Recent stress");
|
||||||
|
using var response = await Record(patient, expected, "Before breakfast", "Actual reading");
|
||||||
|
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||||
|
var saved = (await response.Content.ReadFromJsonAsync<Observation>())!;
|
||||||
|
Assert.Equal(expected, saved.MeasurementContext);
|
||||||
|
Assert.Equal(patient, saved.PatientId);
|
||||||
|
Assert.Equal(new DateTime(2026, 9, 12, 8, 0, 0), saved.MeasuredAt);
|
||||||
|
Assert.Equal(128, saved.Systolic);
|
||||||
|
Assert.Equal(82, saved.Diastolic);
|
||||||
|
Assert.Equal(68, saved.Pulse);
|
||||||
|
Assert.Equal("Before breakfast", saved.Context);
|
||||||
|
Assert.Equal("Actual reading", saved.Note);
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
Assert.Equal(saved, await fixture.Client.GetFromJsonAsync<Observation>(response.Headers.Location));
|
||||||
|
var latest = await fixture.Client.GetFromJsonAsync<Observation>($"/api/patients/{patient}/observations/latest");
|
||||||
|
Assert.Equal(saved, latest);
|
||||||
|
var history = await fixture.Client.GetFromJsonAsync<Observation[]>($"/api/patients/{patient}/observations?from=2026-09-11&to=2026-09-13");
|
||||||
|
Assert.Equal(saved, Assert.Single(history!));
|
||||||
|
using var corrected = await fixture.Client.PutAsJsonAsync($"/api/observations/{saved.ObservationId}",
|
||||||
|
new { systolic = 130, diastolic = 84, pulse = 70 });
|
||||||
|
Assert.Equal(HttpStatusCode.OK, corrected.StatusCode);
|
||||||
|
Assert.Equal(expected, (await corrected.Content.ReadFromJsonAsync<Observation>())!.MeasurementContext);
|
||||||
|
await using var db = fixture.CreateObservationDbContext();
|
||||||
|
var persisted = await db.Observations.SingleAsync(o => o.ObservationId == saved.ObservationId);
|
||||||
|
Assert.Equal(5.5m, persisted.MeasurementContext.RestDurationMinutes);
|
||||||
|
Assert.Equal("Home", persisted.MeasurementContext.Setting);
|
||||||
|
Assert.Equal("Example cuff", persisted.MeasurementContext.CuffDetails);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Home", "AtRest")]
|
||||||
|
[InlineData("Home", "DuringActivity")]
|
||||||
|
[InlineData("Clinic", "AfterActivity")]
|
||||||
|
[InlineData("Other", "Unknown")]
|
||||||
|
[InlineData("Unknown", "AtRest")]
|
||||||
|
[InlineData("Unknown", "Unknown")]
|
||||||
|
public async Task Setting_and_activity_are_independent_and_departures_from_guidance_are_valid(string setting, string activity)
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
using var response = await Record(patient, new { setting, activityCondition = activity,
|
||||||
|
restDurationMinutes = 0m, bodyPosition = "Standing", additionalCircumstances = "Walking immediately beforehand" });
|
||||||
|
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||||
|
var saved = (await response.Content.ReadFromJsonAsync<Observation>())!;
|
||||||
|
Assert.Equal(setting, saved.MeasurementContext.Setting);
|
||||||
|
Assert.Equal(activity, saved.MeasurementContext.ActivityCondition);
|
||||||
|
Assert.Equal(0m, saved.MeasurementContext.RestDurationMinutes);
|
||||||
|
Assert.Equal("Standing", saved.MeasurementContext.BodyPosition);
|
||||||
|
Assert.Equal("Walking immediately beforehand", saved.MeasurementContext.AdditionalCircumstances);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Partial_and_absent_context_remain_unknown_without_reinterpreting_legacy_text()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
using var partial = await Record(patient, new { setting = "Clinic" });
|
||||||
|
var first = (await partial.Content.ReadFromJsonAsync<Observation>())!;
|
||||||
|
Assert.Equal(HttpStatusCode.Created, partial.StatusCode);
|
||||||
|
Assert.Equal("Clinic", first.MeasurementContext.Setting);
|
||||||
|
Assert.Equal("Unknown", first.MeasurementContext.ActivityCondition);
|
||||||
|
Assert.Null(first.MeasurementContext.RestDurationMinutes);
|
||||||
|
Assert.Null(first.MeasurementContext.BodyPosition);
|
||||||
|
using var absent = await Record(patient, null, "Morning reading; resting?", "Keep original text");
|
||||||
|
var second = (await absent.Content.ReadFromJsonAsync<Observation>())!;
|
||||||
|
Assert.Equal(HttpStatusCode.Created, absent.StatusCode);
|
||||||
|
Assert.Equal("Unknown", second.MeasurementContext.Setting);
|
||||||
|
Assert.Equal("Unknown", second.MeasurementContext.ActivityCondition);
|
||||||
|
Assert.Equal("Morning reading; resting?", second.Context);
|
||||||
|
Assert.Equal("Keep original text", second.Note);
|
||||||
|
Assert.Equal(second, await fixture.Client.GetFromJsonAsync<Observation>(absent.Headers.Location));
|
||||||
|
using var explicitNulls = await Record(patient, new { setting = (string?)null, activityCondition = (string?)null });
|
||||||
|
Assert.Equal(HttpStatusCode.Created, explicitNulls.StatusCode);
|
||||||
|
var third = (await explicitNulls.Content.ReadFromJsonAsync<Observation>())!;
|
||||||
|
Assert.Equal("Unknown", third.MeasurementContext.Setting);
|
||||||
|
Assert.Equal("Unknown", third.MeasurementContext.ActivityCondition);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Conflicting_categories_and_narrative_are_preserved_without_relabelling()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
using var response = await Record(patient, new { setting = "Home", activityCondition = "AtRest",
|
||||||
|
additionalCircumstances = "During exercise" }, "During exercise", "Recorded as supplied");
|
||||||
|
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||||
|
var saved = (await response.Content.ReadFromJsonAsync<Observation>())!;
|
||||||
|
Assert.Equal("AtRest", saved.MeasurementContext.ActivityCondition);
|
||||||
|
Assert.Equal("During exercise", saved.MeasurementContext.AdditionalCircumstances);
|
||||||
|
Assert.Equal("During exercise", saved.Context);
|
||||||
|
Assert.Equal(saved, await fixture.Client.GetFromJsonAsync<Observation>(response.Headers.Location));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("{\"setting\":\"Unsupported\"}")]
|
||||||
|
[InlineData("{\"activityCondition\":\"Unsupported\"}")]
|
||||||
|
[InlineData("{\"setting\":42}")]
|
||||||
|
[InlineData("{\"activityCondition\":true}")]
|
||||||
|
[InlineData("{\"restDurationMinutes\":-1}")]
|
||||||
|
public async Task Invalid_context_is_rejected_with_validation_details_without_saving(string contextJson)
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
await using var db = fixture.CreateObservationDbContext();
|
||||||
|
var before = await db.Observations.CountAsync();
|
||||||
|
var json = "{\"measuredAt\":\"2026-09-12T08:00:00\",\"systolic\":128,\"diastolic\":82,\"pulse\":68,\"measurementContext\":" + contextJson + "}";
|
||||||
|
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||||
|
using var response = await fixture.Client.PostAsync($"/api/patients/{patient}/observations", 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(before, await db.Observations.CountAsync());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Context_is_protected_against_other_patient_reads_and_submissions_and_professional_writes()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
var otherPatient = await Patient();
|
||||||
|
using var recorded = await Record(patient, new { setting = "Home", activityCondition = "AtRest" });
|
||||||
|
Assert.Equal(HttpStatusCode.Created, recorded.StatusCode);
|
||||||
|
var observation = (await recorded.Content.ReadFromJsonAsync<Observation>())!;
|
||||||
|
var otherToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, fixture.Authentication.PatientAccounts[otherPatient]);
|
||||||
|
await using var db = fixture.CreateObservationDbContext();
|
||||||
|
var count = await db.Observations.CountAsync();
|
||||||
|
using var read = new HttpRequestMessage(HttpMethod.Get, $"/api/observations/{observation.ObservationId}");
|
||||||
|
read.Headers.Authorization = new("Bearer", otherToken);
|
||||||
|
using var rejectedRead = await fixture.RawClient.SendAsync(read);
|
||||||
|
Assert.Equal(HttpStatusCode.NotFound, rejectedRead.StatusCode);
|
||||||
|
Assert.Empty(await rejectedRead.Content.ReadAsStringAsync());
|
||||||
|
foreach (var token in new[] { otherToken, await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional") })
|
||||||
|
{
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Post, $"/api/patients/{patient}/observations")
|
||||||
|
{
|
||||||
|
Content = JsonContent.Create(new { measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82,
|
||||||
|
pulse = 68, measurementContext = new { setting = "Clinic" } })
|
||||||
|
};
|
||||||
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||||
|
using var response = await fixture.RawClient.SendAsync(request);
|
||||||
|
Assert.Equal(token == otherToken ? HttpStatusCode.NotFound : HttpStatusCode.Forbidden, response.StatusCode);
|
||||||
|
}
|
||||||
|
Assert.Equal(count, await db.Observations.CountAsync());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Assigned_professional_can_retrieve_saved_context()
|
||||||
|
{
|
||||||
|
var patient = await Patient();
|
||||||
|
using var recorded = await Record(patient, new { setting = "Clinic", activityCondition = "AtRest", deviceDetails = "Clinic device" });
|
||||||
|
Assert.Equal(HttpStatusCode.Created, recorded.StatusCode);
|
||||||
|
var saved = (await recorded.Content.ReadFromJsonAsync<Observation>())!;
|
||||||
|
fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = patient.ToString();
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Get, $"/api/observations/{saved.ObservationId}");
|
||||||
|
request.Headers.Authorization = new("Bearer", token);
|
||||||
|
using var response = await fixture.RawClient.SendAsync(request);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
Assert.Equal(saved, await response.Content.ReadFromJsonAsync<Observation>());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using HealthApp.TestSupport;
|
||||||
|
using ObservationService.Domain;
|
||||||
|
using PatientProfileService.Domain;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace Observation.AcceptanceTests;
|
||||||
|
|
||||||
|
public sealed class ViewObservationContextTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||||
|
{
|
||||||
|
private static int nextAccount = 180;
|
||||||
|
private sealed record Saved(string AccountId, Guid PatientId, Guid ObservationId);
|
||||||
|
private sealed record ContextData(string Setting, string ActivityCondition, decimal? RestDurationMinutes,
|
||||||
|
string? BodyPosition, string? MeasuredArm, string? DeviceDetails, string? CuffDetails, string? AdditionalCircumstances);
|
||||||
|
private sealed record ObservationData(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||||
|
int Systolic, int Diastolic, int Pulse, string? Context, string? Note, ContextData MeasurementContext);
|
||||||
|
|
||||||
|
// Establish Given directly, independently of observation creation and its response.
|
||||||
|
private async Task<Saved> Seed(MeasurementContext? context = null, string? legacyText = null)
|
||||||
|
{
|
||||||
|
var account = "test-" + Interlocked.Increment(ref nextAccount);
|
||||||
|
var patientId = Guid.NewGuid();
|
||||||
|
var observationId = Guid.NewGuid();
|
||||||
|
var timestamp = new DateTime(2026, 9, 12, 8, 0, 0);
|
||||||
|
await using var patients = fixture.CreateDbContext();
|
||||||
|
patients.Patients.Add(new Patient
|
||||||
|
{
|
||||||
|
PatientId = patientId, AccountId = account, Name = "Retrieval patient",
|
||||||
|
DateOfBirth = new DateOnly(1980, 1, 1), CreatedAt = timestamp, UpdatedAt = timestamp
|
||||||
|
});
|
||||||
|
await patients.SaveChangesAsync();
|
||||||
|
await using var observations = fixture.CreateObservationDbContext();
|
||||||
|
observations.Observations.Add(new BloodPressureObservation
|
||||||
|
{
|
||||||
|
ObservationId = observationId, PatientId = patientId, MeasuredAt = timestamp,
|
||||||
|
Systolic = 128, Diastolic = 82, Pulse = 68, Context = legacyText, Note = "Saved note",
|
||||||
|
MeasurementContext = context ?? new(), CreatedAt = timestamp, UpdatedAt = timestamp
|
||||||
|
});
|
||||||
|
await observations.SaveChangesAsync();
|
||||||
|
return new Saved(account, patientId, observationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<HttpResponseMessage> Read(Guid observationId, string? token)
|
||||||
|
{
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Get, $"/api/observations/{observationId}");
|
||||||
|
if (token is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||||
|
return await fixture.RawClient.SendAsync(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Complete_saved_context_is_returned_with_its_measurements_and_timestamp_after_restart()
|
||||||
|
{
|
||||||
|
var saved = await Seed(new MeasurementContext
|
||||||
|
{
|
||||||
|
Setting = "Home", ActivityCondition = "AtRest", RestDurationMinutes = 5.5m,
|
||||||
|
BodyPosition = "Seated", MeasuredArm = "Right", DeviceDetails = "Recorded device",
|
||||||
|
CuffDetails = "Recorded cuff", AdditionalCircumstances = "Recorded circumstances"
|
||||||
|
}, "Original context text");
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, saved.AccountId);
|
||||||
|
using var response = await Read(saved.ObservationId, token);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
var observation = (await response.Content.ReadFromJsonAsync<ObservationData>())!;
|
||||||
|
Assert.Equal(saved.ObservationId, observation.ObservationId);
|
||||||
|
Assert.Equal(saved.PatientId, observation.PatientId);
|
||||||
|
Assert.Equal(new DateTime(2026, 9, 12, 8, 0, 0), observation.MeasuredAt);
|
||||||
|
Assert.Equal(128, observation.Systolic);
|
||||||
|
Assert.Equal(82, observation.Diastolic);
|
||||||
|
Assert.Equal(68, observation.Pulse);
|
||||||
|
Assert.Equal("Original context text", observation.Context);
|
||||||
|
Assert.Equal("Saved note", observation.Note);
|
||||||
|
Assert.Equal(new ContextData("Home", "AtRest", 5.5m, "Seated", "Right", "Recorded device",
|
||||||
|
"Recorded cuff", "Recorded circumstances"), observation.MeasurementContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Partial_saved_context_distinguishes_known_setting_from_unknown_condition_and_details()
|
||||||
|
{
|
||||||
|
var saved = await Seed(new MeasurementContext { Setting = "Clinic" });
|
||||||
|
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, saved.AccountId);
|
||||||
|
using var response = await Read(saved.ObservationId, token);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
var observation = (await response.Content.ReadFromJsonAsync<ObservationData>())!;
|
||||||
|
Assert.Equal(new ContextData("Clinic", "Unknown", null, null, null, null, null, null), observation.MeasurementContext);
|
||||||
|
Assert.Equal(saved.ObservationId, observation.ObservationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Historical_free_text_is_returned_without_inventing_setting_or_activity()
|
||||||
|
{
|
||||||
|
var saved = await Seed(legacyText: "Morning reading");
|
||||||
|
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, saved.AccountId);
|
||||||
|
using var response = await Read(saved.ObservationId, token);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
var observation = (await response.Content.ReadFromJsonAsync<ObservationData>())!;
|
||||||
|
Assert.Equal("Morning reading", observation.Context);
|
||||||
|
Assert.Equal("Saved note", observation.Note);
|
||||||
|
Assert.Equal(new ContextData("Unknown", "Unknown", null, null, null, null, null, null), observation.MeasurementContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Missing_observation_reports_not_found_without_disclosing_saved_context()
|
||||||
|
{
|
||||||
|
var saved = await Seed(new MeasurementContext { Setting = "Home" });
|
||||||
|
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, saved.AccountId);
|
||||||
|
using var response = await Read(Guid.NewGuid(), token);
|
||||||
|
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||||
|
Assert.Empty(await response.Content.ReadAsStringAsync());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Unauthorised_callers_cannot_read_observation_context()
|
||||||
|
{
|
||||||
|
var saved = await Seed(new MeasurementContext { Setting = "Home", DeviceDetails = "Private device details" });
|
||||||
|
var other = await Seed();
|
||||||
|
var otherToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, other.AccountId);
|
||||||
|
var professional = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional-empty");
|
||||||
|
foreach (var (token, expected) in new[]
|
||||||
|
{
|
||||||
|
((string?)null, HttpStatusCode.Unauthorized),
|
||||||
|
((string?)"invalid", HttpStatusCode.Unauthorized),
|
||||||
|
((string?)otherToken, HttpStatusCode.NotFound),
|
||||||
|
((string?)professional, HttpStatusCode.NotFound)
|
||||||
|
})
|
||||||
|
{
|
||||||
|
using var response = await Read(saved.ObservationId, token);
|
||||||
|
Assert.Equal(expected, response.StatusCode);
|
||||||
|
Assert.Empty(await response.Content.ReadAsStringAsync());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Assigned_professional_reads_the_same_context_as_the_owner()
|
||||||
|
{
|
||||||
|
var saved = await Seed(new MeasurementContext { Setting = "Clinic", ActivityCondition = "AfterActivity",
|
||||||
|
AdditionalCircumstances = "Actual circumstances" }, "Original narrative");
|
||||||
|
fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = saved.PatientId.ToString();
|
||||||
|
await fixture.RestartHostsAsync();
|
||||||
|
var patientToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, saved.AccountId);
|
||||||
|
var professionalToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
|
||||||
|
using var patient = await Read(saved.ObservationId, patientToken);
|
||||||
|
using var professional = await Read(saved.ObservationId, professionalToken);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, patient.StatusCode);
|
||||||
|
Assert.Equal(HttpStatusCode.OK, professional.StatusCode);
|
||||||
|
Assert.Equal(await patient.Content.ReadFromJsonAsync<ObservationData>(), await professional.Content.ReadFromJsonAsync<ObservationData>());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Security.Claims;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Encodings.Web;
|
||||||
|
using HealthApp.TestSupport;
|
||||||
|
using Microsoft.AspNetCore.Authentication;
|
||||||
|
using Microsoft.AspNetCore.Hosting;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Testing;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace PatientProfile.AcceptanceTests;
|
||||||
|
|
||||||
|
public sealed class AuthenticationIntegrationTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task Production_gateway_rejects_plain_http_even_for_login_and_public_guidance()
|
||||||
|
{
|
||||||
|
var authentication = new AuthenticatedTestClient();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var configuration = authentication.Configuration();
|
||||||
|
foreach (var service in new[] { "PatientProfile", "Observation", "Insights", "HealthOverview" })
|
||||||
|
configuration[$"Services:{service}:BaseUrl"] = "https://service.example.test/";
|
||||||
|
using var host = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
|
||||||
|
{
|
||||||
|
builder.UseEnvironment("Production");
|
||||||
|
builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(configuration));
|
||||||
|
});
|
||||||
|
using var http = host.CreateClient();
|
||||||
|
using var guidance = await http.GetAsync("/api/measurement-guidance");
|
||||||
|
Assert.Equal(HttpStatusCode.BadRequest, guidance.StatusCode);
|
||||||
|
using var login = await http.PostAsync("/api/authentication/login", new StringContent("{}", Encoding.UTF8, "application/json"));
|
||||||
|
Assert.Equal(HttpStatusCode.BadRequest, login.StatusCode);
|
||||||
|
using var https = host.CreateClient(new WebApplicationFactoryClientOptions { BaseAddress = new Uri("https://localhost") });
|
||||||
|
using var available = await https.GetAsync("/api/measurement-guidance");
|
||||||
|
Assert.Equal(HttpStatusCode.OK, available.StatusCode);
|
||||||
|
}
|
||||||
|
finally { if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Patient", "test-0")]
|
||||||
|
[InlineData("HealthcareProfessional", "professional")]
|
||||||
|
public async Task Standard_replacement_handler_with_same_identity_retains_ownership_policy(string role, string accountId)
|
||||||
|
{
|
||||||
|
var authentication = new AuthenticatedTestClient();
|
||||||
|
var patient = Guid.NewGuid();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var configuration = authentication.Configuration();
|
||||||
|
configuration["TestIdentity:Role"] = role;
|
||||||
|
configuration["TestIdentity:AccountId"] = accountId;
|
||||||
|
configuration[$"Access:ProfessionalAssignments:{accountId}:0"] = patient.ToString();
|
||||||
|
foreach (var service in new[] { "PatientProfile", "Observation", "Insights", "HealthOverview" })
|
||||||
|
configuration[$"Services:{service}:BaseUrl"] = "http://service.example.test/";
|
||||||
|
using var host = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
|
||||||
|
{
|
||||||
|
builder.UseEnvironment("Development");
|
||||||
|
builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(configuration));
|
||||||
|
builder.ConfigureServices(services =>
|
||||||
|
{
|
||||||
|
services.AddAuthentication().AddScheme<AuthenticationSchemeOptions, ReplacementHandler>("Replacement", null);
|
||||||
|
services.PostConfigure<PolicySchemeOptions>("ClientOrService", options => options.ForwardDefaultSelector = _ => "Replacement");
|
||||||
|
services.AddHttpClient("PatientProfile").ConfigurePrimaryHttpMessageHandler(() => new PatientHandler(patient));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
using var client = host.CreateClient();
|
||||||
|
using var own = await client.GetAsync($"/api/patients/{patient}");
|
||||||
|
Assert.Equal(HttpStatusCode.OK, own.StatusCode);
|
||||||
|
using var other = await client.GetAsync($"/api/patients/{Guid.NewGuid()}");
|
||||||
|
Assert.Equal(HttpStatusCode.NotFound, other.StatusCode);
|
||||||
|
Assert.Empty(await other.Content.ReadAsStringAsync());
|
||||||
|
}
|
||||||
|
finally { if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class ReplacementHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, IConfiguration configuration)
|
||||||
|
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||||
|
{
|
||||||
|
protected override Task<AuthenticateResult> HandleAuthenticateAsync() => Task.FromResult(
|
||||||
|
AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(new[]
|
||||||
|
{
|
||||||
|
new Claim(ClaimTypes.NameIdentifier, configuration["TestIdentity:AccountId"]!), new Claim(ClaimTypes.Role, configuration["TestIdentity:Role"]!)
|
||||||
|
}, Scheme.Name)), Scheme.Name)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class PatientHandler(Guid patientId) : HttpMessageHandler
|
||||||
|
{
|
||||||
|
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
Assert.True(request.Headers.Contains("X-Gateway-Key"));
|
||||||
|
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
|
||||||
|
{
|
||||||
|
Content = new StringContent($"{{\"patientId\":\"{patientId}\"}}", Encoding.UTF8, "application/json")
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
using System.Net;
|
using System.Net;
|
||||||
|
using HealthApp.TestSupport;
|
||||||
|
using Microsoft.AspNetCore.Hosting;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Microsoft.AspNetCore.Mvc.Testing;
|
using Microsoft.AspNetCore.Mvc.Testing;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
@@ -12,12 +14,14 @@ public sealed class MeasurementGuidanceTests : IDisposable
|
|||||||
private readonly WebApplicationFactory<ApiGateway.Program> host;
|
private readonly WebApplicationFactory<ApiGateway.Program> host;
|
||||||
private readonly HttpClient client;
|
private readonly HttpClient client;
|
||||||
private int upstreamCalls;
|
private int upstreamCalls;
|
||||||
|
private readonly AuthenticatedTestClient authentication = new();
|
||||||
|
|
||||||
public MeasurementGuidanceTests()
|
public MeasurementGuidanceTests()
|
||||||
{
|
{
|
||||||
host = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
|
host = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
|
||||||
{
|
{
|
||||||
builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(
|
builder.UseEnvironment("Development");
|
||||||
|
builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(authentication.Configuration()).AddInMemoryCollection(
|
||||||
new Dictionary<string, string?>
|
new Dictionary<string, string?>
|
||||||
{
|
{
|
||||||
["Services:PatientProfile:BaseUrl"] = "http://127.0.0.1:1/",
|
["Services:PatientProfile:BaseUrl"] = "http://127.0.0.1:1/",
|
||||||
@@ -118,6 +122,7 @@ public sealed class MeasurementGuidanceTests : IDisposable
|
|||||||
{
|
{
|
||||||
client.Dispose();
|
client.Dispose();
|
||||||
host.Dispose();
|
host.Dispose();
|
||||||
|
if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed class RejectUpstreamHandler(Action called) : HttpMessageHandler
|
private sealed class RejectUpstreamHandler(Action called) : HttpMessageHandler
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
using Microsoft.AspNetCore.Authentication.BearerToken;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using HealthApp.TestSupport;
|
||||||
using Microsoft.AspNetCore.Hosting;
|
using Microsoft.AspNetCore.Hosting;
|
||||||
using System.Net;
|
using System.Net;
|
||||||
using Microsoft.AspNetCore.Mvc.Testing;
|
using Microsoft.AspNetCore.Mvc.Testing;
|
||||||
@@ -17,6 +20,8 @@ public sealed class PatientApiFixture : IAsyncLifetime
|
|||||||
private WebApplicationFactory<ApiGateway.Program>? gateway;
|
private WebApplicationFactory<ApiGateway.Program>? gateway;
|
||||||
public string ConnectionString { get; private set; } = "";
|
public string ConnectionString { get; private set; } = "";
|
||||||
public HttpClient Client { get; private set; } = null!;
|
public HttpClient Client { get; private set; } = null!;
|
||||||
|
public HttpClient RawClient { get; private set; } = null!;
|
||||||
|
public AuthenticatedTestClient Authentication { get; } = new();
|
||||||
|
|
||||||
public async Task InitializeAsync()
|
public async Task InitializeAsync()
|
||||||
{
|
{
|
||||||
@@ -42,24 +47,29 @@ public sealed class PatientApiFixture : IAsyncLifetime
|
|||||||
{
|
{
|
||||||
service = new WebApplicationFactory<PatientProfileService.Program>().WithWebHostBuilder(builder =>
|
service = new WebApplicationFactory<PatientProfileService.Program>().WithWebHostBuilder(builder =>
|
||||||
{
|
{
|
||||||
|
builder.UseEnvironment("Development");
|
||||||
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
||||||
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
||||||
new Dictionary<string, string?> { ["ConnectionStrings:PatientDatabase"] = ConnectionString }));
|
new Dictionary<string, string?> { ["ConnectionStrings:PatientDatabase"] = ConnectionString, ["InternalAccess:GatewayKey"] = Authentication.GatewayKey }));
|
||||||
});
|
});
|
||||||
service.UseKestrel(0);
|
service.UseKestrel(0);
|
||||||
using var serviceClient = service.CreateClient();
|
using var serviceClient = service.CreateClient();
|
||||||
|
|
||||||
gateway = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
|
gateway = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
|
||||||
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
builder.UseEnvironment("Development").ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(Authentication.Configuration()).AddInMemoryCollection(
|
||||||
new Dictionary<string, string?> { ["Services:PatientProfile:BaseUrl"] = serviceClient.BaseAddress!.ToString(),
|
new Dictionary<string, string?> { ["Services:PatientProfile:BaseUrl"] = serviceClient.BaseAddress!.ToString(),
|
||||||
["Services:Insights:BaseUrl"] = "http://127.0.0.1:1/",
|
["Services:Insights:BaseUrl"] = "http://127.0.0.1:1/",
|
||||||
["Services:Observation:BaseUrl"] = "http://127.0.0.1:1/" })));
|
["Services:Observation:BaseUrl"] = "http://127.0.0.1:1/" })));
|
||||||
Client = gateway.CreateClient();
|
gateway = gateway.WithWebHostBuilder(builder => builder.ConfigureServices(services =>
|
||||||
|
services.PostConfigure<BearerTokenOptions>("Bearer", options => options.TimeProvider = Authentication.Clock)));
|
||||||
|
RawClient = gateway.CreateClient();
|
||||||
|
Client = Authentication.Wrap(RawClient);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task RestartHostsAsync()
|
public async Task RestartHostsAsync()
|
||||||
{
|
{
|
||||||
Client.Dispose();
|
Client.Dispose();
|
||||||
|
RawClient.Dispose();
|
||||||
await gateway!.DisposeAsync();
|
await gateway!.DisposeAsync();
|
||||||
await service!.DisposeAsync();
|
await service!.DisposeAsync();
|
||||||
StartHosts();
|
StartHosts();
|
||||||
@@ -68,8 +78,10 @@ public sealed class PatientApiFixture : IAsyncLifetime
|
|||||||
public async Task DisposeAsync()
|
public async Task DisposeAsync()
|
||||||
{
|
{
|
||||||
Client?.Dispose();
|
Client?.Dispose();
|
||||||
|
RawClient?.Dispose();
|
||||||
if (gateway is not null) await gateway.DisposeAsync();
|
if (gateway is not null) await gateway.DisposeAsync();
|
||||||
if (service is not null) await service.DisposeAsync();
|
if (service is not null) await service.DisposeAsync();
|
||||||
|
if (Directory.Exists(Authentication.KeyDirectory)) Directory.Delete(Authentication.KeyDirectory, true);
|
||||||
if (string.IsNullOrEmpty(adminConnectionString)) return;
|
if (string.IsNullOrEmpty(adminConnectionString)) return;
|
||||||
|
|
||||||
NpgsqlConnection.ClearAllPools();
|
NpgsqlConnection.ClearAllPools();
|
||||||
|
|||||||
@@ -14,4 +14,7 @@
|
|||||||
<ProjectReference Include="../../src/PatientProfileService/PatientProfileService.csproj" />
|
<ProjectReference Include="../../src/PatientProfileService/PatientProfileService.csproj" />
|
||||||
<ProjectReference Include="../../src/ApiGateway/ApiGateway.csproj" />
|
<ProjectReference Include="../../src/ApiGateway/ApiGateway.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<Compile Include="../Support/AuthenticatedTestClient.cs" Link="Support/AuthenticatedTestClient.cs" />
|
||||||
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
using ApiGateway.Security;
|
||||||
|
using Microsoft.AspNetCore.Identity;
|
||||||
|
|
||||||
|
namespace HealthApp.TestSupport;
|
||||||
|
|
||||||
|
// Existing functional tests use real login and an authorised account for each resource.
|
||||||
|
// Security tests use RawClient instead to exercise rejected requests explicitly.
|
||||||
|
public sealed class AuthenticatedTestClient
|
||||||
|
{
|
||||||
|
public const string Password = "synthetic-test-password";
|
||||||
|
public readonly string GatewayKey = new('g', 48);
|
||||||
|
public readonly string ObservationServiceKey = new('o', 48);
|
||||||
|
public readonly string InsightsServiceKey = new('i', 48);
|
||||||
|
public readonly string OverviewServiceKey = new('v', 48);
|
||||||
|
public TestClock Clock { get; } = new();
|
||||||
|
public string KeyDirectory { get; } = Path.Combine(Path.GetTempPath(), "healthapp-keys-" + Guid.NewGuid());
|
||||||
|
public ConcurrentDictionary<Guid, string> PatientAccounts { get; } = new();
|
||||||
|
private readonly ConcurrentDictionary<Guid, string> observationAccounts = new();
|
||||||
|
private readonly ConcurrentDictionary<string, string> tokens = new();
|
||||||
|
private int accountNumber;
|
||||||
|
private string lastAccount = "test-0";
|
||||||
|
private readonly string hash = new PasswordHasher<PrototypeAccount>().HashPassword(new(), Password);
|
||||||
|
|
||||||
|
public Dictionary<string, string?> Configuration()
|
||||||
|
{
|
||||||
|
var values = new Dictionary<string, string?>
|
||||||
|
{
|
||||||
|
["Authentication:KeyDirectory"] = KeyDirectory,
|
||||||
|
["Services:PatientProfile:Key"] = GatewayKey,
|
||||||
|
["Services:Observation:Key"] = GatewayKey,
|
||||||
|
["Services:Insights:Key"] = GatewayKey,
|
||||||
|
["InternalAccess:Observation:Key"] = ObservationServiceKey,
|
||||||
|
["InternalAccess:Insights:Key"] = InsightsServiceKey,
|
||||||
|
["InternalAccess:HealthOverview:Key"] = OverviewServiceKey,
|
||||||
|
["Services:HealthOverview:Key"] = GatewayKey,
|
||||||
|
["Services:HealthOverview:BaseUrl"] = "http://127.0.0.1:1/"
|
||||||
|
};
|
||||||
|
for (var i = 0; i < 256; i++)
|
||||||
|
{
|
||||||
|
values[$"Authentication:Accounts:{i}:AccountId"] = "test-" + i;
|
||||||
|
values[$"Authentication:Accounts:{i}:PasswordHash"] = hash;
|
||||||
|
values[$"Authentication:Accounts:{i}:Role"] = "Patient";
|
||||||
|
}
|
||||||
|
values["Authentication:Accounts:256:AccountId"] = "professional";
|
||||||
|
values["Authentication:Accounts:256:PasswordHash"] = hash;
|
||||||
|
values["Authentication:Accounts:256:Role"] = "HealthcareProfessional";
|
||||||
|
for (var i = 257; i <= 258; i++)
|
||||||
|
{
|
||||||
|
values[$"Authentication:Accounts:{i}:AccountId"] = i == 257 ? "professional-second" : "professional-empty";
|
||||||
|
values[$"Authentication:Accounts:{i}:PasswordHash"] = hash;
|
||||||
|
values[$"Authentication:Accounts:{i}:Role"] = "HealthcareProfessional";
|
||||||
|
}
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
|
||||||
|
public HttpClient Wrap(HttpClient raw) => new(new Handler(this, raw)) { BaseAddress = raw.BaseAddress };
|
||||||
|
|
||||||
|
public static async Task<string> LoginAsync(HttpClient raw, string account = "test-0", string password = Password)
|
||||||
|
{
|
||||||
|
using var response = await raw.PostAsJsonAsync("/api/authentication/login", new { accountId = account, password });
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||||
|
return json.RootElement.GetProperty("accessToken").GetString()!;
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class Handler(AuthenticatedTestClient owner, HttpClient raw) : HttpMessageHandler
|
||||||
|
{
|
||||||
|
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var path = request.RequestUri!.AbsolutePath;
|
||||||
|
var parts = path.Trim('/').Split('/');
|
||||||
|
var account = owner.lastAccount;
|
||||||
|
if (path == "/api/patients" && request.Method == HttpMethod.Post)
|
||||||
|
account = "test-" + Interlocked.Increment(ref owner.accountNumber);
|
||||||
|
else if (parts.Length >= 3 && Guid.TryParse(parts[2], out var id))
|
||||||
|
{
|
||||||
|
var map = parts[1] == "patients" ? owner.PatientAccounts : owner.observationAccounts;
|
||||||
|
if (map.TryGetValue(id, out var found)) account = found;
|
||||||
|
}
|
||||||
|
if (!owner.tokens.TryGetValue(account, out var token))
|
||||||
|
{
|
||||||
|
token = await LoginAsync(raw, account);
|
||||||
|
owner.tokens[account] = token;
|
||||||
|
}
|
||||||
|
using var forwarded = new HttpRequestMessage(request.Method, request.RequestUri) { Content = request.Content };
|
||||||
|
foreach (var header in request.Headers) forwarded.Headers.TryAddWithoutValidation(header.Key, header.Value);
|
||||||
|
forwarded.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||||
|
var response = await raw.SendAsync(forwarded, cancellationToken);
|
||||||
|
if (response.IsSuccessStatusCode && request.Method == HttpMethod.Post)
|
||||||
|
{
|
||||||
|
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken));
|
||||||
|
if (json.RootElement.TryGetProperty("patientId", out var patient))
|
||||||
|
owner.PatientAccounts[patient.GetGuid()] = account;
|
||||||
|
if (json.RootElement.TryGetProperty("observationId", out var observation))
|
||||||
|
owner.observationAccounts[observation.GetGuid()] = account;
|
||||||
|
owner.lastAccount = account;
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class TestClock : TimeProvider
|
||||||
|
{
|
||||||
|
private DateTimeOffset now = DateTimeOffset.UtcNow;
|
||||||
|
public override DateTimeOffset GetUtcNow() => now;
|
||||||
|
public void Advance(TimeSpan span) => now += span;
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
using Microsoft.AspNetCore.Identity;
|
||||||
|
|
||||||
|
// Read from standard input, never from a command-line argument or environment dump.
|
||||||
|
var password = Console.ReadLine();
|
||||||
|
if (string.IsNullOrEmpty(password))
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine("Supply a nonempty password on standard input.");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
Console.WriteLine(new PasswordHasher<object>().HashPassword(new object(), password));
|
||||||
|
return 0;
|
||||||
Reference in new issue
Block a user