feat(web): two-stage questionnaires, screening result and diary by result
- Sign-in: centred ЕМИАС card without the sidebar; anonymous entry asks «Депрессия / ПТСР».
- Stage 1 is the same for everyone and follows the fixed order of the MVP questionnaire:
PHQ-2 → trauma filter/TSQ → RUS-AUDIT-S → C-SSRS → context; stage 2 only where stage 1
is positive. Starts without a profile.
- After stage 1 the patient sees a preliminary result (screening, not a diagnosis), stored
with the record; it switches on the diary modules (depression / PTSD).
- Stage 2 diary: morning (sleep, sleep quality, alcohol) and evening (mood, medication,
3 PHQ-9 items in rotation, short PCL-5); C-SSRS since last contact only under risk;
flags on weekly means against the personal norm; scheduled full scales with change
(remission, response, worsening).
- Questionnaire log: GET /me/{token}/results and the «Мои результаты» screen.
- Questionnaires centred without the sidebar and without scale names; «Продолжить позже»
goes home; confirmations are toasts; free-text comments are optional.
- Demo policy config/questionnaire_demo.yaml (INTAKE_DEMO only, not a clinical approval).
ADR-012.
Refs #77
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+108
-6
@@ -29,7 +29,9 @@ from sqlalchemy import select
|
||||
from app.api import fixtures
|
||||
from app.core import clock
|
||||
from app.core.instrument_catalog import Catalog, catalog
|
||||
from app.core.intake_questions import DIARY_KINDS
|
||||
from app.core.intake_runtime import intake_enabled, load_runtime
|
||||
from app.core.interpretation import texts as results_texts
|
||||
from app.core.meds_reference import find_drug, indication_for, load_reference
|
||||
from app.core.safety import CrisisResource, crisis_reply
|
||||
from app.db import repo
|
||||
@@ -56,6 +58,15 @@ class EmiasCodeIn(BaseModel):
|
||||
code: str = Field(min_length=1, max_length=CODE_MAX_LEN)
|
||||
|
||||
|
||||
class AnonymousIn(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
focus: Literal["depression", "ptsd"] | None = None # what the person suspects; picks the module
|
||||
|
||||
|
||||
# Self-selected focus of an anonymous person → clinical module (PTSD is the veteran module, ADR-010).
|
||||
_FOCUS_MODULE = {"depression": "depression", "ptsd": "veteran"}
|
||||
|
||||
|
||||
class EmiasDemoIn(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
persona_token: str = Field(min_length=1, max_length=64)
|
||||
@@ -134,9 +145,16 @@ async def auth_emias_demo(body: EmiasDemoIn) -> AuthOut:
|
||||
|
||||
|
||||
@router.post("/auth/anonymous", response_model=AuthOut)
|
||||
async def auth_anonymous() -> AuthOut:
|
||||
"""Anonymous sign-in: a fresh random token; nothing about the person is stored anywhere."""
|
||||
async def auth_anonymous(body: AnonymousIn | None = None) -> AuthOut:
|
||||
"""Anonymous sign-in: a fresh random token; no identity record, no doctor.
|
||||
|
||||
With `focus` a doctor-less pseudonymous profile keeps only the chosen module, so the engine starts the
|
||||
matching onboarding instead of going straight to the menu. Without it nothing is stored at all.
|
||||
"""
|
||||
token = secrets.token_hex(TOKEN_LEN // 2)
|
||||
if body is not None and body.focus is not None:
|
||||
async with get_clinical_session() as s:
|
||||
await repo.upsert_profile(s, token=token, doctor_id="", modules=[_FOCUS_MODULE[body.focus]])
|
||||
log.info("web auth: anonymous tok=%s", token[:6])
|
||||
return AuthOut(token=token, mode="anonymous")
|
||||
|
||||
@@ -170,7 +188,8 @@ class Questionnaires(BaseModel):
|
||||
|
||||
enabled: bool
|
||||
intake: Literal["none", "active", "paused", "complete", "review"]
|
||||
diary_done: bool
|
||||
diary_done: bool # both parts of today's diary
|
||||
diary_next: Literal["morning", "evening"] | None = None # the part still open today
|
||||
|
||||
|
||||
class TodayOut(BaseModel):
|
||||
@@ -240,7 +259,9 @@ async def my_today(token: str) -> TodayOut:
|
||||
week = [week_start + timedelta(days=i) for i in range(7)]
|
||||
modules = list(profile.modules or []) if profile else []
|
||||
diary_day = now.astimezone(ZoneInfo(load_runtime().timezone)).date()
|
||||
diary_done = any(r.kind == "diary" and r.day == diary_day and r.status == "complete" for r in records)
|
||||
done_parts = {r.kind for r in records if r.day == diary_day and r.status == "complete"}
|
||||
open_parts = [k.removeprefix("diary_") for k in DIARY_KINDS if k not in done_parts]
|
||||
diary_done = not open_parts
|
||||
|
||||
def item(p: Prescription) -> PrescriptionItem:
|
||||
ref = find_drug(p.drug)
|
||||
@@ -258,7 +279,7 @@ async def my_today(token: str) -> TodayOut:
|
||||
return TodayOut(
|
||||
today=today,
|
||||
now=now.strftime("%H:%M"),
|
||||
has_doctor=profile is not None,
|
||||
has_doctor=profile is not None and bool(profile.doctor_id),
|
||||
checkin_done=(checkin is not None and checkin.mood is not None) or diary_done,
|
||||
next_visit=profile.next_visit if profile else None,
|
||||
doses=today_doses,
|
||||
@@ -268,13 +289,94 @@ async def my_today(token: str) -> TodayOut:
|
||||
if (p.end_date is None or p.end_date >= today) and (p.start_date is None or p.start_date <= today)
|
||||
],
|
||||
questionnaires=Questionnaires(
|
||||
enabled=intake_enabled() and profile is not None,
|
||||
# Stage 1 needs no profile: the screening creates it (anonymous people have none before it).
|
||||
enabled=intake_enabled(),
|
||||
intake=_intake_state(records),
|
||||
diary_done=diary_done,
|
||||
diary_next=open_parts[0] if open_parts else None,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class ResultFinding(BaseModel):
|
||||
code: str
|
||||
title: str
|
||||
|
||||
|
||||
class Conclusion(BaseModel):
|
||||
"""Preliminary conclusion of stage 1 — a screening result, not a diagnosis."""
|
||||
|
||||
day: date
|
||||
title: str
|
||||
lines: list[str]
|
||||
findings: list[ResultFinding]
|
||||
modules: list[str]
|
||||
disclaimer: str
|
||||
|
||||
|
||||
class HistoryItem(BaseModel):
|
||||
id: str
|
||||
kind: str
|
||||
kind_title: str
|
||||
status: str
|
||||
status_title: str
|
||||
day: date
|
||||
started_at: datetime
|
||||
completed_at: datetime | None
|
||||
title: str | None # interpretation shown to the patient when the form was finished
|
||||
lines: list[str]
|
||||
|
||||
|
||||
class ResultsOut(BaseModel):
|
||||
conclusion: Conclusion | None
|
||||
history: list[HistoryItem]
|
||||
|
||||
|
||||
@router.get("/me/{token}/results", response_model=ResultsOut)
|
||||
async def my_results(token: str) -> ResultsOut:
|
||||
"""The patient's own questionnaire log: every administration with its date, status and the interpretation that
|
||||
was shown when it was finished (stored with the record, so it never changes afterwards). No raw answers."""
|
||||
async with get_clinical_session() as s:
|
||||
records = list(
|
||||
(
|
||||
await s.scalars(
|
||||
select(QuestionnaireRecord)
|
||||
.where(QuestionnaireRecord.token == token)
|
||||
.order_by(QuestionnaireRecord.started_at.desc(), QuestionnaireRecord.id)
|
||||
)
|
||||
).all()
|
||||
)
|
||||
t = results_texts()
|
||||
intake = next((r for r in records if r.kind == "intake" and r.status == "complete"), None)
|
||||
conclusion = None
|
||||
if intake and intake.details.get("interpretation"):
|
||||
i = intake.details["interpretation"]
|
||||
conclusion = Conclusion(
|
||||
day=intake.day,
|
||||
title=i["title"],
|
||||
lines=i["lines"],
|
||||
findings=[ResultFinding(**f) for f in i.get("findings", [])],
|
||||
modules=i.get("modules", []),
|
||||
disclaimer=i.get("disclaimer", t["disclaimer"]),
|
||||
)
|
||||
history = [
|
||||
HistoryItem(
|
||||
id=r.id,
|
||||
kind=r.kind,
|
||||
kind_title=t["kinds"].get(r.kind, r.kind),
|
||||
status=r.status,
|
||||
status_title=t["status"].get(r.status, r.status),
|
||||
day=r.day,
|
||||
started_at=r.started_at,
|
||||
completed_at=r.completed_at,
|
||||
title=(r.details.get("interpretation") or {}).get("title"),
|
||||
lines=(r.details.get("interpretation") or {}).get("lines", []),
|
||||
)
|
||||
for r in records
|
||||
]
|
||||
return ResultsOut(conclusion=conclusion, history=history)
|
||||
|
||||
|
||||
@router.get("/crisis/resources", response_model=list[CrisisResource])
|
||||
async def crisis_resources() -> list[CrisisResource]:
|
||||
"""Help lines for the always-visible «help now» button — the same list as the fixed crisis script."""
|
||||
|
||||
Reference in New Issue
Block a user