Files
HealthAppRepository/src

Patient profiles, observations, insights, overview and authentication

Implemented with .NET 10 LTS (see the official download page), 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.

US-13 now protects the patient-data APIs. Read 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

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:

dotnet restore HealthApp.slnx
dotnet build HealthApp.slnx -c Release --no-restore

# In the Patient/Profile service terminal; substitute your own database configuration.
export ConnectionStrings__PatientDatabase='Host=127.0.0.1;Database=patient_profile;Username=patient_profile;Password=YOUR_LOCAL_PASSWORD'
dotnet run --project src/PatientProfileService -c Release --no-build -- --migrate
ASPNETCORE_URLS=http://127.0.0.1:5081 dotnet run --project src/PatientProfileService -c Release --no-build

# 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/ 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.
export ConnectionStrings__ObservationDatabase='Host=127.0.0.1;Database=observations;Username=observations;Password=YOUR_LOCAL_PASSWORD'
dotnet run --project src/ObservationService -c Release --no-build -- --migrate
Services__ApiGateway__BaseUrl=http://127.0.0.1:5080/ ASPNETCORE_URLS=http://127.0.0.1:5082 dotnet run --project src/ObservationService -c Release --no-build

# 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

# 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.

API

Send requests to the gateway:

curl -i http://127.0.0.1:5080/api/patients \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer YOUR_LOGIN_TOKEN' \
  -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.

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.

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.

US-04 now supports structured context independently of legacy free text:

{
  "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"
}

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.

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.

PATCH /api/observations/{observationId} accepts a partial JSON object. For example:

{
  "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.

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. 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.

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.

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.

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 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 for response semantics, service credentials, deployment and consistency limits.

US-13 authentication and patient ownership are implemented as described in 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

US-15 public measurement guidance

GET /api/measurement-guidance returns ordered instructions for resting home self-measurement, with source URLs, source update dates and review date. It works before a patient or observation exists and requires no authentication or upstream service access. The gateway serves this static general content without persistence.

Optional setting accepts Home, Clinic, Other, or Unknown; omission means unknown. Home or unknown requests return explicitly labelled home instructions; clinic/other requests return available: false and no instructions because no verified guidance for those settings is bundled. Optional activityCondition accepts AtRest, DuringActivity, AfterActivity, or Unknown. The response preserves requested conditions while identifying the resting applicability of the instructions. Unsupported categories return 400 problem details.

The bundled content was reviewed on 2026-10-04 against the two Sundhed.dk pages specified in US-15. It distinguishes the planned Danish three-day monitoring protocol from an individual observation. Review sources again when updating the content; requests do not fetch live guidance. Viewing/declining instructions never records context, certifies compliance or gates observation submission. Pulse information describes the device-reported rate rather than rhythm assessment.

The MeasurementGuidanceTests HTTP tests need no PostgreSQL server and cover public access, ordered sourced content, unknown setting, activity limitations, unavailable guidance, invalid selections, and absence of patient-service calls. Run them with dotnet test tests/PatientProfile.AcceptanceTests -c Release --filter FullyQualifiedName~MeasurementGuidanceTests. Existing observation recording tests cover submission without viewing guidance. No dependencies were added.

Tests require a real PostgreSQL instance. Provide an administrator connection with permission to create/drop databases; the fixture creates an isolated database named us01_<random>, applies the committed migration, and deletes that database at teardown. Never point this connection at a production server.

TEST_POSTGRES_CONNECTION='Host=127.0.0.1;Database=postgres;Username=postgres;Password=YOUR_LOCAL_TEST_PASSWORD' \
  dotnet test HealthApp.slnx -c Release

The xUnit tests send HTTP requests to the gateway; the gateway reaches a real Kestrel Patient/Profile service over HTTP. They cover every US-01 acceptance scenario, retrieval after host restart, distinct identifiers, optional contact information, invalid JSON/dates, and rejection without database writes. Test assertions use an independent HTTP response contract. Production projects have no references to each other's implementation.

US-02 retrieval scenarios are covered by the creation tests. US-03 tests cover persisted updates after restart, preservation of identity and date of birth, missing-patient rejection without insertion, and invalid-name rejection without changing the profile.

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.

Provisioning installer (US-16)

Build a portable release using bash deploy/build-release.sh --output NEW_DIRECTORY. A normal supported Linux installation is sudo bash install.sh --services all --host DNS_OR_IP; it provisions missing runtime/PostgreSQL dependencies, separate databases and roles, generated service/account credentials, HTTPS/trust, independent configuration, migrations, service registration/startup and installation verification. No prepared env files, service passwords or prototype certificates are required.

Shared C# provisioning also generates Windows/macOS configuration. Native adapters use Windows Services or launchd without changing application binaries/service boundaries. See INSTALLATION.md for supported hosts, native commands, automatic SSH topology distribution, generated credentials and test evidence/limitations. The existing deploy/*.env.example files remain useful for advanced/manual development; they are no longer prerequisites for the normal installer.

Linux deployment

Publish each service separately:

dotnet publish src/PatientProfileService -c Release -o /tmp/healthapp-publish/patient-profile
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/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.

Apply the database migration using the published Patient/Profile executable with its database configuration:

dotnet /opt/healthapp/patient-profile/PatientProfileService.dll --migrate
dotnet /opt/healthapp/observation/ObservationService.dll --migrate

Install the corresponding unit on each host and enable/start it with systemd. The units are independent, write logs to journald, restart after failures, and allow graceful shutdown. The gateway has no systemd dependency on a local Patient/Profile process; it uses the configured network endpoint.

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 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.