From 1cafaa87ec11fc801dd584546ec0ea2e75f16819 Mon Sep 17 00:00:00 2001 From: Lacky1234union Date: Sat, 31 Oct 2026 11:22:44 +0300 Subject: [PATCH] =?UTF-8?q?feat(backend):=20patient=20garden=20=E2=80=94?= =?UTF-8?q?=20deterministic=20growth=20from=20activities?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GET /api/v1/me/{token}/garden computes the garden on the fly from taken doses, check-ins/diary and finished questionnaires (no new table). Rules and texts in config/garden.yaml: per-day caps, points only add up, answers never count. Refs #118 Co-Authored-By: Claude Opus 5.5 --- app/api/patient_web.py | 13 +++ app/services/garden.py | 156 ++++++++++++++++++++++++++++++++++ config/garden.yaml | 38 +++++++++ tests/test_services_garden.py | 88 +++++++++++++++++++ 4 files changed, 295 insertions(+) create mode 100644 app/services/garden.py create mode 100644 config/garden.yaml create mode 100644 tests/test_services_garden.py diff --git a/app/api/patient_web.py b/app/api/patient_web.py index d5907ef..ac12c30 100644 --- a/app/api/patient_web.py +++ b/app/api/patient_web.py @@ -43,6 +43,7 @@ from app.db.intake import QuestionnaireRecord from app.db.session import get_clinical_session, get_identity_session from app.integrations.emias_mock import CODE_MAX_LEN, EmiasMock from app.services import anonymous_care +from app.services.garden import Garden, garden_for log = logging.getLogger(__name__) @@ -374,6 +375,18 @@ async def my_today(token: str) -> TodayOut: ) +@router.get("/me/{token}/garden", response_model=Garden) +async def my_garden(token: str) -> Garden: + """The patient's garden (#118): grows from medication marks, check-ins/diary and finished questionnaires. + + Never shrinks and never depends on answers. Seen only by the patient — not on the dashboard, not in summaries. + """ + async with get_clinical_session() as s: + if await repo.get_profile(s, token) is None: + raise HTTPException(404, "patient not found") + return await garden_for(s, token) + + class ResultFinding(BaseModel): code: str title: str diff --git a/app/services/garden.py b/app/services/garden.py new file mode 100644 index 0000000..ac71ae8 --- /dev/null +++ b/app/services/garden.py @@ -0,0 +1,156 @@ +"""The patient's garden (#118, slide 13): light gamification over all modules. + +Deterministic, no LLM (guardrail 3), rules in `config/garden.yaml` (ADR-008). Computed on the fly from existing +activity rows — no own table, no migration (ADR-003), and changing the rules replays the whole history. + +«Without pressure»: points only add up (a skipped day takes nothing away), growth counts the fact of an activity +and never its content (scale scores, mood), and there is no comparison between patients. Only the patient sees it. +""" + +from collections import defaultdict +from collections.abc import Iterable +from datetime import date, datetime +from functools import lru_cache +from pathlib import Path +from typing import Literal + +import yaml +from pydantic import BaseModel +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.core import clock +from app.core.intake_questions import DIARY_KINDS +from app.db.clinical import DailyCheckin, Dose, ScaleResult +from app.db.intake import QuestionnaireRecord + +Activity = Literal["meds", "diary", "questionnaire"] + + +class ActivityRule(BaseModel): + points: int + daily_cap: int + + +class TitleRule(BaseModel): + from_steps: int + title: str + + +class GardenConfig(BaseModel): + activities: dict[Activity, ActivityRule] + step_points: int + stages_per_plant: int + max_plants: int + titles: list[TitleRule] + today: dict[Activity, str] + + +@lru_cache +def load_config(path: Path | None = None) -> GardenConfig: + from app.config import get_settings + + path = path or get_settings().config_dir / "garden.yaml" + return GardenConfig.model_validate(yaml.safe_load(path.read_text(encoding="utf-8"))) + + +class Plant(BaseModel): + stage: int # 0 = not yet sprouted … stages_per_plant = in bloom + + +class TodayItem(BaseModel): + activity: Activity + title: str + done: bool + detail: str | None = None # e.g. "1 из 2" for doses + + +class Garden(BaseModel): + points: int + steps: int + title: str + step_points: int + points_in_step: int # progress towards the next growth step: «8 из 10» + plants: list[Plant] + today: list[TodayItem] + + +def compute(events: Iterable[tuple[Activity, date]], today: date, cfg: GardenConfig | None = None) -> Garden: + """Points from (activity, day) events: per-day caps, events after `today` (demo clock) ignored.""" + cfg = cfg or load_config() + per_day: dict[tuple[Activity, date], int] = defaultdict(int) + for kind, day in events: + if day <= today: + per_day[(kind, day)] += 1 + points = sum( + min(n, cfg.activities[kind].daily_cap) * cfg.activities[kind].points for (kind, _), n in per_day.items() + ) + steps = points // cfg.step_points + plants = [ + Plant(stage=max(0, min(cfg.stages_per_plant, steps - i * cfg.stages_per_plant))) for i in range(cfg.max_plants) + ] + title = next(t.title for t in sorted(cfg.titles, key=lambda t: -t.from_steps) if steps >= t.from_steps) + return Garden( + points=points, + steps=steps, + title=title, + step_points=cfg.step_points, + points_in_step=points % cfg.step_points, + plants=plants, + today=[], + ) + + +def _day(ts: datetime, tz) -> date: + return ts.astimezone(tz).date() + + +async def garden_for(s: AsyncSession, token: str) -> Garden: + cfg = load_config() + now = clock.now() + tz, today = now.tzinfo, now.date() + events: list[tuple[Activity, date]] = [] + + doses = (await s.scalars(select(Dose).where(Dose.token == token))).all() + for d in doses: + if d.status == "taken": + events.append(("meds", _day(d.answered_at or d.planned_at, tz))) + checkins = (await s.scalars(select(DailyCheckin).where(DailyCheckin.token == token))).all() + for c in checkins: + if c.mood is not None: + events.append(("diary", c.day)) + records = (await s.scalars(select(QuestionnaireRecord).where(QuestionnaireRecord.token == token))).all() + for r in records: + if r.status != "complete": + continue + if r.kind in DIARY_KINDS: + events.append(("diary", r.day)) + else: + events.append(("questionnaire", _day(r.completed_at, tz) if r.completed_at else r.day)) + scales = (await s.scalars(select(ScaleResult).where(ScaleResult.token == token))).all() + for sc in scales: + if sc.complete: + events.append(("questionnaire", _day(sc.ts, tz))) + + garden = compute(events, today, cfg) + done_today = {kind for kind, day in events if day == today} + + items: list[TodayItem] = [] + due = [d for d in doses if _day(d.planned_at, tz) == today] + if due: + taken = sum(d.status == "taken" for d in due) + due_now = sum(d.planned_at <= now for d in due) + items.append( + TodayItem( + activity="meds", + title=cfg.today["meds"], + done=taken > 0 and taken >= due_now, + detail=f"{taken} из {len(due)}", + ) + ) + items.append(TodayItem(activity="diary", title=cfg.today["diary"], done="diary" in done_today)) + # A questionnaire is not due every day: show it only once done, so an empty day is never a «missed» item. + if "questionnaire" in done_today: + items.append(TodayItem(activity="questionnaire", title=cfg.today["questionnaire"], done=True)) + garden.today = items + return garden diff --git a/config/garden.yaml b/config/garden.yaml new file mode 100644 index 0000000..4aec888 --- /dev/null +++ b/config/garden.yaml @@ -0,0 +1,38 @@ +# Сад (#118, слайд 13): лёгкая геймификация поверх модулей. Расчёт детерминированный, без LLM. +# Принципы «без давления» (вычитка — #120): +# 1. Сад не вянет: очки только прибавляются, пропуск ничего не отнимает. +# 2. Рост не зависит от ответов: считается факт активности, а не баллы шкал или настроение. +# 3. Нет соревнования: только свой сад, никаких сравнений. + +# Очки за активность и дневной лимит по каждому типу (чтобы пять одинаковых действий подряд не давали пятикратный рост). +activities: + meds: # отметка «Принял(а)» по назначенной дозе + points: 2 + daily_cap: 4 + diary: # ежедневный чек-ин или запись дневника + points: 3 + daily_cap: 1 + questionnaire: # завершённый опрос (шкала, этап опроса) + points: 4 + daily_cap: 1 + +# Каждые step_points очков — один шаг роста. Растения растут по очереди: у каждого stages_per_plant стадий +# (росток → стебель → бутон → цветок); распустился один — проклёвывается следующий. +step_points: 10 +stages_per_plant: 4 +max_plants: 6 + +# Название сада по числу шагов роста (берётся последний порог ≤ шагов). +titles: + - {from_steps: 0, title: "Сад ждёт первых ростков"} + - {from_steps: 1, title: "Появились первые ростки"} + - {from_steps: 4, title: "Распустился первый цветок"} + - {from_steps: 10, title: "Сад растёт"} + - {from_steps: 18, title: "Сад цветёт"} + - {from_steps: 24, title: "Цветущий сад"} + +# Подписи пунктов «Сегодня». +today: + meds: "Приём лекарств" + diary: "Запись в дневнике" + questionnaire: "Назначенный опрос" diff --git a/tests/test_services_garden.py b/tests/test_services_garden.py new file mode 100644 index 0000000..6959040 --- /dev/null +++ b/tests/test_services_garden.py @@ -0,0 +1,88 @@ +"""Garden (#118): deterministic growth from activities, daily caps, never shrinks, ignores answers.""" + +from collections.abc import AsyncIterator +from datetime import date, datetime, timedelta + +import pytest +from httpx import ASGITransport, AsyncClient +from sqlalchemy import select + +from app.config import Settings +from app.core import clock +from app.db import session +from app.db.clinical import DailyCheckin, Dose +from app.main import app +from app.services.garden import compute, load_config +from scripts.seed_demo import seed + +MEM = "sqlite+aiosqlite:///:memory:" +NOW = datetime(2026, 10, 5, 14, 0) +D = date(2026, 10, 5) + + +def test_points_steps_and_daily_caps() -> None: + cfg = load_config() + one_diary = compute([("diary", D)], D) + assert one_diary.points == cfg.activities["diary"].points + # Five diary entries on one day count as one; on five days — five times. + assert compute([("diary", D)] * 5, D).points == one_diary.points + five_days = compute([("diary", D - timedelta(days=i)) for i in range(5)], D) + assert five_days.points == 5 * one_diary.points + assert five_days.steps == five_days.points // cfg.step_points + assert five_days.points_in_step == five_days.points % cfg.step_points + + +def test_never_shrinks_and_future_ignored() -> None: + events = [("meds", D), ("diary", D), ("questionnaire", D)] + now = compute(events, D) + # A week without any activity takes nothing away. + assert compute(events, D + timedelta(days=7)).points == now.points + # Rows dated after the (demo) today are not counted yet. + assert compute([*events, ("diary", D + timedelta(days=1))], D).points == now.points + + +def test_plants_grow_one_after_another() -> None: + cfg = load_config() + per_plant = cfg.stages_per_plant + g = compute([("questionnaire", D - timedelta(days=i)) for i in range(100)], D) + stages = [p.stage for p in g.plants] + assert stages == sorted(stages, reverse=True) and stages[0] == per_plant + assert sum(stages) == min(g.steps, per_plant * cfg.max_plants) + assert compute([], D).title == cfg.titles[0].title + + +@pytest.fixture +async def client(monkeypatch: pytest.MonkeyPatch) -> AsyncIterator[AsyncClient]: + monkeypatch.setattr(clock, "get_settings", lambda: Settings(_env_file=None, demo_clock=True)) + clock.set_now(NOW) + await session.configure(identity_url=MEM, clinical_url=MEM) + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c: + yield c + await session.configure() + + +async def test_andrey_has_a_living_garden_that_grows_and_ignores_mood(client: AsyncClient) -> None: + token = (await seed(12)).andrey_token + url = f"/api/v1/me/{token}/garden" + before = (await client.get(url)).json() + assert before["steps"] >= 4 and before["plants"][0]["stage"] > 0 + + # Mood is an answer: a bad day and a good day grow the garden the same way. + async with session.get_clinical_session() as s: + rows = (await s.scalars(select(DailyCheckin).where(DailyCheckin.token == token))).all() + for r in rows: + r.mood = 1 + assert (await client.get(url)).json()["points"] == before["points"] + + # Taking a dose today adds points. + async with session.get_clinical_session() as s: + dose = Dose(token=token, prescription_id=1, planned_at=clock.now(), status="taken", answered_at=clock.now()) + s.add(dose) + after = (await client.get(url)).json() + assert after["points"] >= before["points"] + assert any(i["activity"] == "diary" for i in after["today"]) + + +async def test_unknown_patient_404(client: AsyncClient) -> None: + await seed(0) + assert (await client.get("/api/v1/me/nobody/garden")).status_code == 404