Compare commits
10
Commits
d6f79a91c0
...
ebf50827d6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ebf50827d6 | ||
|
|
fa5e20f4d6 | ||
|
|
a5b269cfc3 | ||
|
|
4cb6798ec9 | ||
|
|
e4379ad2f4 | ||
|
|
0ea7866f82 | ||
|
|
df47bcbbd7 | ||
|
|
05f57dcba3 | ||
|
|
a9633e49e1 | ||
|
|
eb2cf2e54a |
No files matched your search
@@ -0,0 +1,8 @@
|
||||
**/bin/
|
||||
**/obj/
|
||||
TestResults/
|
||||
.env
|
||||
*.user
|
||||
|
||||
# Draw.io backup files
|
||||
Docs/Architecture/.*.bkp
|
||||
@@ -0,0 +1,73 @@
|
||||
<mxfile host="Electron">
|
||||
<diagram id="04_class_observation_service" name="Observation Service — updated class model">
|
||||
<mxGraphModel dx="2090" dy="1240" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="1740" pageHeight="1280" math="0" shadow="0">
|
||||
<root>
|
||||
<mxCell id="0" />
|
||||
<mxCell id="1" parent="0" />
|
||||
<mxCell id="title" parent="1" style="text;html=0;fontSize=24;fontStyle=1;align=center;" value="Observation Service — updated class model" vertex="1">
|
||||
<mxGeometry height="50" width="1660" x="40" y="10" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="e0" edge="1" parent="1" source="c" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=0;endArrow=open;dashed=1;fontSize=13;labelBackgroundColor=#ffffff;" target="a" value="uses">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="e1" edge="1" parent="1" source="a" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=0;endArrow=open;dashed=1;fontSize=13;labelBackgroundColor=#ffffff;" target="r" value="uses">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="e2" edge="1" parent="1" source="r" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=0;endArrow=open;dashed=1;fontSize=13;labelBackgroundColor=#ffffff;" target="sql" value="implemented by">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="e3" edge="1" parent="1" source="o" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=0;endArrow=open;dashed=1;fontSize=13;labelBackgroundColor=#ffffff;" target="ctx" value="contains">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="c" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="ObservationController" vertex="1">
|
||||
<mxGeometry height="260" width="500" x="40" y="100" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="cbody" parent="c" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="record(request): acknowledgement
getById(id): ObservationDto
getLatest(patientId): ObservationDto?
getByPeriod(patientId, period, selection)
update(id, patch): acknowledgement
delete(id): acknowledgement" vertex="1">
|
||||
<mxGeometry height="224" width="500" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="a" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="ObservationApplicationService" vertex="1">
|
||||
<mxGeometry height="260" width="500" x="620" y="100" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="abody" parent="a" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="record / getById / getLatest
getByPeriod(period, selection)
update(id, patch) / delete(id)
Validate context categories and values
Preserve omitted values in partial updates" vertex="1">
|
||||
<mxGeometry height="224" width="500" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="r" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="ObservationRepository «interface»" vertex="1">
|
||||
<mxGeometry height="260" width="500" x="1200" y="100" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="rbody" parent="r" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="save(observation)
findById(id) / findLatest(patientId)
findByPeriod(patientId, period, selection)
update(id, patch) / delete(id)
Persist context and original recording time" vertex="1">
|
||||
<mxGeometry height="224" width="500" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="o" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="BloodPressureObservation / ObservationDto" vertex="1">
|
||||
<mxGeometry height="360" width="500" x="40" y="520" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="obody" parent="o" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="observationId: UUID; patientId: UUID
measuredAt: DateTime
systolic, diastolic, pulse: int
measurementContext: MeasurementContext
context: String? (legacy text)
note: String?
createdAt: DateTime (original recording)
updatedAt: DateTime" vertex="1">
|
||||
<mxGeometry height="324" width="500" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="ctx" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="MeasurementContext «value object»" vertex="1">
|
||||
<mxGeometry height="360" width="500" x="620" y="520" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="ctxbody" parent="ctx" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="setting: Home / Clinic / Other / Unknown
activity: Rest / During / After / Unknown
restDuration: optional
bodyPosition: optional
measuredArm: optional
device / cuff details: optional
additionalCircumstances: optional
Missing details remain unknown" vertex="1">
|
||||
<mxGeometry height="324" width="500" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="sql" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="SqlObservationRepository" vertex="1">
|
||||
<mxGeometry height="200" width="500" x="1200" y="520" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="sqlbody" parent="sql" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="Implements ObservationRepository
Owns persistence within Observation Service
No other service accesses its database" vertex="1">
|
||||
<mxGeometry height="164" width="500" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="sel" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="ContextSelection «request value»" vertex="1">
|
||||
<mxGeometry height="180" width="500" x="620" y="930" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="selbody" parent="sel" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="optional setting; optional activity
Both supplied: match both
Unknown is selectable
Omitted selections include all contexts" vertex="1">
|
||||
<mxGeometry height="144" width="500" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="note0" parent="1" style="text;html=0;align=left;fontSize=15;" value="Latest = measurement time, then original recording time, then documented deterministic tie rule." vertex="1">
|
||||
<mxGeometry height="25" width="1660" x="40" y="1175" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="note1" parent="1" style="text;html=0;align=left;fontSize=15;" value="Gateway enforces access. Other services consume Observation APIs through the gateway." vertex="1">
|
||||
<mxGeometry height="25" width="1660" x="40" y="1200" as="geometry" />
|
||||
</mxCell>
|
||||
</root>
|
||||
</mxGraphModel>
|
||||
</diagram>
|
||||
</mxfile>
|
||||
@@ -0,0 +1,82 @@
|
||||
<mxfile host="Electron">
|
||||
<diagram id="05_class_insights_service" name="Insights Service — updated class and result model">
|
||||
<mxGraphModel dx="1951" dy="1157" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="1740" pageHeight="1220" math="0" shadow="0">
|
||||
<root>
|
||||
<mxCell id="0" />
|
||||
<mxCell id="1" parent="0" />
|
||||
<mxCell id="title" parent="1" style="text;html=0;fontSize=24;fontStyle=1;align=center;" value="Insights Service — updated class and result model" vertex="1">
|
||||
<mxGeometry height="50" width="1660" x="40" y="10" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="e0" edge="1" parent="1" source="c" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=0;endArrow=open;dashed=1;fontSize=13;labelBackgroundColor=#ffffff;" target="a" value="uses">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="e1" edge="1" parent="1" source="a" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=0;endArrow=open;dashed=1;fontSize=13;labelBackgroundColor=#ffffff;" target="http" value="uses">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="e2" edge="1" parent="1" source="a" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=0;endArrow=open;dashed=1;fontSize=13;labelBackgroundColor=#ffffff;" target="calc" value="uses">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="e3" edge="1" parent="1" source="http" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=0;endArrow=open;dashed=1;fontSize=13;labelBackgroundColor=#ffffff;" target="dto" value="returns">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="e4" edge="1" parent="1" source="calc" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=0;endArrow=open;dashed=1;fontSize=13;labelBackgroundColor=#ffffff;" target="trend" value="creates">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="e5" edge="1" parent="1" source="trend" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=0;endArrow=open;dashed=1;fontSize=13;labelBackgroundColor=#ffffff;" target="ma" value="contains three">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="c" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="InsightsController" vertex="1">
|
||||
<mxGeometry height="190" width="500" x="40" y="90" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="cbody" parent="c" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="getSummary(patientId, period, selection)
getTrend(patientId, period, selection)
Return result metadata and limitations" vertex="1">
|
||||
<mxGeometry height="154" width="500" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="a" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="InsightsApplicationService" vertex="1">
|
||||
<mxGeometry height="190" width="500" x="620" y="90" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="abody" parent="a" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="Obtain current observations
Apply requested selection
Invoke summary / trend calculations" vertex="1">
|
||||
<mxGeometry height="154" width="500" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="http" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="ObservationServiceClient «interface»" vertex="1">
|
||||
<mxGeometry height="190" width="500" x="1200" y="90" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="httpbody" parent="http" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="getByPeriod(patientId, period, selection)
HttpObservationServiceClient implements it
HTTP requests pass through API Gateway" vertex="1">
|
||||
<mxGeometry height="154" width="500" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="calc" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="InsightCalculator" vertex="1">
|
||||
<mxGeometry height="190" width="500" x="620" y="390" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="calcbody" parent="calc" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="calculateSummary(observations, selection)
calculateTrend(observations, selection)
Document mathematical methods
No stored summaries or trend results" vertex="1">
|
||||
<mxGeometry height="154" width="500" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dto" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="ObservationDto" vertex="1">
|
||||
<mxGeometry height="230" width="500" x="1200" y="390" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dtobody" parent="dto" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="observationId, patientId, measuredAt
systolic, diastolic, pulse
measurementContext (setting / conditions)
legacy context text and note
Carry unknown or conflicting context" vertex="1">
|
||||
<mxGeometry height="194" width="500" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="sum" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="HealthInsight" vertex="1">
|
||||
<mxGeometry height="340" width="500" x="40" y="740" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="sumbody" parent="sum" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="patientId; periodStart; periodEnd
appliedSelection; contributingCount
averageSystolic / Diastolic / Pulse
minimumSystolic / maximumSystolic
minimumDiastolic / maximumDiastolic
context explanation
Final means: 2 decimals, half-up
No summary persistence identifier" vertex="1">
|
||||
<mxGeometry height="304" width="500" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="trend" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="TrendAssessment" vertex="1">
|
||||
<mxGeometry height="340" width="500" x="620" y="740" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="trendbody" parent="trend" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="patientId; periodStart; periodEnd
appliedSelection; contributingCount
systolic: MeasurementAssessment
diastolic: MeasurementAssessment
pulse: MeasurementAssessment
comparability evidence and limitations
Unavailable parts explained explicitly" vertex="1">
|
||||
<mxGeometry height="304" width="500" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="ma" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="MeasurementAssessment «value object»" vertex="1">
|
||||
<mxGeometry height="340" width="500" x="1260" y="740" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="mabody" parent="ma" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="measurement name and unit
observed level / numerical description
direction and variation when supported
interpretation and explanatory hint
reference values / guidance basis
data sufficiency and limitations
No direction inferred from storage order" vertex="1">
|
||||
<mxGeometry height="304" width="500" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="note0" parent="1" style="text;html=0;align=left;fontSize=15;" value="HealthInsight is also created by InsightCalculator. All results reflect current observations." vertex="1">
|
||||
<mxGeometry height="25" width="1660" x="40" y="1115" as="geometry" />
|
||||
</mxCell>
|
||||
</root>
|
||||
</mxGraphModel>
|
||||
</diagram>
|
||||
</mxfile>
|
||||
@@ -0,0 +1,76 @@
|
||||
<mxfile host="Electron">
|
||||
<diagram id="06_class_health_overview_service" name="Health Overview Service — updated class model">
|
||||
<mxGraphModel dx="1721" dy="1021" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="1740" pageHeight="840" math="0" shadow="0">
|
||||
<root>
|
||||
<mxCell id="0" />
|
||||
<mxCell id="1" parent="0" />
|
||||
<mxCell id="title" parent="1" style="text;html=0;fontSize=24;fontStyle=1;align=center;" value="Health Overview Service — updated class model" vertex="1">
|
||||
<mxGeometry height="50" width="1660" x="40" y="10" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="e0" edge="1" parent="1" source="c" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=0;endArrow=open;dashed=1;fontSize=13;labelBackgroundColor=#ffffff;" target="a" value="uses">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="e1" edge="1" parent="1" source="a" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=0;endArrow=open;dashed=1;fontSize=13;labelBackgroundColor=#ffffff;exitX=1;exitY=0.25;exitDx=0;exitDy=0;" target="v" value="creates">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="e2" edge="1" parent="1" source="a" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=0;endArrow=open;dashed=1;fontSize=13;labelBackgroundColor=#ffffff;" target="p" value="uses">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="e3" edge="1" parent="1" source="a" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=0;endArrow=open;dashed=1;fontSize=13;labelBackgroundColor=#ffffff;" target="o" value="uses">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="e4" edge="1" parent="1" source="a" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=0;endArrow=open;dashed=1;fontSize=13;labelBackgroundColor=#ffffff;" target="i" value="uses">
|
||||
<mxGeometry relative="1" x="0.0255" y="-5" as="geometry">
|
||||
<mxPoint as="offset" />
|
||||
<Array as="points">
|
||||
<mxPoint x="1160.06" y="185" />
|
||||
<mxPoint x="1160.06" y="545" />
|
||||
</Array>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="c" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="HealthOverviewController" vertex="1">
|
||||
<mxGeometry height="190" width="500" x="40" y="90" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="cbody" parent="c" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="getOverview(patientId, period, selection)
selection applies to insight only
Returns HealthOverviewDto" vertex="1">
|
||||
<mxGeometry height="154" width="500" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="a" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="HealthOverviewApplicationService" vertex="1">
|
||||
<mxGeometry height="190" width="500" x="620" y="90" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="abody" parent="a" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="Load profile
Load latest overall observation
Load selected-period numerical insight
Aggregate without own persistence" vertex="1">
|
||||
<mxGeometry height="154" width="500" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="v" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="HealthOverview / HealthOverviewDto" vertex="1">
|
||||
<mxGeometry height="240" width="500" x="1280" y="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="vbody" parent="v" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="patient: PatientDto
latestObservation: ObservationDto?
insight: HealthInsightDto?
Preserve context, selection and limitations
Explain unavailable insight
No implicit trend component" vertex="1">
|
||||
<mxGeometry height="204" width="500" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="p" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="PatientProfileServiceClient" vertex="1">
|
||||
<mxGeometry height="210" width="500" x="40" y="440" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="pbody" parent="p" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="getPatient(patientId): PatientDto
Implemented by HTTP client
Calls through API Gateway" vertex="1">
|
||||
<mxGeometry height="174" width="500" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="o" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="ObservationServiceClient" vertex="1">
|
||||
<mxGeometry height="210" width="500" x="620" y="440" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="obody" parent="o" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="getLatest(patientId): ObservationDto?
Implemented by HTTP client
Calls through API Gateway
Latest remains unfiltered by context" vertex="1">
|
||||
<mxGeometry height="174" width="500" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="i" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="InsightsServiceClient" vertex="1">
|
||||
<mxGeometry height="210" width="500" x="1200" y="440" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="ibody" parent="i" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="getSummary(patientId, period, selection)
Implemented by HTTP client
Calls through API Gateway
Propagate selection and contributing count" vertex="1">
|
||||
<mxGeometry height="174" width="500" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="note0" parent="1" style="text;html=0;align=left;fontSize=15;" value="Only client abstractions are shown; arrows do not represent direct links between service-domain classes." vertex="1">
|
||||
<mxGeometry height="25" width="1660" x="40" y="735" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="note1" parent="1" style="text;html=0;align=left;fontSize=15;" value="No matching insight data does not remove an available profile or latest observation." vertex="1">
|
||||
<mxGeometry height="25" width="1660" x="40" y="760" as="geometry" />
|
||||
</mxCell>
|
||||
</root>
|
||||
</mxGraphModel>
|
||||
</diagram>
|
||||
</mxfile>
|
||||
@@ -0,0 +1,34 @@
|
||||
<mxfile host="Electron">
|
||||
<diagram id="08_er_observation_service" name="Observation Service — updated logical persistence model">
|
||||
<mxGraphModel dx="1721" dy="1021" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="1740" pageHeight="900" math="0" shadow="0">
|
||||
<root>
|
||||
<mxCell id="0" />
|
||||
<mxCell id="1" parent="0" />
|
||||
<mxCell id="title" parent="1" style="text;html=0;fontSize=24;fontStyle=1;align=center;" value="Observation Service — updated logical persistence model" vertex="1">
|
||||
<mxGeometry height="50" width="1660" x="40" y="10" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="e0" edge="1" parent="1" source="o" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=0;endArrow=open;dashed=1;fontSize=13;labelBackgroundColor=#ffffff;" target="p" value="contains optional value">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="o" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="BloodPressureObservation «owned record»" vertex="1">
|
||||
<mxGeometry height="550" width="700" x="60" y="110" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="obody" parent="o" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="PK observation_id: UUID
patient_id: UUID (external identifier)
measured_at: timestamp
systolic / diastolic / pulse: integers
context: optional original text
note: optional text
setting: category or unknown
activity_condition: category or unknown
preparation_details: optional owned value
additional_circumstances: optional text
created_at: original recording timestamp
updated_at: update timestamp" vertex="1">
|
||||
<mxGeometry height="514" width="700" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="p" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="Preparation details «logical value»" vertex="1">
|
||||
<mxGeometry height="320" width="650" x="970" y="110" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="pbody" parent="p" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="rest duration (with unit), if recorded
body position, if recorded
measured arm, if recorded
device details, if recorded
cuff details, if recorded
Unknown is not presumed correct technique" vertex="1">
|
||||
<mxGeometry height="284" width="650" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="note0" parent="1" style="text;html=0;align=left;fontSize=15;" value="This logical model supersedes the old field list; it does not mandate a separate preparation table." vertex="1">
|
||||
<mxGeometry height="25" width="1660" x="40" y="795" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="note1" parent="1" style="text;html=0;align=left;fontSize=15;" value="Patient identifier is not a cross-service database foreign key." vertex="1">
|
||||
<mxGeometry height="25" width="1660" x="40" y="820" as="geometry" />
|
||||
</mxCell>
|
||||
</root>
|
||||
</mxGraphModel>
|
||||
</diagram>
|
||||
</mxfile>
|
||||
@@ -0,0 +1,28 @@
|
||||
<mxfile host="Electron">
|
||||
<diagram id="09_er_insights_service" name="Insights Service — no persisted summary entities">
|
||||
<mxGraphModel dx="1721" dy="1021" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="1740" pageHeight="600" math="0" shadow="0">
|
||||
<root>
|
||||
<mxCell id="0" />
|
||||
<mxCell id="1" parent="0" />
|
||||
<mxCell id="title" parent="1" style="text;html=0;fontSize=24;fontStyle=1;align=center;" value="Insights Service — no persisted summary entities" vertex="1">
|
||||
<mxGeometry height="50" width="1660" x="40" y="10" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="n" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="Baseline persistence decision" vertex="1">
|
||||
<mxGeometry height="310" width="720" x="80" y="120" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="nbody" parent="n" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="Insights owns no database or repository.
HealthSummary is not a persisted table.
No generated-summary persistence ID.
Summaries and trends use current observations.
Recalculate on request in the baseline.
Corrections and deletions affect new results." vertex="1">
|
||||
<mxGeometry height="274" width="720" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="v" parent="1" style="swimlane;html=0;startSize=36;horizontal=1;fillColor=#eeeeee;swimlaneFillColor=#ffffff;strokeColor=#333333;fontColor=#111111;fontSize=17;fontStyle=1;align=center;" value="Calculated response objects" vertex="1">
|
||||
<mxGeometry height="310" width="720" x="920" y="120" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="vbody" parent="v" style="text;html=0;align=left;verticalAlign=top;spacing=10;fontSize=15;fontFamily=Helvetica;whiteSpace=wrap;overflow=hidden;" value="HealthInsight: numerical summary
TrendAssessment: three metric assessments
Neither object represents a stored entity.
Observation data remains Observation-owned.
HTTP observation access passes through gateway." vertex="1">
|
||||
<mxGeometry height="274" width="720" y="36" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="note0" parent="1" style="text;html=0;align=left;fontSize=15;" value="Supersedes the HealthSummary table in the former ER JPEG." vertex="1">
|
||||
<mxGeometry height="25" width="1660" x="40" y="495" as="geometry" />
|
||||
</mxCell>
|
||||
</root>
|
||||
</mxGraphModel>
|
||||
</diagram>
|
||||
</mxfile>
|
||||
@@ -0,0 +1,13 @@
|
||||
# Architecture diagrams
|
||||
|
||||
The editable draw.io files below are the current definitions for the changed diagrams. Open them in draw.io / diagrams.net. Their same-stem JPEGs are retained historical snapshots and are superseded, including where they show older fields or signatures.
|
||||
|
||||
- [04_class_observation_service.drawio](04_class_observation_service.drawio)
|
||||
- [05_class_insights_service.drawio](05_class_insights_service.drawio)
|
||||
- [06_class_health_overview_service.drawio](06_class_health_overview_service.drawio)
|
||||
- [08_er_observation_service.drawio](08_er_observation_service.drawio)
|
||||
- [09_er_insights_service.drawio](09_er_insights_service.drawio)
|
||||
|
||||
Unlisted diagrams remain as supplied. The changes preserve independent processes, service-owned persistence and gateway-routed communication. New shapes express required context and assessment data; logical optional values do not mandate additional tables or services.
|
||||
|
||||
The baseline Insights persistence decision is recorded in [us10-insights-correction.md](us10-insights-correction.md). Updated functional requirements are in ../Requirements. Exact contract field names, physical mapping and mathematical methods can be developed within those requirements and the repository's implementation rules.
|
||||
@@ -0,0 +1,11 @@
|
||||
# US-10 Insights architecture correction
|
||||
|
||||
This document is the baseline architecture decision for US-10 and US-11. It incorporates the former `Docs/Requirements/US_10_Correction`; that duplicate requirement file has been retired. Functional requirements are in `../Requirements/us10-calculated-insight.md` and `../Requirements/us11-health-trend.md`.
|
||||
|
||||
The Insights Service is an independent process and calculates summaries on demand. Its HTTP observation client retrieves observations through the API Gateway. `InsightsController`, `InsightsApplicationService`, `InsightCalculator`, and the observation client follow `05_class_insights_service.drawio`.
|
||||
|
||||
The service has no database, repository, stored summary identifier, or generated-summary persistence. `HealthInsight` is a calculated response object. The `HealthSummary` table shown in `09_er_insights_service.jpg` is an architectural inconsistency and does not apply; `09_er_insights_service.drawio` and this correction supersede that table. The absence of an Insights database in `02_microservice_architecture.jpg` is intentional.
|
||||
|
||||
Each summary request uses current observations, including corrections and deletions. Trend calculation remains under US-11.
|
||||
|
||||
Trend assessments also use current observations and are calculated on demand without storing generated assessments. This is a baseline design constraint, not an invariant persistence constraint on all architectural variants. Any experimental variant must retain the required freshness and access behaviour.
|
||||
@@ -0,0 +1,84 @@
|
||||
Prototype authentication and access-control design
|
||||
Date: 2026-10-01
|
||||
System: Personal Health Measurement System
|
||||
Related requirements: US-01, US-13 and US-14
|
||||
1. Status and purpose
|
||||
This document records the authentication and access-control decisions agreed for the thesis prototype. It replaces the proposed HTTP Basic mechanism in replaceable-prototype-authentication.md with token-based authentication and clarifies initial patient-profile creation.
|
||||
The token format is deliberately undecided. This document does not select JWT, a particular identity provider, or an additional service or database. Open implementation decisions are listed in Section 10 and must not be treated as already approved.
|
||||
The purpose is to provide credible patient and healthcare-professional access restrictions without turning the prototype into a production identity-management project. The system uses synthetic patient data and pre-created test accounts. No production-readiness or regulatory-compliance claim is made.
|
||||
Reconciliation update (2026-10-04): account/profile lifecycle and access wording have been aligned with the consolidated US-01, US-13, US-14, and public general guidance in US-15. Open token, persistence ownership, and deployment choices in Section 10 remain open; this requirements reconciliation does not select them.
|
||||
2. Decision summary
|
||||
Topic Decision
|
||||
Authentication Validate account credentials at login; issue a time-limited authentication token for subsequent requests.
|
||||
Token format Open; a concrete mechanism and library must be proposed separately.
|
||||
Framework integration Use ASP.NET Core authentication handlers, authenticated identities (ClaimsPrincipal) and authorization policies.
|
||||
Enforcement point The API gateway handles client authentication and authorization. Protected service APIs must not allow clients to bypass it.
|
||||
Account provisioning Use pre-created patient and healthcare-professional test accounts.
|
||||
Patient association A patient account may initially have no profile. It can create its own profile once; the generated patient identifier is persistently associated with that account.
|
||||
Patient access Existing story-defined operations on the patient's own information only.
|
||||
Professional access Read-only access to assigned patients and access to the professional's own assignment list.
|
||||
Assignments Predefined; assignment-management functionality is outside scope.
|
||||
Replacement Keep credential validation and token handling separate from application access policies.
|
||||
|
||||
|
||||
3. Authentication flow and token boundary
|
||||
1. A client submits credentials to a login endpoint over HTTPS.
|
||||
2. The gateway validates them against trusted pre-created account data using an established password-hashing facility.
|
||||
3. Successful login issues a time-limited token. Invalid credentials do not issue a token, and the rejection does not identify which credential component was incorrect.
|
||||
4. The client presents its token on subsequent protected requests.
|
||||
5. The gateway validates the token using the selected standard framework/library mechanism and establishes the application account identifier and role.
|
||||
6. The gateway applies the relevant authorization policy before returning or changing patient information.
|
||||
7. Missing, invalid or expired tokens are rejected. On expiration, the client authenticates again. Refresh tokens are outside scope.
|
||||
Credential verification must not be repeated for every protected operation. Token validation and authorization still occur on every protected request.
|
||||
The chosen mechanism must protect against token forgery and enforce expiration and the intended trust boundary. If signed self-contained tokens are selected, validation must include signature, trusted issuer and intended audience. Equivalent checks must be specified for any alternative mechanism. Custom cryptography or a custom authentication framework is outside the design.
|
||||
The normalized authenticated identity contains a stable application account identifier and a trusted role: Patient or HealthcareProfessional. The token either carries this validated identity or securely references it, depending on the selected format. Client-supplied role values are never authoritative.
|
||||
Patient health information must not be included in tokens. Patient ownership and professional assignments remain application access data, separate from token contents, and are evaluated by authorization policies.
|
||||
4. Access policy
|
||||
Actor and state Permitted access Restriction
|
||||
Unauthenticated client Submit credentials to the login endpoint and read general US-15 measurement guidance. No patient information or professional assignment lists.
|
||||
Patient account without a profile Create its own initial profile under US-01. Cannot select another patient's identity or access another patient's data.
|
||||
Patient account with a profile Perform operations permitted by the existing stories on its own profile, observations, insights and overview. Cannot create a second profile or use professional-only operations.
|
||||
Healthcare professional List its own assigned patients; read their profiles, observations, insights and overviews. Cannot access unassigned patients or create, modify or delete patient information.
|
||||
|
||||
|
||||
An authenticated identity alone is not sufficient for access. The requested operation and the actual patient associated with the resource must also be checked.
|
||||
For requests addressed by an observation identifier or another resource identifier, the gateway must establish the actual owning patient through documented service APIs. A patient identifier supplied by the client is not proof of ownership. No direct access to another service's database or reliance on shared process memory is permitted.
|
||||
Rejected requests must not return protected patient information or change patient data. Existing retrieval requirements continue to govern genuinely missing information after access has been established. An empty professional assignment list must not expose other patients.
|
||||
5. Initial profile creation and persistent association
|
||||
A patient account and a patient profile are distinct concepts. A pre-created patient account may exist before its profile. Once profile creation succeeds, that account is associated with exactly one generated patient identifier.
|
||||
The association must derive from the authenticated account, not an account identifier chosen by the caller. An account with an existing profile cannot create another profile or replace its association through profile creation.
|
||||
The association must survive process restarts. Repeated or concurrent creation attempts must not result in multiple profiles associated with the same account. The implementation proposal must explain recovery if profile creation succeeds but recording the association fails, so retries do not silently create duplicate or inaccessible profiles.
|
||||
These are required outcomes, not a choice of persistence technology or cross-service coordination mechanism. The owning component, persistence location and recovery mechanism remain open. Static external mappings alone do not satisfy the complete creation lifecycle.
|
||||
US-01 and US-13 now define zero profiles before initial creation and exactly one afterwards. US-14 defines professional assignments. See the consolidated numbered files in Docs/Requirements. Retries after completed creation report the existing-profile condition; interrupted operations must recover without duplicate or inaccessible profiles.
|
||||
6. Responsibility and deployment boundaries
|
||||
Use standard ASP.NET Core extension points so controllers and access policies consume normalized identities rather than passwords or token-format details. This decision does not introduce a new identity microservice or shared authentication implementation library across services.
|
||||
Services remain independently runnable processes and may be deployed on separate machines. The deployment must prevent untrusted clients from reaching protected service operations through a route that bypasses gateway authorization. Arbitrary client-supplied identity headers must not establish trusted identity.
|
||||
The concrete protection of gateway-to-service access is an open deployment decision. It must be documented before claiming that gateway-only enforcement satisfies the access requirements. It must preserve the established independent-service boundaries.
|
||||
Actual credentials, signing or protection keys, tokens and authorization headers must not be committed to the repository or written to logs. Provide safe example configuration and load operational secrets externally. Use HTTPS for client login and authenticated requests. Document any additional transport requirements in the deployment decision.
|
||||
7. Replaceability
|
||||
A future identity provider should replace credential validation and token integration without requiring a redesign of patient ownership or professional-assignment policies.
|
||||
Map the provider's validated identity explicitly to the stable application account identifier and trusted application role. Do not assume a provider subject automatically equals an application account identifier.
|
||||
Provider replacement may change the client's login flow and credential transport. Replaceability does not promise an unchanged client. A replacement must not silently enable the prototype mechanism as a fallback.
|
||||
8. Thesis measurement implications
|
||||
Authentication and authorization are part of the implemented system and its measured workload. Using login followed by token validation avoids deliberately repeating password verification for every business operation. This is a design rationale, not evidence of an energy reduction; any energy effect remains to be measured.
|
||||
Before baseline measurement, record the authentication implementation, token lifetime, validation settings, account and role mix, patient assignments, login frequency and treatment of expiration. State whether login is included in the measured workload or occurs during setup. Account for re-authentication if tokens expire during a run.
|
||||
Keep these factors consistent across compared architectural variants unless an explicitly scoped experimental change concerns them. Preserve equivalent access behaviour in all variants. Do not substitute a test authentication handler in measured runs while describing results as those of the implemented authentication mechanism.
|
||||
Authentication-related work can affect bottlenecks and measured energy, even when configuration is identical. Interpret results in the context of the selected workload; lower authentication latency or CPU use alone does not demonstrate lower energy consumption.
|
||||
9. Verification and exclusions
|
||||
Automated verification must cover the US-13 and US-14 acceptance criteria, including valid login, invalid credentials, missing/invalid/expired tokens, cross-patient access attempts, professional assignment restrictions and prohibited professional writes. Include resource-identifier ownership checks and verify that rejected operations do not disclose or modify patient data.
|
||||
Verify initial profile creation, rejection of subsequent creation, persistence of the account association, and the agreed retry/concurrency behaviour. Verify gateway-bypass protection in the intended deployment. Check that authorization policies behave equivalently when a test handler supplies the same normalized identity; this is a replaceability test, not a measurement configuration.
|
||||
Outside scope: public registration, password recovery, multifactor authentication, account-administration interfaces, refresh tokens, professional credential verification, assignment-management interfaces, consent workflows, emergency access and professional editing of patient information. No full production identity-provider integration is required.
|
||||
10. Open implementation decisions
|
||||
Decision Required follow-up
|
||||
Token format and library Propose a standard implementation, validation rules, client transport and necessary key or state management. JWT is not preselected.
|
||||
Token lifetime Select and document a lifetime together with experimental login and expiration behaviour.
|
||||
Account-to-patient persistence Identify the owning component and persistent storage without silently adding a service or violating database ownership.
|
||||
Profile creation consistency Specify duplicate prevention and recovery across profile creation and association recording.
|
||||
Gateway-to-service protection Specify a concrete deployment control that works across separate machines.
|
||||
API contract details Reconcile endpoint contracts and rejection responses with the repository's existing conventions and acceptance criteria.
|
||||
|
||||
|
||||
The agent may propose these details, but this decision record does not approve an unselected token format or undocumented architectural additions. Update the relevant requirements and architecture records when the remaining choices are accepted.
|
||||
|
||||
|
||||
The prototype shall implement the minimum authentication, ownership, profile-creation consistency, and deployment protection needed to satisfy US-01, US-13, and US-14. The implementation may select and document simple, established mechanisms within the agreed architecture. Production hardening and capabilities outside these user stories are deferred until a decision is made to develop the system further.
|
||||
@@ -0,0 +1,80 @@
|
||||
# Common requirements
|
||||
|
||||
## Authority and scope
|
||||
|
||||
This directory contains one current definition for each user story US-01 through US-15. These files consolidate the supplied requirements and addenda. The replacement mapping is in `../requirements-reconciliation-changelog.md`; retired filenames are not additional active requirements.
|
||||
|
||||
Requirements describe observable behaviour. Baseline service decomposition, gateway routing, persistence, and token mechanism decisions belong in Architecture and Design. All compared architectural variants must satisfy the same functional requirements under equivalent data and conditions.
|
||||
|
||||
## Access and profile lifecycle
|
||||
|
||||
US-13 governs authenticated patient access and US-14 governs assigned, read-only healthcare-professional access. These rules apply to every patient-specific operation, including context, filtered statistics, trends, and overview results. Professionals may read assigned-patient information but cannot create, update, or delete it. Assignment lists remain protected. General US-15 guidance is public and discloses no patient-specific information.
|
||||
|
||||
A patient account has zero profiles before initial creation and exactly one afterwards. US-01 defines creation and retry outcomes. Accounts without profiles may authenticate and create their own initial profile; other own-data requests report that the requested information is unavailable and do not expose other patients.
|
||||
|
||||
Unless a scenario explicitly tests access rejection, it assumes an authenticated caller authorised for the operation. Missing-resource scenarios apply after access checks, without disclosing another patient's existence or information. Authentication and ownership are not established by caller-supplied patient identifiers alone.
|
||||
|
||||
## Periods and ordering
|
||||
|
||||
US-07, US-10, US-11, and the selected-period insight in US-12 use inclusive boundaries: start <= measurement timestamp <= end. An end before the start is rejected. Equal bounds are valid and include observations exactly at that instant; valid periods do not guarantee sufficient data for an assessment.
|
||||
|
||||
Times denote measurement instants. Equivalent instants expressed with different offsets are treated equally. A timestamp without an offset must have a documented interpretation; it must not change with the machine running the service. No particular wire format is prescribed.
|
||||
|
||||
Observation history is ordered by ascending measurement timestamp. US-06 separately defines latest-observation ties. Recording order never determines US-11 direction.
|
||||
|
||||
## Measurement context and selection
|
||||
|
||||
US-04 defines the recordable setting, activity condition, and optional details. Missing or ambiguous context stays unknown; original text and notes are preserved. Similar values do not prove comparable conditions.
|
||||
|
||||
US-07, US-10, US-11, and US-12 insight support setting and activity selections. When both are selected, both must match. Unknown is a selectable category distinct from known values. Without selections, context alone excludes nothing. Each result identifies applied selections. Individual stories define empty-result and sufficiency behaviour.
|
||||
|
||||
## Acceptance-test conventions
|
||||
|
||||
Each scenario can establish its own state directly. It need not run another user story for setup. Create, update, and delete success does not require returning a complete object or a particular HTTP status. Persistence and subsequent-read assertions may be verified using independent read scenarios with the required state established in Given.
|
||||
|
||||
Documented numerical methods and their concrete test fixtures must satisfy the functional criteria. No specific trend formula is prescribed. Clinical claims require applicable Danish/European guidance; mathematical-method freedom does not authorise invented clinical cutoffs.
|
||||
|
||||
## Shared period acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: Inclusive periods
|
||||
|
||||
Scenario Outline: Include both boundaries
|
||||
Given an authorised patient has eligible observations exactly at the start and end and outside the period
|
||||
When <operation> is requested for that period
|
||||
Then both boundary observations contribute
|
||||
And observations outside the period do not contribute
|
||||
|
||||
Examples:
|
||||
| operation |
|
||||
| history |
|
||||
| numerical insight |
|
||||
| trend assessment |
|
||||
| overview insight |
|
||||
|
||||
Scenario Outline: Equal bounds are valid
|
||||
Given eligible observations exist exactly at the selected instant and elsewhere
|
||||
When <operation> is requested with start and end equal to that instant
|
||||
Then the period is accepted
|
||||
And only observations at that instant are selected
|
||||
And the operation applies its own data-sufficiency rules
|
||||
|
||||
Examples:
|
||||
| operation |
|
||||
| history |
|
||||
| numerical insight |
|
||||
| trend assessment |
|
||||
| overview insight |
|
||||
|
||||
Scenario Outline: Reject reversed bounds
|
||||
Given the caller is authorised
|
||||
When <operation> is requested with end before start
|
||||
Then the request is rejected
|
||||
|
||||
Examples:
|
||||
| operation |
|
||||
| history |
|
||||
| numerical insight |
|
||||
| trend assessment |
|
||||
| overview insight |
|
||||
```
|
||||
@@ -1,479 +0,0 @@
|
||||
# Personal Health Measurement System — User Stories and Acceptance Criteria
|
||||
|
||||
## Purpose
|
||||
|
||||
This document defines the externally observable behaviour of the Personal Health Measurement System.
|
||||
|
||||
The user stories and acceptance criteria are intentionally architecture-neutral. They do not prescribe microservices, databases, controllers, repositories, communication mechanisms, or deployment choices.
|
||||
|
||||
For the thesis experiment, these requirements should remain stable across architectural variants so that functional behaviour is held constant while architecture changes.
|
||||
|
||||
---
|
||||
|
||||
## US-01 — Create a patient profile
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want to create a patient profile so that my health measurements can be associated with me.
|
||||
|
||||
### Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: Create patient profile
|
||||
|
||||
Scenario: Create a patient with valid information
|
||||
Given no patient exists with the generated patient identifier
|
||||
When a patient profile is created with
|
||||
| name | Steffen Example |
|
||||
| dateOfBirth | 1980-01-01 |
|
||||
| contactInfo | steffen@example.test |
|
||||
Then the patient profile is created successfully
|
||||
And a patient identifier is assigned
|
||||
And the patient profile can be retrieved using that identifier
|
||||
|
||||
Scenario: A patient name is required
|
||||
When a patient profile is created without a name
|
||||
Then the patient profile is rejected
|
||||
|
||||
Scenario: A date of birth is required
|
||||
When a patient profile is created without a date of birth
|
||||
Then the patient profile is rejected
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## US-02 — View a patient profile
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want to view my patient profile so that I can verify the information associated with my measurements.
|
||||
|
||||
### Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: View patient profile
|
||||
|
||||
Scenario: Retrieve an existing patient
|
||||
Given a patient exists
|
||||
When the patient profile is requested using the patient identifier
|
||||
Then the patient profile is returned
|
||||
And the returned patient identifier matches the requested patient
|
||||
And the patient's name is included
|
||||
And the patient's date of birth is included
|
||||
And the patient's contact information is included
|
||||
|
||||
Scenario: Request a patient that does not exist
|
||||
Given no patient exists with the requested patient identifier
|
||||
When the patient profile is requested
|
||||
Then the request reports that the patient does not exist
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## US-03 — Update a patient profile
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want to update my profile information so that the system contains my current information.
|
||||
|
||||
### Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: Update patient profile
|
||||
|
||||
Scenario: Update an existing patient
|
||||
Given a patient exists with
|
||||
| name | Steffen Example |
|
||||
| contactInfo | old@example.test |
|
||||
When the patient profile is updated with
|
||||
| name | Steffen Example |
|
||||
| contactInfo | new@example.test |
|
||||
Then the update succeeds
|
||||
And the patient identifier is unchanged
|
||||
And the patient profile contains contact information "new@example.test"
|
||||
|
||||
Scenario: Update a patient that does not exist
|
||||
Given no patient exists with the requested patient identifier
|
||||
When an update is requested for that patient
|
||||
Then the update is rejected
|
||||
And no new patient is created
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## US-04 — Record a blood-pressure observation
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want to record a blood-pressure observation so that I can maintain a history of my measurements.
|
||||
|
||||
### Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: Record blood-pressure observation
|
||||
|
||||
Scenario: Record a valid observation
|
||||
Given a patient exists
|
||||
When the patient records a blood-pressure observation with
|
||||
| measuredAt | 2026-09-12T08:00:00 |
|
||||
| systolic | 128 |
|
||||
| diastolic | 82 |
|
||||
| pulse | 68 |
|
||||
| context | Resting |
|
||||
| note | Before breakfast |
|
||||
Then the observation is accepted
|
||||
And an observation identifier is assigned
|
||||
And the observation is associated with the patient
|
||||
And the observation can be retrieved later
|
||||
|
||||
Scenario: Record an observation without optional fields
|
||||
Given a patient exists
|
||||
When the patient records a blood-pressure observation with
|
||||
| measuredAt | 2026-09-12T08:00:00 |
|
||||
| systolic | 128 |
|
||||
| diastolic | 82 |
|
||||
| pulse | 68 |
|
||||
Then the observation is accepted
|
||||
|
||||
Scenario Outline: Reject an observation containing a non-positive measured value
|
||||
Given a patient exists
|
||||
When the patient records a blood-pressure observation with
|
||||
| measuredAt | 2026-09-12T08:00:00 |
|
||||
| systolic | <systolic> |
|
||||
| diastolic | <diastolic> |
|
||||
| pulse | <pulse> |
|
||||
Then the observation is rejected
|
||||
|
||||
Examples:
|
||||
| systolic | diastolic | pulse |
|
||||
| 0 | 82 | 68 |
|
||||
| -1 | 82 | 68 |
|
||||
| 128 | 0 | 68 |
|
||||
| 128 | -1 | 68 |
|
||||
| 128 | 82 | 0 |
|
||||
| 128 | 82 | -1 |
|
||||
|
||||
Scenario: Reject an observation without a measurement timestamp
|
||||
Given a patient exists
|
||||
When the patient records a blood-pressure observation without a measurement timestamp
|
||||
Then the observation is rejected
|
||||
|
||||
Scenario: Record an observation for a patient that does not exist
|
||||
Given no patient exists with the requested patient identifier
|
||||
When a blood-pressure observation is recorded for that patient
|
||||
Then the observation is rejected
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## US-05 — View a specific blood-pressure observation
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want to retrieve a specific blood-pressure observation so that I can review a previously recorded measurement.
|
||||
|
||||
### Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: View specific blood-pressure observation
|
||||
|
||||
Scenario: Retrieve an existing observation
|
||||
Given a patient has recorded a blood-pressure observation with
|
||||
| systolic | 128 |
|
||||
| diastolic | 82 |
|
||||
| pulse | 68 |
|
||||
When that observation is requested using its observation identifier
|
||||
Then the observation is returned
|
||||
And the systolic value is 128
|
||||
And the diastolic value is 82
|
||||
And the pulse value is 68
|
||||
|
||||
Scenario: Retrieve an observation that does not exist
|
||||
Given no observation exists with the requested observation identifier
|
||||
When the observation is requested
|
||||
Then the request reports that the observation does not exist
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## US-06 — View the latest blood-pressure observation
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want to see my latest blood-pressure observation so that I can quickly review my most recent measurement.
|
||||
|
||||
### Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: View latest blood-pressure observation
|
||||
|
||||
Scenario: Return the most recent observation
|
||||
Given a patient has observations recorded at
|
||||
| measuredAt | systolic | diastolic | pulse |
|
||||
| 2026-09-10T08:00:00 | 130 | 84 | 70 |
|
||||
| 2026-09-12T08:00:00 | 126 | 80 | 66 |
|
||||
| 2026-09-11T08:00:00 | 128 | 82 | 68 |
|
||||
When the latest observation is requested
|
||||
Then the observation measured at "2026-09-12T08:00:00" is returned
|
||||
|
||||
Scenario: Patient has no observations
|
||||
Given a patient exists
|
||||
And the patient has no recorded observations
|
||||
When the latest observation is requested
|
||||
Then the result indicates that no observation is available
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## US-07 — View blood-pressure observation history
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want to view my blood-pressure observations for a selected period so that I can review my measurement history.
|
||||
|
||||
### Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: View blood-pressure observation history
|
||||
|
||||
Scenario: Retrieve observations within a period
|
||||
Given a patient has observations recorded at
|
||||
| measuredAt | systolic | diastolic | pulse |
|
||||
| 2026-09-01T08:00:00 | 120 | 80 | 60 |
|
||||
| 2026-09-05T08:00:00 | 125 | 82 | 65 |
|
||||
| 2026-09-10T08:00:00 | 130 | 84 | 70 |
|
||||
When observations are requested from "2026-09-03T00:00:00" to "2026-09-08T23:59:59"
|
||||
Then exactly 1 observation is returned
|
||||
And the returned observation was measured at "2026-09-05T08:00:00"
|
||||
|
||||
Scenario: Return observations in chronological order
|
||||
Given a patient has multiple observations within the requested period
|
||||
When the observation history is requested
|
||||
Then the observations are returned in chronological order by measurement timestamp
|
||||
|
||||
Scenario: No observations exist within the requested period
|
||||
Given a patient exists
|
||||
And no observations exist within the requested period
|
||||
When the observation history is requested
|
||||
Then an empty observation collection is returned
|
||||
|
||||
Scenario: Reject an invalid period
|
||||
Given a patient exists
|
||||
When observations are requested with an end time earlier than the start time
|
||||
Then the request is rejected
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## US-08 — Update a blood-pressure observation
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want to correct a previously recorded observation so that accidental entry errors can be fixed.
|
||||
|
||||
### Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: Update blood-pressure observation
|
||||
|
||||
Scenario: Correct an existing observation
|
||||
Given a patient has an observation with
|
||||
| systolic | 182 |
|
||||
| diastolic | 82 |
|
||||
| pulse | 68 |
|
||||
When the systolic value is corrected to 128
|
||||
Then the update succeeds
|
||||
And the observation identifier is unchanged
|
||||
And the observation contains systolic value 128
|
||||
|
||||
Scenario Outline: Reject an update containing a non-positive measured value
|
||||
Given a patient has an existing observation
|
||||
When the observation is updated with
|
||||
| systolic | <systolic> |
|
||||
| diastolic | <diastolic> |
|
||||
| pulse | <pulse> |
|
||||
Then the update is rejected
|
||||
|
||||
Examples:
|
||||
| systolic | diastolic | pulse |
|
||||
| 0 | 82 | 68 |
|
||||
| 128 | 0 | 68 |
|
||||
| 128 | 82 | 0 |
|
||||
|
||||
Scenario: Update an observation that does not exist
|
||||
Given no observation exists with the requested observation identifier
|
||||
When an update is requested
|
||||
Then the update is rejected
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## US-09 — Delete a blood-pressure observation
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want to delete an incorrectly recorded observation so that it is no longer part of my measurement history.
|
||||
|
||||
### Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: Delete blood-pressure observation
|
||||
|
||||
Scenario: Delete an existing observation
|
||||
Given a patient has a recorded observation
|
||||
When that observation is deleted
|
||||
Then the deletion succeeds
|
||||
And the observation can no longer be retrieved
|
||||
And the observation no longer appears in the patient's observation history
|
||||
|
||||
Scenario: Delete an observation that does not exist
|
||||
Given no observation exists with the requested observation identifier
|
||||
When deletion is requested
|
||||
Then the request reports that the observation does not exist
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## US-10 — View calculated health insight for a period
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want to see calculated statistics for my observations over a selected period so that I can understand the measurements I have recorded.
|
||||
|
||||
### Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: View calculated health insight
|
||||
|
||||
Scenario: Calculate averages for a period
|
||||
Given a patient has the following observations within the requested period
|
||||
| systolic | diastolic | pulse |
|
||||
| 120 | 80 | 60 |
|
||||
| 130 | 84 | 70 |
|
||||
When health insight is requested for that period
|
||||
Then the average systolic value is 125
|
||||
And the average diastolic value is 82
|
||||
And the average pulse value is 65
|
||||
|
||||
Scenario: Calculate minimum and maximum blood-pressure values
|
||||
Given a patient has the following observations within the requested period
|
||||
| systolic | diastolic | pulse |
|
||||
| 118 | 76 | 61 |
|
||||
| 130 | 84 | 70 |
|
||||
| 124 | 80 | 66 |
|
||||
When health insight is requested for that period
|
||||
Then the minimum systolic value is 118
|
||||
And the maximum systolic value is 130
|
||||
And the minimum diastolic value is 76
|
||||
And the maximum diastolic value is 84
|
||||
|
||||
Scenario: Insight uses only observations in the requested period
|
||||
Given a patient has observations both inside and outside the requested period
|
||||
When health insight is requested for that period
|
||||
Then only observations within the requested period contribute to the calculated values
|
||||
|
||||
Scenario: No observations exist in the requested period
|
||||
Given a patient exists
|
||||
And no observations exist within the requested period
|
||||
When health insight is requested
|
||||
Then the result indicates that insufficient observation data is available for calculation
|
||||
|
||||
Scenario: Reject an invalid insight period
|
||||
Given a patient exists
|
||||
When health insight is requested with an end time earlier than the start time
|
||||
Then the request is rejected
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## US-11 — View a health trend
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want to see how my recorded measurements change over time so that I can identify the direction of my measured values.
|
||||
|
||||
### Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: View health trend
|
||||
|
||||
Scenario: Calculate a trend from observations
|
||||
Given a patient has sufficient observations within the requested period
|
||||
When a health trend is requested for that period
|
||||
Then a trend result is returned
|
||||
And the trend is derived only from observations within the requested period
|
||||
|
||||
Scenario: No observations exist for trend calculation
|
||||
Given a patient exists
|
||||
And no observations exist within the requested period
|
||||
When a health trend is requested
|
||||
Then the result indicates that insufficient observation data is available for trend calculation
|
||||
|
||||
Scenario: Reject an invalid trend period
|
||||
Given a patient exists
|
||||
When a health trend is requested with an end time earlier than the start time
|
||||
Then the request is rejected
|
||||
```
|
||||
|
||||
> **Note:** The exact mathematical definition of a trend should be specified before implementation if this story is retained. The acceptance criteria deliberately avoid prescribing an algorithm at this stage.
|
||||
|
||||
---
|
||||
|
||||
## US-12 — View a consolidated health overview
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want a consolidated overview of my profile, latest observation, and calculated insight so that I can review the most important information in one place.
|
||||
|
||||
### Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: View consolidated health overview
|
||||
|
||||
Scenario: View an overview for a patient with observations
|
||||
Given a patient exists
|
||||
And the patient has recorded blood-pressure observations
|
||||
And health insight can be calculated for the requested period
|
||||
When the health overview is requested for that period
|
||||
Then the patient's profile is included
|
||||
And the latest blood-pressure observation is included
|
||||
And the calculated health insight is included
|
||||
|
||||
Scenario: View an overview for a patient without observations
|
||||
Given a patient exists
|
||||
And the patient has no recorded observations
|
||||
When the health overview is requested
|
||||
Then the patient's profile is included
|
||||
And no latest blood-pressure observation is returned
|
||||
And the overview indicates that no calculated health insight is available
|
||||
|
||||
Scenario: Request an overview for a patient that does not exist
|
||||
Given no patient exists with the requested patient identifier
|
||||
When the health overview is requested
|
||||
Then the request reports that the patient does not exist
|
||||
|
||||
Scenario: Reject an invalid overview period
|
||||
Given a patient exists
|
||||
When the health overview is requested with an end time earlier than the start time
|
||||
Then the request is rejected
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# Functional invariance requirement for the experiment
|
||||
|
||||
All architecture variants evaluated in the thesis should satisfy the same user stories and acceptance criteria.
|
||||
|
||||
A modified architecture should not be considered functionally equivalent to the baseline unless the same acceptance-test suite passes against both systems under equivalent test data and conditions.
|
||||
|
||||
The acceptance criteria define required observable behaviour. They intentionally do not require any particular:
|
||||
|
||||
- service decomposition,
|
||||
- internal class structure,
|
||||
- database technology,
|
||||
- persistence implementation,
|
||||
- communication mechanism,
|
||||
- deployment model,
|
||||
- caching strategy,
|
||||
- concurrency mechanism,
|
||||
- or other architectural implementation choice.
|
||||
@@ -0,0 +1,89 @@
|
||||
# US-01 — Create a patient profile
|
||||
|
||||
The [common requirements](00-common-requirements.md) apply to this story.
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want to create a patient profile so that my health measurements can be associated with me.
|
||||
|
||||
## Functional requirements
|
||||
|
||||
A patient must be authenticated to create their own initial profile. A patient account has no associated profile before successful initial creation and exactly one afterwards. The association derives from the authenticated account, never an account or patient identity selected by the caller.
|
||||
|
||||
Creation assigns a patient identifier and persistently associates it with the account. The association survives process restart. A later create request shall report that a profile already exists and shall neither create a second profile nor replace the association.
|
||||
|
||||
Concurrent requests and retries after a lost response or an interrupted creation shall not produce duplicate or inaccessible profiles. After recovery, at most one profile exists for the account and a successful outcome leaves that profile accessible to it. The implementation may choose the recovery and concurrency mechanisms. It shall not report successful creation before both profile creation and association are complete.
|
||||
|
||||
Healthcare professionals cannot create patient profiles. Unauthenticated requests are rejected. Account registration remains outside scope.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: Create patient profile
|
||||
|
||||
Scenario: Create a patient with valid information
|
||||
Given an authenticated patient account has no associated profile
|
||||
When a patient profile is created with
|
||||
| name | Steffen Example |
|
||||
| dateOfBirth | 1980-01-01 |
|
||||
| contactInfo | steffen@example.test |
|
||||
Then the patient profile is created successfully
|
||||
And a patient identifier is assigned
|
||||
And the identifier is associated with the authenticated account
|
||||
|
||||
Scenario: A patient name is required
|
||||
When a patient profile is created without a name
|
||||
Then the patient profile is rejected
|
||||
|
||||
Scenario: A date of birth is required
|
||||
When a patient profile is created without a date of birth
|
||||
Then the patient profile is rejected
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Reject a second profile
|
||||
Given an authenticated patient account already has a profile
|
||||
When another profile creation is requested
|
||||
Then the request reports that a profile already exists
|
||||
And no second profile is created and the association is unchanged
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Persistent account association
|
||||
Given a profile and its account association were successfully created
|
||||
And the application processes have restarted
|
||||
When the authenticated account requests its profile
|
||||
Then the same associated profile is returned
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Retry after a successful creation response was lost
|
||||
Given profile creation and account association succeeded but the response was lost
|
||||
When the authenticated account retries creation
|
||||
Then the result indicates that the profile already exists
|
||||
And no duplicate profile or replacement association is created
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Concurrent initial creation
|
||||
Given an authenticated patient account has no profile
|
||||
When two valid initial-creation requests are made concurrently
|
||||
Then at most one profile is created and associated with the account
|
||||
And no request reports a second profile as created
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Recovery after interrupted creation
|
||||
Given initial profile creation was interrupted before profile creation and association both completed
|
||||
And the system is able to process requests again
|
||||
When the authenticated account retries creation
|
||||
Then the operation recovers to one accessible associated profile or reports that creation remains incomplete
|
||||
And it neither produces duplicate profiles nor reports an inaccessible profile as successfully created
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Unauthenticated initial creation
|
||||
Given the caller is not authenticated
|
||||
When initial profile creation is requested
|
||||
Then the request is rejected and no profile is created
|
||||
```
|
||||
@@ -0,0 +1,27 @@
|
||||
# US-02 — View a patient profile
|
||||
|
||||
The [common requirements](00-common-requirements.md) apply to this story.
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want to view my patient profile so that I can verify the information associated with my measurements.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: View patient profile
|
||||
|
||||
Scenario: Retrieve an existing patient
|
||||
Given a patient exists
|
||||
When the patient profile is requested using the patient identifier
|
||||
Then the patient profile is returned
|
||||
And the returned patient identifier matches the requested patient
|
||||
And the patient's name is included
|
||||
And the patient's date of birth is included
|
||||
And the patient's contact information is included
|
||||
|
||||
Scenario: Request a patient that does not exist
|
||||
Given no patient exists with the requested patient identifier
|
||||
When the patient profile is requested
|
||||
Then the request reports that the patient does not exist
|
||||
```
|
||||
@@ -0,0 +1,30 @@
|
||||
# US-03 — Update a patient profile
|
||||
|
||||
The [common requirements](00-common-requirements.md) apply to this story.
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want to update my profile information so that the system contains my current information.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: Update patient profile
|
||||
|
||||
Scenario: Update an existing patient
|
||||
Given a patient exists with
|
||||
| name | Steffen Example |
|
||||
| contactInfo | old@example.test |
|
||||
When the patient profile is updated with
|
||||
| name | Steffen Example |
|
||||
| contactInfo | new@example.test |
|
||||
Then the update succeeds
|
||||
And the patient identifier is unchanged
|
||||
And the patient profile contains contact information "new@example.test"
|
||||
|
||||
Scenario: Update a patient that does not exist
|
||||
Given no patient exists with the requested patient identifier
|
||||
When an update is requested for that patient
|
||||
Then the update is rejected
|
||||
And no new patient is created
|
||||
```
|
||||
@@ -0,0 +1,124 @@
|
||||
# US-04 — Record a blood-pressure observation
|
||||
|
||||
The [common requirements](00-common-requirements.md) apply to this story.
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want to record a blood-pressure observation so that I can maintain a history of my measurements.
|
||||
|
||||
## Functional requirements
|
||||
|
||||
The patient shall be able to record and save the following information with an observation:
|
||||
|
||||
| Information | Required supported distinctions |
|
||||
| --- | --- |
|
||||
| Setting | Home, clinic, other, unknown/not recorded |
|
||||
| Activity condition | At rest, during activity, after activity, unknown/not recorded |
|
||||
| Preparation and technique | Optional details about rest duration, body position, measured arm, and device/cuff used |
|
||||
| Additional circumstances | Optional descriptions such as recent activity, stress, pain, or a departure from the usual measurement routine |
|
||||
|
||||
Setting and activity condition shall be independently recordable and usable for subsequent selection and comparison; users shall not have to encode both solely in an undifferentiated note. The representation and storage design are implementation choices.
|
||||
|
||||
Partial context shall be accepted. Missing information shall remain unknown, without defaulting to home, resting, or correct technique. Existing observations and valid submissions without context shall remain supported.
|
||||
|
||||
The existing optional context text and note shall be preserved. Ambiguous historical text shall not be converted into definite categories. Where recorded categories and narrative descriptions conflict, the system shall retain the supplied information and make the conflict apparent when relevant to interpretation.
|
||||
|
||||
Users shall record the actual circumstances, including departures from guidance. A measurement taken after activity is valid to record; it is not a validation error merely because it is unsuitable for a resting comparison.
|
||||
|
||||
Context shall remain associated with its observation and be available on subsequent authorised reads. No separate patient-level context record or manually entered consistency score is required. Comparability is assessed across observations under US-11.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: Record blood-pressure observation
|
||||
|
||||
Scenario: Record a valid observation
|
||||
Given a patient exists
|
||||
When the patient records a blood-pressure observation with
|
||||
| measuredAt | 2026-09-12T08:00:00 |
|
||||
| systolic | 128 |
|
||||
| diastolic | 82 |
|
||||
| pulse | 68 |
|
||||
| context | Resting |
|
||||
| note | Before breakfast |
|
||||
Then the observation is accepted
|
||||
And an observation identifier is assigned
|
||||
And the observation is associated with the patient
|
||||
And the observation can be retrieved later
|
||||
|
||||
Scenario: Record an observation without optional fields
|
||||
Given a patient exists
|
||||
When the patient records a blood-pressure observation with
|
||||
| measuredAt | 2026-09-12T08:00:00 |
|
||||
| systolic | 128 |
|
||||
| diastolic | 82 |
|
||||
| pulse | 68 |
|
||||
Then the observation is accepted
|
||||
|
||||
Scenario Outline: Reject an observation containing a non-positive measured value
|
||||
Given a patient exists
|
||||
When the patient records a blood-pressure observation with
|
||||
| measuredAt | 2026-09-12T08:00:00 |
|
||||
| systolic | <systolic> |
|
||||
| diastolic | <diastolic> |
|
||||
| pulse | <pulse> |
|
||||
Then the observation is rejected
|
||||
|
||||
Examples:
|
||||
| systolic | diastolic | pulse |
|
||||
| 0 | 82 | 68 |
|
||||
| -1 | 82 | 68 |
|
||||
| 128 | 0 | 68 |
|
||||
| 128 | -1 | 68 |
|
||||
| 128 | 82 | 0 |
|
||||
| 128 | 82 | -1 |
|
||||
|
||||
Scenario: Reject an observation without a measurement timestamp
|
||||
Given a patient exists
|
||||
When the patient records a blood-pressure observation without a measurement timestamp
|
||||
Then the observation is rejected
|
||||
|
||||
Scenario: Record an observation for a patient that does not exist
|
||||
Given no patient exists with the requested patient identifier
|
||||
When a blood-pressure observation is recorded for that patient
|
||||
Then the observation is rejected
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Feature: US-04 — Record measurement setting and conditions
|
||||
|
||||
Scenario: Record setting and condition independently
|
||||
Given a patient exists and the submitting patient is authorised
|
||||
When a valid observation is submitted with setting Home and activity condition At rest
|
||||
Then observation creation succeeds
|
||||
|
||||
Scenario: Record partial context
|
||||
Given a patient exists
|
||||
When a valid observation is submitted with setting Clinic and no activity condition
|
||||
Then observation creation succeeds
|
||||
|
||||
Scenario: Retain support for absent context
|
||||
Given a patient exists
|
||||
When an otherwise valid observation is submitted without context
|
||||
Then observation creation succeeds
|
||||
|
||||
Scenario: Record departure from routine
|
||||
Given a patient exists
|
||||
When a valid observation is submitted as After activity with a description of the activity
|
||||
Then observation creation succeeds
|
||||
|
||||
Scenario: Reject unsupported category
|
||||
Given a patient exists
|
||||
When an observation is submitted with a setting category outside the supported distinctions
|
||||
Then the operation is rejected with an explanation of the invalid category
|
||||
|
||||
Scenario: Retrieve previously saved context
|
||||
Given an observation exists with saved setting, activity condition, preparation details, and a note
|
||||
When an authorised user requests that observation
|
||||
Then the returned observation contains those saved details associated with that observation
|
||||
|
||||
Scenario: Reject another patient’s context submission
|
||||
Given the submitting patient is not authorised to record observations for another patient
|
||||
When an observation with measurement context is submitted for that other patient
|
||||
Then the operation is rejected
|
||||
```
|
||||
@@ -0,0 +1,62 @@
|
||||
# US-05 — View a specific blood-pressure observation
|
||||
|
||||
The [common requirements](00-common-requirements.md) apply to this story.
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want to retrieve a specific blood-pressure observation so that I can review a previously recorded measurement.
|
||||
|
||||
## Functional requirements
|
||||
|
||||
The returned observation shall include its recorded setting, activity condition, optional preparation details, and existing context text and note. Unknown information shall be distinguishable from explicitly recorded values. Context shall remain attached to the correct numerical measurements and timestamp.
|
||||
|
||||
These details are patient observation data and receive the same access protection as the observation itself.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: View specific blood-pressure observation
|
||||
|
||||
Scenario: Retrieve an existing observation
|
||||
Given a patient has recorded a blood-pressure observation with
|
||||
| systolic | 128 |
|
||||
| diastolic | 82 |
|
||||
| pulse | 68 |
|
||||
When that observation is requested using its observation identifier
|
||||
Then the observation is returned
|
||||
And the systolic value is 128
|
||||
And the diastolic value is 82
|
||||
And the pulse value is 68
|
||||
|
||||
Scenario: Retrieve an observation that does not exist
|
||||
Given no observation exists with the requested observation identifier
|
||||
When the observation is requested
|
||||
Then the request reports that the observation does not exist
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Feature: US-05 — View the context of a specific observation
|
||||
|
||||
Scenario: Return complete saved context
|
||||
Given an observation exists with Home, At rest, and preparation details
|
||||
When an authorised user requests the observation
|
||||
Then its saved context is returned with its numerical measurements and timestamp
|
||||
|
||||
Scenario: Return partial context
|
||||
Given an observation exists with Clinic and an unknown activity condition
|
||||
When the observation is requested by an authorised user
|
||||
Then Clinic is returned as the setting
|
||||
And activity condition is represented as unknown
|
||||
|
||||
Scenario: Preserve historical free text
|
||||
Given an observation exists with only the context text "Morning reading"
|
||||
When the observation is requested by an authorised user
|
||||
Then the original text is returned
|
||||
And no definite setting or activity condition is invented
|
||||
|
||||
Scenario: Protect context
|
||||
Given a user is not authorised to access an observation
|
||||
When that user requests the observation
|
||||
Then access is rejected
|
||||
And its context is not disclosed
|
||||
```
|
||||
@@ -0,0 +1,66 @@
|
||||
# US-06 — View the latest blood-pressure observation
|
||||
|
||||
The [common requirements](00-common-requirements.md) apply to this story.
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want to see my latest blood-pressure observation so that I can quickly review my most recent measurement.
|
||||
|
||||
## Functional requirements
|
||||
|
||||
The latest observation shall include its recorded context as defined in US-04. Select the greatest measurement timestamp. If multiple observations share it, select the latest original recording time. A later edit does not change original recording time. If those times also tie, use a documented deterministic final tie rule so unchanged data yields the same result. This selection is independent of context completeness and does not determine US-11 trend direction. A recent observation shall not be replaced with an older observation merely because the older one has more suitable conditions.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: View latest blood-pressure observation
|
||||
|
||||
Scenario: Return the most recent observation
|
||||
Given a patient has observations recorded at
|
||||
| measuredAt | systolic | diastolic | pulse |
|
||||
| 2026-09-10T08:00:00 | 130 | 84 | 70 |
|
||||
| 2026-09-12T08:00:00 | 126 | 80 | 66 |
|
||||
| 2026-09-11T08:00:00 | 128 | 82 | 68 |
|
||||
When the latest observation is requested
|
||||
Then the observation measured at "2026-09-12T08:00:00" is returned
|
||||
|
||||
Scenario: Patient has no observations
|
||||
Given a patient exists
|
||||
And the patient has no recorded observations
|
||||
When the latest observation is requested
|
||||
Then the result indicates that no observation is available
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Feature: US-06 — Include context with the latest observation
|
||||
|
||||
Scenario: Return context of latest observation
|
||||
Given an authorised patient has an older resting observation and a newer after-activity observation
|
||||
When the latest observation is requested
|
||||
Then the newer observation is returned with its after-activity context
|
||||
|
||||
Scenario: Do not substitute a more complete observation
|
||||
Given the latest observation has no recorded context
|
||||
And an older observation has complete context
|
||||
When the latest observation is requested
|
||||
Then the latest observation is returned
|
||||
And its context is represented as unknown
|
||||
|
||||
Scenario: Preserve timestamp tie selection
|
||||
Given two observations share the latest measurement timestamp and have different settings
|
||||
And the second observation was recorded most recently
|
||||
When the latest observation is requested
|
||||
Then the second observation is returned with its own setting
|
||||
|
||||
Scenario: No observations
|
||||
Given the patient has no observations
|
||||
When the latest observation is requested
|
||||
Then the system reports that no observation is available
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Resolve a complete timestamp tie reproducibly
|
||||
Given two observations share the latest measurement timestamp and original recording time
|
||||
When the latest observation is requested repeatedly without data changes
|
||||
Then the same observation is returned under the documented final tie rule
|
||||
```
|
||||
@@ -0,0 +1,87 @@
|
||||
# US-07 — View blood-pressure observation history
|
||||
|
||||
The [common requirements](00-common-requirements.md) apply to this story.
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want to view my blood-pressure observations for a selected period so that I can review my measurement history.
|
||||
|
||||
## Functional requirements
|
||||
|
||||
Observation history shall include the recorded context of each observation. Users shall be able to select observations by setting, activity condition, or both, including an explicit unknown/not-recorded selection for either dimension.
|
||||
|
||||
When both dimensions are selected, an observation must match both. Without context selections, all otherwise eligible observations shall be returned, including those with missing context. Results shall identify the applied selections and retain the existing ascending measurement-time order and inclusive period boundaries.
|
||||
|
||||
Ambiguous historical text shall not count as a confirmed match for Home, Clinic, or an activity category. No matching observations shall produce an empty collection. Unsupported selection values shall be rejected with an explanation.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: View blood-pressure observation history
|
||||
|
||||
Scenario: Retrieve observations within a period
|
||||
Given a patient has observations recorded at
|
||||
| measuredAt | systolic | diastolic | pulse |
|
||||
| 2026-09-01T08:00:00 | 120 | 80 | 60 |
|
||||
| 2026-09-05T08:00:00 | 125 | 82 | 65 |
|
||||
| 2026-09-10T08:00:00 | 130 | 84 | 70 |
|
||||
When observations are requested from "2026-09-03T00:00:00" to "2026-09-08T23:59:59"
|
||||
Then exactly 1 observation is returned
|
||||
And the returned observation was measured at "2026-09-05T08:00:00"
|
||||
|
||||
Scenario: Return observations in chronological order
|
||||
Given a patient has multiple observations within the requested period
|
||||
When the observation history is requested
|
||||
Then the observations are returned in chronological order by measurement timestamp
|
||||
|
||||
Scenario: No observations exist within the requested period
|
||||
Given a patient exists
|
||||
And no observations exist within the requested period
|
||||
When the observation history is requested
|
||||
Then an empty observation collection is returned
|
||||
|
||||
Scenario: Reject an invalid period
|
||||
Given a patient exists
|
||||
When observations are requested with an end time earlier than the start time
|
||||
Then the request is rejected
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Feature: US-07 — Distinguish history by setting and conditions
|
||||
|
||||
Scenario: Select home observations
|
||||
Given a patient has home, clinic, and unknown-setting observations within the period
|
||||
When history is requested for Home
|
||||
Then only home observations within the period are returned with their context
|
||||
|
||||
Scenario: Combine setting and activity
|
||||
Given a patient has home-resting, home-after-activity, and clinic-resting observations in the period
|
||||
When history is requested for Home and At rest
|
||||
Then only home-resting observations are returned
|
||||
|
||||
Scenario: Select unknown context
|
||||
Given some observations have no known setting
|
||||
When history is requested for unknown setting
|
||||
Then only observations with unknown setting are returned
|
||||
|
||||
Scenario: No selection excludes nothing on context alone
|
||||
Given observations in the period have complete, partial, and absent context
|
||||
When history is requested without context selections
|
||||
Then all those observations are returned in ascending measurement-time order
|
||||
|
||||
Scenario: No matching observations
|
||||
Given no observations match the selected context and period
|
||||
When history is requested with those selections
|
||||
Then an empty collection is returned
|
||||
|
||||
Scenario: Reject unsupported selection
|
||||
When history is requested with an unsupported activity-condition selection
|
||||
Then the request is rejected with an explanation
|
||||
|
||||
Scenario: Preserve patient and boundary rules
|
||||
Given matching observations exist for the patient exactly at both period boundaries
|
||||
And matching observations also exist outside the period and for another patient
|
||||
When the patient’s history is requested for that period and context
|
||||
Then both boundary observations are returned
|
||||
And the outside-period and other-patient observations are excluded
|
||||
```
|
||||
@@ -0,0 +1,90 @@
|
||||
# US-08 — Update a blood-pressure observation
|
||||
|
||||
The [common requirements](00-common-requirements.md) apply to this story.
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want to correct a previously recorded observation so that accidental entry errors can be fixed.
|
||||
|
||||
## Functional requirements
|
||||
|
||||
The patient shall be able to add, correct, or clear individual setting, activity-condition, and optional preparation/circumstance details defined in US-04, including on historical observations. Clearing a value makes it unknown; it does not assign a default.
|
||||
|
||||
An update to context alone shall preserve numerical measurements, measurement timestamp, patient association, and all context or note values not explicitly changed. Partial updates shall not erase unrelated information. Unsupported categories shall be rejected without partially applying the requested update.
|
||||
|
||||
Subsequent reads, context selections, and assessments shall use the current recorded context. They shall not retain classifications derived from context that was corrected or cleared.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: Update blood-pressure observation
|
||||
|
||||
Scenario: Correct an existing observation
|
||||
Given a patient has an observation with
|
||||
| systolic | 182 |
|
||||
| diastolic | 82 |
|
||||
| pulse | 68 |
|
||||
When the systolic value is corrected to 128
|
||||
Then the update succeeds
|
||||
And the observation identifier is unchanged
|
||||
And the observation contains systolic value 128
|
||||
|
||||
Scenario Outline: Reject an update containing a non-positive measured value
|
||||
Given a patient has an existing observation
|
||||
When the observation is updated with
|
||||
| systolic | <systolic> |
|
||||
| diastolic | <diastolic> |
|
||||
| pulse | <pulse> |
|
||||
Then the update is rejected
|
||||
|
||||
Examples:
|
||||
| systolic | diastolic | pulse |
|
||||
| 0 | 82 | 68 |
|
||||
| 128 | 0 | 68 |
|
||||
| 128 | 82 | 0 |
|
||||
|
||||
Scenario: Update an observation that does not exist
|
||||
Given no observation exists with the requested observation identifier
|
||||
When an update is requested
|
||||
Then the update is rejected
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Feature: US-08 — Correct or remove recorded measurement context
|
||||
|
||||
Scenario: Add context to historical observation
|
||||
Given an authorised patient has an observation without context
|
||||
When Home and At rest are added
|
||||
Then the update succeeds
|
||||
|
||||
Scenario: Correct one context value
|
||||
Given an authorised patient has an observation recorded as Home and At rest
|
||||
When the setting alone is corrected to Clinic
|
||||
Then the update succeeds
|
||||
|
||||
Scenario: Clear optional context
|
||||
Given an authorised patient has an observation with a known activity condition
|
||||
When that activity condition is cleared
|
||||
Then the update succeeds
|
||||
|
||||
Scenario: Retrieve partially corrected observation
|
||||
Given an observation’s setting was corrected to Clinic without changing its other values
|
||||
When an authorised user requests that observation
|
||||
Then Clinic is returned
|
||||
And the original numerical values, timestamp, activity condition, and note are returned unchanged
|
||||
|
||||
Scenario: Reject invalid context correction
|
||||
Given an observation exists
|
||||
When an update contains an unsupported setting category
|
||||
Then the update is rejected
|
||||
|
||||
Scenario: Nonexistent observation
|
||||
Given the observation does not exist
|
||||
When a context correction is submitted
|
||||
Then the update is rejected
|
||||
|
||||
Scenario: Unauthorised correction
|
||||
Given a user is not authorised to modify an observation
|
||||
When the user submits a context correction
|
||||
Then the operation is rejected
|
||||
```
|
||||
@@ -0,0 +1,56 @@
|
||||
# US-09 — Delete a blood-pressure observation
|
||||
|
||||
The [common requirements](00-common-requirements.md) apply to this story.
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want to delete an incorrectly recorded observation so that it is no longer part of my measurement history.
|
||||
|
||||
## Functional requirements
|
||||
|
||||
Deleting an observation shall also remove its context from ordinary observation retrieval, history, numerical summaries, and assessments. Context belonging to other observations shall remain unaffected. Context has no separate user-visible lifecycle after its observation is deleted.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: Delete blood-pressure observation
|
||||
|
||||
Scenario: Delete an existing observation
|
||||
Given a patient has a recorded observation
|
||||
When that observation is deleted
|
||||
Then the deletion succeeds
|
||||
And the observation can no longer be retrieved
|
||||
And the observation no longer appears in the patient's observation history
|
||||
|
||||
Scenario: Delete an observation that does not exist
|
||||
Given no observation exists with the requested observation identifier
|
||||
When deletion is requested
|
||||
Then the request reports that the observation does not exist
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Feature: US-09 — Remove context with a deleted observation
|
||||
|
||||
Scenario: Delete contextualised observation
|
||||
Given an authorised patient has an observation with setting and conditions
|
||||
When that observation is deleted
|
||||
Then deletion succeeds
|
||||
|
||||
Scenario: History excludes previously deleted observation
|
||||
Given an observation with Home and At rest was deleted
|
||||
And other home-resting observations remain in the selected period
|
||||
When history is requested for Home and At rest
|
||||
Then the deleted observation and its context are absent
|
||||
And the remaining matching observations are returned
|
||||
|
||||
Scenario: Assessment excludes deleted data
|
||||
Given a contextualised observation was deleted
|
||||
And sufficient remaining observations exist for an assessment
|
||||
When the assessment is requested
|
||||
Then the deleted values and context do not contribute to the result
|
||||
|
||||
Scenario: Reject unauthorised deletion
|
||||
Given a user is not authorised to delete an observation
|
||||
When the user requests its deletion
|
||||
Then the operation is rejected
|
||||
```
|
||||
@@ -0,0 +1,112 @@
|
||||
# US-10 — View calculated health insight for a period
|
||||
|
||||
The [common requirements](00-common-requirements.md) apply to this story.
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want to see calculated statistics for my observations over a selected period so that I can understand the measurements I have recorded.
|
||||
|
||||
## Functional requirements
|
||||
|
||||
Users shall be able to request the existing numerical insight for a selected setting, activity condition, or both, using the same selection meanings as US-07. Without context selections, the existing all-observations-in-period calculation remains available.
|
||||
|
||||
The returned insight shall identify the applied context selections and number of contributing observations. Calculate arithmetic means for systolic pressure, diastolic pressure, and pulse, and minimum/maximum values for systolic and diastolic pressure. Round final means to two decimal places using half-up rounding, without intermediate rounding. Extrema retain the recorded values. A single observation is sufficient: its values are the means and its blood-pressure values are both the minima and maxima. Numeric representation need not retain trailing zero characters. Unknown context shall not prevent numerical calculations, but shall not match a known category.
|
||||
|
||||
A result spanning different or unknown conditions shall make that fact apparent. A pooled numerical average shall not be labelled a clinically comparable resting or home measurement series unless the supporting context justifies that description. This story does not replace descriptive averages with a diagnostic monitoring protocol.
|
||||
|
||||
If selection leaves no observations, the system shall report that no insight can be calculated for the selection. Context corrections and deletions shall be reflected in subsequent calculations.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: View calculated health insight
|
||||
|
||||
Scenario: Calculate averages for a period
|
||||
Given a patient has the following observations within the requested period
|
||||
| systolic | diastolic | pulse |
|
||||
| 120 | 80 | 60 |
|
||||
| 130 | 84 | 70 |
|
||||
When health insight is requested for that period
|
||||
Then the average systolic value is 125
|
||||
And the average diastolic value is 82
|
||||
And the average pulse value is 65
|
||||
|
||||
Scenario: Calculate minimum and maximum blood-pressure values
|
||||
Given a patient has the following observations within the requested period
|
||||
| systolic | diastolic | pulse |
|
||||
| 118 | 76 | 61 |
|
||||
| 130 | 84 | 70 |
|
||||
| 124 | 80 | 66 |
|
||||
When health insight is requested for that period
|
||||
Then the minimum systolic value is 118
|
||||
And the maximum systolic value is 130
|
||||
And the minimum diastolic value is 76
|
||||
And the maximum diastolic value is 84
|
||||
|
||||
Scenario: Insight uses only observations in the requested period
|
||||
Given a patient has observations both inside and outside the requested period
|
||||
When health insight is requested for that period
|
||||
Then only observations within the requested period contribute to the calculated values
|
||||
|
||||
Scenario: No observations exist in the requested period
|
||||
Given a patient exists
|
||||
And no observations exist within the requested period
|
||||
When health insight is requested
|
||||
Then the result indicates that insufficient observation data is available for calculation
|
||||
|
||||
Scenario: Reject an invalid insight period
|
||||
Given a patient exists
|
||||
When health insight is requested with an end time earlier than the start time
|
||||
Then the request is rejected
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Feature: US-10 — Calculate insight for selected measurement contexts
|
||||
|
||||
Scenario: Calculate from selected context only
|
||||
Given the period contains two home-resting observations with systolic values 120 and 130
|
||||
And a clinic-resting observation with systolic value 160
|
||||
When insight is requested for Home and At rest
|
||||
Then average systolic pressure is 125.00
|
||||
And the result identifies Home, At rest, and two contributing observations
|
||||
|
||||
Scenario: No filter preserves pooled calculation
|
||||
Given the period contains observations with different and unknown conditions
|
||||
When insight is requested without context selections
|
||||
Then all eligible observations contribute to the existing numerical calculations
|
||||
And the mixed or unknown context is made apparent
|
||||
|
||||
Scenario: One selected observation
|
||||
Given exactly one observation matches the selected period and context
|
||||
When insight is requested for that selection
|
||||
Then each mean equals that observation’s corresponding value
|
||||
And each blood-pressure minimum and maximum equals its corresponding value
|
||||
|
||||
Scenario: No matching observations
|
||||
Given observations exist in the period but none match the context selection
|
||||
When insight is requested for that selection
|
||||
Then the system reports that no insight can be calculated for the selection
|
||||
|
||||
Scenario: Correction changes membership
|
||||
Given an observation’s setting was corrected from Home to Clinic
|
||||
When home-only insight is requested for its period
|
||||
Then that observation does not contribute to the home-only calculation
|
||||
|
||||
Scenario: Reject unsupported selection
|
||||
When insight is requested with an unsupported setting selection
|
||||
Then the request is rejected with an explanation
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Round a halfway mean upwards
|
||||
Given eight eligible observations have systolic values 120, 120, 120, 120, 120, 120, 120, and 121
|
||||
When insight is requested for their period
|
||||
Then the average systolic value is 120.13
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Round a repeating fractional mean
|
||||
Given three eligible observations have systolic values 120, 120, and 121
|
||||
When insight is requested for their period
|
||||
Then the average systolic value is 120.33
|
||||
```
|
||||
@@ -0,0 +1,315 @@
|
||||
# US-11 — View a health trend
|
||||
|
||||
The [common requirements](00-common-requirements.md) apply to this story.
|
||||
|
||||
**User story**
|
||||
|
||||
As a user reviewing a patient’s health measurements, I want to see how systolic blood pressure, diastolic blood pressure, and pulse develop over a selected period, so that I can understand their direction, variation, and whether the observed development may be favourable or concerning.
|
||||
|
||||
## Functional requirements
|
||||
|
||||
### Measurements and period
|
||||
|
||||
The assessment shall include systolic blood pressure, diastolic blood pressure, and pulse, reported separately with their respective units.
|
||||
|
||||
Only observations belonging to the selected patient and period shall contribute to the assessment. Measurements shall be evaluated according to their measurement timestamps.
|
||||
|
||||
### Measurement levels
|
||||
|
||||
The assessment shall describe the observed measurement levels and compare them with applicable Danish or European clinical reference values.
|
||||
|
||||
Reference values shall be appropriate to the measurement setting. Home blood-pressure measurements shall not automatically be interpreted using clinic-measurement thresholds.
|
||||
|
||||
The explanation shall identify the reference values used and distinguish reference thresholds from individual treatment targets. It shall not imply that a general reference value is a personalised treatment goal.
|
||||
|
||||
### Direction over time
|
||||
|
||||
The assessment shall describe whether each measurement generally increases, decreases, or shows no clear direction over the selected period.
|
||||
|
||||
The direction assessment shall consider measurements throughout the period. It shall not rely solely on the first and last observations.
|
||||
|
||||
Where the measurements show a reversal or conflicting movements, the explanation shall describe this rather than imply a consistent increase or decrease.
|
||||
|
||||
### Observed variation
|
||||
|
||||
The assessment shall describe the amount of variation within the selected period, including intermediate excursions that would be hidden by comparing only the beginning and end.
|
||||
|
||||
Observed variation shall be distinguished from overall direction. A measurement may decrease overall while also showing substantial variation.
|
||||
|
||||
The system shall not classify a period as clinically stable or unstable using an arbitrary maximum–minimum threshold. A clinical classification of variation shall only be provided where an applicable, documented clinical rule supports it.
|
||||
|
||||
### Interpretation and hints
|
||||
|
||||
The assessment shall explain whether the observed development may be favourable, concerning, mixed, or cannot be interpreted from the available information.
|
||||
|
||||
The explanation shall consider measurement levels together with direction and variation. It shall not assume that:
|
||||
|
||||
- Decreasing values are always favourable.
|
||||
- Increasing values are always concerning.
|
||||
- Limited variation means the measurements are healthy.
|
||||
- Equal beginning and ending values mean the period was uneventful.
|
||||
|
||||
Systolic pressure, diastolic pressure, and pulse may support different interpretations. Where they do, the result shall explain the differences rather than force a single overall good/bad conclusion.
|
||||
|
||||
Hints shall describe the basis and limitations of the interpretation without presenting a diagnosis or recommending changes to medication.
|
||||
|
||||
### Measurement conditions and sufficient data
|
||||
|
||||
Clinical interpretation shall account for relevant measurement conditions where these are available, including whether measurements were taken at rest and whether they were recorded at home or in a clinical setting.
|
||||
|
||||
The system shall distinguish between having enough data to describe numerical changes and having enough suitable data to support a clinical interpretation.
|
||||
|
||||
Where the available observations do not support an assessment, the result shall identify which part cannot be assessed and explain why. It shall not silently assume missing measurement conditions or manufacture a conclusion.
|
||||
|
||||
### Current observations
|
||||
|
||||
The assessment shall reflect the current observations, including corrections and deletions. Each requested assessment shall reflect the current observations. The baseline calculation and persistence design is specified under Architecture.
|
||||
|
||||
### Mathematical methods
|
||||
|
||||
The implementation may select or develop mathematical methods for assessing measurement levels, direction, and variation. No particular formula or algorithm is prescribed.
|
||||
|
||||
The chosen methods shall satisfy the functional requirements and acceptance criteria, produce reproducible results, and be documented with their assumptions and limitations.
|
||||
|
||||
Mathematical methods shall not introduce unsupported clinical thresholds or interpretations. Clinical reference values and rules used to describe a result as potentially favourable or concerning shall be grounded in applicable Danish or European guidance. Where that guidance does not support a conclusion, the result shall communicate the limitation.
|
||||
|
||||
### Context selection and comparability
|
||||
|
||||
Users shall be able to request assessments for a selected setting, activity condition, or both, using the same meanings as US-07 and US-10. Each of systolic pressure, diastolic pressure, and pulse shall be assessed separately. Results shall identify their selections and the number of contributing observations.
|
||||
|
||||
Without context selection, the assessment shall cover eligible observations in the period and distinguish any mixed conditions. Users shall be able to compare separate context selections over the same period; each result shall identify its basis. Comparing a clinic series with a home series shall not by itself be described as improvement or deterioration over time.
|
||||
|
||||
Comparability shall be assessed from recorded setting, activity condition, and relevant optional preparation details. The explanation shall distinguish supported comparable conditions, known differences, and insufficient context. It shall identify the evidence or missing information behind that assessment. It shall not infer comparability from similar numerical values or from matching broad categories alone when other relevant details are unknown. No manually supplied consistency score is required.
|
||||
|
||||
Missing optional preparation details limit only claims that depend on those details. They do not automatically prevent a setting-appropriate reference comparison supported by the known information. Applicable Danish or European guidance determines which details are necessary for each clinical claim; the explanation shall distinguish the supported comparison from remaining uncertainty.
|
||||
|
||||
Sufficient numerical observations may still support direction and variation when context is absent. Clinical interpretation shall explain its limits and use applicable Danish/European guidance. The system shall not assume home, rest, or guideline-compliant technique from absent, ambiguous, or conflicting context.
|
||||
|
||||
Selected subsets shall satisfy the mathematical methods’ own sufficiency rules. Empty selections, a single observation, or a series with no temporal separation shall not produce an invented temporal direction. Supported descriptive values may still be returned with an explicit explanation of the unavailable assessment.
|
||||
|
||||
The implementation may develop and document mathematical methods satisfying the agreed requirements. Formula freedom does not authorise inventing clinical thresholds. Equality of first and last values alone shall not establish clinical stability. Direction requires at least two observations at distinct measurement timestamps; the documented method may require more. Equal-timestamp observations shall be handled reproducibly without recording or retrieval order determining direction. Assessments shall use current context and measurements after correction or deletion.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: View health trend
|
||||
|
||||
Scenario: Calculate a trend from observations
|
||||
Given a patient has sufficient observations within the requested period
|
||||
When a health trend is requested for that period
|
||||
Then a trend result is returned
|
||||
And the trend is derived only from observations within the requested period
|
||||
|
||||
Scenario: No observations exist for trend calculation
|
||||
Given a patient exists
|
||||
And no observations exist within the requested period
|
||||
When a health trend is requested
|
||||
Then the result indicates that insufficient observation data is available for trend calculation
|
||||
|
||||
Scenario: Reject an invalid trend period
|
||||
Given a patient exists
|
||||
When a health trend is requested with an end time earlier than the start time
|
||||
Then the request is rejected
|
||||
```
|
||||
|
||||
|
||||
|
||||
```gherkin
|
||||
Feature: US-11 — Context selection, comparability, and interpretation
|
||||
|
||||
Scenario: Assess a comparable selection
|
||||
Given sufficient valid home-resting observations with documented comparable preparation details exist
|
||||
When a trend is requested for Home and At rest
|
||||
Then separate systolic, diastolic, and pulse assessments are returned
|
||||
And the result identifies the selection, contributing count, and recorded basis for comparability
|
||||
|
||||
Scenario: Different conditions remain visible
|
||||
Given the selected series includes resting and after-activity observations
|
||||
When an assessment is requested without activity selection
|
||||
Then the result identifies the differing conditions
|
||||
And explains limitations on interpreting their combined trajectory
|
||||
|
||||
Scenario: Unknown details limit comparability
|
||||
Given observations share Home and At rest but have no recorded preparation details
|
||||
When their comparability is assessed
|
||||
Then the explanation identifies the known similarities and missing details
|
||||
And does not certify that all measurement conditions were identical
|
||||
|
||||
Scenario: Missing context preserves numerical information
|
||||
Given sufficient numerical observations exist with no context
|
||||
When an assessment is requested
|
||||
Then supported numerical direction and variation are returned
|
||||
And the limitations on clinical interpretation and comparability are explained
|
||||
|
||||
Scenario: Conflicting descriptions
|
||||
Given an observation is categorised At rest but its narrative states "during exercise"
|
||||
When an assessment includes that observation
|
||||
Then the conflict is identified
|
||||
And an unsupported resting interpretation is not asserted
|
||||
|
||||
Scenario: Compare labelled selections
|
||||
Given sufficient home-resting and clinic-resting series exist in the same period
|
||||
When the user compares assessments for those two selections
|
||||
Then each result identifies its own selection and contributing observations
|
||||
And a difference between settings alone is not labelled improvement or deterioration over time
|
||||
|
||||
Scenario: Insufficient selected series
|
||||
Given many observations exist but only one matches the selected context
|
||||
When a trend is requested for that selection
|
||||
Then the result reports insufficient observations for temporal direction
|
||||
And does not use excluded observations to manufacture a trend
|
||||
|
||||
Scenario: No temporal separation
|
||||
Given all selected observations have the same measurement timestamp
|
||||
When a trend is requested
|
||||
Then temporal direction is reported as unavailable
|
||||
|
||||
Scenario: No matching data
|
||||
Given no observations match the selected period and context
|
||||
When an assessment is requested
|
||||
Then the result reports that no matching observations are available
|
||||
|
||||
Scenario: Updated context is used
|
||||
Given an observation’s activity condition was corrected from At rest to After activity
|
||||
When a resting-only assessment is requested
|
||||
Then that observation no longer contributes to the result
|
||||
|
||||
Scenario: Reject invalid selection
|
||||
When an assessment is requested with an unsupported context selection
|
||||
Then the request is rejected with an explanation
|
||||
```
|
||||
|
||||
### AC-11-A — Separate assessments
|
||||
|
||||
```gherkin
|
||||
Given sufficient observations containing systolic pressure, diastolic pressure, and pulse
|
||||
When the user requests an assessment for the patient and period
|
||||
Then the result presents each measurement separately
|
||||
And identifies its unit, observed level, direction, and variation
|
||||
```
|
||||
|
||||
### AC-11-B — Patient and period selection
|
||||
|
||||
```gherkin
|
||||
Given observations exist for multiple patients and periods
|
||||
When the user requests an assessment for one patient and period
|
||||
Then only observations for that patient within the selected period contribute to the result
|
||||
```
|
||||
|
||||
### AC-11-C — Direction across the period
|
||||
|
||||
```gherkin
|
||||
Given sufficient measurements showing a consistent upward or downward development
|
||||
When the assessment is requested
|
||||
Then the result identifies the corresponding direction
|
||||
And bases that assessment on measurements throughout the period
|
||||
```
|
||||
|
||||
### AC-11-D — Intermediate excursion
|
||||
|
||||
```gherkin
|
||||
Given the beginning and ending measurements are similar
|
||||
And intermediate measurements differ substantially from them
|
||||
When the assessment is requested
|
||||
Then the result describes the intermediate variation
|
||||
And does not describe the period as clinically stable merely because its endpoints are similar
|
||||
```
|
||||
|
||||
### AC-11-E — Reversal or mixed direction
|
||||
|
||||
```gherkin
|
||||
Given measurements rise during one part of the period and fall during another
|
||||
When the assessment is requested
|
||||
Then the explanation describes the reversal or mixed development
|
||||
And does not imply that all measurements follow one consistent direction
|
||||
```
|
||||
|
||||
### AC-11-F — Limited variation outside reference values
|
||||
|
||||
```gherkin
|
||||
Given measurements remain outside the applicable reference values
|
||||
And show limited variation
|
||||
When the assessment is requested
|
||||
Then the explanation identifies their position relative to the reference values
|
||||
And does not describe them as healthy solely because their variation is limited
|
||||
```
|
||||
|
||||
### AC-11-G — Potentially favourable development
|
||||
|
||||
```gherkin
|
||||
Given suitable measurements show development that applicable clinical guidance supports describing as potentially favourable
|
||||
When the assessment is requested
|
||||
Then the explanation describes that development and its basis
|
||||
And distinguishes improvement from having reached an appropriate level
|
||||
```
|
||||
|
||||
### AC-11-H — Potentially concerning development
|
||||
|
||||
```gherkin
|
||||
Given suitable measurements show development that applicable clinical guidance supports describing as potentially concerning
|
||||
When the assessment is requested
|
||||
Then the explanation describes the concern and its basis
|
||||
And does not treat a decrease as favourable solely because the values are falling
|
||||
```
|
||||
|
||||
### AC-11-I — Conflicting measurements
|
||||
|
||||
```gherkin
|
||||
Given systolic pressure, diastolic pressure, or pulse support different interpretations
|
||||
When the assessment is requested
|
||||
Then the result explains the interpretation of each affected measurement
|
||||
And does not force them into a single favourable or concerning classification
|
||||
```
|
||||
|
||||
### AC-11-J — Missing measurement context
|
||||
|
||||
```gherkin
|
||||
Given numerical changes can be described
|
||||
But measurement conditions needed for clinical interpretation are unavailable
|
||||
When the assessment is requested
|
||||
Then the result presents the supported numerical information
|
||||
And explains that the clinical interpretation is limited by missing context
|
||||
```
|
||||
|
||||
### AC-11-K — Insufficient observations
|
||||
|
||||
```gherkin
|
||||
Given the observations are insufficient to determine a direction
|
||||
When the assessment is requested
|
||||
Then the result explicitly reports that direction cannot be determined
|
||||
And does not substitute an increasing, decreasing, or unchanged conclusion
|
||||
```
|
||||
|
||||
### AC-11-L — Applicable reference values
|
||||
|
||||
```gherkin
|
||||
Given sufficient measurement context to select applicable reference values
|
||||
When an interpretation is returned
|
||||
Then the result identifies the reference values used
|
||||
And does not present a general reference threshold as an individual treatment target
|
||||
```
|
||||
|
||||
### AC-11-M — Independence from storage order
|
||||
|
||||
```gherkin
|
||||
Given the same measurement values and timestamps
|
||||
When their insertion or retrieval order changes
|
||||
Then the assessment remains unchanged
|
||||
```
|
||||
|
||||
### AC-11-N — Corrected or deleted observations
|
||||
|
||||
```gherkin
|
||||
Given an observation has been corrected or deleted
|
||||
When the user requests a new assessment
|
||||
Then the result reflects the current observations
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Supported reference comparison despite incomplete preparation details
|
||||
Given known measurement context meets the applicable guidance for a particular reference comparison
|
||||
And optional preparation details not required for that comparison are missing
|
||||
When the assessment is requested
|
||||
Then the supported reference comparison is provided
|
||||
And the explanation identifies the remaining limits without rejecting all clinical interpretation
|
||||
```
|
||||
@@ -0,0 +1,78 @@
|
||||
# US-12 — View a consolidated health overview
|
||||
|
||||
The [common requirements](00-common-requirements.md) apply to this story.
|
||||
|
||||
**User story**
|
||||
|
||||
> As a patient, I want a consolidated overview of my profile, latest observation, and calculated insight so that I can review the most important information in one place.
|
||||
|
||||
## Functional requirements
|
||||
|
||||
The latest observation in the overview shall include its recorded context and retain the existing latest-observation selection rules. Its context shall not be presented as applying to every observation contributing to the insight.
|
||||
|
||||
Users shall be able to apply the US-10 setting and activity selections to the overview’s calculated insight. Those selections affect the insight only; the latest observation remains the latest overall observation for the patient. The overview shall identify this distinction, the insight selection, and its contributing count.
|
||||
|
||||
Without selections, the existing overview behaviour remains. Mixed or unknown context explanations accompanying the insight shall remain visible. When a selection has no contributing observations, the profile and available latest observation shall still be returned, with an explanation that no insight is available for that selection. This story does not add a trend component to the overview.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: View consolidated health overview
|
||||
|
||||
Scenario: View an overview for a patient with observations
|
||||
Given a patient exists
|
||||
And the patient has recorded blood-pressure observations
|
||||
And health insight can be calculated for the requested period
|
||||
When the health overview is requested for that period
|
||||
Then the patient's profile is included
|
||||
And the latest blood-pressure observation is included
|
||||
And the calculated health insight is included
|
||||
|
||||
Scenario: View an overview for a patient without observations
|
||||
Given a patient exists
|
||||
And the patient has no recorded observations
|
||||
When the health overview is requested
|
||||
Then the patient's profile is included
|
||||
And no latest blood-pressure observation is returned
|
||||
And the overview indicates that no calculated health insight is available
|
||||
|
||||
Scenario: Request an overview for a patient that does not exist
|
||||
Given no patient exists with the requested patient identifier
|
||||
When the health overview is requested
|
||||
Then the request reports that the patient does not exist
|
||||
|
||||
Scenario: Reject an invalid overview period
|
||||
Given a patient exists
|
||||
When the health overview is requested with an end time earlier than the start time
|
||||
Then the request is rejected
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Feature: US-12 — Preserve measurement context in the health overview
|
||||
|
||||
Scenario: Latest context and insight selection differ
|
||||
Given a patient has a latest after-activity observation and earlier home-resting observations in the period
|
||||
When an overview is requested with Home and At rest selected for insight
|
||||
Then the latest after-activity observation and its context are returned
|
||||
And the insight uses only matching home-resting observations
|
||||
And the result distinguishes their different bases
|
||||
|
||||
Scenario: No matching insight observations
|
||||
Given a patient has a profile and a latest observation
|
||||
And no observations match the selected insight context
|
||||
When the overview is requested for that selection
|
||||
Then the profile and latest observation remain available
|
||||
And the absence of insight for the selection is explained
|
||||
|
||||
Scenario: Unknown context remains unknown
|
||||
Given the latest observation has no context
|
||||
When the overview is requested
|
||||
Then its context is represented as unknown
|
||||
And no context is copied from other observations
|
||||
|
||||
Scenario: Default overview preserves context limitations
|
||||
Given insight spans differing measurement conditions
|
||||
When an overview is requested without context selections
|
||||
Then the original pooled insight is returned
|
||||
And its mixed-context explanation is included
|
||||
```
|
||||
@@ -0,0 +1,95 @@
|
||||
# US-13 — Authenticate and access own health information
|
||||
|
||||
The [common requirements](00-common-requirements.md) apply to this story.
|
||||
|
||||
**As a patient,**
|
||||
I want to authenticate using my credentials and access only my own health information,
|
||||
so that I can use the system while access to my information is restricted to me and healthcare professionals assigned to me.
|
||||
|
||||
## Functional requirements
|
||||
|
||||
The thesis prototype uses pre-created test accounts and synthetic patient data. A patient account has zero profiles before initial creation and exactly one afterwards, as defined in US-01. Healthcare professional accounts use predefined patient assignments under US-14.
|
||||
|
||||
Authentication is required for all patient profile, observation, insight, trend and health overview operations. General US-15 guidance is available without authentication. Patients may perform the operations defined by the existing user stories only on their own information.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Scenario: Successful authentication
|
||||
Given I have a pre-created account
|
||||
When I authenticate using valid credentials
|
||||
Then the system recognises my account and Patient role
|
||||
And recognises its associated patient profile if one has been created
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Access to my own information
|
||||
Given I am authenticated
|
||||
When I request an available operation on my own health information
|
||||
Then access is permitted
|
||||
And the operation follows its existing acceptance criteria
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Invalid credentials
|
||||
Given I am not authenticated
|
||||
When I attempt to authenticate using an incorrect account identifier or incorrect secret
|
||||
Then authentication is rejected
|
||||
And the response does not reveal which part of the credentials was incorrect
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Missing authentication
|
||||
Given I have not authenticated
|
||||
When I request an operation involving patient information
|
||||
Then the request is rejected
|
||||
And no patient information is returned or changed
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Invalid authentication information
|
||||
Given my request contains authentication information that the system cannot validate
|
||||
When I request an operation involving patient information
|
||||
Then the request is rejected
|
||||
And no patient information is returned or changed
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Access to another patient’s information
|
||||
Given I am authenticated as one patient
|
||||
When I attempt to view or change another patient’s information
|
||||
Then access is rejected
|
||||
And none of that patient’s information is returned or changed
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Own information does not yet exist
|
||||
Given I am authenticated
|
||||
And the requested information does not yet exist for my patient account
|
||||
When I request that information
|
||||
Then the system follows the existing behaviour for missing information
|
||||
And does not return another patient’s information
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Login before profile creation
|
||||
Given I have a pre-created patient account with no associated profile
|
||||
When I authenticate using valid credentials
|
||||
Then authentication succeeds and recognises my account and Patient role
|
||||
And I may create my initial profile under US-01
|
||||
And I gain no access to another patient’s information
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Expired authentication
|
||||
Given my authentication information has expired
|
||||
When I request protected patient information
|
||||
Then the request is rejected
|
||||
And no patient information is returned or changed
|
||||
```
|
||||
|
||||
## Prototype limitations
|
||||
|
||||
Account registration, password recovery, multifactor authentication, account administration, access by unassigned third parties, and writes by healthcare professionals are outside scope. Assigned healthcare professionals have the read-only access defined in US-14.
|
||||
|
||||
These criteria apply to every applicable API operation. The authentication mechanism and internal implementation are separate design decisions. The prototype does not claim production readiness.
|
||||
@@ -0,0 +1,100 @@
|
||||
# US-14 — Read assigned patients’ information
|
||||
|
||||
The [common requirements](00-common-requirements.md) apply to this story.
|
||||
|
||||
**As a healthcare professional,**
|
||||
I want to authenticate using my credentials and view health information for patients assigned to me,
|
||||
so that I can review their measurements and health insights.
|
||||
|
||||
## Functional requirements
|
||||
|
||||
The thesis prototype uses pre-created healthcare professional accounts and predefined patient assignments. A healthcare professional may be assigned to multiple patients, and a patient may be assigned to multiple healthcare professionals.
|
||||
|
||||
Access is read-only and covers the assigned patients’ profiles, observations and their context, numerical insights, trend assessments and health overviews.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Scenario: Successful authentication
|
||||
Given I have a pre-created healthcare professional account
|
||||
When I authenticate using valid credentials
|
||||
Then the system recognises my identity and healthcare professional role
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: View assigned patients
|
||||
Given I am authenticated as a healthcare professional
|
||||
When I request my assigned patients
|
||||
Then the system returns only patients assigned to me
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: View an assigned patient’s information
|
||||
Given I am authenticated as a healthcare professional
|
||||
And a patient is assigned to me
|
||||
When I request their profile, observations and context, numerical insights, trend assessment or health overview
|
||||
Then access is permitted
|
||||
And the requested information is returned according to the existing retrieval requirements
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: No assigned patients
|
||||
Given I am authenticated as a healthcare professional
|
||||
And no patients are assigned to me
|
||||
When I request my assigned patients
|
||||
Then the system indicates that no patients are assigned
|
||||
And does not return other patients
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Patient information does not yet exist
|
||||
Given I am authenticated as a healthcare professional
|
||||
And a patient is assigned to me
|
||||
And the requested information does not yet exist
|
||||
When I request that information
|
||||
Then the system follows the existing behaviour for missing information
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Access to an unassigned patient
|
||||
Given I am authenticated as a healthcare professional
|
||||
When I request information about a patient who is not assigned to me
|
||||
Then access is rejected
|
||||
And no information about that patient is returned
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Attempt to change patient information
|
||||
Given I am authenticated as a healthcare professional
|
||||
When I attempt to create, modify or delete patient information
|
||||
Then the operation is rejected
|
||||
And the patient information remains unchanged
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Invalid credentials
|
||||
Given I am not authenticated
|
||||
When I attempt to authenticate using an incorrect account identifier or incorrect secret
|
||||
Then authentication is rejected
|
||||
And the response does not reveal which part of the credentials was incorrect
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Missing or invalid authentication
|
||||
Given my request has missing or invalid authentication information
|
||||
When I request assigned patients or patient information
|
||||
Then the request is rejected
|
||||
And no patient information is returned
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: Patient account attempts professional access
|
||||
Given I am authenticated only as a patient
|
||||
When I attempt to use access reserved for healthcare professionals
|
||||
Then access is rejected
|
||||
And my existing access to my own information is unaffected
|
||||
```
|
||||
|
||||
## Prototype limitations
|
||||
|
||||
Patient assignments are predefined. Assignment management, professional credential verification, consent workflows, emergency access and editing by healthcare professionals are outside scope.
|
||||
@@ -0,0 +1,85 @@
|
||||
# US-15 — Follow measurement instructions
|
||||
|
||||
The [common requirements](00-common-requirements.md) apply to this story.
|
||||
|
||||
## User story
|
||||
|
||||
As a patient, I want clear instructions for taking and recording blood-pressure and pulse measurements, so that my observations are as accurate and comparable as practicable.
|
||||
|
||||
## Scope
|
||||
|
||||
Measurement guidance is separate from saving context under US-04. Guidance shall be available before any observation exists and while preparing to record an observation. Existing access rules continue to protect patient data; general guidance is available without authentication and shall neither require nor disclose patient information or assignment lists. Patient-specific records and assessments remain protected under US-13 and US-14.
|
||||
|
||||
## Functional requirements
|
||||
|
||||
The system shall provide clear, ordered instructions for obtaining accurate and repeatable blood-pressure and accompanying pulse measurements, based on applicable Danish or European clinical guidance. The instructions shall identify their source and review date, and distinguish home self-measurement from clinical measurement.
|
||||
|
||||
Home guidance shall cover preparation and rest, a suitable validated device and cuff, posture and arm positioning, remaining still during measurement, repeated readings and timing, and recording actual values and conditions. It shall explain how maintaining comparable conditions helps later comparison. Where numeric waiting times or repeat schedules are given, they shall follow the identified guidance rather than invented values.
|
||||
|
||||
The Danish home protocol described in [Sundhed.dk — Højt blodtryk](https://www.sundhed.dk/sundhedsfaglig/laegehaandbogen/hjerte-kar/symptomer-og-tegn/hoejt-blodtryk/) includes five minutes of seated rest and repeated morning/evening readings over three days. Instructions shall distinguish such a planned monitoring protocol from recording an individual observation. Device and cuff guidance shall be consistent with [Sundhed.dk — Blodtryksmåling](https://www.sundhed.dk/sundhedsfaglig/laegehaandbogen/undersoegelser-og-proever/kliniske-procedurer/hjertekar/blodtryksmaaling/).
|
||||
|
||||
Guidance for accompanying pulse shall explain recording the device-reported pulse and the relevance of rest/activity context; it shall not assume that a single pulse value measures rhythm regularity. The guidance shall not claim to guarantee accuracy or replace the device instructions or individually supplied clinical instructions.
|
||||
|
||||
If the setting is unknown, guidance shall clearly label its applicability rather than assuming home measurement. Departures from recommended conditions shall be recordable; guidance shall advise recording the actual circumstances instead of changing, discarding, or inventing readings.
|
||||
|
||||
Reading or declining guidance shall not create, change, or delete an observation, mark a procedure as followed, or block an otherwise valid observation submission. If guidance cannot be provided, the system shall communicate this without presenting unverified instructions as authoritative. Guidance shall not recommend changes to prescribed medication.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
```gherkin
|
||||
Feature: US-15 — Follow measurement instructions
|
||||
|
||||
Scenario: Access guidance before first observation
|
||||
Given a patient has no observations
|
||||
When measurement guidance is requested
|
||||
Then preparation, measurement, and recording instructions are available
|
||||
And the source, applicability, and review date are identified
|
||||
|
||||
Scenario: Home measurement guidance
|
||||
When home measurement guidance is requested
|
||||
Then the instructions cover rest, equipment and cuff, positioning, repeated readings, and recording conditions
|
||||
And any numeric instructions follow the identified Danish or European guidance
|
||||
|
||||
Scenario: Unknown setting
|
||||
Given no measurement setting has been supplied
|
||||
When guidance is requested
|
||||
Then its supported setting is identified
|
||||
And no measurement setting is saved or assumed on the user’s behalf
|
||||
|
||||
Scenario: Different measurement conditions
|
||||
Given the user is preparing to record an after-activity measurement
|
||||
When guidance is requested
|
||||
Then the guidance distinguishes it from a resting measurement
|
||||
And explains recording the actual conditions without relabelling the result as resting
|
||||
|
||||
Scenario: Pulse context
|
||||
When guidance for accompanying pulse is requested
|
||||
Then it explains recording the pulse value and relevant activity condition
|
||||
And does not describe the single pulse value as a rhythm assessment
|
||||
|
||||
Scenario: Guidance does not certify compliance
|
||||
Given an observation entry is being prepared
|
||||
When measurement guidance is viewed
|
||||
Then no observation is saved or altered
|
||||
And following the procedure is not recorded automatically
|
||||
|
||||
Scenario: Guidance is optional
|
||||
Given otherwise valid observation data is supplied
|
||||
And the patient has not viewed guidance
|
||||
When the observation is submitted
|
||||
Then creation succeeds
|
||||
|
||||
Scenario: Guidance unavailable
|
||||
Given no verified guidance is available for the requested setting
|
||||
When guidance for that setting is requested
|
||||
Then its unavailability is explained
|
||||
And unsupported instructions are not presented as verified guidance
|
||||
```
|
||||
|
||||
```gherkin
|
||||
Scenario: General guidance without login
|
||||
Given I am not authenticated
|
||||
When I request general measurement guidance
|
||||
Then the general guidance is available
|
||||
And no patient-specific information or assignment list is returned
|
||||
```
|
||||
@@ -0,0 +1,60 @@
|
||||
# Requirements reconciliation — 2026-10-04
|
||||
|
||||
## Result
|
||||
|
||||
The supplied Docs.zip was used as the source of truth. Requirements now have one current numbered file per story (US-01–US-15), plus one common-rules file. Compatible original scenarios and addendum criteria are retained; replaced clauses are listed below. The source ZIP was not edited in place.
|
||||
|
||||
Replace the old Docs directory with this corrected Docs directory rather than merely overlaying files: retired addenda and original aggregate requirements must not remain active beside the consolidated definitions. Retain the old version in version control.
|
||||
|
||||
## Review findings resolved
|
||||
|
||||
| Finding | Resolution |
|
||||
| --- | --- |
|
||||
| 1. Clinician exclusion | US-13 permits US-14 assigned read-only professional access and excludes unassigned access/professional writes. |
|
||||
| 2. Account cardinality | US-01/13 define zero then one profile; cover login without profile, initial association, duplicates, restart, concurrency and retry/recovery. US-14 retains predefined assignments. |
|
||||
| 3. Algorithm prerequisite | Removed the requirement for a prescribed preimplementation formula. US-11 permits selecting/developing and documenting methods with reproducibility and evidence constraints. |
|
||||
| 4. Absent v4 references | Removed v4/convention references. The operative full-period, temporal sufficiency, and endpoint limitations stand directly in US-11. |
|
||||
| 5. Latest ties | US-06 explicitly selects latest measurement time, then original recording time, then a documented deterministic final rule. No recording-order dependency for US-11. |
|
||||
| 6. Rounding | US-10 explicitly defines arithmetic means, two-decimal half-up final rounding, no intermediate rounding, extrema and single-observation results. Added exact fractional examples. No implementation was available to verify existing behaviour; this is the intended contract for implementation. |
|
||||
| 7. Periods | Common inclusive boundaries; equal bounds valid; reversed bounds rejected. Added parameterised criteria for every period-based operation. |
|
||||
| 8. Comparability | US-11 permits supported reference comparisons despite missing irrelevant optional details while explaining limits on stronger claims. |
|
||||
| 9. Guidance access | US-15 general guidance public; patient-specific data and assignments remain protected. Authentication design access table aligned. |
|
||||
|
||||
## Replaced clauses and baseline design
|
||||
|
||||
- US-13’s unconditional one-patient-per-account statement and blanket clinician exclusion are replaced by the lifecycle and role rules.
|
||||
- US-14’s instructions to patch US-13 are incorporated; they are no longer a separate competing replacement paragraph.
|
||||
- The US-11 preimplementation-formula note is removed. No unseen endpoint-only definition is treated as a source requirement.
|
||||
- “Existing” rounding and tie behaviour is now specified explicitly rather than assumed.
|
||||
- The US-11 ban on persisting generated assessments is moved to baseline Architecture. Functional freshness remains in requirements.
|
||||
- US_10_Correction is consolidated into the existing Architecture correction; its circular reference back into Requirements is removed.
|
||||
- The authentication design’s technology choices remain open. This reconciliation does not select JWT, token lifetime, association storage, or gateway-to-service controls.
|
||||
- Five editable draw.io diagrams update Observation classes/persistence, Insights classes/results, Overview classes and the no-persistence Insights model. `Architecture/README.md` identifies which JPEG snapshots they supersede. All original JPEG bytes are retained unchanged. Logical data shapes do not prescribe extra services or a specific physical storage mapping.
|
||||
|
||||
## Original-file mapping
|
||||
|
||||
All paths below are relative to Requirements unless stated otherwise. Retired files are replaced in the corrected copy, not retained as competing requirements.
|
||||
|
||||
| Supplied file | Current location |
|
||||
| --- | --- |
|
||||
| `us15-measurement-guidance.md` | `us15-measurement-guidance.md` |
|
||||
| `US_10_Correction` | `../Architecture/us10-insights-correction.md` |
|
||||
| `us06-latest-observation-context-addendum.md` | `us06-latest-observation.md` |
|
||||
| `us11-measurement-context-addendum.md` | `us11-health-trend.md` |
|
||||
| `us04-record-measurement-context-addendum.md` | `us04-record-observation.md` |
|
||||
| `us_13_Authentication_own_Data.md` | `us13-patient-authentication.md` |
|
||||
| `us08-update-measurement-context-addendum.md` | `us08-update-observation.md` |
|
||||
| `us07-filter-observation-history-context-addendum.md` | `us07-observation-history.md` |
|
||||
| `us12-overview-measurement-context-addendum.md` | `us12-health-overview.md` |
|
||||
| `personal_health_user_stories_and_acceptance_criteria.md` | `00-common-requirements.md and US-01–US-12 files` |
|
||||
| `us11-trend-stability-and-interpretation-addendum.md` | `us11-health-trend.md` |
|
||||
| `us10-context-selected-insights-addendum.md` | `us10-calculated-insight.md` |
|
||||
| `us05-view-measurement-context-addendum.md` | `us05-view-observation.md` |
|
||||
| `us09-delete-observation-context-addendum.md` | `us09-delete-observation.md` |
|
||||
| `us_14_Authentication_Healthcare_Professional_Data_Access.md` | `us14-professional-access.md` |
|
||||
|
||||
## Validation and limits
|
||||
|
||||
Checked editable draw.io XML structure and independently rendered shape-layout previews (the draw.io application was not available for an export check); checked story numbering, inclusion of all original scenario titles and all addendum criteria, local Markdown links, absent retired-reference dependencies, balanced Markdown fences, and byte preservation of supplied JPEGs. Added requirements scenarios do not constitute a passing application test suite; application source and AGENTS.md were not included.
|
||||
|
||||
The unapproved endpoint-only suggestion mentioned by the review is outside this archive. If still present in the repository, mark it superseded by the consolidated US-11; it must not govern implementation. No original suggestion file was deleted or modified here.
|
||||
@@ -0,0 +1,12 @@
|
||||
<Solution>
|
||||
<Folder Name="/src/">
|
||||
<Project Path="src/InsightsService/InsightsService.csproj" />
|
||||
<Project Path="src/ApiGateway/ApiGateway.csproj" />
|
||||
<Project Path="src/PatientProfileService/PatientProfileService.csproj" />
|
||||
<Project Path="src/ObservationService/ObservationService.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/tests/">
|
||||
<Project Path="tests/Observation.AcceptanceTests/Observation.AcceptanceTests.csproj" />
|
||||
<Project Path="tests/PatientProfile.AcceptanceTests/PatientProfile.AcceptanceTests.csproj" />
|
||||
</Folder>
|
||||
</Solution>
|
||||
@@ -0,0 +1,8 @@
|
||||
ASPNETCORE_ENVIRONMENT=Production
|
||||
Services__PatientProfile__BaseUrl=http://patient-profile.example.test:5081/
|
||||
ASPNETCORE_URLS=https://0.0.0.0:5443
|
||||
Kestrel__Certificates__Default__Path=/etc/healthapp/gateway.pfx
|
||||
Kestrel__Certificates__Default__Password=REPLACE_ME
|
||||
Services__Observation__BaseUrl=http://observation.example.test:5082/
|
||||
|
||||
Services__Insights__BaseUrl=http://insights.example.test:5083/
|
||||
@@ -0,0 +1,3 @@
|
||||
ASPNETCORE_ENVIRONMENT=Production
|
||||
ASPNETCORE_URLS=http://0.0.0.0:5083
|
||||
Services__ApiGateway__BaseUrl=https://gateway.example.test:5443/
|
||||
@@ -0,0 +1,4 @@
|
||||
ASPNETCORE_ENVIRONMENT=Production
|
||||
ASPNETCORE_URLS=http://0.0.0.0:5082
|
||||
ConnectionStrings__ObservationDatabase="Host=database.example.test;Port=5432;Database=observations;Username=observations;Password=REPLACE_ME"
|
||||
Services__ApiGateway__BaseUrl=https://gateway.example.test:5443/
|
||||
@@ -0,0 +1,3 @@
|
||||
ASPNETCORE_ENVIRONMENT=Production
|
||||
ASPNETCORE_URLS=http://0.0.0.0:5081
|
||||
ConnectionStrings__PatientDatabase="Host=database.example.test;Port=5432;Database=patient_profile;Username=patient_profile;Password=REPLACE_ME"
|
||||
@@ -0,0 +1,20 @@
|
||||
[Unit]
|
||||
Description=HealthApp API gateway
|
||||
Wants=network-online.target
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=healthapp
|
||||
Group=healthapp
|
||||
WorkingDirectory=/opt/healthapp/api-gateway
|
||||
ExecStart=/usr/bin/dotnet /opt/healthapp/api-gateway/ApiGateway.dll
|
||||
EnvironmentFile=/etc/healthapp/api-gateway.env
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
KillSignal=SIGINT
|
||||
TimeoutStopSec=30
|
||||
SyslogIdentifier=healthapp-api-gateway
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,20 @@
|
||||
[Unit]
|
||||
Description=HealthApp Insights service
|
||||
Wants=network-online.target
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=healthapp
|
||||
Group=healthapp
|
||||
WorkingDirectory=/opt/healthapp/insights
|
||||
ExecStart=/usr/bin/dotnet /opt/healthapp/insights/InsightsService.dll
|
||||
EnvironmentFile=/etc/healthapp/insights.env
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
KillSignal=SIGINT
|
||||
TimeoutStopSec=30
|
||||
SyslogIdentifier=healthapp-insights
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,20 @@
|
||||
[Unit]
|
||||
Description=HealthApp Observation service
|
||||
Wants=network-online.target
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=healthapp
|
||||
Group=healthapp
|
||||
WorkingDirectory=/opt/healthapp/observation
|
||||
ExecStart=/usr/bin/dotnet /opt/healthapp/observation/ObservationService.dll
|
||||
EnvironmentFile=/etc/healthapp/observation.env
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
KillSignal=SIGINT
|
||||
TimeoutStopSec=30
|
||||
SyslogIdentifier=healthapp-observation
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,20 @@
|
||||
[Unit]
|
||||
Description=HealthApp Patient/Profile service
|
||||
Wants=network-online.target
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=healthapp
|
||||
Group=healthapp
|
||||
WorkingDirectory=/opt/healthapp/patient-profile
|
||||
ExecStart=/usr/bin/dotnet /opt/healthapp/patient-profile/PatientProfileService.dll
|
||||
EnvironmentFile=/etc/healthapp/patient-profile.env
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
KillSignal=SIGINT
|
||||
TimeoutStopSec=30
|
||||
SyslogIdentifier=healthapp-patient-profile
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sdk": {
|
||||
"version": "10.0.100",
|
||||
"rollForward": "latestFeature"
|
||||
}
|
||||
}
|
||||
@@ -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,48 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace ApiGateway.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api")]
|
||||
public sealed class InsightsController(IHttpClientFactory clients) : ControllerBase
|
||||
{
|
||||
[HttpGet("patients/{patientId:guid}/insights")]
|
||||
public Task GetSummary(Guid patientId, CancellationToken cancellationToken) =>
|
||||
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/insights{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("Insights")
|
||||
.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: "Insights service is unavailable.")
|
||||
.ExecuteAsync(HttpContext);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace ApiGateway.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[AllowAnonymous]
|
||||
[Route("api/measurement-guidance")]
|
||||
public sealed class MeasurementGuidanceController : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
public IActionResult Get([FromQuery] string? setting, [FromQuery] string? activityCondition)
|
||||
{
|
||||
var requestedSetting = string.IsNullOrWhiteSpace(setting) ? "Unknown" : setting.Trim();
|
||||
var requestedActivity = string.IsNullOrWhiteSpace(activityCondition) ? "Unknown" : activityCondition.Trim();
|
||||
if (!new[] { "Home", "Clinic", "Other", "Unknown" }.Contains(requestedSetting, StringComparer.OrdinalIgnoreCase))
|
||||
return Problem(statusCode: 400, title: "Unsupported measurement setting.");
|
||||
if (!new[] { "AtRest", "DuringActivity", "AfterActivity", "Unknown" }.Contains(requestedActivity, StringComparer.OrdinalIgnoreCase))
|
||||
return Problem(statusCode: 400, title: "Unsupported activity condition.");
|
||||
|
||||
var available = requestedSetting.Equals("Home", StringComparison.OrdinalIgnoreCase)
|
||||
|| requestedSetting.Equals("Unknown", StringComparison.OrdinalIgnoreCase);
|
||||
return Ok(new
|
||||
{
|
||||
available,
|
||||
requestedSetting,
|
||||
requestedActivityCondition = requestedActivity,
|
||||
applicableSetting = available ? "Home" : null,
|
||||
applicableActivityCondition = available ? "AtRest" : null,
|
||||
reviewedOn = available ? "2026-10-04" : null,
|
||||
explanation = available
|
||||
? "These instructions apply to resting home self-measurement, not a clinical measurement protocol. Unknown conditions remain unknown; requesting guidance does not record a setting or certify compliance."
|
||||
: "Verified guidance is unavailable for the requested setting. Home instructions have not been substituted for clinical or other-setting instructions.",
|
||||
steps = available ? new[]
|
||||
{
|
||||
new GuidanceStep(1, "Equipment", "Use a validated upper-arm device with a cuff suited to your arm. Follow its instructions for placement and maintenance; incorrect cuff size can distort readings."),
|
||||
new GuidanceStep(2, "Preparation", "Choose a quiet place. Avoid smoking for 30 minutes beforehand and rest seated for five minutes."),
|
||||
new GuidanceStep(3, "Position", "Sit with back and arm supported and legs uncrossed. Put the cuff on bare skin, clear of tight clothing, and keep the arm relaxed and still during measurement."),
|
||||
new GuidanceStep(4, "Measure", "Use the device as instructed. Reproduce your setting, posture and preparation when possible to help later comparisons."),
|
||||
new GuidanceStep(5, "Planned monitoring", "The cited Danish home protocol uses three readings in the morning before breakfast and three in the evening before dinner, over three consecutive days. This planned series differs from saving one observation; follow individually supplied clinical instructions."),
|
||||
new GuidanceStep(6, "Record", "Save actual blood-pressure values in mmHg, device-reported pulse in beats/minute, and measurement time. Record setting, activity and preparation where known, including departures from routine. Do not discard, change or invent values to fit guidance.")
|
||||
} : Array.Empty<GuidanceStep>(),
|
||||
pulseExplanation = available
|
||||
? "Rest and activity affect the context of pulse readings. One device-reported pulse value does not assess rhythm regularity."
|
||||
: null,
|
||||
activityExplanation = available
|
||||
? "During-activity and after-activity measurements differ from resting measurements. Record the actual conditions; do not relabel them as resting. Such observations remain valid to record."
|
||||
: null,
|
||||
limitations = available
|
||||
? "Guidance does not guarantee accuracy or replace device or individual clinical instructions. It does not recommend medication changes. Viewing or declining it does not save or alter observations, certify a procedure, or prevent a valid submission."
|
||||
: null,
|
||||
sources = available ? new[]
|
||||
{
|
||||
new GuidanceSource("Sundhed.dk — Højt blodtryk", "https://www.sundhed.dk/sundhedsfaglig/laegehaandbogen/hjerte-kar/symptomer-og-tegn/hoejt-blodtryk/", "2024-09-25"),
|
||||
new GuidanceSource("Sundhed.dk — Blodtryksmåling", "https://www.sundhed.dk/sundhedsfaglig/laegehaandbogen/undersoegelser-og-proever/kliniske-procedurer/hjertekar/blodtryksmaaling/", "2025-03-13")
|
||||
} : Array.Empty<GuidanceSource>()
|
||||
});
|
||||
}
|
||||
|
||||
private sealed record GuidanceStep(int Order, string Topic, string Instruction);
|
||||
private sealed record GuidanceSource(string Title, string Url, string UpdatedOn);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace ApiGateway.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api")]
|
||||
public sealed class ObservationController(IHttpClientFactory clients) : ControllerBase
|
||||
{
|
||||
[HttpPost("patients/{patientId:guid}/observations")]
|
||||
public Task RecordObservation(Guid patientId, CancellationToken cancellationToken) =>
|
||||
ForwardAsync(HttpMethod.Post, $"api/patients/{patientId}/observations", cancellationToken);
|
||||
|
||||
[HttpDelete("observations/{observationId:guid}")]
|
||||
public Task DeleteObservation(Guid observationId, CancellationToken cancellationToken) =>
|
||||
ForwardAsync(HttpMethod.Delete, $"api/observations/{observationId}", cancellationToken);
|
||||
|
||||
[HttpPut("observations/{observationId:guid}")]
|
||||
public Task UpdateObservation(Guid observationId, CancellationToken cancellationToken) =>
|
||||
ForwardAsync(HttpMethod.Put, $"api/observations/{observationId}", cancellationToken);
|
||||
|
||||
[HttpGet("observations/{observationId:guid}")]
|
||||
public Task GetObservation(Guid observationId, CancellationToken cancellationToken) =>
|
||||
ForwardAsync(HttpMethod.Get, $"api/observations/{observationId}", cancellationToken);
|
||||
|
||||
[HttpGet("patients/{patientId:guid}/observations/latest")]
|
||||
public Task GetLatest(Guid patientId, CancellationToken cancellationToken) =>
|
||||
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/observations/latest", cancellationToken);
|
||||
|
||||
[HttpGet("patients/{patientId:guid}/observations")]
|
||||
public Task GetByPeriod(Guid patientId, CancellationToken cancellationToken) =>
|
||||
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/observations{Request.QueryString}", cancellationToken);
|
||||
|
||||
private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken)
|
||||
{
|
||||
using var request = new HttpRequestMessage(method, path);
|
||||
if (method == HttpMethod.Post || method == HttpMethod.Put)
|
||||
{
|
||||
request.Content = new StreamContent(Request.Body);
|
||||
if (Request.ContentType is not null)
|
||||
request.Content.Headers.TryAddWithoutValidation("Content-Type", Request.ContentType);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var upstream = await clients.CreateClient("Observation")
|
||||
.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: "Observation service is unavailable.")
|
||||
.ExecuteAsync(HttpContext);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace ApiGateway.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/patients")]
|
||||
public sealed class PatientController(IHttpClientFactory clients) : ControllerBase
|
||||
{
|
||||
[HttpPost]
|
||||
public Task CreatePatient(CancellationToken cancellationToken) =>
|
||||
ForwardAsync(HttpMethod.Post, "api/patients", cancellationToken);
|
||||
|
||||
[HttpGet("{patientId:guid}")]
|
||||
public Task GetPatient(Guid patientId, CancellationToken cancellationToken) =>
|
||||
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}", cancellationToken);
|
||||
|
||||
[HttpPut("{patientId:guid}")]
|
||||
public Task UpdatePatient(Guid patientId, CancellationToken cancellationToken) =>
|
||||
ForwardAsync(HttpMethod.Put, $"api/patients/{patientId}", cancellationToken);
|
||||
|
||||
private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken)
|
||||
{
|
||||
using var request = new HttpRequestMessage(method, path);
|
||||
if (method == HttpMethod.Post || method == HttpMethod.Put)
|
||||
{
|
||||
request.Content = new StreamContent(Request.Body);
|
||||
if (Request.ContentType is not null)
|
||||
request.Content.Headers.TryAddWithoutValidation("Content-Type", Request.ContentType);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var upstream = await clients.CreateClient("PatientProfile")
|
||||
.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: "Patient/Profile service is unavailable.")
|
||||
.ExecuteAsync(HttpContext);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
namespace ApiGateway;
|
||||
|
||||
public class Program
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddProblemDetails();
|
||||
builder.Services.AddHttpClient("PatientProfile", (services, client) =>
|
||||
client.BaseAddress = GetBaseUri(services.GetRequiredService<IConfiguration>(), "PatientProfile"))
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
|
||||
builder.Services.AddHttpClient("Observation", (services, client) =>
|
||||
client.BaseAddress = GetBaseUri(services.GetRequiredService<IConfiguration>(), "Observation"))
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
|
||||
builder.Services.AddHttpClient("Insights", (services, client) =>
|
||||
client.BaseAddress = GetBaseUri(services.GetRequiredService<IConfiguration>(), "Insights"))
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
|
||||
var app = builder.Build();
|
||||
_ = GetBaseUri(app.Configuration, "PatientProfile");
|
||||
_ = GetBaseUri(app.Configuration, "Observation");
|
||||
_ = GetBaseUri(app.Configuration, "Insights");
|
||||
app.UseExceptionHandler();
|
||||
app.MapControllers();
|
||||
app.Run();
|
||||
}
|
||||
|
||||
private static Uri GetBaseUri(IConfiguration configuration, string service)
|
||||
{
|
||||
var endpoint = configuration[$"Services:{service}:BaseUrl"];
|
||||
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var baseUri) ||
|
||||
(baseUri.Scheme != "http" && baseUri.Scheme != "https") ||
|
||||
baseUri.AbsolutePath != "/" || !string.IsNullOrEmpty(baseUri.Query) ||
|
||||
!string.IsNullOrEmpty(baseUri.Fragment) || !string.IsNullOrEmpty(baseUri.UserInfo))
|
||||
throw new InvalidOperationException($"Services:{service}:BaseUrl must be an HTTP(S) origin URL.");
|
||||
return baseUri;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using InsightsService.Clients;
|
||||
using InsightsService.Domain;
|
||||
|
||||
namespace InsightsService.Application;
|
||||
|
||||
public sealed class InsightsApplicationService(ObservationServiceClient observations, InsightCalculator calculator)
|
||||
{
|
||||
public async Task<HealthInsight?> GetSummaryAsync(Guid patientId, DateTime from, DateTime to,
|
||||
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));
|
||||
var history = await observations.GetByPeriodAsync(patientId, from, to, cancellationToken);
|
||||
return calculator.CalculateSummary(patientId, from, to, history);
|
||||
}
|
||||
|
||||
private static DateTime NormalizeTimestamp(DateTime value) =>
|
||||
DateTime.SpecifyKind(value.Kind == DateTimeKind.Unspecified ? value : value.ToUniversalTime(),
|
||||
DateTimeKind.Unspecified);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using System.Globalization;
|
||||
using InsightsService.Contracts;
|
||||
|
||||
namespace InsightsService.Clients;
|
||||
|
||||
public sealed class HttpObservationServiceClient(HttpClient client) : ObservationServiceClient
|
||||
{
|
||||
public async Task<List<ObservationDto>> GetByPeriodAsync(Guid patientId, DateTime from, DateTime to,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var start = Uri.EscapeDataString(from.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}",
|
||||
HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
||||
response.EnsureSuccessStatusCode();
|
||||
return await response.Content.ReadFromJsonAsync<List<ObservationDto>>(cancellationToken)
|
||||
?? throw new HttpRequestException("Observation history response was empty.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using InsightsService.Contracts;
|
||||
|
||||
namespace InsightsService.Clients;
|
||||
|
||||
public interface ObservationServiceClient
|
||||
{
|
||||
Task<List<ObservationDto>> GetByPeriodAsync(Guid patientId, DateTime from, DateTime to,
|
||||
CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
namespace InsightsService.Contracts;
|
||||
|
||||
public sealed record HealthInsightDto(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
|
||||
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
|
||||
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic);
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace InsightsService.Contracts;
|
||||
|
||||
public sealed record ObservationDto(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||
int Systolic, int Diastolic, int Pulse);
|
||||
@@ -0,0 +1,44 @@
|
||||
using InsightsService.Application;
|
||||
using InsightsService.Contracts;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
|
||||
namespace InsightsService.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/patients/{patientId:guid}/insights")]
|
||||
public sealed class InsightsController(InsightsApplicationService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<ActionResult<HealthInsightDto>> GetSummary(Guid patientId,
|
||||
[FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var insight = await service.GetSummaryAsync(patientId, from, to, cancellationToken);
|
||||
return insight is null
|
||||
? Problem(statusCode: StatusCodes.Status404NotFound, title: "Insufficient observation data for calculation.")
|
||||
: Ok(new HealthInsightDto(insight.PatientId, insight.PeriodStart, insight.PeriodEnd,
|
||||
insight.AverageSystolic, insight.AverageDiastolic, insight.AveragePulse,
|
||||
insight.MinSystolic, insight.MaxSystolic, insight.MinDiastolic, insight.MaxDiastolic));
|
||||
}
|
||||
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,5 @@
|
||||
namespace InsightsService.Domain;
|
||||
|
||||
public sealed record HealthInsight(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
|
||||
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
|
||||
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic);
|
||||
@@ -0,0 +1,17 @@
|
||||
using InsightsService.Contracts;
|
||||
|
||||
namespace InsightsService.Domain;
|
||||
|
||||
public sealed class InsightCalculator
|
||||
{
|
||||
public HealthInsight? CalculateSummary(Guid patientId, DateTime from, DateTime to,
|
||||
IReadOnlyList<ObservationDto> observations)
|
||||
{
|
||||
if (observations.Count == 0)
|
||||
return null;
|
||||
return new HealthInsight(patientId, from, to,
|
||||
observations.Average(o => (decimal)o.Systolic), observations.Average(o => (decimal)o.Diastolic),
|
||||
observations.Average(o => (decimal)o.Pulse), observations.Min(o => o.Systolic),
|
||||
observations.Max(o => o.Systolic), observations.Min(o => o.Diastolic), observations.Max(o => o.Diastolic));
|
||||
}
|
||||
}
|
||||
@@ -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,35 @@
|
||||
using InsightsService.Application;
|
||||
using InsightsService.Clients;
|
||||
using InsightsService.Domain;
|
||||
|
||||
namespace InsightsService;
|
||||
|
||||
public class Program
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddProblemDetails();
|
||||
builder.Services.AddScoped<InsightsApplicationService>();
|
||||
builder.Services.AddSingleton<InsightCalculator>();
|
||||
builder.Services.AddHttpClient<ObservationServiceClient, HttpObservationServiceClient>((services, client) =>
|
||||
client.BaseAddress = GetGatewayUri(services.GetRequiredService<IConfiguration>()))
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
var app = builder.Build();
|
||||
_ = GetGatewayUri(app.Configuration);
|
||||
app.UseExceptionHandler();
|
||||
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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using System.Net;
|
||||
using ObservationService.Contracts;
|
||||
using ObservationService.Domain;
|
||||
|
||||
namespace ObservationService.Application;
|
||||
|
||||
public sealed class ObservationApplicationService(ObservationRepository repository, IHttpClientFactory clients)
|
||||
{
|
||||
public Task<bool> DeleteAsync(Guid observationId, CancellationToken cancellationToken) =>
|
||||
repository.DeleteAsync(observationId, cancellationToken);
|
||||
|
||||
public Task<BloodPressureObservation?> UpdateAsync(Guid observationId, UpdateObservationRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (request.Systolic is null or <= 0 || request.Diastolic is null or <= 0 || request.Pulse is null or <= 0)
|
||||
throw new ArgumentException("Positive measured values are required.", nameof(request));
|
||||
|
||||
return repository.UpdateValuesAsync(observationId, request.Systolic.Value, request.Diastolic.Value,
|
||||
request.Pulse.Value, DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified), cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<BloodPressureObservation?> RecordAsync(Guid patientId, RecordObservationRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (request.MeasuredAt is null || request.Systolic 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));
|
||||
|
||||
using var patient = await clients.CreateClient("ApiGateway").GetAsync($"api/patients/{patientId}",
|
||||
HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
||||
if (patient.StatusCode == HttpStatusCode.NotFound)
|
||||
return null;
|
||||
// Upstream failures must never be interpreted as an existing patient.
|
||||
patient.EnsureSuccessStatusCode();
|
||||
|
||||
var now = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);
|
||||
var measuredAt = request.MeasuredAt.Value;
|
||||
if (measuredAt.Kind != DateTimeKind.Unspecified)
|
||||
measuredAt = measuredAt.ToUniversalTime();
|
||||
|
||||
return await repository.SaveAsync(new BloodPressureObservation
|
||||
{
|
||||
ObservationId = Guid.NewGuid(), PatientId = patientId,
|
||||
MeasuredAt = DateTime.SpecifyKind(measuredAt, DateTimeKind.Unspecified),
|
||||
Systolic = request.Systolic.Value, Diastolic = request.Diastolic.Value,
|
||||
Pulse = request.Pulse.Value, Context = request.Context, Note = request.Note,
|
||||
CreatedAt = now, UpdatedAt = now
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
public Task<BloodPressureObservation?> GetByIdAsync(Guid observationId, CancellationToken cancellationToken) =>
|
||||
repository.FindByIdAsync(observationId, cancellationToken);
|
||||
|
||||
public Task<BloodPressureObservation?> GetLatestAsync(Guid patientId, CancellationToken cancellationToken) =>
|
||||
repository.FindLatestByPatientIdAsync(patientId, cancellationToken);
|
||||
|
||||
public Task<List<BloodPressureObservation>> GetByPeriodAsync(Guid patientId, DateTime from, DateTime to,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
from = NormalizeTimestamp(from);
|
||||
to = NormalizeTimestamp(to);
|
||||
if (to < from)
|
||||
throw new ArgumentException("The end time must not be earlier than the start time.", nameof(to));
|
||||
return repository.FindByPatientIdAndPeriodAsync(patientId, from, to, cancellationToken);
|
||||
}
|
||||
|
||||
private static DateTime NormalizeTimestamp(DateTime timestamp) =>
|
||||
DateTime.SpecifyKind(timestamp.Kind == DateTimeKind.Unspecified ? timestamp : timestamp.ToUniversalTime(),
|
||||
DateTimeKind.Unspecified);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using ObservationService.Domain;
|
||||
|
||||
namespace ObservationService.Application;
|
||||
|
||||
public interface ObservationRepository
|
||||
{
|
||||
Task<bool> DeleteAsync(Guid observationId, CancellationToken cancellationToken);
|
||||
Task<BloodPressureObservation?> UpdateValuesAsync(Guid observationId, int systolic, int diastolic, int pulse,
|
||||
DateTime updatedAt, CancellationToken cancellationToken);
|
||||
Task<BloodPressureObservation> SaveAsync(BloodPressureObservation observation, CancellationToken cancellationToken);
|
||||
Task<BloodPressureObservation?> FindByIdAsync(Guid observationId, CancellationToken cancellationToken);
|
||||
Task<BloodPressureObservation?> FindLatestByPatientIdAsync(Guid patientId, CancellationToken cancellationToken);
|
||||
Task<List<BloodPressureObservation>> FindByPatientIdAndPeriodAsync(Guid patientId, DateTime from, DateTime to,
|
||||
CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace ObservationService.Contracts;
|
||||
|
||||
public sealed record ObservationDto(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||
int Systolic, int Diastolic, int Pulse, string? Context, string? Note);
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace ObservationService.Contracts;
|
||||
|
||||
public sealed record RecordObservationRequest
|
||||
{
|
||||
[Required]
|
||||
public DateTime? MeasuredAt { get; init; }
|
||||
|
||||
[Required, Range(1, int.MaxValue)]
|
||||
public int? Systolic { get; init; }
|
||||
|
||||
[Required, Range(1, int.MaxValue)]
|
||||
public int? Diastolic { get; init; }
|
||||
|
||||
[Required, Range(1, int.MaxValue)]
|
||||
public int? Pulse { get; init; }
|
||||
|
||||
public string? Context { get; init; }
|
||||
public string? Note { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace ObservationService.Contracts;
|
||||
|
||||
public sealed record UpdateObservationRequest
|
||||
{
|
||||
[Required, Range(1, int.MaxValue)]
|
||||
public int? Systolic { get; init; }
|
||||
|
||||
[Required, Range(1, int.MaxValue)]
|
||||
public int? Diastolic { get; init; }
|
||||
|
||||
[Required, Range(1, int.MaxValue)]
|
||||
public int? Pulse { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
using ObservationService.Application;
|
||||
using ObservationService.Contracts;
|
||||
using ObservationService.Domain;
|
||||
|
||||
namespace ObservationService.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api")]
|
||||
public sealed class ObservationController(ObservationApplicationService service) : ControllerBase
|
||||
{
|
||||
[HttpPost("patients/{patientId:guid}/observations")]
|
||||
public async Task<ActionResult<ObservationDto>> RecordObservation(Guid patientId, RecordObservationRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var observation = await service.RecordAsync(patientId, request, cancellationToken);
|
||||
return observation is null
|
||||
? NotFound()
|
||||
: CreatedAtAction(nameof(GetObservation), new { observationId = observation.ObservationId }, ToDto(observation));
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
return Problem(statusCode: StatusCodes.Status502BadGateway, title: "Patient lookup is unavailable.");
|
||||
}
|
||||
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
return Problem(statusCode: StatusCodes.Status504GatewayTimeout, title: "Patient lookup timed out.");
|
||||
}
|
||||
}
|
||||
|
||||
[HttpDelete("observations/{observationId:guid}")]
|
||||
public async Task<IActionResult> DeleteObservation(Guid observationId, CancellationToken cancellationToken) =>
|
||||
await service.DeleteAsync(observationId, cancellationToken) ? NoContent() : NotFound();
|
||||
|
||||
[HttpPut("observations/{observationId:guid}")]
|
||||
public async Task<ActionResult<ObservationDto>> UpdateObservation(Guid observationId, UpdateObservationRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var observation = await service.UpdateAsync(observationId, request, cancellationToken);
|
||||
return observation is null ? NotFound() : Ok(ToDto(observation));
|
||||
}
|
||||
|
||||
[HttpGet("observations/{observationId:guid}")]
|
||||
public async Task<ActionResult<ObservationDto>> GetObservation(Guid observationId, CancellationToken cancellationToken)
|
||||
{
|
||||
var observation = await service.GetByIdAsync(observationId, cancellationToken);
|
||||
return observation is null ? NotFound() : Ok(ToDto(observation));
|
||||
}
|
||||
|
||||
[HttpGet("patients/{patientId:guid}/observations/latest")]
|
||||
public async Task<ActionResult<ObservationDto>> GetLatest(Guid patientId, CancellationToken cancellationToken)
|
||||
{
|
||||
var observation = await service.GetLatestAsync(patientId, cancellationToken);
|
||||
return observation is null ? NotFound() : Ok(ToDto(observation));
|
||||
}
|
||||
|
||||
[HttpGet("patients/{patientId:guid}/observations")]
|
||||
public async Task<ActionResult<List<ObservationDto>>> GetByPeriod(Guid patientId,
|
||||
[FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var observations = await service.GetByPeriodAsync(patientId, from, to, cancellationToken);
|
||||
return Ok(observations.Select(ToDto).ToList());
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
ModelState.AddModelError(nameof(to), "The end time must not be earlier than the start time.");
|
||||
return ValidationProblem(ModelState);
|
||||
}
|
||||
}
|
||||
|
||||
private static ObservationDto ToDto(BloodPressureObservation observation) =>
|
||||
new(observation.ObservationId, observation.PatientId, observation.MeasuredAt, observation.Systolic,
|
||||
observation.Diastolic, observation.Pulse, observation.Context, observation.Note);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace ObservationService.Domain;
|
||||
|
||||
public sealed class BloodPressureObservation
|
||||
{
|
||||
public Guid ObservationId { get; set; }
|
||||
public Guid PatientId { get; set; }
|
||||
public DateTime MeasuredAt { get; set; }
|
||||
public int Systolic { get; set; }
|
||||
public int Diastolic { get; set; }
|
||||
public int Pulse { get; set; }
|
||||
public string? Context { get; set; }
|
||||
public string? Note { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime UpdatedAt { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.12" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.12" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
Generated
+77
@@ -0,0 +1,77 @@
|
||||
// <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("20261001095222_InitialObservationSchema")]
|
||||
partial class InitialObservationSchema
|
||||
{
|
||||
/// <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);
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace ObservationService.Persistence.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class InitialObservationSchema : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "blood_pressure_observation",
|
||||
columns: table => new
|
||||
{
|
||||
observation_id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
patient_id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
measured_at = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
|
||||
systolic = table.Column<int>(type: "integer", nullable: false),
|
||||
diastolic = table.Column<int>(type: "integer", nullable: false),
|
||||
pulse = table.Column<int>(type: "integer", nullable: false),
|
||||
context = table.Column<string>(type: "character varying", nullable: true),
|
||||
note = table.Column<string>(type: "character varying", nullable: true),
|
||||
created_at = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
|
||||
updated_at = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_blood_pressure_observation", x => x.observation_id);
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "blood_pressure_observation");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
using ObservationService.Persistence;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace ObservationService.Persistence.Migrations
|
||||
{
|
||||
[DbContext(typeof(ObservationDbContext))]
|
||||
partial class ObservationDbContextModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(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);
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using ObservationService.Domain;
|
||||
|
||||
namespace ObservationService.Persistence;
|
||||
|
||||
public sealed class ObservationDbContext(DbContextOptions<ObservationDbContext> options) : DbContext(options)
|
||||
{
|
||||
public DbSet<BloodPressureObservation> Observations => Set<BloodPressureObservation>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
var observation = modelBuilder.Entity<BloodPressureObservation>();
|
||||
observation.ToTable("blood_pressure_observation");
|
||||
observation.HasKey(o => o.ObservationId);
|
||||
observation.Property(o => o.ObservationId).HasColumnName("observation_id").ValueGeneratedNever();
|
||||
// An external patient identifier, not a cross-database foreign key.
|
||||
observation.Property(o => o.PatientId).HasColumnName("patient_id");
|
||||
observation.Property(o => o.MeasuredAt).HasColumnName("measured_at").HasColumnType("timestamp without time zone");
|
||||
observation.Property(o => o.Systolic).HasColumnName("systolic");
|
||||
observation.Property(o => o.Diastolic).HasColumnName("diastolic");
|
||||
observation.Property(o => o.Pulse).HasColumnName("pulse");
|
||||
observation.Property(o => o.Context).HasColumnName("context").HasColumnType("character varying");
|
||||
observation.Property(o => o.Note).HasColumnName("note").HasColumnType("character varying");
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using ObservationService.Application;
|
||||
using ObservationService.Domain;
|
||||
|
||||
namespace ObservationService.Persistence;
|
||||
|
||||
public sealed class SqlObservationRepository(ObservationDbContext db) : ObservationRepository
|
||||
{
|
||||
public async Task<bool> DeleteAsync(Guid observationId, CancellationToken cancellationToken) =>
|
||||
await db.Observations.Where(o => o.ObservationId == observationId)
|
||||
.ExecuteDeleteAsync(cancellationToken) > 0;
|
||||
|
||||
public async Task<BloodPressureObservation?> UpdateValuesAsync(Guid observationId, int systolic, int diastolic,
|
||||
int pulse, DateTime updatedAt, CancellationToken cancellationToken)
|
||||
{
|
||||
var observation = await db.Observations.SingleOrDefaultAsync(o => o.ObservationId == observationId,
|
||||
cancellationToken);
|
||||
if (observation is null)
|
||||
return null;
|
||||
|
||||
observation.Systolic = systolic;
|
||||
observation.Diastolic = diastolic;
|
||||
observation.Pulse = pulse;
|
||||
observation.UpdatedAt = updatedAt;
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
return observation;
|
||||
}
|
||||
|
||||
public async Task<BloodPressureObservation> SaveAsync(BloodPressureObservation observation, CancellationToken cancellationToken)
|
||||
{
|
||||
db.Observations.Add(observation);
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
return observation;
|
||||
}
|
||||
|
||||
public Task<BloodPressureObservation?> FindByIdAsync(Guid observationId, CancellationToken cancellationToken) =>
|
||||
db.Observations.AsNoTracking().SingleOrDefaultAsync(o => o.ObservationId == observationId, cancellationToken);
|
||||
|
||||
public Task<BloodPressureObservation?> FindLatestByPatientIdAsync(Guid patientId, CancellationToken cancellationToken) =>
|
||||
db.Observations.AsNoTracking().Where(o => o.PatientId == patientId)
|
||||
.OrderByDescending(o => o.MeasuredAt).ThenByDescending(o => o.ObservationId)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
public Task<List<BloodPressureObservation>> FindByPatientIdAndPeriodAsync(Guid patientId, DateTime from, DateTime to,
|
||||
CancellationToken cancellationToken) =>
|
||||
db.Observations.AsNoTracking()
|
||||
.Where(o => o.PatientId == patientId && o.MeasuredAt >= from && o.MeasuredAt <= to)
|
||||
.OrderBy(o => o.MeasuredAt).ThenBy(o => o.ObservationId).ToListAsync(cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using ObservationService.Application;
|
||||
using ObservationService.Persistence;
|
||||
|
||||
namespace ObservationService;
|
||||
|
||||
public class Program
|
||||
{
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddProblemDetails();
|
||||
builder.Services.AddDbContext<ObservationDbContext>((services, options) =>
|
||||
options.UseNpgsql(services.GetRequiredService<IConfiguration>().GetConnectionString("ObservationDatabase")));
|
||||
builder.Services.AddScoped<ObservationRepository, SqlObservationRepository>();
|
||||
builder.Services.AddScoped<ObservationApplicationService>();
|
||||
builder.Services.AddHttpClient("ApiGateway", (services, client) =>
|
||||
client.BaseAddress = GetGatewayUri(services.GetRequiredService<IConfiguration>()))
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
|
||||
var app = builder.Build();
|
||||
if (string.IsNullOrWhiteSpace(app.Configuration.GetConnectionString("ObservationDatabase")))
|
||||
throw new InvalidOperationException("ConnectionStrings:ObservationDatabase must be configured.");
|
||||
|
||||
if (args.Contains("--migrate"))
|
||||
{
|
||||
await using var scope = app.Services.CreateAsyncScope();
|
||||
await scope.ServiceProvider.GetRequiredService<ObservationDbContext>().Database.MigrateAsync();
|
||||
return;
|
||||
}
|
||||
|
||||
_ = GetGatewayUri(app.Configuration);
|
||||
app.UseExceptionHandler();
|
||||
app.MapControllers();
|
||||
await app.RunAsync();
|
||||
}
|
||||
|
||||
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,9 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning",
|
||||
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using PatientProfileService.Contracts;
|
||||
using PatientProfileService.Domain;
|
||||
|
||||
namespace PatientProfileService.Application;
|
||||
|
||||
public sealed class PatientApplicationService(PatientRepository repository)
|
||||
{
|
||||
public Task<Patient> CreatePatientAsync(CreatePatientRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(request.Name);
|
||||
if (request.DateOfBirth is null)
|
||||
throw new ArgumentException("A date of birth is required.", nameof(request));
|
||||
|
||||
// The documented TIMESTAMP columns store UTC without a time-zone component.
|
||||
var now = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);
|
||||
return repository.SaveAsync(new Patient
|
||||
{
|
||||
PatientId = Guid.NewGuid(),
|
||||
Name = request.Name,
|
||||
DateOfBirth = request.DateOfBirth.Value,
|
||||
ContactInfo = request.ContactInfo,
|
||||
CreatedAt = now,
|
||||
UpdatedAt = now
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
public Task<Patient?> GetPatientAsync(Guid patientId, CancellationToken cancellationToken) =>
|
||||
repository.FindByIdAsync(patientId, cancellationToken);
|
||||
|
||||
public async Task<Patient?> UpdatePatientAsync(Guid patientId, UpdatePatientRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(request.Name);
|
||||
if (!await repository.UpdateProfileAsync(patientId, request.Name, request.ContactInfo, cancellationToken))
|
||||
return null;
|
||||
|
||||
return await repository.FindByIdAsync(patientId, cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using PatientProfileService.Domain;
|
||||
|
||||
namespace PatientProfileService.Application;
|
||||
|
||||
public interface PatientRepository
|
||||
{
|
||||
Task<Patient> SaveAsync(Patient patient, CancellationToken cancellationToken);
|
||||
Task<Patient?> FindByIdAsync(Guid patientId, CancellationToken cancellationToken);
|
||||
Task<bool> UpdateProfileAsync(Guid patientId, string name, string? contactInfo, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace PatientProfileService.Contracts;
|
||||
|
||||
public sealed record CreatePatientRequest
|
||||
{
|
||||
[Required]
|
||||
public string? Name { get; init; }
|
||||
|
||||
[Required]
|
||||
public DateOnly? DateOfBirth { get; init; }
|
||||
|
||||
public string? ContactInfo { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace PatientProfileService.Contracts;
|
||||
|
||||
public sealed record PatientDto(Guid PatientId, string Name, DateOnly DateOfBirth, string? ContactInfo);
|
||||
@@ -0,0 +1,11 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace PatientProfileService.Contracts;
|
||||
|
||||
public sealed record UpdatePatientRequest
|
||||
{
|
||||
[Required]
|
||||
public string? Name { get; init; }
|
||||
|
||||
public string? ContactInfo { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using PatientProfileService.Application;
|
||||
using PatientProfileService.Contracts;
|
||||
using PatientProfileService.Domain;
|
||||
|
||||
namespace PatientProfileService.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/patients")]
|
||||
public sealed class PatientController(PatientApplicationService service) : ControllerBase
|
||||
{
|
||||
[HttpPost]
|
||||
public async Task<ActionResult<PatientDto>> CreatePatient(CreatePatientRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var patient = await service.CreatePatientAsync(request, cancellationToken);
|
||||
return CreatedAtAction(nameof(GetPatient), new { patientId = patient.PatientId }, ToDto(patient));
|
||||
}
|
||||
|
||||
[HttpGet("{patientId:guid}")]
|
||||
public async Task<ActionResult<PatientDto>> GetPatient(Guid patientId, CancellationToken cancellationToken)
|
||||
{
|
||||
var patient = await service.GetPatientAsync(patientId, cancellationToken);
|
||||
return patient is null ? NotFound() : Ok(ToDto(patient));
|
||||
}
|
||||
|
||||
[HttpPut("{patientId:guid}")]
|
||||
public async Task<ActionResult<PatientDto>> UpdatePatient(Guid patientId, UpdatePatientRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var patient = await service.UpdatePatientAsync(patientId, request, cancellationToken);
|
||||
return patient is null ? NotFound() : Ok(ToDto(patient));
|
||||
}
|
||||
|
||||
private static PatientDto ToDto(Patient patient) =>
|
||||
new(patient.PatientId, patient.Name, patient.DateOfBirth, patient.ContactInfo);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace PatientProfileService.Domain;
|
||||
|
||||
public sealed class Patient
|
||||
{
|
||||
public Guid PatientId { get; set; }
|
||||
public string Name { get; set; } = "";
|
||||
public DateOnly DateOfBirth { get; set; }
|
||||
public string? ContactInfo { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime UpdatedAt { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.12" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.12" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
Generated
+62
@@ -0,0 +1,62 @@
|
||||
// <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("20260930200031_InitialPatientSchema")]
|
||||
partial class InitialPatientSchema
|
||||
{
|
||||
/// <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>("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.ToTable("patient", (string)null);
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace PatientProfileService.Persistence.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class InitialPatientSchema : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "patient",
|
||||
columns: table => new
|
||||
{
|
||||
patient_id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
name = table.Column<string>(type: "character varying", nullable: false),
|
||||
date_of_birth = table.Column<DateOnly>(type: "date", nullable: false),
|
||||
contact_info = table.Column<string>(type: "character varying", nullable: true),
|
||||
created_at = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
|
||||
updated_at = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_patient", x => x.patient_id);
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "patient");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
using PatientProfileService.Persistence;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace PatientProfileService.Persistence.Migrations
|
||||
{
|
||||
[DbContext(typeof(PatientDbContext))]
|
||||
partial class PatientDbContextModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(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>("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.ToTable("patient", (string)null);
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PatientProfileService.Domain;
|
||||
|
||||
namespace PatientProfileService.Persistence;
|
||||
|
||||
public sealed class PatientDbContext(DbContextOptions<PatientDbContext> options) : DbContext(options)
|
||||
{
|
||||
public DbSet<Patient> Patients => Set<Patient>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
var patient = modelBuilder.Entity<Patient>();
|
||||
patient.ToTable("patient");
|
||||
patient.HasKey(p => p.PatientId);
|
||||
patient.Property(p => p.PatientId).HasColumnName("patient_id").ValueGeneratedNever();
|
||||
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.ContactInfo).HasColumnName("contact_info").HasColumnType("character varying");
|
||||
patient.Property(p => p.CreatedAt).HasColumnName("created_at").HasColumnType("timestamp without time zone");
|
||||
patient.Property(p => p.UpdatedAt).HasColumnName("updated_at").HasColumnType("timestamp without time zone");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PatientProfileService.Application;
|
||||
using PatientProfileService.Domain;
|
||||
|
||||
namespace PatientProfileService.Persistence;
|
||||
|
||||
public sealed class SqlPatientRepository(PatientDbContext db) : PatientRepository
|
||||
{
|
||||
public async Task<Patient> SaveAsync(Patient patient, CancellationToken cancellationToken)
|
||||
{
|
||||
db.Patients.Add(patient);
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
return patient;
|
||||
}
|
||||
|
||||
public Task<Patient?> FindByIdAsync(Guid patientId, CancellationToken cancellationToken) =>
|
||||
db.Patients.AsNoTracking().SingleOrDefaultAsync(p => p.PatientId == patientId, cancellationToken);
|
||||
|
||||
public async Task<bool> UpdateProfileAsync(Guid patientId, string name, string? contactInfo, CancellationToken cancellationToken)
|
||||
{
|
||||
var now = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);
|
||||
var affected = await db.Patients.Where(p => p.PatientId == patientId)
|
||||
.ExecuteUpdateAsync(update => update
|
||||
.SetProperty(p => p.Name, name)
|
||||
.SetProperty(p => p.ContactInfo, contactInfo)
|
||||
.SetProperty(p => p.UpdatedAt, now), cancellationToken);
|
||||
return affected != 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PatientProfileService.Application;
|
||||
using PatientProfileService.Persistence;
|
||||
|
||||
namespace PatientProfileService;
|
||||
|
||||
public class Program
|
||||
{
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddProblemDetails();
|
||||
builder.Services.AddDbContext<PatientDbContext>((services, options) =>
|
||||
options.UseNpgsql(services.GetRequiredService<IConfiguration>().GetConnectionString("PatientDatabase")));
|
||||
builder.Services.AddScoped<PatientRepository, SqlPatientRepository>();
|
||||
builder.Services.AddScoped<PatientApplicationService>();
|
||||
|
||||
var app = builder.Build();
|
||||
if (string.IsNullOrWhiteSpace(app.Configuration.GetConnectionString("PatientDatabase")))
|
||||
throw new InvalidOperationException("ConnectionStrings:PatientDatabase must be configured.");
|
||||
|
||||
if (args.Contains("--migrate"))
|
||||
{
|
||||
await using var scope = app.Services.CreateAsyncScope();
|
||||
await scope.ServiceProvider.GetRequiredService<PatientDbContext>().Database.MigrateAsync();
|
||||
return;
|
||||
}
|
||||
|
||||
app.UseExceptionHandler();
|
||||
app.MapControllers();
|
||||
await app.RunAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning",
|
||||
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
# US-01–US-10: Patient profiles and blood-pressure observations
|
||||
|
||||
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`.
|
||||
|
||||
The controller calls `PatientApplicationService`, which uses `PatientRepository`, implemented by `SqlPatientRepository`. The service owns the `patient` table from the ER diagram, including creation/update timestamps stored as UTC in PostgreSQL `timestamp` columns.
|
||||
|
||||
## Build and run
|
||||
|
||||
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
|
||||
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/ 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
|
||||
```
|
||||
|
||||
`--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:
|
||||
|
||||
```bash
|
||||
curl -i http://127.0.0.1:5080/api/patients \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"name":"Steffen Example","dateOfBirth":"1980-01-01","contactInfo":"steffen@example.test"}'
|
||||
```
|
||||
|
||||
`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 `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.
|
||||
|
||||
`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.
|
||||
|
||||
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.
|
||||
|
||||
`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.
|
||||
|
||||
`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.
|
||||
|
||||
`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.
|
||||
|
||||
`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`.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
## 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.
|
||||
|
||||
```bash
|
||||
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 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.
|
||||
|
||||
Dependencies: Npgsql's EF Core PostgreSQL provider supplies persistence; EF Core Relational is pinned to the same patch as EF Core Design to keep runtime/tooling versions aligned; EF Core Design supports migration maintenance. xUnit, its Visual Studio runner, Microsoft.NET.Test.Sdk, and ASP.NET Core MVC Testing are used only for automated tests. The gateway uses the platform's HttpClient and has no extra package dependency.
|
||||
|
||||
## Linux deployment
|
||||
|
||||
Publish each service separately:
|
||||
|
||||
```bash
|
||||
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
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```bash
|
||||
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.
|
||||
@@ -0,0 +1,5 @@
|
||||
# API gateway authentication policy
|
||||
|
||||
The architecture assigns authentication and authorization to the API gateway, but the requirements do not define credentials, an identity provider, patient ownership, or which operations require authentication.
|
||||
|
||||
US-01 is implemented without inventing access restrictions. Before implementing authentication, specify the identity mechanism, patient ownership relationship, and access policy for the existing API operations. This suggestion does not authorize an implementation or change the current requirements.
|
||||
@@ -0,0 +1,54 @@
|
||||
# Replaceable prototype authentication
|
||||
|
||||
## Status and purpose
|
||||
|
||||
Proposed design for US-13 and US-14, pending review. This suggestion does not authorize implementation or modify the authoritative requirements or architecture.
|
||||
|
||||
Use a simple authentication placeholder for the thesis prototype while making it straightforward to replace with a proper identity provider. Keep the ownership and access rules defined by US-13 and US-14 independent of how credentials are validated.
|
||||
|
||||
## Responsibility and replacement point
|
||||
|
||||
Authentication and authorization remain responsibilities of the API gateway, as shown in `Docs/Architecture/02_microservice_architecture.jpg`.
|
||||
|
||||
Use ASP.NET Core's standard authentication handlers, authenticated identities (`ClaimsPrincipal`), and authorization policies. Implement one small prototype authentication handler at the gateway. Avoid a custom authentication framework, a new identity microservice, or shared authentication implementation libraries across services.
|
||||
|
||||
The prototype handler validates pre-created test credentials and produces a stable application account identifier and role (`Patient` or `HealthcareProfessional`). Authorization and controllers consume this normalized identity rather than credentials or details specific to the authentication handler.
|
||||
|
||||
Roles must come from trusted account data, never from a role supplied by the client.
|
||||
|
||||
## Simple prototype mechanism
|
||||
|
||||
Use HTTP Basic authentication over HTTPS for the placeholder. The gateway validates the account identifier and password on each request, using password hashes and an established platform password-hashing facility. This requires no login endpoint, token issuance, session store, registration, or account administration.
|
||||
|
||||
Provide pre-created accounts through external configuration with safe example values. Do not commit actual credentials or log passwords or authorization headers. Enable the placeholder explicitly through configuration so it cannot become an accidental fallback when a replacement scheme is selected.
|
||||
|
||||
HTTP Basic is the initial credential transport, not a dependency of controllers or access policies.
|
||||
|
||||
## Application access data and policies
|
||||
|
||||
For the prototype, use externally configured account-to-patient mappings and predefined professional-to-patient assignments. Keep these application access records separate from credential validation. They do not require a new database or service for this prototype proposal.
|
||||
|
||||
- A patient account maps to exactly one patient identifier and may perform the operations permitted by the existing stories only for that patient.
|
||||
- A healthcare professional account may read information for assigned patients and retrieve only its own assignment list. It may not create, modify, or delete patient information.
|
||||
- A patient account cannot use operations reserved for healthcare professionals.
|
||||
- Missing or invalid authentication rejects the request before patient information is returned or changed.
|
||||
|
||||
The gateway must establish the actual owner of resources addressed by resource identifiers, such as an observation identifier. A patient identifier supplied by the client alone is not proof of ownership. Ownership checks must use the documented service APIs; they must not access service databases directly or rely on shared process memory.
|
||||
|
||||
Protected service APIs must be reachable only through an authorized gateway path. The deployment must prevent clients from bypassing gateway authorization, including when services run on separate machines. Client-supplied identity headers must not be treated as trusted identity. The concrete gateway-to-service protection must be reviewed before implementation if it requires additions to the documented deployment design.
|
||||
|
||||
## Replacing the placeholder
|
||||
|
||||
Replace the prototype handler with the appropriate standard ASP.NET Core authentication integration for the selected identity provider. Normalize its validated identity into the same application account identifier and role used by the access policies. Maintain an explicit mapping from the provider's trusted identity to the application account; do not assume an arbitrary provider subject already equals the application account identifier.
|
||||
|
||||
Patient mappings, professional assignments, controllers, and authorization rules remain in place. Gateway authentication configuration and identity mapping change. Clients will also need to adopt the replacement provider's login and credential transport; replacement does not imply an unchanged client authentication flow.
|
||||
|
||||
Selecting an identity provider, implementing account lifecycle management, and claiming production readiness are outside this proposal.
|
||||
|
||||
## Verification when implemented
|
||||
|
||||
Cover the US-13 and US-14 acceptance criteria with automated tests. Verify that the same authorization behaviour holds when a test authentication handler supplies the normalized identity instead of the prototype handler. Include resource-ownership checks for operations addressed by observation identifier and confirm that unauthorized requests cannot return or change patient data.
|
||||
|
||||
## Separate requirement clarification
|
||||
|
||||
US-01 generates a patient identifier when creating a profile, while US-13 associates a patient account with a patient. Before implementing authenticated profile creation, clarify how the generated identifier becomes associated with that account. This proposal does not silently choose or change that behaviour.
|
||||
@@ -0,0 +1,47 @@
|
||||
# Requirements consistency review
|
||||
|
||||
Reviewed all 15 files currently under `Docs/Requirements/`, with the authentication design consulted for its explicit requirement reconciliation. Recommendations only; no authoritative documents or implementation changed.
|
||||
|
||||
## Conflicts and reconciliation recommendations
|
||||
|
||||
1. **US-13 excludes clinicians, whereas US-14 permits assigned healthcare professionals.** US-14 explicitly supplies replacement purpose and account wording but does not explicitly remove US-13's clinician exclusion. Keep US-14's assigned, read-only professional access. Amend US-13's exclusion to exclude unassigned third parties and professional writes, rather than all clinicians. Preserve its patient ownership restrictions.
|
||||
|
||||
2. **Account/profile cardinality is inconsistent.** US-13 says every account has exactly one patient; US-14 narrows this to patient accounts, but still requires exactly one. The authentication design allows a patient account to have no profile before US-01 creation and exactly one afterwards. Keep the design's lifecycle and US-14's professional assignments. State: a patient account has zero profiles before initial creation and exactly one afterwards; professional accounts have predefined assignments. Add US-01 scenarios for authenticated initial creation, duplicate prevention, persistent association and retry/concurrency recovery. US-13 successful login must also cover an account awaiting profile creation rather than require an existing associated patient in every case.
|
||||
|
||||
3. **US-11 implementation prerequisite differs.** The original story says the exact mathematical definition should be specified before implementation; the trend/interpretation addendum expressly lets implementation choose and document methods. Keep the newer permission, constrained by the full-period, reproducibility and clinical-evidence requirements. Explicitly replace the original prerequisite while retaining its invalid-period and no-data acceptance criteria.
|
||||
|
||||
## Missing or ambiguous requirement references
|
||||
|
||||
4. **US-11 context addendum references absent material.** Its scope refers to an original v4 document, temporary conventions 12 and 13, endpoint-only acceptance scenarios and an original two-observation rule. None are present in the current requirements set. Keep the new full-period and temporal-sufficiency requirements; remove those references and state the operative rules directly. Two observations at distinct timestamps may be a minimum, but sufficiency must follow the documented method. Endpoint equality alone must not establish stability.
|
||||
|
||||
5. **US-06 tie rule has no original definition.** The context addendum claims to preserve timestamp tie rules, but the original US-06 supplies none. The new acceptance scenario selects the observation recorded most recently. Keep that new rule and state it explicitly in US-06: select greatest measurement timestamp, then latest recording time. Define a deterministic final tie rule if recording times also match; do not reuse recording order to determine US-11 direction.
|
||||
|
||||
6. **US-10 refers to unspecified rounding.** The addendum says existing rounding and one-observation behaviour remain unchanged, although the original story defines neither explicitly. `125.00` in an example does not define fractional rounding. Keep original arithmetic means and extrema, including a one-observation summary; explicitly document precision/rounding after checking existing behaviour. Do not silently infer two-decimal rounding from formatting.
|
||||
|
||||
7. **Repeated inclusive-boundary references lack a baseline definition.** Original period examples do not state boundary inclusion, while the new US-07 boundary scenario explicitly includes both endpoints. Keep the new inclusive rule and define it once for all period-based stories: start <= measurement timestamp <= end. Preserve rejection of end before start; clarify equal-bound periods as valid if that is the intended rule.
|
||||
|
||||
8. **Comparability and interpretation need a clear relationship.** The US-11 context addendum correctly says broad matching categories alone do not certify identical conditions. Clarify that missing preparation details limit the claims that can be made; they do not automatically prevent every setting-appropriate reference comparison. Keep both numerical assessment with limitations and evidence-based clinical interpretation. Applicable guidance determines which details are necessary for a particular clinical claim.
|
||||
|
||||
9. **Guidance access is unspecified.** US-15 protects patient data but does not explicitly choose whether general guidance itself requires authentication. This is a gap, not a conflict with US-13's protected patient-data operations. Recommendation: general guidance can be read without patient-data access; any patient-specific information remains protected. Record an explicit decision before implementing its access contract.
|
||||
|
||||
## Compatible additions to retain
|
||||
|
||||
- US-04's independently recordable setting/activity extends optional context; absent context and original free text remain valid. It does not make context mandatory.
|
||||
- US-05 through US-09 preserve retrieval, latest-by-measurement-time selection, chronological history, numerical validation, ownership and deletion while adding context behaviour. US-08 adds context-only partial updates; the original does not forbid them.
|
||||
- US-10 context filtering is optional; unfiltered arithmetic statistics still include all eligible observations, including unknown conditions. Numerical summaries and US-11 clinical assessments have different sufficiency needs.
|
||||
- US-11's two addenda complement each other: one defines assessment behaviour, the other context selection and comparability. Preserve both, with explicit precedence over the original algorithm prerequisite.
|
||||
- US-12 explicitly applies context selection to insight only and leaves latest observation overall. This is compatible with the original. Keep profile/latest when a selection produces no insight; do not add a trend component implicitly.
|
||||
- US-15 is an additional story, compatible with valid observations made under nonrecommended conditions. Guidance must remain optional.
|
||||
- The US-10 correction is compatible with numerical requirements but prescribes the baseline architecture. Recommend locating that architectural decision under Architecture and retaining architecture-neutral functional requirements so it does not constrain every experimental variant.
|
||||
- US-01 through US-03 have no new numerical/context conflict. Authentication adds access preconditions; missing-resource behaviour applies after authorization without disclosing another patient's information.
|
||||
- Functional invariance remains valid once the expanded requirements are applied to every compared variant and the acceptance suite. Previously completed stories need additional work for the new addenda; an old passing suite does not establish compliance with the expanded requirements.
|
||||
|
||||
## Separate design alignment
|
||||
|
||||
The Insights class diagram currently describes one Trend direction/description and an ObservationDto without structured measurement context. The new requirements need separate measurement assessments and context transfer. This is a design-alignment issue rather than a reason to discard the new requirements. Review and approve the necessary contract/design updates before implementation under AGENTS.md; keep service/process boundaries and on-demand calculation.
|
||||
|
||||
The endpoint-only proposal in `suggestions/us11-trend-definition.md` is unapproved and incompatible with the new US-11. It is not an authoritative requirement conflict; retire it after the new requirements are reconciled.
|
||||
|
||||
## Recommended consolidation
|
||||
|
||||
Keep the original US-01–US-12 behaviours wherever compatible, incorporate the new context requirements and full US-11 assessment, and retain US-13–US-15. Give each story one current definition, explicitly record replaced clauses, and state common access/period/context rules once. Do not rely on absent document versions or implementation conventions as requirements.
|
||||
@@ -0,0 +1,9 @@
|
||||
# US-06 implementation order and authentication prerequisite
|
||||
|
||||
Resolved: the user explicitly instructed that authentication be deferred until its relevant user story. Implement US-06 using the existing API conventions; defer the authentication decisions below to US-13/US-14.
|
||||
|
||||
US-01–US-04 are committed. US-05 retrieval and both acceptance scenarios are already implemented and tested as part of US-04. The next unfinished sequential story is US-06 (latest blood-pressure observation).
|
||||
|
||||
US-13 requires authentication for all observation operations. Existing services and acceptance tests currently have no authentication. The newly incorporated authentication design explicitly leaves token selection, account-association persistence, profile-creation recovery, and gateway-to-service protection open and requires accepted decisions before implementation.
|
||||
|
||||
Before authentication implementation, also reconcile US-13's statement that every account has exactly one patient with the design's zero-profile initial state and US-14's healthcare-professional assignments. No authoritative documents have been modified.
|
||||
@@ -0,0 +1,21 @@
|
||||
# US-10 — Clarify Insights persistence
|
||||
|
||||
Resolved by `Docs/Requirements/US_10_Correction`: summaries are calculated on demand without persistence. The ER table is an inconsistency, not a deferred requirement. See `Docs/Architecture/us10-insights-correction.md`.
|
||||
|
||||
## Documents requiring reconciliation
|
||||
|
||||
- `Docs/Architecture/05_class_insights_service.jpg` shows `InsightsController`, `InsightsApplicationService`, `InsightCalculator`, and an HTTP observation client. It shows no summary repository or persistence path.
|
||||
- `Docs/Architecture/02_microservice_architecture.jpg` assigns databases to Patient/Profile and Observation, but shows no Insights database.
|
||||
- `Docs/Architecture/09_er_insights_service.jpg` defines a `HealthSummary` table with a primary key, patient identifier, period, calculated values, and generation timestamp.
|
||||
- US-10 requires calculating averages and minimum/maximum values from observations in a selected period. It does not specify storing or retrieving generated summaries.
|
||||
|
||||
The diagrams do not establish whether the ER table must be implemented for US-10 or is intended for later work. Choosing persistence changes the service's deployment, dependencies, configuration, and component responsibilities, so this is not merely an endpoint implementation detail.
|
||||
|
||||
## Proposed options, pending user decision
|
||||
|
||||
1. Calculate summaries on demand without persistence for US-10. Implement an independent ASP.NET Core Insights Service following the class diagram, obtaining period observations over HTTP through the gateway and returning fresh calculations. The ER table is deferred. This is the smallest implementation satisfying US-10 and automatically reflects corrections/deletions.
|
||||
2. Persist generated summaries in an Insights-owned PostgreSQL database using EF Core. This requires approval of the database ownership/deployment and persistence components missing from the other diagrams. Clarify whether each request records a fresh summary or reuses a stored one and how corrections/deletions affect stored results.
|
||||
|
||||
In either option, preserve service process boundaries, calculate decimal averages and integer extrema, reject invalid periods, indicate insufficient data for an empty observation set, and defer authentication as already authorized. Trend calculation belongs to US-11 and is outside US-10.
|
||||
|
||||
No authoritative documents or implementation files have been changed. This suggestion does not authorize either option.
|
||||
@@ -0,0 +1,23 @@
|
||||
# US-11 — Proposed trend definition
|
||||
|
||||
## Required clarification
|
||||
|
||||
US-11 explicitly requires a mathematical definition before implementation. No definition was found in the requirements or design documents. The Insights class diagram defines a single `direction` and `description`, but does not identify the measured value, algorithm, or minimum sufficient data.
|
||||
|
||||
## Proposed definition (pending approval)
|
||||
|
||||
- Calculate on demand in the existing Insights Service using observations retrieved through the gateway for the requested patient and inclusive period. Do not store trend results.
|
||||
- The single direction describes systolic blood pressure. State this explicitly in the response description; do not imply a combined trend across systolic, diastolic, and pulse.
|
||||
- Require observations at two or more distinct measurement timestamps. Empty data, a single observation, or observations all measured at the same timestamp indicate insufficient data.
|
||||
- Compare mean systolic values at the earliest and latest measurement timestamps. If multiple observations share either endpoint timestamp, use their decimal arithmetic mean, so identifier ordering does not determine direction.
|
||||
- Return `Increasing` when the latest mean exceeds the earliest mean, `Decreasing` when it is lower, and `Stable` when equal. No tolerance threshold, regression, smoothing, or clinical interpretation is introduced. Intermediate observations do not affect this endpoint comparison.
|
||||
- Return the documented patient identifier, period start/end, direction, and a description explaining the comparison.
|
||||
- Use existing period validation and missing-data conventions: `400` for invalid bounds, `404` problem details for insufficient data, and `502`/`504` for upstream failures.
|
||||
|
||||
This simple definition identifies net change between the endpoints, not the shape of change during the period. Choosing a different measured value or a regression-based trend would produce different product behaviour and requires an explicit decision.
|
||||
|
||||
## Verification after approval
|
||||
|
||||
Cover increasing/decreasing/stable results, endpoint timestamp ties, sufficient/insufficient data, exclusion of other patients and out-of-period measurements, independence from insertion order, invalid periods, and fresh results following observation corrections/deletions. Retain existing Insights architecture and independent process boundaries.
|
||||
|
||||
This suggestion does not authorize implementation or modify authoritative requirements.
|
||||
@@ -0,0 +1,91 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Xunit;
|
||||
|
||||
namespace Observation.AcceptanceTests;
|
||||
|
||||
public sealed class DeleteObservationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||
{
|
||||
private sealed record Profile(Guid PatientId);
|
||||
private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||
int Systolic, int Diastolic, int Pulse, string? Context, string? Note);
|
||||
|
||||
private async Task<Guid> CreatePatientAsync()
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new
|
||||
{
|
||||
name = "Deletion Example", dateOfBirth = "1980-01-01"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||
}
|
||||
|
||||
private async Task<Observation> RecordAsync(Guid patientId, string measuredAt)
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
|
||||
{
|
||||
measuredAt, systolic = 128, diastolic = 82, pulse = 68, context = "Resting", note = "Before breakfast"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Observation>())!;
|
||||
}
|
||||
|
||||
private Task<Observation[]?> HistoryAsync(Guid patientId) =>
|
||||
fixture.Client.GetFromJsonAsync<Observation[]>(
|
||||
$"/api/patients/{patientId}/observations?from=2026-09-01T00:00:00&to=2026-09-30T23:59:59");
|
||||
|
||||
[Fact]
|
||||
public async Task Deleted_observation_stays_absent_after_restart_and_other_observations_are_preserved()
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
var earlier = await RecordAsync(patientId, "2026-09-10T08:00:00");
|
||||
var deleted = await RecordAsync(patientId, "2026-09-12T08:00:00");
|
||||
var other = await RecordAsync(await CreatePatientAsync(), "2026-09-13T08:00:00");
|
||||
|
||||
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 retrieval = await fixture.Client.GetAsync($"/api/observations/{deleted.ObservationId}");
|
||||
Assert.Equal(HttpStatusCode.NotFound, retrieval.StatusCode);
|
||||
Assert.Equal(earlier, Assert.Single((await HistoryAsync(patientId))!));
|
||||
Assert.Equal(earlier, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{earlier.ObservationId}"));
|
||||
Assert.Equal(earlier, await fixture.Client.GetFromJsonAsync<Observation>(
|
||||
$"/api/patients/{patientId}/observations/latest"));
|
||||
Assert.Equal(other, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{other.ObservationId}"));
|
||||
Assert.Equal(other, Assert.Single((await HistoryAsync(other.PatientId))!));
|
||||
Assert.Equal(patientId, (await fixture.Client.GetFromJsonAsync<Profile>($"/api/patients/{patientId}"))!.PatientId);
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
Assert.False(await db.Observations.AnyAsync(o => o.ObservationId == deleted.ObservationId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Deleting_the_only_observation_leaves_empty_history_and_no_latest_observation()
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
var observation = await RecordAsync(patientId, "2026-09-12T08:00:00");
|
||||
using var response = await fixture.Client.DeleteAsync($"/api/observations/{observation.ObservationId}");
|
||||
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
|
||||
Assert.Empty((await HistoryAsync(patientId))!);
|
||||
using var latest = await fixture.Client.GetAsync($"/api/patients/{patientId}/observations/latest");
|
||||
Assert.Equal(HttpStatusCode.NotFound, latest.StatusCode);
|
||||
using var repeated = await fixture.Client.DeleteAsync($"/api/observations/{observation.ObservationId}");
|
||||
Assert.Equal(HttpStatusCode.NotFound, repeated.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Missing_observation_returns_not_found_without_changing_existing_data()
|
||||
{
|
||||
var observation = await RecordAsync(await CreatePatientAsync(), "2026-09-12T08:00:00");
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var count = await db.Observations.CountAsync();
|
||||
using var response = await fixture.Client.DeleteAsync($"/api/observations/{Guid.NewGuid()}");
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.Equal(count, await db.Observations.CountAsync());
|
||||
Assert.Equal(observation, await fixture.Client.GetFromJsonAsync<Observation>(
|
||||
$"/api/observations/{observation.ObservationId}"));
|
||||
Assert.Equal(observation, Assert.Single((await HistoryAsync(observation.PatientId))!));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Xunit;
|
||||
|
||||
namespace Observation.AcceptanceTests;
|
||||
|
||||
public sealed class HealthInsightTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||
{
|
||||
private sealed record Profile(Guid PatientId);
|
||||
private sealed record Observation(Guid ObservationId);
|
||||
private sealed record Insight(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
|
||||
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
|
||||
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic);
|
||||
|
||||
private async Task<Guid> PatientAsync()
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new
|
||||
{ name = "Insight Example", dateOfBirth = "1980-01-01" });
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||
}
|
||||
|
||||
private async Task<Guid> RecordAsync(Guid patientId, string time, int systolic, int diastolic, int pulse)
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
|
||||
{ measuredAt = time, systolic, diastolic, pulse });
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Observation>())!.ObservationId;
|
||||
}
|
||||
|
||||
private string PathFor(Guid patientId, string from = "2026-09-03T00:00:00", string to = "2026-09-08T23:59:59") =>
|
||||
$"/api/patients/{patientId}/insights?from={Uri.EscapeDataString(from)}&to={Uri.EscapeDataString(to)}";
|
||||
|
||||
private async Task<Insight> SummaryAsync(Guid patientId)
|
||||
{
|
||||
using var response = await fixture.Client.GetAsync(PathFor(patientId));
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Insight>())!;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Averages_use_only_the_requested_patient_and_period_after_restart()
|
||||
{
|
||||
var patientId = await PatientAsync();
|
||||
await RecordAsync(patientId, "2026-09-03T00:00:00", 120, 80, 60);
|
||||
await RecordAsync(patientId, "2026-09-08T23:59:59", 130, 84, 70);
|
||||
await RecordAsync(patientId, "2026-09-01T08:00:00", 200, 100, 90);
|
||||
await RecordAsync(patientId, "2026-09-10T08:00:00", 210, 110, 95);
|
||||
await RecordAsync(await PatientAsync(), "2026-09-05T08:00:00", 220, 120, 100);
|
||||
await fixture.RestartHostsAsync();
|
||||
var insight = await SummaryAsync(patientId);
|
||||
Assert.Equal(patientId, insight.PatientId);
|
||||
Assert.Equal(new DateTime(2026, 9, 3), insight.PeriodStart);
|
||||
Assert.Equal(new DateTime(2026, 9, 8, 23, 59, 59), insight.PeriodEnd);
|
||||
Assert.Equal(125m, insight.AverageSystolic);
|
||||
Assert.Equal(82m, insight.AverageDiastolic);
|
||||
Assert.Equal(65m, insight.AveragePulse);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Minimum_and_maximum_values_are_calculated()
|
||||
{
|
||||
var patientId = await PatientAsync();
|
||||
await RecordAsync(patientId, "2026-09-04T08:00:00", 118, 76, 61);
|
||||
await RecordAsync(patientId, "2026-09-05T08:00:00", 130, 84, 70);
|
||||
await RecordAsync(patientId, "2026-09-06T08:00:00", 124, 80, 66);
|
||||
var insight = await SummaryAsync(patientId);
|
||||
Assert.Equal(118, insight.MinSystolic);
|
||||
Assert.Equal(130, insight.MaxSystolic);
|
||||
Assert.Equal(76, insight.MinDiastolic);
|
||||
Assert.Equal(84, insight.MaxDiastolic);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Fractional_averages_are_preserved_and_recalculated_after_correction_and_deletion()
|
||||
{
|
||||
var patientId = await PatientAsync();
|
||||
var first = await RecordAsync(patientId, "2026-09-04T08:00:00", 120, 80, 60);
|
||||
var second = await RecordAsync(patientId, "2026-09-05T08:00:00", 121, 81, 61);
|
||||
var initial = await SummaryAsync(patientId);
|
||||
Assert.Equal(120.5m, initial.AverageSystolic);
|
||||
Assert.Equal(80.5m, initial.AverageDiastolic);
|
||||
Assert.Equal(60.5m, initial.AveragePulse);
|
||||
using var updated = await fixture.Client.PutAsJsonAsync($"/api/observations/{second}",
|
||||
new { systolic = 130, diastolic = 84, pulse = 70 });
|
||||
Assert.Equal(HttpStatusCode.OK, updated.StatusCode);
|
||||
Assert.Equal(125m, (await SummaryAsync(patientId)).AverageSystolic);
|
||||
using var deleted = await fixture.Client.DeleteAsync($"/api/observations/{second}");
|
||||
Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
|
||||
var single = await SummaryAsync(patientId);
|
||||
Assert.Equal(120m, single.AverageSystolic);
|
||||
Assert.Equal(single.MinSystolic, single.MaxSystolic);
|
||||
using var last = await fixture.Client.DeleteAsync($"/api/observations/{first}");
|
||||
Assert.Equal(HttpStatusCode.NoContent, last.StatusCode);
|
||||
using var empty = await fixture.Client.GetAsync(PathFor(patientId));
|
||||
Assert.Equal(HttpStatusCode.NotFound, empty.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task No_matching_observations_reports_insufficient_data()
|
||||
{
|
||||
var patientId = await PatientAsync();
|
||||
await RecordAsync(patientId, "2026-09-01T08:00:00", 120, 80, 60);
|
||||
await RecordAsync(await PatientAsync(), "2026-09-05T08:00:00", 130, 84, 70);
|
||||
using var response = await fixture.Client.GetAsync(PathFor(patientId));
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
Assert.Equal("Insufficient observation data for calculation.", problem.RootElement.GetProperty("title").GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("from=2026-09-08T00:00:00&to=2026-09-03T00:00:00")]
|
||||
[InlineData("from=invalid&to=2026-09-08T00:00:00")]
|
||||
[InlineData("from=2026-09-03T00:00:00&to=invalid")]
|
||||
[InlineData("from=2026-09-03T00:00:00")]
|
||||
[InlineData("to=2026-09-08T00:00:00")]
|
||||
[InlineData("")]
|
||||
public async Task Invalid_or_missing_period_is_rejected(string query)
|
||||
{
|
||||
var patientId = await PatientAsync();
|
||||
using var response = await fixture.Client.GetAsync($"/api/patients/{patientId}/insights?{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 Equal_bounds_and_offsets_match_recording_timestamp_semantics()
|
||||
{
|
||||
var patientId = await PatientAsync();
|
||||
await RecordAsync(patientId, "2026-09-05T10:00:00+02:00", 120, 80, 60);
|
||||
using var response = await fixture.Client.GetAsync(PathFor(patientId,
|
||||
"2026-09-05T10:00:00+02:00", "2026-09-05T08:00:00Z"));
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var insight = (await response.Content.ReadFromJsonAsync<Insight>())!;
|
||||
Assert.Equal(120m, insight.AverageSystolic);
|
||||
Assert.Equal(insight.PeriodStart, insight.PeriodEnd);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Unavailable_observations_report_failure_instead_of_insufficient_data()
|
||||
{
|
||||
var patientId = await PatientAsync();
|
||||
await RecordAsync(patientId, "2026-09-05T08:00:00", 120, 80, 60);
|
||||
await fixture.StopObservationServiceAsync();
|
||||
try
|
||||
{
|
||||
using var response = await fixture.Client.GetAsync(PathFor(patientId));
|
||||
Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await fixture.RestartHostsAsync();
|
||||
}
|
||||
Assert.Equal(120m, (await SummaryAsync(patientId)).AverageSystolic);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Xunit;
|
||||
|
||||
namespace Observation.AcceptanceTests;
|
||||
|
||||
public sealed class LatestObservationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||
{
|
||||
private sealed record Profile(Guid PatientId);
|
||||
private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||
int Systolic, int Diastolic, int Pulse, string? Context, string? Note);
|
||||
|
||||
private async Task<Guid> CreatePatientAsync()
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new
|
||||
{
|
||||
name = "Latest Example", dateOfBirth = "1980-01-01"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||
}
|
||||
|
||||
private async Task<Observation> RecordAsync(Guid patientId, string measuredAt, int systolic, int diastolic, int pulse)
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
|
||||
{
|
||||
measuredAt, systolic, diastolic, pulse, context = "Resting", note = "Before breakfast"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Observation>())!;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Latest_is_selected_by_measurement_time_for_the_requested_patient_after_restart()
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
await RecordAsync(patientId, "2026-09-10T08:00:00", 130, 84, 70);
|
||||
var latest = await RecordAsync(patientId, "2026-09-12T08:00:00", 126, 80, 66);
|
||||
await RecordAsync(patientId, "2026-09-11T08:00:00", 128, 82, 68);
|
||||
var otherPatientId = await CreatePatientAsync();
|
||||
var otherLatest = await RecordAsync(otherPatientId, "2026-09-13T08:00:00", 140, 90, 75);
|
||||
|
||||
await fixture.RestartHostsAsync();
|
||||
|
||||
Assert.Equal(latest, await fixture.Client.GetFromJsonAsync<Observation>(
|
||||
$"/api/patients/{patientId}/observations/latest"));
|
||||
Assert.Equal(otherLatest, await fixture.Client.GetFromJsonAsync<Observation>(
|
||||
$"/api/patients/{otherPatientId}/observations/latest"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Patient_without_observations_returns_not_found_even_when_another_patient_has_observations()
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
await RecordAsync(await CreatePatientAsync(), "2026-09-12T08:00:00", 128, 82, 68);
|
||||
|
||||
using var response = await fixture.Client.GetAsync($"/api/patients/{patientId}/observations/latest");
|
||||
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.DoesNotContain("observationId", await response.Content.ReadAsStringAsync());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5" PrivateAssets="all" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.12" />
|
||||
<ProjectReference Include="../../src/PatientProfileService/PatientProfileService.csproj" />
|
||||
<ProjectReference Include="../../src/ApiGateway/ApiGateway.csproj" />
|
||||
<ProjectReference Include="../../src/InsightsService/InsightsService.csproj" />
|
||||
<ProjectReference Include="../../src/ObservationService/ObservationService.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,140 @@
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using System.Net;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Npgsql;
|
||||
using PatientProfileService.Persistence;
|
||||
using Xunit;
|
||||
|
||||
namespace Observation.AcceptanceTests;
|
||||
|
||||
public sealed class ObservationApiFixture : IAsyncLifetime
|
||||
{
|
||||
private readonly string databaseName = "us04_patient_" + Guid.NewGuid().ToString("N");
|
||||
private readonly string observationDatabaseName = "us04_observation_" + Guid.NewGuid().ToString("N");
|
||||
private WebApplicationFactory<ObservationService.Program>? observation;
|
||||
private WebApplicationFactory<InsightsService.Program>? insights;
|
||||
public string ObservationConnectionString { get; private set; } = "";
|
||||
private string adminConnectionString = "";
|
||||
private WebApplicationFactory<PatientProfileService.Program>? service;
|
||||
private WebApplicationFactory<ApiGateway.Program>? gateway;
|
||||
public string ConnectionString { get; private set; } = "";
|
||||
public HttpClient Client { get; private set; } = null!;
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
adminConnectionString = Environment.GetEnvironmentVariable("TEST_POSTGRES_CONNECTION")
|
||||
?? throw new InvalidOperationException(
|
||||
"Set TEST_POSTGRES_CONNECTION to a PostgreSQL connection with permission to create test databases.");
|
||||
await using var connection = new NpgsqlConnection(adminConnectionString);
|
||||
await connection.OpenAsync();
|
||||
await using var command = new NpgsqlCommand($"CREATE DATABASE {databaseName}", connection);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
await using var observationCommand = new NpgsqlCommand($"CREATE DATABASE {observationDatabaseName}", connection);
|
||||
await observationCommand.ExecuteNonQueryAsync();
|
||||
ObservationConnectionString = new NpgsqlConnectionStringBuilder(adminConnectionString) { Database = observationDatabaseName }.ConnectionString;
|
||||
await using var observationDb = CreateObservationDbContext();
|
||||
await observationDb.Database.MigrateAsync();
|
||||
await observationDb.Database.MigrateAsync();
|
||||
ConnectionString = new NpgsqlConnectionStringBuilder(adminConnectionString) { Database = databaseName }.ConnectionString;
|
||||
await using var db = CreateDbContext();
|
||||
await db.Database.MigrateAsync();
|
||||
// Applying the committed migration twice must be harmless.
|
||||
await db.Database.MigrateAsync();
|
||||
StartHosts();
|
||||
}
|
||||
|
||||
public PatientDbContext CreateDbContext() => new(
|
||||
new DbContextOptionsBuilder<PatientDbContext>().UseNpgsql(ConnectionString).Options);
|
||||
|
||||
public ObservationService.Persistence.ObservationDbContext CreateObservationDbContext() => new(
|
||||
new DbContextOptionsBuilder<ObservationService.Persistence.ObservationDbContext>()
|
||||
.UseNpgsql(ObservationConnectionString).Options);
|
||||
|
||||
private void StartHosts()
|
||||
{
|
||||
service = new WebApplicationFactory<PatientProfileService.Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
||||
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
||||
new Dictionary<string, string?> { ["ConnectionStrings:PatientDatabase"] = ConnectionString }));
|
||||
});
|
||||
service.UseKestrel(0);
|
||||
using var serviceClient = service.CreateClient();
|
||||
|
||||
gateway = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
||||
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
||||
new Dictionary<string, string?> { ["Services:PatientProfile:BaseUrl"] = serviceClient.BaseAddress!.ToString(),
|
||||
["Services:Insights:BaseUrl"] = "http://127.0.0.1:1/",
|
||||
["Services:Observation:BaseUrl"] = "http://127.0.0.1:1/" }));
|
||||
});
|
||||
gateway.UseKestrel(0);
|
||||
Client = gateway.CreateClient();
|
||||
observation = new WebApplicationFactory<ObservationService.Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
||||
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
||||
new Dictionary<string, string?>
|
||||
{
|
||||
["ConnectionStrings:ObservationDatabase"] = ObservationConnectionString,
|
||||
["Services:ApiGateway:BaseUrl"] = Client.BaseAddress!.ToString()
|
||||
}));
|
||||
});
|
||||
observation.UseKestrel(0);
|
||||
using var observationClient = observation.CreateClient();
|
||||
gateway.Services.GetRequiredService<IConfiguration>()["Services:Observation:BaseUrl"] = observationClient.BaseAddress!.ToString();
|
||||
insights = new WebApplicationFactory<InsightsService.Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
||||
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
||||
new Dictionary<string, string?> { ["Services:ApiGateway:BaseUrl"] = Client.BaseAddress!.ToString() }));
|
||||
});
|
||||
insights.UseKestrel(0);
|
||||
using var insightsClient = insights.CreateClient();
|
||||
gateway.Services.GetRequiredService<IConfiguration>()["Services:Insights:BaseUrl"] = insightsClient.BaseAddress!.ToString();
|
||||
}
|
||||
|
||||
public async Task RestartHostsAsync()
|
||||
{
|
||||
Client.Dispose();
|
||||
await insights!.DisposeAsync();
|
||||
if (observation is not null) await observation.DisposeAsync();
|
||||
await gateway!.DisposeAsync();
|
||||
if (service is not null) await service.DisposeAsync();
|
||||
StartHosts();
|
||||
}
|
||||
|
||||
public async Task StopObservationServiceAsync()
|
||||
{
|
||||
if (observation is not null) await observation.DisposeAsync();
|
||||
observation = null;
|
||||
}
|
||||
|
||||
public async Task StopPatientServiceAsync()
|
||||
{
|
||||
await service!.DisposeAsync();
|
||||
service = null;
|
||||
}
|
||||
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
Client?.Dispose();
|
||||
if (insights is not null) await insights.DisposeAsync();
|
||||
if (observation is not null) await observation.DisposeAsync();
|
||||
if (gateway is not null) await gateway.DisposeAsync();
|
||||
if (service is not null) await service.DisposeAsync();
|
||||
if (string.IsNullOrEmpty(adminConnectionString)) return;
|
||||
|
||||
NpgsqlConnection.ClearAllPools();
|
||||
await using var connection = new NpgsqlConnection(adminConnectionString);
|
||||
await connection.OpenAsync();
|
||||
await using var command = new NpgsqlCommand($"DROP DATABASE IF EXISTS {databaseName} WITH (FORCE)", connection);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
await using var observationCommand = new NpgsqlCommand($"DROP DATABASE IF EXISTS {observationDatabaseName} WITH (FORCE)", connection);
|
||||
await observationCommand.ExecuteNonQueryAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Xunit;
|
||||
|
||||
namespace Observation.AcceptanceTests;
|
||||
|
||||
public sealed class ObservationHistoryTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||
{
|
||||
private sealed record Profile(Guid PatientId);
|
||||
private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||
int Systolic, int Diastolic, int Pulse, string? Context, string? Note);
|
||||
|
||||
private async Task<Guid> CreatePatientAsync()
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new
|
||||
{
|
||||
name = "History Example", dateOfBirth = "1980-01-01"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||
}
|
||||
|
||||
private async Task<Observation> RecordAsync(Guid patientId, string measuredAt, int systolic, int diastolic, int pulse)
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
|
||||
{
|
||||
measuredAt, systolic, diastolic, pulse, context = "Resting", note = "Before breakfast"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Observation>())!;
|
||||
}
|
||||
|
||||
private Task<Observation[]?> HistoryAsync(Guid patientId, string from, string to) =>
|
||||
fixture.Client.GetFromJsonAsync<Observation[]>(
|
||||
$"/api/patients/{patientId}/observations?from={Uri.EscapeDataString(from)}&to={Uri.EscapeDataString(to)}");
|
||||
|
||||
[Fact]
|
||||
public async Task Selected_period_returns_only_the_matching_observation_after_restart()
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
await RecordAsync(patientId, "2026-09-01T08:00:00", 120, 80, 60);
|
||||
var expected = await RecordAsync(patientId, "2026-09-05T08:00:00", 125, 82, 65);
|
||||
await RecordAsync(patientId, "2026-09-10T08:00:00", 130, 84, 70);
|
||||
await RecordAsync(await CreatePatientAsync(), "2026-09-05T08:00:00", 140, 90, 75);
|
||||
await fixture.RestartHostsAsync();
|
||||
|
||||
var history = await HistoryAsync(patientId, "2026-09-03T00:00:00", "2026-09-08T23:59:59");
|
||||
|
||||
Assert.Equal(expected, Assert.Single(history!));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Results_are_chronological_and_include_both_period_boundaries()
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
var last = await RecordAsync(patientId, "2026-09-10T08:00:00", 130, 84, 70);
|
||||
var first = await RecordAsync(patientId, "2026-09-01T08:00:00", 120, 80, 60);
|
||||
var middle = await RecordAsync(patientId, "2026-09-05T08:00:00", 125, 82, 65);
|
||||
|
||||
Assert.Equal(new[] { first, middle, last },
|
||||
await HistoryAsync(patientId, "2026-09-01T08:00:00", "2026-09-10T08:00:00"));
|
||||
Assert.Equal(first, Assert.Single((await HistoryAsync(patientId,
|
||||
"2026-09-01T08:00:00", "2026-09-01T08:00:00"))!));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task No_matching_observations_returns_an_empty_array()
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
await RecordAsync(await CreatePatientAsync(), "2026-09-05T08:00:00", 125, 82, 65);
|
||||
Assert.Empty((await HistoryAsync(patientId, "2026-09-03T00:00:00", "2026-09-08T23:59:59"))!);
|
||||
await RecordAsync(patientId, "2026-09-01T08:00:00", 120, 80, 60);
|
||||
Assert.Empty((await HistoryAsync(patientId, "2026-09-03T00:00:00", "2026-09-08T23:59:59"))!);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("from=2026-09-08T00:00:00&to=2026-09-03T00:00:00")]
|
||||
[InlineData("from=invalid&to=2026-09-08T00:00:00")]
|
||||
[InlineData("from=2026-09-03T00:00:00&to=invalid")]
|
||||
[InlineData("from=2026-09-03T00:00:00")]
|
||||
[InlineData("to=2026-09-08T00:00:00")]
|
||||
[InlineData("")]
|
||||
public async Task Invalid_or_missing_period_is_rejected_without_changing_observations(string query)
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
var saved = await RecordAsync(patientId, "2026-09-05T08:00:00", 125, 82, 65);
|
||||
using var response = await fixture.Client.GetAsync($"/api/patients/{patientId}/observations?{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(saved, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{saved.ObservationId}"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Offset_bounds_are_normalized_consistently_with_recorded_measurements()
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
var saved = await RecordAsync(patientId, "2026-09-05T10:00:00+02:00", 125, 82, 65);
|
||||
|
||||
Assert.Equal(saved, Assert.Single((await HistoryAsync(patientId,
|
||||
"2026-09-05T10:00:00+02:00", "2026-09-05T08:00:00Z"))!));
|
||||
Assert.Empty((await HistoryAsync(patientId, "2026-09-05T08:00:01Z", "2026-09-05T11:00:00Z"))!);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Xunit;
|
||||
|
||||
namespace Observation.AcceptanceTests;
|
||||
|
||||
public sealed class RecordObservationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||
{
|
||||
private sealed record Profile(Guid PatientId);
|
||||
private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||
int Systolic, int Diastolic, int Pulse, string? Context, string? Note);
|
||||
|
||||
private async Task<Guid> CreatePatientAsync()
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new
|
||||
{
|
||||
name = "Steffen Example", dateOfBirth = "1980-01-01"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Valid_observation_is_assigned_an_identifier_associated_with_the_patient_and_retrievable_after_restart()
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
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 = "Before breakfast"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var saved = await response.Content.ReadFromJsonAsync<Observation>();
|
||||
Assert.NotNull(saved);
|
||||
Assert.NotEqual(Guid.Empty, saved.ObservationId);
|
||||
Assert.Equal(patientId, 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("Resting", saved.Context);
|
||||
Assert.Equal("Before breakfast", saved.Note);
|
||||
Assert.Equal($"/api/observations/{saved.ObservationId}", response.Headers.Location!.ToString());
|
||||
|
||||
await fixture.RestartHostsAsync();
|
||||
Assert.Equal(saved, await fixture.Client.GetFromJsonAsync<Observation>(response.Headers.Location));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Optional_fields_can_be_omitted_and_identifiers_are_distinct()
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
var request = new { measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68 };
|
||||
using var first = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", request);
|
||||
using var second = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", request);
|
||||
Assert.Equal(HttpStatusCode.Created, first.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Created, second.StatusCode);
|
||||
var saved = (await first.Content.ReadFromJsonAsync<Observation>())!;
|
||||
Assert.Null(saved.Context);
|
||||
Assert.Null(saved.Note);
|
||||
Assert.NotEqual(saved.ObservationId, (await second.Content.ReadFromJsonAsync<Observation>())!.ObservationId);
|
||||
Assert.Equal(saved, await fixture.Client.GetFromJsonAsync<Observation>(first.Headers.Location));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 82, 68)]
|
||||
[InlineData(-1, 82, 68)]
|
||||
[InlineData(128, 0, 68)]
|
||||
[InlineData(128, -1, 68)]
|
||||
[InlineData(128, 82, 0)]
|
||||
[InlineData(128, 82, -1)]
|
||||
public async Task Non_positive_values_are_rejected_without_saving(int systolic, int diastolic, int pulse)
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var before = await db.Observations.CountAsync();
|
||||
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
|
||||
{
|
||||
measuredAt = "2026-09-12T08:00:00", systolic, diastolic, pulse
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Equal(before, await db.Observations.CountAsync());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("{\"systolic\":128,\"diastolic\":82,\"pulse\":68}")]
|
||||
[InlineData("{\"measuredAt\":null,\"systolic\":128,\"diastolic\":82,\"pulse\":68}")]
|
||||
[InlineData("{\"measuredAt\":\"invalid\",\"systolic\":128,\"diastolic\":82,\"pulse\":68}")]
|
||||
[InlineData("{\"measuredAt\":\"2026-09-12T08:00:00\",\"diastolic\":82,\"pulse\":68}")]
|
||||
[InlineData("{\"measuredAt\":\"2026-09-12T08:00:00\",\"systolic\":128,\"pulse\":68}")]
|
||||
[InlineData("{\"measuredAt\":\"2026-09-12T08:00:00\",\"systolic\":128,\"diastolic\":82}")]
|
||||
[InlineData("{")]
|
||||
public async Task Missing_or_malformed_information_is_rejected_without_saving(string json)
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var before = await db.Observations.CountAsync();
|
||||
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
using var response = await fixture.Client.PostAsync($"/api/patients/{patientId}/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 Missing_patient_is_rejected_without_saving()
|
||||
{
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var before = await db.Observations.CountAsync();
|
||||
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{Guid.NewGuid()}/observations", new
|
||||
{
|
||||
measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.Equal(before, await db.Observations.CountAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Missing_observation_returns_not_found()
|
||||
{
|
||||
using var response = await fixture.Client.GetAsync($"/api/observations/{Guid.NewGuid()}");
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Failed_patient_lookup_is_rejected_without_saving()
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var before = await db.Observations.CountAsync();
|
||||
await fixture.StopPatientServiceAsync();
|
||||
try
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
|
||||
{
|
||||
measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode);
|
||||
Assert.Equal(before, await db.Observations.CountAsync());
|
||||
}
|
||||
finally
|
||||
{
|
||||
await fixture.RestartHostsAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Xunit;
|
||||
|
||||
namespace Observation.AcceptanceTests;
|
||||
|
||||
public sealed class UpdateObservationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||
{
|
||||
private sealed record Profile(Guid PatientId);
|
||||
private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||
int Systolic, int Diastolic, int Pulse, string? Context, string? Note);
|
||||
|
||||
private async Task<Observation> RecordAsync()
|
||||
{
|
||||
using var patient = await fixture.Client.PostAsJsonAsync("/api/patients", new
|
||||
{
|
||||
name = "Correction Example", 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 = "Resting", note = "Before breakfast"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Observation>())!;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Correction_preserves_other_information_and_is_visible_in_all_retrievals_after_restart()
|
||||
{
|
||||
var original = await RecordAsync();
|
||||
var other = await RecordAsync();
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var before = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId);
|
||||
using var response = await fixture.Client.PutAsJsonAsync($"/api/observations/{original.ObservationId}",
|
||||
new { systolic = 128, diastolic = 82, pulse = 68 });
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var expected = original with { Systolic = 128 };
|
||||
Assert.Equal(expected, await response.Content.ReadFromJsonAsync<Observation>());
|
||||
await fixture.RestartHostsAsync();
|
||||
Assert.Equal(expected, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{original.ObservationId}"));
|
||||
Assert.Equal(expected, await fixture.Client.GetFromJsonAsync<Observation>(
|
||||
$"/api/patients/{original.PatientId}/observations/latest"));
|
||||
var history = await fixture.Client.GetFromJsonAsync<Observation[]>(
|
||||
$"/api/patients/{original.PatientId}/observations?from=2026-09-12T00:00:00&to=2026-09-12T23:59:59");
|
||||
Assert.Equal(expected, Assert.Single(history!));
|
||||
Assert.Equal(other, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{other.ObservationId}"));
|
||||
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 All_three_measured_values_can_be_corrected()
|
||||
{
|
||||
var original = await RecordAsync();
|
||||
using var response = await fixture.Client.PutAsJsonAsync($"/api/observations/{original.ObservationId}",
|
||||
new { systolic = 120, diastolic = 80, pulse = 60 });
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal(original with { Systolic = 120, Diastolic = 80, Pulse = 60 },
|
||||
await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{original.ObservationId}"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 82, 68)]
|
||||
[InlineData(128, 0, 68)]
|
||||
[InlineData(128, 82, 0)]
|
||||
[InlineData(-1, 82, 68)]
|
||||
[InlineData(128, -1, 68)]
|
||||
[InlineData(128, 82, -1)]
|
||||
public async Task Non_positive_values_are_rejected_without_changing_observation(int systolic, int diastolic, int pulse)
|
||||
{
|
||||
var original = await RecordAsync();
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var before = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId);
|
||||
using var response = await fixture.Client.PutAsJsonAsync($"/api/observations/{original.ObservationId}",
|
||||
new { systolic, diastolic, pulse });
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Equal(original, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{original.ObservationId}"));
|
||||
var after = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId);
|
||||
Assert.Equal(before.UpdatedAt, after.UpdatedAt);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("{\"diastolic\":82,\"pulse\":68}")]
|
||||
[InlineData("{\"systolic\":128,\"pulse\":68}")]
|
||||
[InlineData("{\"systolic\":128,\"diastolic\":82}")]
|
||||
[InlineData("{\"systolic\":null,\"diastolic\":82,\"pulse\":68}")]
|
||||
[InlineData("{\"systolic\":\"invalid\",\"diastolic\":82,\"pulse\":68}")]
|
||||
[InlineData("{")]
|
||||
public async Task Missing_or_malformed_values_are_rejected_without_changes(string json)
|
||||
{
|
||||
var original = await RecordAsync();
|
||||
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
using var response = await fixture.Client.PutAsync($"/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 fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{original.ObservationId}"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Missing_observation_is_rejected_without_inserting_a_new_observation()
|
||||
{
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var count = await db.Observations.CountAsync();
|
||||
var observationId = Guid.NewGuid();
|
||||
using var response = await fixture.Client.PutAsJsonAsync($"/api/observations/{observationId}",
|
||||
new { systolic = 128, diastolic = 82, pulse = 68 });
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.Equal(count, await db.Observations.CountAsync());
|
||||
using var retrieval = await fixture.Client.GetAsync($"/api/observations/{observationId}");
|
||||
Assert.Equal(HttpStatusCode.NotFound, retrieval.StatusCode);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user