diff --git a/.env.example b/.env.example index 53e7253..9b90399 100644 --- a/.env.example +++ b/.env.example @@ -37,3 +37,13 @@ GITEA_URL=https://gitea.24studbank.ru GITEA_REPO=MedITron/PTSRaiAgent GITEA_USER= GITEA_TOKEN= +# MAX notifications: keep disabled until the backend/channel PRs and a real bot are installed. +MAX_ENABLED=false +MAX_BOT_TOKEN= +MAX_BOT_USERNAME= +MAX_WEBHOOK_SECRET= +MAX_WEBHOOK_URL= +MAX_SITE_URL= +# Optional path to a trusted PEM CA bundle; never disable TLS verification. +MAX_CA_BUNDLE= +MAX_LINK_TTL_SECONDS=600 diff --git a/.streamlit/config.toml b/.streamlit/config.toml index c66a55f..4900afa 100644 --- a/.streamlit/config.toml +++ b/.streamlit/config.toml @@ -1,15 +1,15 @@ # Dashboard-only Streamlit settings (doctor dashboard + demo console). [theme] base = "light" -primaryColor = "#2A78D6" -backgroundColor = "#F6F7F9" +primaryColor = "#285E4E" +backgroundColor = "#F6F7F3" secondaryBackgroundColor = "#FFFFFF" -textColor = "#1B1F24" -borderColor = "#E3E6EA" +textColor = "#213B38" +borderColor = "#E1E7E3" baseRadius = "medium" # Falls back to the system sans-serif when offline (ADR-004). -font = "Inter:https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap, sans-serif" -headingFontWeights = 700 +font = "sans-serif" +headingFontWeights = 600 [client] toolbarMode = "minimal" diff --git a/app/api/max_notifications.py b/app/api/max_notifications.py new file mode 100644 index 0000000..c8e759e --- /dev/null +++ b/app/api/max_notifications.py @@ -0,0 +1,115 @@ +"""Server API for a future MAX connect UI; webhook processing is supplied by the channel adapter.""" + +import hmac +import json +import re +from datetime import datetime +from typing import Annotated, Literal + +from fastapi import APIRouter, Depends, HTTPException, Request +from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer +from pydantic import BaseModel, ConfigDict +from sqlalchemy import select +from sqlalchemy.exc import SQLAlchemyError + +from app.config import get_settings +from app.core import clock +from app.db import repo +from app.db.max_notifications import MaxBinding, MaxDelivery +from app.db.session import get_clinical_session, get_identity_session +from app.integrations import max_store + +router = APIRouter(tags=["max-notifications"]) +bearer = HTTPBearer(auto_error=False) + + +async def patient_token(auth: Annotated[HTTPAuthorizationCredentials | None, Depends(bearer)]) -> str: + if auth is None or auth.scheme.lower() != "bearer" or not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", auth.credentials): + raise HTTPException(401, "patient authentication required", headers={"WWW-Authenticate": "Bearer"}) + async with get_clinical_session() as session: + if await repo.get_profile(session, auth.credentials) is None: + raise HTTPException(401, "patient authentication required") + return auth.credentials + + +PatientToken = Annotated[str, Depends(patient_token)] + + +class MaxStatus(BaseModel): + available: bool + connected: bool + last_delivery: str | None = None + + +class LinkConsent(BaseModel): + model_config = ConfigDict(extra="forbid") + consent: Literal[True] + + +class MaxLink(BaseModel): + url: str + expires_at: datetime + + +@router.get("/me/notifications/max", response_model=MaxStatus) +async def status(token: PatientToken) -> MaxStatus: + async with get_identity_session() as session: + binding = await session.get(MaxBinding, token) + last = await session.scalar( + select(MaxDelivery.state) + .where(MaxDelivery.token == token) + .order_by(MaxDelivery.created_at.desc(), MaxDelivery.id.desc()) + .limit(1) + ) + return MaxStatus( + available=get_settings().max_enabled, connected=bool(binding and binding.enabled), last_delivery=last + ) + + +@router.post("/me/notifications/max/link", response_model=MaxLink) +async def link(body: LinkConsent, token: PatientToken) -> MaxLink: + settings = get_settings() + if not settings.max_enabled: + raise HTTPException(503, "MAX is not configured") + if not await max_store.active_patient(token): + raise HTTPException(403, "active consent and adult confirmation required") + async with get_identity_session() as session: + raw, expires = await max_store.issue_code(session, token, clock.now(), settings.max_link_ttl_seconds) + return MaxLink(url=f"https://max.ru/{settings.max_bot_username}?start={raw}", expires_at=expires) + + +@router.delete("/me/notifications/max", response_model=MaxStatus) +async def unlink(token: PatientToken) -> MaxStatus: + async with get_identity_session() as session: + await max_store.disconnect(session, token) + return MaxStatus(available=get_settings().max_enabled, connected=False) + + +@router.post("/webhooks/max") +async def webhook(request: Request) -> dict[str, bool]: + settings = get_settings() + if not settings.max_enabled: + raise HTTPException(503, "MAX is not configured") + expected = settings.max_webhook_secret.get_secret_value().encode() + supplied = request.headers.get("X-Max-Bot-Api-Secret", "").encode() + if not expected or not hmac.compare_digest(supplied, expected): + raise HTTPException(403, "invalid webhook secret") + raw = bytearray() + async for chunk in request.stream(): + raw.extend(chunk) + if len(raw) > 65536: + raise HTTPException(413, "event is too large") + try: + event = json.loads(raw) + except (ValueError, UnicodeError) as exc: + raise HTTPException(400, "invalid JSON") from exc + if not isinstance(event, dict): + raise HTTPException(422, "event must be an object") + from app.channels.max_bot import handle_update + + try: + await handle_update(event) + except SQLAlchemyError: + # Let MAX retry; do not log DB exception parameters containing identity data. + raise HTTPException(503, "notification storage unavailable") from None + return {"success": True} diff --git a/app/api/routes.py b/app/api/routes.py index 8d616b8..88266a7 100644 --- a/app/api/routes.py +++ b/app/api/routes.py @@ -15,7 +15,7 @@ from sqlalchemy import select from app.api import demo as console from app.api import doctor_views as views -from app.api import fixtures +from app.api import fixtures, max_notifications from app.api.patient_web import router as patient_web_router from app.api.questionnaire import router as questionnaire_router from app.api.schemas import ( @@ -46,6 +46,7 @@ from app.scheduler import jobs as scheduler from app.services.monitoring import refresh_status router = APIRouter(prefix="/api/v1") +router.include_router(max_notifications.router) router.include_router(questionnaire_router) router.include_router(patient_web_router) diff --git a/app/channels/MAX_SETUP.md b/app/channels/MAX_SETUP.md new file mode 100644 index 0000000..f612b24 --- /dev/null +++ b/app/channels/MAX_SETUP.md @@ -0,0 +1,150 @@ +# Подключение будущего бота MAX + +Серверная часть готова к подключению. Сам бот ещё не создан, секреты не заполнены, +реальная отправка не включена. Изменений интерфейса сайта в этой поставке нет. +Интеграция уведомляет **самого пациента**; врачебные оповещения остаются в существующем канале проекта. + +## Что реализовано + +- Одноразовая ссылка для привязки аккаунта MAX к текущему пациенту сайта, срок по умолчанию 10 минут. +- Подтверждение подключения, `/help`, `/stop`, отключение при остановке или удалении бота в MAX. +- Нейтральные напоминания из существующего планировщика сайта: тесты, дневник, приём лекарств и другие события outbox. +- Уведомление о завершении теста: сервер каждые примерно 30 секунд находит новые завершённые + `QuestionnaireRecord` и `ScaleResult`, начиная с момента подключения MAX. Незавершённые и старые тесты не отправляются. +- Постоянная очередь, восстановление после перезапуска, ограниченные повторы при сетевых ошибках и ответах 429/5xx. +- В сообщении только короткий текст и кнопка на сайт. Ответы, оценки, диагнозы, назначения и ключ входа на сайт + в MAX не передаются. Переписка с ботом не сохраняется и не отправляется в LLM. + +## 1. Создать бота — будущему владельцу + +1. Открыть [MAX для партнёров](https://business.max.ru/) и пройти регистрацию/проверку профиля. + Условия допуска зависят от типа владельца; актуальный порядок — в + [официальной инструкции подключения](https://dev.max.ru/help/platform_connection). +2. Создать чат-бота, оформить описание и пройти требуемую MAX модерацию. +3. В настройках бота получить токен и скопировать имя из его публичной ссылки `https://max.ru/ИМЯ`. +4. Передать администратору сервера имя бота, а токен — через защищённое хранилище секретов. + Токен не нужен в переписке, MR или репозитории. + +## 2. Заполнить настройки сервера + +Нужны доступная identity/clinical БД проекта, публичный HTTPS-адрес сайта и HTTPS-адрес API на порту 443. +Входящие POST от MAX должны доходить до API без браузерной CAPTCHA или страницы авторизации. +Прокси должен передавать заголовок `X-Max-Bot-Api-Secret` и не журналировать тело webhook/Authorization. +Дополнительные таблицы identity создаются существующим `init_db()` при запуске приложения. + +В `.env` сервера (вне Git) заполнить: + +```dotenv +MAX_ENABLED=false +MAX_BOT_TOKEN= +MAX_BOT_USERNAME= +MAX_WEBHOOK_SECRET= +MAX_WEBHOOK_URL=https://api.example.org/api/v1/webhooks/max +MAX_SITE_URL=https://patient.example.org/ +MAX_LINK_TTL_SECONDS=600 +# При необходимости — PEM-файл доверенного CA, доступный внутри контейнера: +MAX_CA_BUNDLE= +DEMO_CLOCK=false +``` + +- `MAX_BOT_USERNAME` — только имя, без `@`, домена или параметров ссылки. +- `MAX_WEBHOOK_SECRET` — отдельная случайная строка, не токен бота: 32–256 символов из `A–Z a–z 0–9 _ -`. + Сгенерировать локально, например `python -c 'import secrets; print(secrets.token_urlsafe(32))'`, сохранить в секреты. +- `MAX_SITE_URL` ведёт в обычный личный кабинет; не добавлять в адрес ключи доступа или данные пациента. +- Исходящие запросы идут на `https://platform-api2.max.ru`, токен передаётся заголовком `Authorization`. + Верификация TLS всегда включена. Если системе нужен корневой сертификат Минцифры, установить его по + официальной инструкции MAX и указать PEM-путь в `MAX_CA_BUNDLE`; не отключать проверку TLS. +- Переменные должны попасть именно в окружение API-контейнера/процесса, а не только панели сайта. + В текущем Compose сервис `app` уже получает `.env` через `env_file`. + После изменения окружения пересоздать процесс/контейнер API. Новые зависимости не требуются. + +## 3. Проверить и включить + +В каталоге проекта, в том же окружении, где работает API: + +```sh +uv run python -m app.channels.max_setup check +``` + +Команда проверит токен и совпадение имени бота. Сообщений пользователям она не отправляет. +Затем установить `MAX_ENABLED=true`, перезапустить API и выполнить: + +```sh +uv run python -m app.channels.max_setup subscribe +uv run python -m app.channels.max_setup status +``` + +`subscribe` регистрирует только заданный webhook с секретом и событиями +`bot_started`, `message_created`, `bot_stopped`, `dialog_removed`. Старые чужие подписки автоматически +не удаляются: при переносе сервера владелец должен проверить их отдельно через MAX API. +`status` проверяет регистрацию адреса; это ещё не проверка доступности сервера из MAX. +Команды не печатают токены, секрет webhook или сырые ответы платформы. + +При запуске через Compose вместо `uv run python ...` использовать +`docker compose exec app python -m app.channels.max_setup check` (также `subscribe` и `status`). +После изменения `.env` пересоздать API: `docker compose up -d --build --force-recreate app`. + +Запускать один процесс API с MAX на один токен бота: его worker отправляет до одного сообщения в секунду. +БД защищает очередь от параллельного захвата, но общий лимит скорости нескольких процессов не координируется. +Планировщик и MAX worker запускаются вместе с FastAPI, отдельный процесс бота не нужен. +При `MAX_ENABLED=false` сетевых вызовов MAX и фонового worker нет; сайт продолжает обычную работу. + +## API для разработчика сайта + +В проекте используется ключ текущего пациента, полученный при входе. Для этих ручек передавать его +как `Authorization: Bearer `; это существующая авторизация прототипа, не новая система SSO. +Не брать token другого пациента и не публиковать демонстрационные учётные записи для реального использования. + +| Метод и путь | Запрос | Ответ | +|---|---|---| +| `GET /api/v1/me/notifications/max` | Authorization | `available`, `connected`, `last_delivery` | +| `POST /api/v1/me/notifications/max/link` | Authorization; JSON `{"consent": true}` | `url`, `expires_at` | +| `DELETE /api/v1/me/notifications/max` | Authorization | состояние с `connected: false` | +| `POST /api/v1/webhooks/max` | MAX JSON + `X-Max-Bot-Api-Secret` | `{"success": true}` после записи события | + +Поток подключения: пациент явно соглашается на уведомления → сайт получает `url` → открывает ссылку MAX → +пользователь запускает бота → webhook подтверждает привязку → повторный GET показывает `connected: true`. +Ссылка одноразовая; новая ссылка отменяет предыдущую. Изначальный ключ пациента не входит в URL MAX. +Для привязки и доставки дополнительно нужны действующее согласие и подтверждение совершеннолетия в состоянии пациента. +Активную привязку нельзя молча переназначить другому аккаунту: сначала отключить её. + +Коды ошибок: 401 — неизвестный/отсутствующий ключ пациента; 403 — нет согласия или неверный секрет webhook; +422 — неверный запрос; 413 — webhook больше 64 КиБ; 503 — MAX выключен или хранилище события недоступно. +Повтор webhook с тем же идентификатором события не создаёт новых отправок. Групповые чаты игнорируются. + +`last_delivery`: `queued`, `sending`, `sent`, `failed`, `cancelled` или `null`. +`sent` означает принятие сообщения API MAX, а не прочтение человеком. + +## Пробное подключение после создания бота + +1. Войти на сайте синтетическим пациентом и дать необходимые согласия. +2. Получить ссылку через POST выше (Swagger `/docs` или будущий интерфейс сайта), перейти в MAX и запустить бота. +3. Убедиться, что GET показывает `connected: true` и приходит подтверждение. +4. Завершить тест на сайте; примерно через 30 секунд плюс очередь должно прийти сообщение без результатов. +5. Дождаться события планировщика и проверить нейтральное напоминание с кнопкой на сайт. +6. Отправить `/stop`: GET должен показать `connected: false`, ожидающие уведомления отменяются. +7. Повторить подключение новой ссылкой, проверить DELETE через API и остановку бота через интерфейс MAX. + +При недоставке проверить настройки и подписку, доступность HTTPS, состояние очереди и коды ошибок в логах. +`http_401`/`http_403` требуют проверки токена/прав; `http_429` — ожидания; `transport` — сети/TLS; +`failed` после шести попыток требует вмешательства администратора. Детали ответов и идентификаторы в логи не выводятся. +Отключение отменяет очередь; уже принятый MAX запрос отозвать невозможно. + +## Гарантии и ограничения + +Очередь и подтверждения событий сохраняются в identity БД. Клинические записи остаются в clinical БД. +Для событий завершения тестов БД повторно просматривается после перезапуска; ключи уведомлений предотвращают +повторную постановку. Напоминания используют существующий механизм outbox/повторов планировщика. +При временных ошибках — до 6 попыток с увеличением задержки и учётом `Retry-After`; зависшая отправка получает +новую аренду через 60 секунд. Потеря процесса между принятием сообщения MAX и записью успеха в БД может +привести к повторному сообщению: MAX не предоставляет ключ идемпотентности отправки. +Не удалять строки дедупликации/очереди без согласованной политики хранения. При большом количестве пациентов +нужны пакетное сканирование завершённых тестов и общий ограничитель скорости; текущая реализация рассчитана на MVP. + +Проверки разработчика: `make lint test`; тесты MAX работают с синтетикой и подменённым HTTP-транспортом. +Реальную доставку подтвердит только пробное подключение после выдачи токена и настройки публичного сервера. + +Официальные контракты: [отправка сообщений](https://dev.max.ru/docs-api/methods/POST/messages), +[подписка webhook](https://dev.max.ru/docs-api/methods/POST/subscriptions), +[события](https://dev.max.ru/docs-api/objects/Update), +[ссылки запуска бота](https://dev.max.ru/docs/chatbots/bots-coding/prepare). diff --git a/app/channels/max_bot.py b/app/channels/max_bot.py new file mode 100644 index 0000000..e2a2dc6 --- /dev/null +++ b/app/channels/max_bot.py @@ -0,0 +1,224 @@ +"""Notifications-only MAX adapter; no patient text enters the dialog engine or an LLM. + +Webhook transactions persist receipts and replies together, then return immediately. +The worker delivers from identity DB with leases and bounded retries. MAX has no send +idempotency key: a crash after API acceptance and before commit can duplicate a message. +""" + +import asyncio +import contextlib +import json +import logging +from functools import lru_cache + +import yaml +from pydantic import BaseModel, Field +from sqlalchemy import select +from sqlalchemy.exc import IntegrityError + +from app.channels.max_client import MaxApiError, MaxClient +from app.config import get_settings +from app.core import clock +from app.db.max_notifications import MaxBinding, MaxReceipt +from app.db.session import get_identity_session +from app.dialog.contracts import Reply +from app.integrations import max_store as store +from app.integrations.base import Outbox, integrations + +log = logging.getLogger(__name__) + + +class Texts(BaseModel): + connected: str = Field(max_length=4000) + not_connected: str = Field(max_length=4000) + invalid: str = Field(max_length=4000) + stopped: str = Field(max_length=4000) + help: str = Field(max_length=4000) + notification: str = Field(max_length=4000) + completed: str = Field(max_length=4000) + open_site: str = Field(max_length=128) + + +@lru_cache +def texts() -> Texts: + path = get_settings().config_dir / "texts" / "max.yaml" + return Texts.model_validate(yaml.safe_load(path.read_text(encoding="utf-8"))) + + +def _event(event: dict) -> tuple[str, int, str, str] | None: + """Normalize only documented private-user events; unknown/malformed events are ignored.""" + kind = event.get("update_type") + stamp = event.get("timestamp") + if type(stamp) is not int or stamp < 0: + return None + message_id = "" + if kind == "message_created": + message = event.get("message") + if not isinstance(message, dict): + return None + recipient, body = message.get("recipient"), message.get("body") + if not isinstance(recipient, dict) or recipient.get("chat_type") != "dialog" or not isinstance(body, dict): + return None + user, text, message_id = message.get("sender"), body.get("text"), body.get("mid") + if not isinstance(message_id, str) or not message_id or not isinstance(text, str): + return None + elif kind in ("bot_started", "bot_stopped", "dialog_removed"): + user, text = event.get("user"), event.get("payload") or "" + else: + return None + if not isinstance(user, dict) or user.get("is_bot") is not False: + return None + uid = user.get("user_id") + if type(uid) is not int or not 0 < uid < 2**63 or not isinstance(text, str) or len(text) > 4000: + return None + # Names, profile details and raw text are neither persisted nor logged. + receipt = store.digest(f"{kind}:{uid}:{message_id or stamp}") + return kind, uid, text.strip(), receipt + + +async def handle_update(event: dict) -> None: + if not get_settings().max_enabled or (parsed := _event(event)) is None: + return + kind, user_id, text, receipt = parsed + now = clock.now() + try: + async with get_identity_session() as session: + if await session.get(MaxReceipt, receipt): + return + session.add(MaxReceipt(digest=receipt, received_at=now)) + await session.flush() + binding = await session.scalar(select(MaxBinding).where(MaxBinding.user_id == user_id)) + reply_token = None + command, _, payload = text.partition(" ") + if kind in ("bot_stopped", "dialog_removed") or command.lower() == "/stop": + if binding: + await store.disconnect(session, binding.token) + # When MAX itself stops/deletes the bot, do not attempt a reply. + if kind != "message_created": + return + reply = "stopped" + elif kind == "bot_started" or command.lower() == "/start": + code = text if kind == "bot_started" else payload.strip() + if code: + token = await store.code_token(session, code, now) if len(code) <= 128 else None + linked = ( + token and await store.active_patient(token) and await store.bind(session, code, user_id, now) + ) + reply = "connected" if linked else "invalid" + reply_token = token if linked else None + else: + reply = "connected" if binding and binding.enabled else "not_connected" + reply_token = binding.token if binding and binding.enabled else None + else: + reply = "help" + await store.enqueue(session, key=receipt, user_id=user_id, token=reply_token, kind=reply, now=now) + except IntegrityError: + # A concurrent delivery of the same webhook can race on its receipt primary key. + async with get_identity_session() as session: + if await session.get(MaxReceipt, receipt) is None: + raise + + +class MaxOutbox: + def __init__(self, fallback: Outbox): + self.fallback = fallback + + async def push(self, token: str, replies: list[Reply]) -> None: + if replies and get_settings().max_enabled and await store.active_patient(token): + async with get_identity_session() as session: + binding = await session.get(MaxBinding, token) + if binding and binding.enabled: + # Hash the event for retry deduplication; never store/transmit its clinical text. + event = json.dumps([r.model_dump() for r in replies], sort_keys=True, ensure_ascii=False) + key = store.digest(f"{token}:{binding.connected_at.isoformat()}:{clock.today()}:{event}") + await store.enqueue( + session, key=key, user_id=binding.user_id, token=token, kind="notification", now=clock.now() + ) + await self.fallback.push(token, replies) + + +async def deliver_one(client: MaxClient) -> bool: + async with get_identity_session() as session: + row = await store.claim(session, clock.now()) + if row is None: + return False + if row.token is not None: + async with get_identity_session() as session: + binding = await session.get(MaxBinding, row.token) + valid = ( + binding + and binding.enabled + and binding.user_id == row.user_id + and binding.connected_at <= row.created_at + ) + if not valid or not await store.active_patient(row.token): + async with get_identity_session() as session: + await store.finish(session, row, state="cancelled", now=clock.now()) + return True + settings, messages = get_settings(), texts() + try: + await client.send( + row.user_id, getattr(messages, row.kind), site_url=settings.max_site_url, button=messages.open_site + ) + except MaxApiError as exc: + retry = exc.retryable and row.attempts < store.MAX_ATTEMPTS + delay = max(exc.retry_after, min(300, 5 * 2 ** (row.attempts - 1))) + async with get_identity_session() as session: + await store.finish( + session, + row, + state="queued" if retry else "failed", + now=clock.now(), + error=exc.code, + retry_seconds=delay if retry else 0, + ) + log.warning("MAX delivery deferred=%s code=%s", retry, exc.code) + else: + async with get_identity_session() as session: + await store.finish(session, row, state="sent", now=clock.now()) + return True + + +async def _run(client: MaxClient) -> None: + tick = 0 + while True: + try: + if tick % 30 == 0: + async with get_identity_session() as session: + await store.collect_completed(session, clock.now()) + await deliver_one(client) + except Exception as exc: + # No exception text: SQL/HTTP errors may contain identifiers or parameters. + log.error("MAX worker failed type=%s", type(exc).__name__) + tick += 1 + # One send per second per process, below MAX's two-per-second per-dialog limit. + await asyncio.sleep(1) + + +_client: MaxClient | None = None +_task: asyncio.Task | None = None +_wrapper: MaxOutbox | None = None + + +async def start() -> None: + global _client, _task, _wrapper + if not get_settings().max_enabled or _task is not None: + return + texts() # Validate templates before replacing a working outbox. + _client = MaxClient(get_settings()) + _wrapper = MaxOutbox(integrations.outbox) + integrations.outbox = _wrapper + _task = asyncio.create_task(_run(_client), name="max-notifications") + + +async def stop() -> None: + global _client, _task, _wrapper + if _task: + _task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await _task + if _wrapper and integrations.outbox is _wrapper: + integrations.outbox = _wrapper.fallback + if _client: + await _client.close() + _client = _task = _wrapper = None diff --git a/app/channels/max_client.py b/app/channels/max_client.py new file mode 100644 index 0000000..1282423 --- /dev/null +++ b/app/channels/max_client.py @@ -0,0 +1,101 @@ +"""Small MAX Bot API client. Secrets stay in headers; failures never expose response bodies.""" + +import logging +import ssl + +import httpx + +from app.config import Settings + +API_URL = "https://platform-api2.max.ru" +UPDATE_TYPES = ["bot_started", "message_created", "bot_stopped", "dialog_removed"] + + +class _HideRecipient(logging.Filter): + def filter(self, record: logging.LogRecord) -> bool: + # httpx INFO normally logs query strings, which include a MAX user_id. + return "platform-api2.max.ru" not in record.getMessage() + + +logging.getLogger("httpx").addFilter(_HideRecipient()) + + +class MaxApiError(Exception): + def __init__(self, code: str, *, retryable: bool = False, retry_after: float = 0): + self.code, self.retryable, self.retry_after = code, retryable, retry_after + super().__init__(code) + + +class MaxClient: + def __init__(self, settings: Settings, *, transport: httpx.AsyncBaseTransport | None = None): + context = ssl.create_default_context() + if settings.max_ca_bundle: + context.load_verify_locations(cafile=str(settings.max_ca_bundle)) + self.http = httpx.AsyncClient( + base_url=API_URL, + headers={"Authorization": settings.max_bot_token.get_secret_value()}, + timeout=httpx.Timeout(5), + verify=context, + follow_redirects=False, + transport=transport, + ) + + async def close(self) -> None: + await self.http.aclose() + + async def request(self, method: str, path: str, **kwargs) -> dict: + try: + response = await self.http.request(method, path, **kwargs) + except httpx.RequestError: + raise MaxApiError("transport", retryable=True) from None + if not response.is_success: + try: + delay = min(3600, max(0, float(response.headers.get("Retry-After", "0")))) + except ValueError: + delay = 0 + raise MaxApiError( + f"http_{response.status_code}", + retryable=response.status_code in (408, 429) or response.status_code >= 500, + retry_after=delay, + ) + try: + data = response.json() + except ValueError: + raise MaxApiError("invalid_response", retryable=True) from None + if not isinstance(data, dict): + raise MaxApiError("invalid_response", retryable=True) + if data.get("success") is False: + raise MaxApiError("rejected") + return data + + async def send(self, user_id: int, text: str, *, site_url: str, button: str) -> None: + data = await self.request( + "POST", + "/messages", + params={"user_id": user_id, "disable_link_preview": "true"}, + json={ + "text": text, + "notify": True, + "attachments": [ + { + "type": "inline_keyboard", + "payload": {"buttons": [[{"type": "link", "text": button, "url": site_url}]]}, + } + ], + }, + ) + if not isinstance(data.get("message"), dict): + raise MaxApiError("missing_message", retryable=True) + + async def subscribe(self, settings: Settings) -> None: + data = await self.request( + "POST", + "/subscriptions", + json={ + "url": settings.max_webhook_url, + "update_types": UPDATE_TYPES, + "secret": settings.max_webhook_secret.get_secret_value(), + }, + ) + if data.get("success") is not True: + raise MaxApiError("subscription_not_confirmed") diff --git a/app/channels/max_setup.py b/app/channels/max_setup.py new file mode 100644 index 0000000..2fffd08 --- /dev/null +++ b/app/channels/max_setup.py @@ -0,0 +1,56 @@ +"""Operator commands for a future bot owner. Never runs as part of application startup.""" + +import argparse +import asyncio +import sys + +from pydantic import ValidationError + +from app.channels.max_client import MaxApiError, MaxClient +from app.config import Settings + + +async def run(command: str) -> None: + # Validate the same configuration even while the deployed app is still disabled. + settings = Settings(max_enabled=True) + client = MaxClient(settings) + try: + bot = await client.request("GET", "/me") + if bot.get("is_bot") is not True: + raise MaxApiError("not_a_bot") + if bot.get("username") != settings.max_bot_username: + raise MaxApiError("bot_username_mismatch") + if command == "subscribe": + await client.subscribe(settings) + print("Webhook MAX зарегистрирован. Проверьте командой status, затем выполните пробное подключение.") + elif command == "status": + result = await client.request("GET", "/subscriptions") + subscriptions = result.get("subscriptions", []) + configured = any(isinstance(s, dict) and s.get("url") == settings.max_webhook_url for s in subscriptions) + print("Нужный webhook зарегистрирован." if configured else "Нужный webhook не найден.") + if not configured: + raise MaxApiError("webhook_missing") + else: + print("Токен принят MAX, имя бота совпадает с настройкой. Подписка не изменялась.") + finally: + await client.close() + + +def main() -> int: + parser = argparse.ArgumentParser(description="Подготовка MAX: параметры берутся только из .env/окружения.") + parser.add_argument("command", choices=("check", "subscribe", "status")) + args = parser.parse_args() + try: + asyncio.run(run(args.command)) + except ValidationError: + print("Проверьте параметры MAX в .env по app/channels/MAX_SETUP.md.", file=sys.stderr) + return 1 + except (MaxApiError, OSError) as exc: + code = exc.code if isinstance(exc, MaxApiError) else "tls_or_file_error" + print(f"Не удалось выполнить настройку MAX: {code}. Секреты и ответ сервера скрыты.", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/app/config.py b/app/config.py index 35d10e4..55a6e73 100644 --- a/app/config.py +++ b/app/config.py @@ -1,10 +1,12 @@ """Typed application settings. The only place that reads environment variables.""" +import re from functools import lru_cache from pathlib import Path from typing import Literal +from urllib.parse import urlsplit -from pydantic import Field +from pydantic import Field, SecretStr, model_validator from pydantic_settings import BaseSettings, SettingsConfigDict ROOT_DIR = Path(__file__).resolve().parent.parent @@ -12,7 +14,7 @@ ROOT_DIR = Path(__file__).resolve().parent.parent class Settings(BaseSettings): # Empty values in .env (e.g. `TG_BOT_TOKEN=`) fall back to defaults instead of failing validation. - model_config = SettingsConfigDict(env_file=".env", extra="ignore", env_ignore_empty=True) + model_config = SettingsConfigDict(env_file=".env", extra="ignore", env_ignore_empty=True, hide_input_in_errors=True) # Two separate databases (ADR-003): identity holds direct identifiers, clinical holds pseudonymised data. identity_db_url: str = "postgresql+asyncpg://identity_app:identity_app@localhost:5432/identity" @@ -43,6 +45,36 @@ class Settings(BaseSettings): tg_bot_token: str = "" doctor_notify_chat_id: int | None = None + # MAX is opt-in. Its adapter is delivered in the related backend/channel changes. + max_enabled: bool = False + max_bot_token: SecretStr = SecretStr("") + max_bot_username: str = "" + max_webhook_secret: SecretStr = SecretStr("") + max_webhook_url: str = "" + max_site_url: str = "" + max_ca_bundle: Path | None = None + max_link_ttl_seconds: int = Field(default=600, ge=60, le=1800) + + @model_validator(mode="after") + def validate_max(self) -> "Settings": + if not self.max_enabled: + return self + if not self.max_bot_token.get_secret_value().strip(): + raise ValueError("MAX_BOT_TOKEN is required when MAX_ENABLED=true") + if not re.fullmatch(r"[A-Za-z0-9_]{1,128}", self.max_bot_username): + raise ValueError("MAX_BOT_USERNAME must be the bot nickname without @ or a URL") + if not re.fullmatch(r"[A-Za-z0-9_-]{32,256}", self.max_webhook_secret.get_secret_value()): + raise ValueError("MAX_WEBHOOK_SECRET must contain 32..256 URL-safe characters") + for name, value in (("MAX_SITE_URL", self.max_site_url), ("MAX_WEBHOOK_URL", self.max_webhook_url)): + url = urlsplit(value) + if url.scheme != "https" or not url.hostname or url.username or url.password or url.port not in (None, 443): + raise ValueError(f"{name} must use HTTPS on port 443 without credentials") + if url.query or (name == "MAX_WEBHOOK_URL" and url.fragment): + raise ValueError(f"{name} must not contain a query string (or a fragment for webhook)") + if self.max_ca_bundle is not None and not self.max_ca_bundle.is_file(): + raise ValueError("MAX_CA_BUNDLE must point to an existing trusted CA bundle") + return self + # Virtual clock for the demo (ADR-005). demo_clock: bool = True tz: str = "Europe/Moscow" diff --git a/app/db/bootstrap.py b/app/db/bootstrap.py index f4f163d..1b6724b 100644 --- a/app/db/bootstrap.py +++ b/app/db/bootstrap.py @@ -5,6 +5,7 @@ The only module (besides registration code) that touches both schemas — and on from app.db import audit as _audit # noqa: F401 (registers audit_log in clinical metadata) from app.db import intake as _intake # noqa: F401 +from app.db import max_notifications as _max_notifications # noqa: F401 from app.db import scheduler as _scheduler # noqa: F401 from app.db.clinical import ClinicalBase from app.db.identity import IdentityBase diff --git a/app/db/max_notifications.py b/app/db/max_notifications.py new file mode 100644 index 0000000..c8c4391 --- /dev/null +++ b/app/db/max_notifications.py @@ -0,0 +1,50 @@ +"""MAX identifiers and delivery metadata live only in the identity DB; no medical message bodies.""" + +from datetime import datetime + +from sqlalchemy import BigInteger, Boolean, Integer, String +from sqlalchemy.orm import Mapped, mapped_column + +from app.db.identity import IdentityBase +from app.db.types import TZDateTime + + +class MaxBinding(IdentityBase): + __tablename__ = "max_bindings" + + # No FK: anonymous web profiles intentionally have no patients row in identity. + token: Mapped[str] = mapped_column(String(64), primary_key=True) + user_id: Mapped[int] = mapped_column(BigInteger, unique=True) + enabled: Mapped[bool] = mapped_column(Boolean, default=True) + connected_at: Mapped[datetime] = mapped_column(TZDateTime) + + +class MaxLinkCode(IdentityBase): + __tablename__ = "max_link_codes" + + digest: Mapped[str] = mapped_column(String(64), primary_key=True) + token: Mapped[str] = mapped_column(String(64), unique=True) + expires_at: Mapped[datetime] = mapped_column(TZDateTime, index=True) + used_at: Mapped[datetime | None] = mapped_column(TZDateTime) + + +class MaxReceipt(IdentityBase): + __tablename__ = "max_webhook_receipts" + + digest: Mapped[str] = mapped_column(String(64), primary_key=True) + received_at: Mapped[datetime] = mapped_column(TZDateTime, index=True) + + +class MaxDelivery(IdentityBase): + __tablename__ = "max_deliveries" + + id: Mapped[str] = mapped_column(String(64), primary_key=True) + token: Mapped[str | None] = mapped_column(String(64), index=True) + user_id: Mapped[int] = mapped_column(BigInteger) + kind: Mapped[str] = mapped_column(String(24)) + state: Mapped[str] = mapped_column(String(16), default="queued", index=True) + attempts: Mapped[int] = mapped_column(Integer, default=0) + created_at: Mapped[datetime] = mapped_column(TZDateTime) + next_attempt_at: Mapped[datetime] = mapped_column(TZDateTime, index=True) + lease: Mapped[str | None] = mapped_column(String(32)) + error_code: Mapped[str | None] = mapped_column(String(32)) diff --git a/app/integrations/max_store.py b/app/integrations/max_store.py new file mode 100644 index 0000000..76b8495 --- /dev/null +++ b/app/integrations/max_store.py @@ -0,0 +1,201 @@ +"""Registration boundary and durable MAX queue. Callers own the identity transaction. + +Only this boundary joins a pseudonymous profile to a MAX recipient. Clinical modules never import it. +Queue rows contain a template name, never replies, scores, prescriptions or patient-auth tokens in URLs. +""" + +import hashlib +import secrets +from datetime import datetime, timedelta + +from sqlalchemy import delete, select, update +from sqlalchemy.exc import IntegrityError +from sqlalchemy.ext.asyncio import AsyncSession + +from app.db import repo +from app.db.clinical import ScaleResult +from app.db.intake import QuestionnaireRecord +from app.db.max_notifications import MaxBinding, MaxDelivery, MaxLinkCode +from app.db.session import get_clinical_session + +MAX_ATTEMPTS = 6 +LEASE_SECONDS = 60 + + +def digest(value: str) -> str: + return hashlib.sha256(value.encode()).hexdigest() + + +async def active_patient(token: str) -> bool: + """Same consent/adult gate used by the scheduler, checked again at delivery time.""" + async with get_clinical_session() as session: + state = await repo.get_dialog_state(session, token) + return bool( + await repo.get_profile(session, token) + and state + and state.data.get("consent") is True + and state.data.get("adult") is True + ) + + +async def issue_code(session: AsyncSession, token: str, now: datetime, ttl: int) -> tuple[str, datetime]: + raw = secrets.token_urlsafe(32) + expires = now + timedelta(seconds=ttl) + await session.execute(delete(MaxLinkCode).where(MaxLinkCode.token == token)) + session.add(MaxLinkCode(digest=digest(raw), token=token, expires_at=expires)) + await session.flush() + return raw, expires + + +async def code_token(session: AsyncSession, raw: str, now: datetime) -> str | None: + row = await session.get(MaxLinkCode, digest(raw)) + return row.token if row and row.used_at is None and row.expires_at > now else None + + +async def bind(session: AsyncSession, raw: str, user_id: int, now: datetime) -> str | None: + """Atomically consume a code. Existing active identities cannot be silently reassigned.""" + token = await code_token(session, raw, now) + if token is None: + return None + owner = await session.scalar(select(MaxBinding).where(MaxBinding.user_id == user_id)) + binding = await session.get(MaxBinding, token) + if owner and owner.token != token and owner.enabled: + return None + if binding and binding.user_id != user_id and binding.enabled: + return None + used = await session.execute( + update(MaxLinkCode) + .where(MaxLinkCode.digest == digest(raw), MaxLinkCode.used_at.is_(None), MaxLinkCode.expires_at > now) + .values(used_at=now) + .returning(MaxLinkCode.token) + ) + if used.scalar_one_or_none() is None: + return None + if owner and owner.token != token: + await session.delete(owner) + await session.flush() + if binding is None: + binding = MaxBinding(token=token, user_id=user_id, connected_at=now) + session.add(binding) + # Cancel stale deliveries even when the same account reconnects later. + await cancel_pending(session, token) + binding.user_id, binding.enabled, binding.connected_at = user_id, True, now + await session.flush() + return token + + +async def cancel_pending(session: AsyncSession, token: str) -> None: + await session.execute( + update(MaxDelivery) + .where(MaxDelivery.token == token, MaxDelivery.state.in_(("queued", "sending"))) + .values(state="cancelled", lease=None) + ) + + +async def disconnect(session: AsyncSession, token: str) -> None: + binding = await session.get(MaxBinding, token) + if binding: + binding.enabled = False + await session.execute(delete(MaxLinkCode).where(MaxLinkCode.token == token)) + await cancel_pending(session, token) + + +async def enqueue( + session: AsyncSession, *, key: str, user_id: int, kind: str, now: datetime, token: str | None = None +) -> None: + if await session.get(MaxDelivery, key) is not None: + return + try: + async with session.begin_nested(): + session.add( + MaxDelivery(id=key, user_id=user_id, token=token, kind=kind, created_at=now, next_attempt_at=now) + ) + await session.flush() + except IntegrityError: + # Another worker may enqueue the same event between SELECT and INSERT. + if await session.get(MaxDelivery, key) is None: + raise + + +async def collect_completed(session: AsyncSession, now: datetime) -> None: + """Recover completion events from committed clinical records, including after a restart. + + No clinical hooks depend on identity. Read only IDs/dates, then enqueue a generic template. + A binding's activation time bounds history; repeated scans are idempotent. + """ + bindings = (await session.scalars(select(MaxBinding).where(MaxBinding.enabled.is_(True)))).all() + for binding in bindings: + if not await active_patient(binding.token): + continue + async with get_clinical_session() as clinical: + forms = ( + await clinical.scalars( + select(QuestionnaireRecord.id).where( + QuestionnaireRecord.token == binding.token, + QuestionnaireRecord.status == "complete", + QuestionnaireRecord.completed_at >= binding.connected_at, + ) + ) + ).all() + scales = ( + await clinical.scalars( + select(ScaleResult.id).where( + ScaleResult.token == binding.token, + ScaleResult.complete.is_(True), + ScaleResult.ts >= binding.connected_at, + ) + ) + ).all() + for source, ids in (("form", forms), ("scale", scales)): + for record_id in ids: + key = digest(f"completed:{binding.token}:{binding.connected_at.isoformat()}:{source}:{record_id}") + await enqueue(session, key=key, token=binding.token, user_id=binding.user_id, kind="completed", now=now) + + +async def claim(session: AsyncSession, now: datetime) -> MaxDelivery | None: + """One lease per row; recovery after a worker crash is bounded by the lease deadline.""" + ready = (MaxDelivery.state.in_(("queued", "sending"))) & (MaxDelivery.next_attempt_at <= now) + row = await session.scalar( + select(MaxDelivery) + .where(ready) + .order_by(MaxDelivery.created_at, MaxDelivery.id) + .with_for_update(skip_locked=True) + .limit(1) + ) + if row is None: + return None + if row.attempts >= MAX_ATTEMPTS: + row.state, row.error_code, row.lease = "failed", "attempt_limit", None + return None + lease = secrets.token_hex(16) + result = await session.execute( + update(MaxDelivery) + .where(MaxDelivery.id == row.id, ready) + .values( + state="sending", + attempts=MaxDelivery.attempts + 1, + lease=lease, + next_attempt_at=now + timedelta(seconds=LEASE_SECONDS), + ) + .returning(MaxDelivery.id) + ) + if result.scalar_one_or_none() is None: + return None + await session.refresh(row) + return row + + +async def finish( + session: AsyncSession, + row: MaxDelivery, + *, + state: str, + now: datetime, + error: str | None = None, + retry_seconds: float = 0, +) -> None: + await session.execute( + update(MaxDelivery) + .where(MaxDelivery.id == row.id, MaxDelivery.lease == row.lease, MaxDelivery.state == "sending") + .values(state=state, lease=None, error_code=error, next_attempt_at=now + timedelta(seconds=retry_seconds)) + ) diff --git a/app/main.py b/app/main.py index fec6c61..1a90f4d 100644 --- a/app/main.py +++ b/app/main.py @@ -30,13 +30,25 @@ async def lifespan(_: FastAPI) -> AsyncGenerator[None, None]: # In compose Postgres is required and healthy before the app starts; this branch is for running the # API (and its tests) without a database. Endpoints touching the DB will fail until it is reachable. log.error("db init failed, continuing without db: %s", type(exc).__name__) + if settings.max_enabled: + raise # MAX requires persistent bindings and a delivery queue. # Lanes fill these in (#13, #11); main.py itself stays frozen (#34). - await scheduler.start() - await telegram.start() - yield - await telegram.stop() - await scheduler.stop() - await dispose() + max_channel = None + try: + await telegram.start() + if settings.max_enabled: + from app.channels import max_bot + + max_channel = max_bot + await max_channel.start() + await scheduler.start() + yield + finally: + await scheduler.stop() + if max_channel is not None: + await max_channel.stop() + await telegram.stop() + await dispose() app = FastAPI(title="PTSRaiAgent API", version="0.1.0", lifespan=lifespan) diff --git a/config/texts/max.yaml b/config/texts/max.yaml new file mode 100644 index 0000000..7747fe7 --- /dev/null +++ b/config/texts/max.yaml @@ -0,0 +1,8 @@ +connected: "Уведомления подключены. Здесь будут появляться напоминания с сайта. Отключить их можно командой /stop." +not_connected: "Чтобы получать уведомления, откройте сайт и подключите MAX в настройках уведомлений." +invalid: "Не удалось подключить уведомления. Создайте новую ссылку на сайте. Если MAX уже подключён к другому аккаунту, сначала отключите прежнюю привязку." +stopped: "Уведомления отключены. Подключить их снова можно по новой ссылке с сайта." +help: "Этот бот присылает уведомления. Пройти тесты, посмотреть результаты и продолжить общение можно на сайте. Команда /stop отключает уведомления." +notification: "На сайте есть напоминание для вас. Откройте личный кабинет, чтобы продолжить." +completed: "Прохождение теста завершено. Подробности доступны в личном кабинете на сайте." +open_site: "Открыть сайт" diff --git a/dashboard/components/patient_card.py b/dashboard/components/patient_card.py index 91b7764..7b08d72 100644 --- a/dashboard/components/patient_card.py +++ b/dashboard/components/patient_card.py @@ -42,7 +42,10 @@ def dose_strip_html(grid: h.DoseGrid, start: date | None) -> str: f'ожидается · {c["pending"]}' "" ) - return f'
{"".join(cells)}
{legend}' + return ( + f'
' + f"{''.join(cells)}
{legend}" + ) def _tile(label: str, value: str, hint: str = "", tone: str = "blue") -> str: @@ -181,7 +184,7 @@ def render(card: PatientCard, today: date | None) -> None: main, side = st.columns([1.75, 1], gap="large") with main: - with st.container(border=True): + with st.container(border=True, key="panel-scales"): c1, c2 = st.columns(2) for col, scale_id, title in ((c1, "phq9", "PHQ-9"), (c2, "pcl5", "PCL-5")): fig = charts.scale_figure(card.series, scale_id, title, start) @@ -191,22 +194,22 @@ def render(card: PatientCard, today: date | None) -> None: else: st.plotly_chart(fig, config=theme.PLOTLY_CONFIG, key=f"chart-{scale_id}") st.caption("◇ — внеплановое заполнение (по триггеру правил). Полосы — градации тяжести из config/scales.") - with st.container(border=True): + with st.container(border=True, key="panel-wellbeing"): fig = charts.wellbeing_figure(card.series, start) if fig is None: st.caption("Ежедневных чек-инов пока нет") else: st.plotly_chart(fig, config=theme.PLOTLY_CONFIG, key="chart-wellbeing") st.caption("Красная зона настроения ≤ 3 (3 дня → внеплановый PHQ-9); пунктир — сон 4 ч.") - with st.container(border=True): + with st.container(border=True, key="panel-doses"): st.html('
Календарь приёма
') st.html(dose_strip_html(grid, start)) with side: - with st.container(border=True): + with st.container(border=True, key="panel-alerts"): _alerts_feed(card.alerts, today) - with st.container(border=True): + with st.container(border=True, key="panel-summary"): _summary(card.summary) - with st.container(border=True): + with st.container(border=True, key="panel-safety"): _safety_plan(card.safety_plan) - with st.container(border=True): + with st.container(border=True, key="panel-prescriptions"): _prescriptions(card) diff --git a/dashboard/console/playback_ui.py b/dashboard/console/playback_ui.py index a678125..21bdd04 100644 --- a/dashboard/console/playback_ui.py +++ b/dashboard/console/playback_ui.py @@ -51,7 +51,7 @@ def render_playback_panel(persona: dict[str, Any]) -> None: token = persona["token"] scenario, source = w.scenario_for(persona) state = w.playback_state(token) - st.subheader("🎬 Сценарий демо") + st.subheader("Сценарий демо") _scenario_source_controls(persona, source) if scenario.errors: with st.expander(f"⚠️ Замечания к сценарию: {len(scenario.errors)}", expanded=not scenario.days): diff --git a/dashboard/console/widgets.py b/dashboard/console/widgets.py index 3b19d75..d1a8e3e 100644 --- a/dashboard/console/widgets.py +++ b/dashboard/console/widgets.py @@ -368,10 +368,9 @@ def render_doctor_panel(highlight_token: str | None, *, key: str = "doc") -> Non ] for a in fresh_acute[:1]: st.markdown( - "
" + "
" f"🚨 ОСТРЫЙ АЛЕРТ · {_escape(a.get('patient_name', ''))} · {_fmt_ts(a.get('ts'))}
" - f"{_escape(a.get('reason', ''))}
", + f"
{_escape(a.get('reason', ''))}
", unsafe_allow_html=True, ) c1, c2 = st.columns(2) diff --git a/dashboard/pages/1b_Подключить_пациента.py b/dashboard/pages/1b_Подключить_пациента.py index 18386b1..4b9a37a 100644 --- a/dashboard/pages/1b_Подключить_пациента.py +++ b/dashboard/pages/1b_Подключить_пациента.py @@ -68,7 +68,7 @@ def _reset() -> None: def _result(res: ConnectPatientOut, name: str) -> None: link = h.absolute_link(res.deep_link, os.environ.get("DASHBOARD_PUBLIC_URL", "http://localhost:8501")) - with st.container(border=True): + with st.container(border=True, key="panel-connect-result"): st.html( f'
Пациент подключён · {escape(name)}
' '
Покажите QR пациенту или продиктуйте код — бот спросит ' @@ -108,7 +108,7 @@ def main() -> None: st.button("Заполнить демо-данными (Андрей)", icon=":material/auto_fix_high:", on_click=_fill_demo, args=(today,)) left, right = st.columns(2, gap="large") - with left, st.container(border=True): + with left, st.container(border=True, key="panel-connect-person"): st.html('
Пациент
') st.text_input("Имя и инициал фамилии", key="cp_name", placeholder="Андрей С.", help="Без полного ФИО") a, b = st.columns(2) @@ -128,7 +128,7 @@ def main() -> None: key="cp_modules", format_func=lambda m: h.MODULE_LABELS[m], ) - with right, st.container(border=True): + with right, st.container(border=True, key="panel-connect-prescription"): st.html('
Назначение
') d1, d2 = st.columns([1.4, 1]) with d1: diff --git a/dashboard/pages/2_Демо-консоль.py b/dashboard/pages/2_Демо-консоль.py index 903cb5e..427330c 100644 --- a/dashboard/pages/2_Демо-консоль.py +++ b/dashboard/pages/2_Демо-консоль.py @@ -14,21 +14,31 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from console import widgets as w # noqa: E402 from console.playback_ui import render_playback_panel # noqa: E402 +from dashboard import theme # noqa: E402 +from dashboard.components import ui # noqa: E402 + st.set_page_config(page_title="Демо-консоль", page_icon="🎬", layout="wide") +st.html(theme.CSS) +st.html( + ui.page_header( + "Демо-консоль", + "Чат пациента и сценарий сопровождения. Прототип на синтетических данных.", + kicker="Демонстрация", + ) +) + persona = w.select_persona() w.render_connect_hero() w.show_flash() st.sidebar.caption(f"API: {w.get_api().base_url}") -st.title("Демо-консоль") -st.caption("Прототип на синтетических данных. Время — виртуальные демо-часы (ADR-005).") -w.render_clock_bar(persona, key="console-clock") -st.divider() +with st.container(border=True, key="panel-console-clock"): + w.render_clock_bar(persona, key="console-clock") chat_col, play_col = st.columns([1.05, 1], gap="large") -with chat_col: - st.subheader(f"💬 Чат пациента — {persona.get('display_name') or persona['token']}") +with chat_col, st.container(border=True, key="panel-console-chat"): + st.subheader(f"Чат пациента — {persona.get('display_name') or persona['token']}") w.render_chat(persona["token"], height=560, key="console-chat") -with play_col: +with play_col, st.container(border=True, key="panel-console-scenario"): render_playback_panel(persona) diff --git a/dashboard/pages/3_Сплит-экран.py b/dashboard/pages/3_Сплит-экран.py index 2403d3f..8d4b26f 100644 --- a/dashboard/pages/3_Сплит-экран.py +++ b/dashboard/pages/3_Сплит-экран.py @@ -15,12 +15,12 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from console import widgets as w # noqa: E402 +from dashboard import theme # noqa: E402 +from dashboard.components import ui # noqa: E402 + st.set_page_config(page_title="Сплит-экран", page_icon="🖥️", layout="wide", initial_sidebar_state="collapsed") -st.markdown( - "", - unsafe_allow_html=True, -) +st.html(theme.CSS) +st.html(ui.page_header("Сплит-экран", "Пациент и врач: сопровождение в реальном времени.", kicker="Демонстрация")) persona = w.select_persona() w.show_flash() @@ -44,15 +44,15 @@ if clicked and nxt is not None: st.rerun() left, right = st.columns([1.1, 1], gap="large") -with left: +with left, st.container(border=True, key="panel-split-patient"): url = w.patient_web_url() if url: - st.markdown(f"#### 📱 Пациент — {persona.get('display_name') or token}") + st.markdown(f"#### Пациент — {persona.get('display_name') or token}") st.iframe(url, height=760) st.caption(f"Веб-приложение пациента: {url}") else: - st.markdown(f"#### 💬 Пациент — {persona.get('display_name') or token}") + st.markdown(f"#### Пациент — {persona.get('display_name') or token}") w.render_chat(token, height=600, key="split-chat") -with right: - st.markdown("#### 🩺 Кабинет врача — д-р Смирнова Е. А.") +with right, st.container(border=True, key="panel-split-doctor"): + st.markdown("#### Кабинет врача — д-р Смирнова Е. А.") w.polled_doctor_panel(token, key="split-doc") diff --git a/dashboard/theme.py b/dashboard/theme.py index efc4aa9..76ee726 100644 --- a/dashboard/theme.py +++ b/dashboard/theme.py @@ -138,8 +138,8 @@ div[class*="st-key-prow-"] {{ border-top:1px solid var(--line); padding:18px 0 4 .mt-empty p {{ font-size:.85rem; margin:8px 0 0; }} /* ---------- chips, badges, bars ---------- */ -.mt-chip {{ display:inline-block; font-size:.72rem; padding: 1px 8px; border-radius: 999px; margin-right: 4px; - background: var(--blue-tint); color: var(--blue-ink); font-weight: 500; }} +.mt-chip {{ display:inline-block; font-size:.72rem; padding: 1px 8px; border-radius: 5px; margin-right: 4px; + background: #edf3ee; color: #38634b; font-weight: 500; }} .mt-badge {{ display:inline-flex; align-items:center; gap:6px; font-size:.7rem; font-weight:550; padding: 5px 8px; border-radius: 5px; white-space: normal; }} .mt-badge.t-red {{ background: var(--red-tint); color: var(--red-ink); }} @@ -166,7 +166,7 @@ div[class*="st-key-prow-"] {{ border-top:1px solid var(--line); padding:18px 0 4 .mt-banner b {{ color: inherit; }} .mt-pulse {{ width: 12px; height: 12px; border-radius: 50%; background: var(--red); margin-top: 5px; flex: none; box-shadow: 0 0 0 4px #faeeee; }} -.mt-panel-title {{ font-size: .8rem; text-transform: uppercase; letter-spacing: .07em; font-weight: 650; +.mt-panel-title {{ font-size: .82rem; text-transform: uppercase; letter-spacing: .03em; font-weight: 550; color: var(--ink-3); margin: 2px 0 8px; }} .mt-alert {{ border-left: 4px solid var(--grey); padding: 4px 0 4px 12px; }} .mt-alert.t-red {{ border-left-color: var(--red); }} @@ -175,9 +175,9 @@ div[class*="st-key-prow-"] {{ border-top:1px solid var(--line); padding:18px 0 4 .mt-alert .when {{ color: var(--ink-3); font-size: .78rem; }} .mt-alert .why {{ color: var(--ink); font-weight: 600; font-size: .92rem; margin: 2px 0; }} .mt-alert.acked .why {{ color: var(--ink-3); font-weight: 500; }} -.mt-summary {{ background: var(--blue-tint); border-radius: 12px; padding: 14px 16px; color: var(--ink); - line-height: 1.5; font-size: .93rem; }} -.mt-summary .disc {{ color: var(--blue-ink); font-size: .76rem; margin-top: 8px; }} +.mt-summary {{ background: #f4f6f2; border:1px solid var(--line); border-radius: 12px; padding: 14px 16px; + color: var(--ink); line-height: 1.5; font-size: .93rem; }} +.mt-summary .disc {{ color: var(--ink-2); font-size: .76rem; margin-top: 8px; }} .mt-plan ol {{ margin: 0; padding-left: 1.2rem; }} .mt-plan li {{ margin: 3px 0; color: var(--ink); font-size: .9rem; }} @@ -195,6 +195,21 @@ div[class*="st-key-prow-"] {{ border-top:1px solid var(--line); padding:18px 0 4 .mt-legend i {{ display:inline-block; width: 12px; height: 12px; border-radius: 3px; margin-right: 5px; vertical-align: -1px; }} +/* ---------- internal pages ---------- */ +div[class*="st-key-panel-"] {{ background:var(--surface); border:1px solid var(--line); border-radius:12px; + padding:20px; }} +[data-testid="stExpander"] {{ background:var(--surface); border-color:var(--line); border-radius:12px; }} +[data-testid="stChatMessage"] {{ background:#f4f6f2; border:1px solid var(--line); border-radius:12px; }} +[data-testid="stChatInput"] {{ background:var(--surface); border:1px solid var(--line); border-radius:8px; }} +[data-testid="stNumberInputContainer"], [data-testid="stDateInput"] input {{ + background:var(--surface); color:var(--ink); border-color:var(--line); border-radius:8px; }} +[data-testid="stApp"] [data-variant="pills"][data-selected] {{ background:#edf3ee; color:#285e4e; + border-color:#b4c6ba; }} +.mt-console-alert {{ font-size:1.1rem; font-weight:600; }} +.mt-console-alert .mt-sub {{ color:var(--red-ink); font-weight:400; }} +.mt-dose-scroll {{ overflow-x:auto; padding-bottom:4px; }} +.mt-doses {{ min-width:max-content; }} + /* ---------- connect result ---------- */ .mt-code {{ font-size: 2.4rem; font-weight: 700; letter-spacing: .12em; color: var(--ink); font-variant-numeric: tabular-nums; }} @@ -222,6 +237,8 @@ div[class*="st-key-prow-"] {{ border-top:1px solid var(--line); padding:18px 0 4 .mt-mobile-label {{ display:block; color:var(--ink-3); font-size:.68rem; margin-bottom:5px; }} .mt-row-details {{ grid-template-columns:1fr; gap:12px; }} .mt-list-footer {{ flex-wrap:wrap; }} + .mt-head .mt-side {{ text-align:left; }} + div[class*="st-key-panel-"] {{ padding:16px; }} .mt-tip:hover::after, .mt-tip:focus-visible::after {{ display:none; }} }} @media (prefers-reduced-motion: reduce) {{ diff --git a/tests/test_api_max.py b/tests/test_api_max.py new file mode 100644 index 0000000..123f13a --- /dev/null +++ b/tests/test_api_max.py @@ -0,0 +1,103 @@ +"""MAX endpoints authenticate before reading bindings or accepting events.""" + +import sys +from types import SimpleNamespace +from unittest.mock import AsyncMock +from urllib.parse import parse_qs, urlsplit + +import pytest +from httpx import ASGITransport, AsyncClient +from sqlalchemy.exc import OperationalError + +from app.config import get_settings +from app.core import clock +from app.db import repo, session +from app.db.bootstrap import init_db +from app.integrations import max_store +from app.main import app + +BASE = "/api/v1/me/notifications/max" +HOOK = "/api/v1/webhooks/max" +TOKEN = "synthetic-patient" +AUTH = {"Authorization": f"Bearer {TOKEN}"} +SECRET = "test-secret-" * 4 + + +@pytest.fixture +async def client(monkeypatch): + for key, value in { + "MAX_ENABLED": "true", + "MAX_BOT_TOKEN": "fake-token", + "MAX_BOT_USERNAME": "test_bot", + "MAX_WEBHOOK_SECRET": SECRET, + "MAX_WEBHOOK_URL": "https://api.example.org" + HOOK, + "MAX_SITE_URL": "https://example.org", + }.items(): + monkeypatch.setenv(key, value) + get_settings.cache_clear() + await session.configure(identity_url="sqlite+aiosqlite:///:memory:", clinical_url="sqlite+aiosqlite:///:memory:") + await init_db() + async with session.get_clinical_session() as s: + await repo.upsert_profile(s, token=TOKEN, doctor_id="") + await repo.set_dialog_state( + s, token=TOKEN, state="idle", data={"consent": True, "adult": True}, now=clock.now() + ) + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c: + yield c + await session.configure() + get_settings.cache_clear() + + +@pytest.mark.parametrize("auth", [{}, {"Authorization": "Bearer unknown"}, {"Authorization": "Basic test"}]) +async def test_auth_required(client, auth): + assert (await client.get(BASE, headers=auth)).status_code == 401 + assert (await client.post(BASE + "/link", headers=auth, json={"consent": True})).status_code == 401 + assert (await client.delete(BASE, headers=auth)).status_code == 401 + + +async def test_link_requires_consent_and_hides_patient_credential(client): + for body in ({}, {"consent": False}, {"consent": True, "user_id": 100}): + assert (await client.post(BASE + "/link", headers=AUTH, json=body)).status_code == 422 + response = await client.post(BASE + "/link", headers=AUTH, json={"consent": True}) + assert response.status_code == 200 + assert TOKEN not in response.text + url = urlsplit(response.json()["url"]) + assert url.netloc == "max.ru" and url.path == "/test_bot" + code = parse_qs(url.query)["start"][0] + async with session.get_identity_session() as s: + assert await max_store.bind(s, code, 100, clock.now()) == TOKEN + assert (await client.get(BASE, headers=AUTH)).json()["connected"] is True + assert (await client.delete(BASE, headers=AUTH)).json()["connected"] is False + + +async def test_revoke_consent_prevents_linking(client): + async with session.get_clinical_session() as s: + await repo.set_dialog_state( + s, token=TOKEN, state="idle", data={"consent": False, "adult": True}, now=clock.now() + ) + assert (await client.post(BASE + "/link", headers=AUTH, json={"consent": True})).status_code == 403 + + +async def test_disabled_service_still_allows_disconnect(client, monkeypatch): + monkeypatch.setenv("MAX_ENABLED", "false") + get_settings.cache_clear() + assert (await client.get(BASE, headers=AUTH)).json()["available"] is False + assert (await client.post(BASE + "/link", headers=AUTH, json={"consent": True})).status_code == 503 + assert (await client.post(HOOK, json={})).status_code == 503 + assert (await client.delete(BASE, headers=AUTH)).status_code == 200 + + +async def test_webhook_secret_checked_before_body_or_adapter(client): + assert (await client.post(HOOK, content="not-json")).status_code == 403 + assert (await client.post(HOOK, headers={"X-Max-Bot-Api-Secret": "wrong"}, json={})).status_code == 403 + headers = {"X-Max-Bot-Api-Secret": SECRET} + assert (await client.post(HOOK, headers=headers, content="not-json")).status_code == 400 + assert (await client.post(HOOK, headers=headers, json=[])).status_code == 422 + assert (await client.post(HOOK, headers=headers, content=" " * 65537)).status_code == 413 + + +async def test_webhook_storage_failure_is_retryable_without_identity_details(client, monkeypatch): + handler = AsyncMock(side_effect=OperationalError("private SQL", {"token": TOKEN}, Exception("private"))) + monkeypatch.setitem(sys.modules, "app.channels.max_bot", SimpleNamespace(handle_update=handler)) + response = await client.post(HOOK, headers={"X-Max-Bot-Api-Secret": SECRET}, json={}) + assert response.status_code == 503 and TOKEN not in response.text and "private" not in response.text diff --git a/tests/test_contracts_max.py b/tests/test_contracts_max.py new file mode 100644 index 0000000..882c482 --- /dev/null +++ b/tests/test_contracts_max.py @@ -0,0 +1,47 @@ +"""MAX stays off without credentials; enabled deployments fail closed on incomplete settings.""" + +import pytest +from pydantic import ValidationError + +from app.config import Settings + + +def configured(**overrides): + fields = { + "max_enabled": True, + "max_bot_token": "test-only-token", + "max_bot_username": "test_bot", + "max_webhook_secret": "test-only-secret-" * 3, + "max_webhook_url": "https://api.example.org/api/v1/webhooks/max", + "max_site_url": "https://patient.example.org/#/today", + } + return Settings(_env_file=None, **(fields | overrides)) + + +def test_max_disabled_by_default(): + assert not Settings(_env_file=None).max_enabled + + +def test_max_secrets_are_redacted(): + settings = configured() + assert "test-only-token" not in repr(settings) + assert "test-only-secret" not in repr(settings) + + +@pytest.mark.parametrize( + "overrides", + [ + {"max_bot_token": ""}, + {"max_bot_username": "@test_bot"}, + {"max_webhook_secret": "short"}, + {"max_site_url": "http://patient.example.org"}, + {"max_webhook_url": "http://api.example.org"}, + {"max_webhook_url": "https://api.example.org:8443/hook"}, + {"max_webhook_url": "https://user:password@api.example.org/hook"}, + {"max_webhook_url": "https://api.example.org/hook#fragment"}, + {"max_site_url": "https://patient.example.org?token=credential"}, + ], +) +def test_max_rejects_incomplete_or_unsafe_settings(overrides): + with pytest.raises(ValidationError): + configured(**overrides) diff --git a/tests/test_contracts_settings_privacy.py b/tests/test_contracts_settings_privacy.py new file mode 100644 index 0000000..cb926c1 --- /dev/null +++ b/tests/test_contracts_settings_privacy.py @@ -0,0 +1,21 @@ +"""Startup validation errors must not print configuration credentials.""" + +import pytest +from pydantic import ValidationError + +from app.config import Settings + + +def test_incomplete_max_configuration_does_not_expose_token(): + with pytest.raises(ValidationError) as error: + Settings(_env_file=None, max_enabled=True, max_bot_token="SYNTHETIC_SECRET") + message = str(error.value) + assert "MAX_BOT_USERNAME" in message + assert "SYNTHETIC_SECRET" not in message and "input_value" not in message + + +def test_invalid_field_does_not_expose_accidentally_pasted_secret(): + with pytest.raises(ValidationError) as error: + Settings(_env_file=None, max_enabled="SYNTHETIC_SECRET") + assert "max_enabled" in str(error.value) + assert "SYNTHETIC_SECRET" not in str(error.value) diff --git a/tests/test_db.py b/tests/test_db.py index 15d5516..ae7d01e 100644 --- a/tests/test_db.py +++ b/tests/test_db.py @@ -53,7 +53,15 @@ async def _tables(engine_fn: Callable[[], AsyncEngine]) -> set[str]: async def test_create_all_puts_tables_in_the_right_db(dbs: None) -> None: identity_tables = await _tables(session.identity_engine) clinical_tables = await _tables(session.clinical_engine) - assert identity_tables == {"patients", "doctors", "connect_codes"} + assert identity_tables == { + "patients", + "doctors", + "connect_codes", + "max_bindings", + "max_link_codes", + "max_webhook_receipts", + "max_deliveries", + } assert { "patient_profiles", "item_responses", diff --git a/tests/test_integrations_max.py b/tests/test_integrations_max.py new file mode 100644 index 0000000..e63965b --- /dev/null +++ b/tests/test_integrations_max.py @@ -0,0 +1,123 @@ +"""Persistent, one-time linking and queue recovery; synthetic identities only.""" + +from datetime import timedelta + +import pytest +from sqlalchemy import select + +from app.core import clock +from app.db import repo, session +from app.db.bootstrap import init_db +from app.db.clinical import ScaleResult +from app.db.max_notifications import MaxBinding, MaxDelivery, MaxLinkCode +from app.integrations import max_store as store + + +@pytest.fixture(autouse=True) +async def database(): + await session.configure(identity_url="sqlite+aiosqlite:///:memory:", clinical_url="sqlite+aiosqlite:///:memory:") + await init_db() + yield + await session.configure() + + +async def test_codes_are_hashed_expiring_one_time_and_replaced(): + now = clock.now() + async with session.get_identity_session() as s: + old, _ = await store.issue_code(s, "patient", now, 60) + code, expires = await store.issue_code(s, "patient", now, 60) + assert await store.code_token(s, old, now) is None + row = (await s.scalars(select(MaxLinkCode))).one() + assert row.digest != code and row.digest == store.digest(code) + assert await store.code_token(s, code, expires) is None + assert await store.bind(s, code, 100, now) == "patient" + assert await store.bind(s, code, 100, now) is None + async with session.get_identity_session() as s: + assert (await s.get(MaxBinding, "patient")).user_id == 100 + + +async def test_active_binding_cannot_be_reassigned_in_either_direction(): + now = clock.now() + async with session.get_identity_session() as s: + code, _ = await store.issue_code(s, "one", now, 60) + await store.bind(s, code, 100, now) + code, _ = await store.issue_code(s, "two", now, 60) + assert await store.bind(s, code, 100, now) is None + assert await store.code_token(s, code, now) == "two" + code, _ = await store.issue_code(s, "one", now, 60) + assert await store.bind(s, code, 200, now) is None + await store.disconnect(s, "one") + assert await store.code_token(s, code, now) is None + code, _ = await store.issue_code(s, "two", now, 60) + assert await store.bind(s, code, 100, now) == "two" + + +async def test_disconnect_cancels_pending_delivery_and_prevents_stale_ack(): + now = clock.now() + async with session.get_identity_session() as s: + await store.enqueue(s, key="job", user_id=100, token="one", kind="notification", now=now) + row = await store.claim(s, now) + async with session.get_identity_session() as s: + await store.disconnect(s, "one") + await store.finish(s, row, state="sent", now=now) + async with session.get_identity_session() as s: + assert (await s.get(MaxDelivery, "job")).state == "cancelled" + + +async def test_queue_survives_sessions_deduplicates_and_recovers_expired_lease(): + now = clock.now() + async with session.get_identity_session() as s: + for _ in range(2): + await store.enqueue(s, key="job", user_id=100, kind="help", now=now) + async with session.get_identity_session() as s: + first = await store.claim(s, now) + assert first.attempts == 1 + async with session.get_identity_session() as s: + assert await store.claim(s, now + timedelta(seconds=59)) is None + async with session.get_identity_session() as s: + second = await store.claim(s, now + timedelta(seconds=61)) + assert second.id == first.id and second.lease != first.lease and second.attempts == 2 + async with session.get_identity_session() as s: + await store.finish(s, first, state="sent", now=now) + async with session.get_identity_session() as s: + assert (await s.get(MaxDelivery, "job")).state == "sending" + await store.finish(s, second, state="sent", now=now) + async with session.get_identity_session() as s: + assert await store.claim(s, now + timedelta(days=1)) is None + + +async def test_retry_deadline_and_attempt_limit(): + now = clock.now() + async with session.get_identity_session() as s: + await store.enqueue(s, key="job", user_id=100, kind="help", now=now) + for attempt in range(store.MAX_ATTEMPTS): + when = now + timedelta(seconds=attempt * 120) + async with session.get_identity_session() as s: + row = await store.claim(s, when) + async with session.get_identity_session() as s: + await store.finish(s, row, state="queued", now=when, retry_seconds=120, error="http_429") + async with session.get_identity_session() as s: + assert await store.claim(s, when + timedelta(seconds=119)) is None + async with session.get_identity_session() as s: + assert await store.claim(s, now + timedelta(days=1)) is None + async with session.get_identity_session() as s: + row = await s.get(MaxDelivery, "job") + assert row.state == "failed" and row.attempts == store.MAX_ATTEMPTS + + +async def test_completion_scan_ignores_old_and_incomplete_tests_and_recovers_without_duplicates(): + now = clock.now() + async with session.get_clinical_session() as s: + await repo.upsert_profile(s, token="one", doctor_id="") + await repo.set_dialog_state(s, token="one", state="idle", data={"consent": True, "adult": True}, now=now) + for ts, complete in ((now - timedelta(days=1), True), (now, True), (now, False)): + s.add(ScaleResult(token="one", ts=ts, scale="phq9", total=0, severity="none", complete=complete)) + async with session.get_identity_session() as s: + s.add(MaxBinding(token="one", user_id=100, enabled=True, connected_at=now)) + for _ in range(2): + async with session.get_identity_session() as s: + await store.collect_completed(s, now) + async with session.get_identity_session() as s: + row = (await s.scalars(select(MaxDelivery))).one() + assert row.kind == "completed" and row.token == "one" + assert "phq9" not in row.id diff --git a/tests/test_max_bot.py b/tests/test_max_bot.py new file mode 100644 index 0000000..1798118 --- /dev/null +++ b/tests/test_max_bot.py @@ -0,0 +1,281 @@ +"""End-to-end server-only MAX flow, real SQLite transactions and mocked network.""" + +from datetime import timedelta +from unittest.mock import AsyncMock +from urllib.parse import parse_qs, urlsplit + +import pytest +from httpx import ASGITransport, AsyncClient +from sqlalchemy import select + +from app.channels import max_bot +from app.channels.max_client import MaxApiError +from app.config import get_settings +from app.core import clock +from app.db import repo, session +from app.db.bootstrap import init_db +from app.db.clinical import ScaleResult +from app.db.intake import QuestionnaireRecord +from app.db.max_notifications import MaxBinding, MaxDelivery, MaxReceipt +from app.dialog.contracts import Reply +from app.integrations import max_store as store +from app.integrations.base import MemoryOutbox, integrations +from app.main import app + +TOKEN = "synthetic-patient" +SECRET = "synthetic-webhook-secret-" * 2 + + +@pytest.fixture(autouse=True) +async def database(monkeypatch): + for key, value in { + "MAX_ENABLED": "true", + "MAX_BOT_TOKEN": "fake-token", + "MAX_BOT_USERNAME": "test_bot", + "MAX_WEBHOOK_SECRET": SECRET, + "MAX_WEBHOOK_URL": "https://api.example.org/api/v1/webhooks/max", + "MAX_SITE_URL": "https://example.org", + }.items(): + monkeypatch.setenv(key, value) + get_settings.cache_clear() + max_bot.texts.cache_clear() + await session.configure(identity_url="sqlite+aiosqlite:///:memory:", clinical_url="sqlite+aiosqlite:///:memory:") + await init_db() + async with session.get_clinical_session() as s: + await repo.upsert_profile(s, token=TOKEN, doctor_id="") + await repo.set_dialog_state( + s, token=TOKEN, state="idle", data={"consent": True, "adult": True}, now=clock.now() + ) + yield + await max_bot.stop() + await session.configure() + get_settings.cache_clear() + + +def event(kind="bot_started", text="", uid=100, *, stamp=1000): + user = {"user_id": uid, "is_bot": False, "first_name": "Synthetic"} + if kind == "message_created": + return { + "update_type": kind, + "timestamp": stamp, + "message": { + "sender": user, + "recipient": {"chat_type": "dialog", "chat_id": 123}, + "body": {"mid": f"mid-{stamp}", "text": text}, + }, + } + return {"update_type": kind, "timestamp": stamp, "user": user, "chat_id": 123, "payload": text} + + +async def connect(): + async with session.get_identity_session() as s: + code, _ = await store.issue_code(s, TOKEN, clock.now(), 600) + await max_bot.handle_update(event(text=code)) + return code + + +async def test_http_connect_webhook_duplicate_notification_and_stop(): + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + auth = {"Authorization": f"Bearer {TOKEN}"} + linked = await client.post("/api/v1/me/notifications/max/link", headers=auth, json={"consent": True}) + code = parse_qs(urlsplit(linked.json()["url"]).query)["start"][0] + headers = {"X-Max-Bot-Api-Secret": SECRET} + for _ in range(2): + assert ( + await client.post("/api/v1/webhooks/max", headers=headers, json=event(text=code)) + ).status_code == 200 + assert (await client.get("/api/v1/me/notifications/max", headers=auth)).json()["connected"] + async with session.get_identity_session() as s: + assert len((await s.scalars(select(MaxReceipt))).all()) == 1 + assert len((await s.scalars(select(MaxDelivery))).all()) == 1 + sender = AsyncMock() + assert await max_bot.deliver_one(sender) + assert sender.send.call_args.args == (100, max_bot.texts().connected) + await client.post("/api/v1/webhooks/max", headers=headers, json=event("message_created", "/stop", stamp=2000)) + assert not (await client.get("/api/v1/me/notifications/max", headers=auth)).json()["connected"] + + +async def test_unbound_start_help_and_invalid_code_are_generic(): + for e in (event(), event("message_created", "private patient text", stamp=2000), event(text="expired", stamp=3000)): + await max_bot.handle_update(e) + async with session.get_identity_session() as s: + rows = (await s.scalars(select(MaxDelivery))).all() + assert {r.kind for r in rows} == {"not_connected", "help", "invalid"} + assert all(r.token is None for r in rows) + assert not (await s.scalars(select(MaxBinding))).all() + + +@pytest.mark.parametrize("kind", ["bot_stopped", "dialog_removed", "message_created"]) +async def test_stopping_cancels_pending_confirmation_and_reminders(kind): + await connect() + await max_bot.MaxOutbox(MemoryOutbox()).push(TOKEN, [Reply(text="private scheduled question")]) + await max_bot.handle_update(event(kind, "/stop", stamp=2000)) + async with session.get_identity_session() as s: + assert not (await s.get(MaxBinding, TOKEN)).enabled + rows = (await s.scalars(select(MaxDelivery).where(MaxDelivery.token == TOKEN))).all() + assert rows and all(r.state == "cancelled" for r in rows) + sender = AsyncMock() + await max_bot.deliver_one(sender) + assert sender.send.call_count == (1 if kind == "message_created" else 0) + + +async def test_private_patient_content_stays_in_fallback_only(): + await connect() + fallback = MemoryOutbox() + wrapper = max_bot.MaxOutbox(fallback) + replies = [Reply(text="SYNTHETIC confidential result 42", kind="question")] + await wrapper.push(TOKEN, replies) + await wrapper.push(TOKEN, replies) + assert fallback.drain(TOKEN) == replies * 2 + async with session.get_identity_session() as s: + rows = (await s.scalars(select(MaxDelivery).where(MaxDelivery.kind == "notification"))).all() + assert len(rows) == 1 + assert "confidential" not in repr(rows[0].__dict__) + sender = AsyncMock() + while await max_bot.deliver_one(sender): + pass + assert any(c.args[1] == max_bot.texts().notification for c in sender.send.call_args_list) + assert all("confidential" not in c.args[1] and TOKEN not in str(c.kwargs) for c in sender.send.call_args_list) + + +async def test_revoked_consent_prevents_binding_and_delivery(): + await connect() + async with session.get_clinical_session() as s: + await repo.set_dialog_state( + s, token=TOKEN, state="idle", data={"consent": False, "adult": True}, now=clock.now() + ) + sender = AsyncMock() + await max_bot.deliver_one(sender) + sender.send.assert_not_called() + async with session.get_identity_session() as s: + await store.disconnect(s, TOKEN) + code, _ = await store.issue_code(s, TOKEN, clock.now(), 600) + await max_bot.handle_update(event(text=code, stamp=2000)) + async with session.get_identity_session() as s: + assert not (await s.get(MaxBinding, TOKEN)).enabled + + +@pytest.mark.parametrize( + "bad", + [ + {}, + {"update_type": "other", "timestamp": 1}, + event() | {"timestamp": True}, + event() | {"user": {"user_id": True, "is_bot": False}}, + event() | {"user": {"user_id": 100, "is_bot": True}}, + event() | {"payload": {"wrong": "type"}}, + {"update_type": "message_created", "timestamp": 1, "message": {}}, + ], +) +async def test_malformed_or_bot_events_are_ignored(bad): + await max_bot.handle_update(bad) + async with session.get_identity_session() as s: + assert not (await s.scalars(select(MaxReceipt))).all() + + +async def test_group_cannot_claim_a_patient_link(): + async with session.get_identity_session() as s: + code, _ = await store.issue_code(s, TOKEN, clock.now(), 600) + update = event("message_created", "/start " + code) + update["message"]["recipient"]["chat_type"] = "chat" + await max_bot.handle_update(update) + async with session.get_identity_session() as s: + assert await s.get(MaxBinding, TOKEN) is None + assert await store.code_token(s, code, clock.now()) == TOKEN + + +async def test_429_respects_retry_deadline_and_then_succeeds(monkeypatch): + await max_bot.handle_update(event()) + now = clock.now() + monkeypatch.setattr(clock, "now", lambda: now) + sender = AsyncMock() + sender.send.side_effect = MaxApiError("http_429", retryable=True, retry_after=120) + assert await max_bot.deliver_one(sender) + async with session.get_identity_session() as s: + row = (await s.scalars(select(MaxDelivery))).one() + assert row.state == "queued" and row.next_attempt_at == now + timedelta(seconds=120) + assert not await max_bot.deliver_one(sender) + now += timedelta(seconds=121) + sender.send.side_effect = None + assert await max_bot.deliver_one(sender) + async with session.get_identity_session() as s: + row = (await s.scalars(select(MaxDelivery))).one() + assert row.state == "sent" and row.attempts == 2 + + +async def test_permanent_error_does_not_retry(): + await max_bot.handle_update(event()) + sender = AsyncMock() + sender.send.side_effect = MaxApiError("http_403") + await max_bot.deliver_one(sender) + assert not await max_bot.deliver_one(sender) + async with session.get_identity_session() as s: + assert (await s.scalars(select(MaxDelivery))).one().state == "failed" + + +@pytest.mark.parametrize("source", ["scale", "questionnaire"]) +async def test_completed_test_produces_one_neutral_notification(source): + await connect() + sender = AsyncMock() + await max_bot.deliver_one(sender) + sender.reset_mock() + async with session.get_clinical_session() as s: + now = clock.now() + if source == "scale": + s.add(ScaleResult(token=TOKEN, ts=now, scale="phq9", total=1, severity="synthetic", complete=True)) + else: + s.add( + QuestionnaireRecord( + id="synthetic-form", + token=TOKEN, + kind="intake", + version="test", + policy_version="test", + started_at=now, + completed_at=now, + day=now.date(), + status="complete", + answers={}, + details={}, + ) + ) + for _ in range(2): + async with session.get_identity_session() as s: + await store.collect_completed(s, clock.now()) + assert await max_bot.deliver_one(sender) + assert not await max_bot.deliver_one(sender) + sender.send.assert_awaited_once_with( + 100, max_bot.texts().completed, site_url="https://example.org", button=max_bot.texts().open_site + ) + + +async def test_private_start_command_accepts_issued_code(): + async with session.get_identity_session() as s: + code, _ = await store.issue_code(s, TOKEN, clock.now(), 600) + await max_bot.handle_update(event("message_created", "/start " + code)) + async with session.get_identity_session() as s: + assert (await s.get(MaxBinding, TOKEN)).user_id == 100 + + +async def test_disabled_lifecycle_never_constructs_client(monkeypatch): + monkeypatch.setenv("MAX_ENABLED", "false") + get_settings.cache_clear() + monkeypatch.setattr(max_bot, "MaxClient", lambda _: pytest.fail("disabled MAX must not create a network client")) + before = integrations.outbox + await max_bot.start() + await max_bot.handle_update(event()) + await max_bot.stop() + assert integrations.outbox is before + + +async def test_lifecycle_wraps_once_restores_and_closes(monkeypatch): + sender = AsyncMock() + monkeypatch.setattr(max_bot, "MaxClient", lambda _: sender) + before = integrations.outbox + await max_bot.start() + first = integrations.outbox + await max_bot.start() + assert integrations.outbox is first and first.fallback is before + await max_bot.stop() + assert integrations.outbox is before + sender.close.assert_awaited_once() diff --git a/tests/test_max_client.py b/tests/test_max_client.py new file mode 100644 index 0000000..65061de --- /dev/null +++ b/tests/test_max_client.py @@ -0,0 +1,95 @@ +"""Wire contract with MAX, using an in-process HTTP fake (no real bot/token).""" + +import json +import logging + +import httpx +import pytest + +from app.channels.max_client import API_URL, UPDATE_TYPES, MaxApiError, MaxClient +from app.config import Settings + + +def settings(): + return Settings( + _env_file=None, + max_enabled=True, + max_bot_token="synthetic-secret-token", + max_bot_username="synthetic_bot", + max_webhook_secret="synthetic-webhook-secret-" * 2, + max_webhook_url="https://api.example.org/api/v1/webhooks/max", + max_site_url="https://example.org", + ) + + +async def test_message_wire_contract_and_no_identifiers_in_logs(caplog): + def handler(request): + assert str(request.url).startswith(API_URL + "/messages?") + assert request.url.params["user_id"] == "1234567890123" + assert "access_token" not in request.url.params + assert request.headers["Authorization"] == "synthetic-secret-token" + body = json.loads(request.content) + assert body["text"] == "neutral reminder" and "format" not in body + button = body["attachments"][0]["payload"]["buttons"][0][0] + assert button == {"type": "link", "text": "Open", "url": "https://example.org"} + return httpx.Response(200, json={"message": {"body": {"mid": "synthetic-id"}}}) + + client = MaxClient(settings(), transport=httpx.MockTransport(handler)) + with caplog.at_level(logging.INFO): + await client.send(1234567890123, "neutral reminder", site_url="https://example.org", button="Open") + await client.close() + assert "1234567890123" not in caplog.text and "synthetic-secret-token" not in caplog.text + + +@pytest.mark.parametrize( + "status,retry", [(429, True), (500, True), (503, True), (408, True), (401, False), (403, False)] +) +async def test_error_codes_are_redacted_and_classified(status, retry): + client = MaxClient( + settings(), + transport=httpx.MockTransport( + lambda r: httpx.Response( + status, json={"message": "sensitive provider text"}, headers={"Retry-After": "120"} + ) + ), + ) + with pytest.raises(MaxApiError) as error: + await client.send(100, "neutral", site_url="https://example.org", button="Open") + assert error.value.retryable is retry and error.value.retry_after == 120 + assert "sensitive" not in str(error.value) + await client.close() + + +@pytest.mark.parametrize("body", [{"success": False, "message": "private"}, {}, {"success": True}, []]) +async def test_http_200_is_not_enough_to_mark_delivered(body): + client = MaxClient(settings(), transport=httpx.MockTransport(lambda r: httpx.Response(200, json=body))) + with pytest.raises(MaxApiError): + await client.send(100, "neutral", site_url="https://example.org", button="Open") + await client.close() + + +async def test_timeout_is_retryable_without_request_details(): + def handler(request): + raise httpx.ReadTimeout("private URL", request=request) + + client = MaxClient(settings(), transport=httpx.MockTransport(handler)) + with pytest.raises(MaxApiError, match="^transport$") as error: + await client.request("GET", "/me") + assert error.value.retryable + await client.close() + + +async def test_subscription_includes_secret_and_exact_event_types(): + def handler(request): + assert request.url.path == "/subscriptions" + body = json.loads(request.content) + assert body == { + "url": settings().max_webhook_url, + "update_types": UPDATE_TYPES, + "secret": settings().max_webhook_secret.get_secret_value(), + } + return httpx.Response(200, json={"success": True}) + + client = MaxClient(settings(), transport=httpx.MockTransport(handler)) + await client.subscribe(settings()) + await client.close() diff --git a/tests/test_max_setup.py b/tests/test_max_setup.py new file mode 100644 index 0000000..680dde7 --- /dev/null +++ b/tests/test_max_setup.py @@ -0,0 +1,51 @@ +"""Operator tools do not send messages or expose credentials.""" + +from unittest.mock import AsyncMock + +import pytest + +from app.channels import max_setup +from app.channels.max_client import MaxApiError +from app.config import Settings + + +@pytest.fixture +def client(monkeypatch): + settings = Settings(_env_file=None, max_bot_username="test_bot", max_webhook_url="https://api.example.org/hook") + sender = AsyncMock() + sender.request.return_value = {"is_bot": True, "username": "test_bot"} + monkeypatch.setattr(max_setup, "Settings", lambda **kwargs: settings) + monkeypatch.setattr(max_setup, "MaxClient", lambda cfg: sender) + return sender + + +async def test_check_only_reads_bot_identity(client): + await max_setup.run("check") + client.request.assert_awaited_once_with("GET", "/me") + client.subscribe.assert_not_called() + client.send.assert_not_called() + client.close.assert_awaited_once() + + +async def test_subscribe_is_explicit_and_checks_bot_first(client): + await max_setup.run("subscribe") + client.subscribe.assert_awaited_once() + client.send.assert_not_called() + + +async def test_mismatched_bot_does_not_change_webhooks(client): + client.request.return_value = {"is_bot": True, "username": "another_bot"} + with pytest.raises(MaxApiError, match="bot_username_mismatch"): + await max_setup.run("subscribe") + client.subscribe.assert_not_called() + client.close.assert_awaited_once() + + +async def test_status_checks_exact_configured_webhook(client): + client.request.side_effect = [ + {"is_bot": True, "username": "test_bot"}, + {"subscriptions": [{"url": "https://elsewhere.example.org"}]}, + ] + with pytest.raises(MaxApiError, match="webhook_missing"): + await max_setup.run("status") + client.subscribe.assert_not_called() diff --git a/web/public/favicon.svg b/web/public/favicon.svg index 7830f3e..0001347 100644 --- a/web/public/favicon.svg +++ b/web/public/favicon.svg @@ -1 +1 @@ - + diff --git a/web/src/components/AppShell.tsx b/web/src/components/AppShell.tsx index 1fde105..a93786e 100644 --- a/web/src/components/AppShell.tsx +++ b/web/src/components/AppShell.tsx @@ -3,13 +3,14 @@ import { Link, NavLink } from "react-router-dom"; import { ru } from "../content/ru"; import { useDialog } from "../dialog/DialogContext"; +import { useSession } from "../session/SessionContext"; import { HotlineCard, useHelp } from "./HelpSheet"; import { Icon, LogoMark, type IconName } from "./Icon"; /* - * Layout from docs/mock (series 2). + * Shared patient workspace, following the approved doctor dashboard. * phone: content → «Экстренная помощь» block → bottom tab bar (signed in) - * desktop: navy sidebar | content | right rail (optional `aside` + emergency panel) + * desktop: white sidebar | workspace header | content + emergency panel * bare: one centred column on every width (questionnaires) */ @@ -87,6 +88,10 @@ function Sidebar({ signedIn }: { signedIn: boolean }) { )} +
+ {ru.product.supportTitle} + {ru.product.supportText} +
); } @@ -122,6 +127,24 @@ function Rail({ aside }: { aside?: ReactNode }) { ); } +function WorkspaceHeader({ signedIn, bare = false }: { signedIn: boolean; bare?: boolean }) { + const { session } = useSession(); + return ( +
+
+ + {bare ? ru.product.name : signedIn ? ru.product.workspace : ru.nav.signIn} +
+ {signedIn && !bare ? ( + + + {session?.displayName || ru.nav.profile} + + ) : {ru.product.tagline}} +
+ ); +} + export function AppShell({ children, signedIn = true, @@ -144,6 +167,7 @@ export function AppShell({ return (
+
{children} {sos && } @@ -155,6 +179,7 @@ export function AppShell({
+
{children} {sos && } diff --git a/web/src/components/Icon.tsx b/web/src/components/Icon.tsx index cf90800..05510a8 100644 --- a/web/src/components/Icon.tsx +++ b/web/src/components/Icon.tsx @@ -163,8 +163,8 @@ export function Icon({ name, size = 22, label }: { name: IconName; size?: number export function LogoMark({ size = 32 }: { size?: number }) { return ( ); } diff --git a/web/src/content/ru.ts b/web/src/content/ru.ts index 44e0c74..1810915 100644 --- a/web/src/content/ru.ts +++ b/web/src/content/ru.ts @@ -6,6 +6,9 @@ export const ru = { product: { name: "Сопровождение пациента", tagline: "между визитами к врачу", + workspace: "Личный кабинет", + supportTitle: "Рядом между визитами", + supportText: "Наблюдение за самочувствием и поддержка назначенного лечения.", }, nav: { today: "Сегодня", @@ -201,6 +204,7 @@ export const ru = { toIntake: "Пройти первичный опрос", }, flow: { + home: "На главный экран", question: (n: number, total: number) => `Вопрос ${n} из ${total}`, period: "За последний месяц", textPlaceholder: "Напишите несколько слов", diff --git a/web/src/main.tsx b/web/src/main.tsx index 0b98700..4b51591 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -1,7 +1,3 @@ -import "@fontsource/golos-text/400.css"; -import "@fontsource/golos-text/500.css"; -import "@fontsource/golos-text/600.css"; -import "@fontsource/golos-text/700.css"; import "./theme/tokens.css"; import "./theme/global.css"; diff --git a/web/src/screens/Flow.tsx b/web/src/screens/Flow.tsx index 50d15fb..8613b56 100644 --- a/web/src/screens/Flow.tsx +++ b/web/src/screens/Flow.tsx @@ -265,7 +265,7 @@ function FreeText({ {skip.label} ) : ( - )} @@ -362,6 +362,7 @@ function SurveyAct({ press, say, onPause, + onHome, }: { step: Survey; stepKey: string; @@ -369,6 +370,7 @@ function SurveyAct({ press: (b: DialogButton) => void; say: (text: string) => void; onPause: (b: DialogButton) => void; + onHome: () => void; }) { let answer: ReactNode; switch (step.input) { @@ -381,7 +383,7 @@ function SurveyAct({ break; case "text": answer = ( - undefined} /> + ); break; default: @@ -522,17 +524,6 @@ export function Flow() { navigate("/today", { replace: true }); }, [step, stepKey, navigate, toast]); - // Questionnaire: answers are saved on the server per question, and there is no going back to change one. - // The browser «back» is absorbed by a duplicate history entry of this same screen. - const testing = step?.kind === "survey" || step?.kind === "choice" || step?.kind === "consent"; - useEffect(() => { - if (!testing) return; - window.history.pushState(null, "", window.location.href); - const stay = () => window.history.pushState(null, "", window.location.href); - window.addEventListener("popstate", stay); - return () => window.removeEventListener("popstate", stay); - }, [testing]); - const press = (b: DialogButton) => void dialog.send({ type: "button", button: b.data }, b.label); // «Продолжить позже»: answers are already saved on the server — pause and go straight home, no confirmation. const pause = (b: DialogButton) => @@ -588,7 +579,7 @@ export function Flow() { ) : item ? ( ) : null; - const top = {progress}; + const top = progress ? {progress} : null; // Phone: one column. Desktop: question and context on the left, answers and actions on the right. let lead: ReactNode; let act: ReactNode; @@ -702,7 +693,7 @@ export function Flow() { break; case "survey": lead = ; - act = ; + act = ; break; case "choice": lead = ; @@ -725,6 +716,14 @@ export function Flow() { return ( + {content} ); diff --git a/web/src/theme/global.css b/web/src/theme/global.css index 5d351c2..672710b 100644 --- a/web/src/theme/global.css +++ b/web/src/theme/global.css @@ -1,4 +1,4 @@ -/* Phone-first (docs/mock series 2). ≥1024px: navy sidebar | content | emergency rail. Tokens only. */ +/* Phone-first patient workspace, matching the doctor dashboard. */ *, *::before, @@ -122,15 +122,15 @@ button:disabled { } .tabbar__item.active { - color: var(--c-navy); - font-weight: 700; + color: var(--c-primary); + font-weight: 600; } /* ---------------------------------------------------------------- type */ .h1 { font-size: var(--fs-28); - font-weight: 700; + font-weight: 550; line-height: 1.15; letter-spacing: -0.02em; color: var(--c-text); @@ -139,13 +139,13 @@ button:disabled { .h2 { font-size: var(--fs-20); - font-weight: 700; + font-weight: 550; line-height: 1.2; } .h3 { font-size: var(--fs-18); - font-weight: 700; + font-weight: 600; } .lead { @@ -196,7 +196,7 @@ button:disabled { } .tel { - font-weight: 700; + font-weight: 600; white-space: nowrap; color: var(--c-red-strong); } @@ -239,7 +239,7 @@ button:disabled { .topbar__title { font-size: var(--fs-20); - font-weight: 700; + font-weight: 600; } .divider { @@ -284,30 +284,30 @@ button:disabled { } .btn--primary { - background: var(--c-navy); + background: var(--c-primary); color: #fff; } .btn--primary:hover:not(:disabled) { - background: var(--c-navy-hover); + background: var(--c-primary-hover); } .btn--outline { background: var(--c-surface); - border-color: var(--c-navy); - color: var(--c-navy); + border-color: var(--c-primary); + color: var(--c-primary); } .btn--ghost { background: var(--c-tile); border-color: var(--c-border); - color: var(--c-navy); + color: var(--c-primary); } .btn--soft { background: var(--c-blue-soft); - color: var(--c-navy); - border-color: #cfe0f5; + color: var(--c-primary); + border-color: var(--c-border); } .btn--danger { @@ -317,7 +317,7 @@ button:disabled { .btn--primary:disabled, .btn--danger:disabled { - background: #c5cfdc; + background: var(--c-border-strong); color: #fff; } @@ -330,7 +330,7 @@ button:disabled { place-items: center; margin-left: -10px; border: 0; - border-radius: 12px; + border-radius: var(--r-tile); background: transparent; color: var(--c-text); } @@ -366,7 +366,7 @@ button:disabled { } .chip--teal { - background: #cdeee8; + background: var(--c-teal-soft); color: var(--c-teal-strong); } @@ -381,9 +381,9 @@ button:disabled { height: 48px; display: grid; place-items: center; - border-radius: 14px; + border-radius: var(--r-btn); background: var(--c-tile); - color: var(--c-navy); + color: var(--c-primary); } .tile-icon--teal { @@ -435,7 +435,7 @@ button:disabled { border-radius: 50%; background: var(--c-blue-soft); color: var(--c-blue); - font-weight: 700; + font-weight: 600; } .avatar--lg { @@ -514,6 +514,7 @@ button:disabled { /* ---------------------------------------------------------------- cards */ .panel { + border: 1px solid var(--c-border); display: grid; gap: var(--s-3); padding: var(--s-4); @@ -541,7 +542,7 @@ button:disabled { display: flex; align-items: center; gap: var(--s-2); - font-weight: 700; + font-weight: 600; } .iconlist { @@ -665,7 +666,7 @@ button.row-card:hover:not(:disabled) { .signin__name { display: block; font-size: var(--fs-18); - font-weight: 700; + font-weight: 600; color: var(--c-text); } @@ -679,9 +680,9 @@ button.row-card:hover:not(:disabled) { display: grid; gap: var(--s-5); padding: var(--s-8) var(--s-6); - border-radius: 24px; + border-radius: var(--r-tile); background: var(--c-surface); - box-shadow: 0 12px 40px rgba(15, 39, 71, 0.08); + border: 1px solid var(--c-border); } .signin__card .entry__title { @@ -708,6 +709,8 @@ button.row-card:hover:not(:disabled) { } .signin__foot { + border: 1px solid var(--c-red-line); + border-left: 3px solid var(--c-red); display: flex; align-items: center; justify-content: space-between; @@ -718,16 +721,21 @@ button.row-card:hover:not(:disabled) { } .signin__sos { + border: 0; + background: transparent; + padding: 8px 0; + min-height: 44px; + text-align: left; display: inline-flex; align-items: center; gap: var(--s-2); - font-weight: 700; + font-weight: 600; color: var(--c-red-strong); } .signin__tel { font-size: var(--fs-20); - font-weight: 700; + font-weight: 600; color: var(--c-red-strong); text-decoration: none; } @@ -742,7 +750,7 @@ button.row-card:hover:not(:disabled) { gap: var(--s-3); padding: var(--s-5); border: 1.5px solid var(--c-border); - border-radius: 20px; + border-radius: var(--r-tile); background: var(--c-surface); text-align: left; color: var(--c-text); @@ -777,7 +785,7 @@ button.row-card:hover:not(:disabled) { align-items: center; justify-content: space-between; font-size: var(--fs-20); - font-weight: 700; + font-weight: 600; } .entry__title svg { @@ -829,7 +837,7 @@ button.row-card:hover:not(:disabled) { min-height: 60px; padding: var(--s-3) var(--s-4); border: 1.5px solid var(--c-border); - border-radius: 14px; + border-radius: var(--r-btn); background: var(--c-surface); text-align: left; font-size: var(--fs-16); @@ -856,7 +864,7 @@ button.row-card:hover:not(:disabled) { .option.is-on { background: var(--c-teal-soft); - border-color: var(--c-teal-soft); + border-color: var(--c-teal); } .option.is-on .option__mark { @@ -873,9 +881,9 @@ button.row-card:hover:not(:disabled) { .numscale__value { justify-self: center; font-size: var(--fs-48); - font-weight: 700; + font-weight: 600; line-height: 1; - color: var(--c-navy); + color: var(--c-primary); } .numscale__row { @@ -947,7 +955,7 @@ button.row-card:hover:not(:disabled) { gap: var(--s-3); justify-items: center; padding: var(--s-6) var(--s-4); - border-radius: 20px; + border-radius: var(--r-tile); background: var(--c-teal-soft); } @@ -970,8 +978,8 @@ button.row-card:hover:not(:disabled) { border-radius: var(--r-tile); background: var(--c-surface); font-size: var(--fs-28); - font-weight: 700; - color: var(--c-navy); + font-weight: 600; + color: var(--c-primary); } .reminder__time svg { @@ -994,9 +1002,9 @@ button.row-card:hover:not(:disabled) { min-height: 60px; padding: 0 var(--s-4); border: 0; - border-radius: 14px; + border-radius: var(--r-btn); background: var(--c-blue-soft); - color: var(--c-navy); + color: var(--c-primary); font-size: var(--fs-18); font-weight: 600; } @@ -1057,7 +1065,7 @@ button.row-card:hover:not(:disabled) { } .breath__title { - font-weight: 700; + font-weight: 600; } .breath__viz { @@ -1074,7 +1082,7 @@ button.row-card:hover:not(:disabled) { border-radius: 50%; border: 6px solid var(--c-teal-soft); border-top-color: var(--c-teal); - border-right-color: #7fd1c6; + border-right-color: var(--c-border-strong); animation: breathe 10s var(--ease) infinite; } @@ -1206,7 +1214,7 @@ button.row-card:hover:not(:disabled) { } .task__title { - font-weight: 700; + font-weight: 600; } .task__sub { @@ -1214,13 +1222,14 @@ button.row-card:hover:not(:disabled) { color: var(--c-text-2); overflow: hidden; text-overflow: ellipsis; - white-space: nowrap; + white-space: normal; } .task--hero { - background: var(--c-navy); - border-color: var(--c-navy); - color: #fff; + background: var(--c-teal-soft); + border-color: var(--c-border-strong); + border-left: 3px solid var(--c-primary); + color: var(--c-text); } .task--hero .task__icon { @@ -1230,7 +1239,7 @@ button.row-card:hover:not(:disabled) { .task--hero .task__sub, .task--hero > svg:last-child { - color: #c9d6e8; + color: var(--c-text-2); } .done-row { @@ -1257,7 +1266,7 @@ button.row-card:hover:not(:disabled) { display: grid; gap: var(--s-3); padding: var(--s-6) var(--s-5); - border-radius: 20px; + border-radius: var(--r-tile); background: var(--c-teal-soft); } @@ -1277,13 +1286,13 @@ button.row-card:hover:not(:disabled) { border-radius: var(--r-tile); background: var(--c-surface); text-align: left; - color: var(--c-navy); + color: var(--c-primary); } .quick__title { display: block; font-size: var(--fs-14); - font-weight: 700; + font-weight: 600; } .quick__sub { @@ -1368,7 +1377,7 @@ button.row-card:hover:not(:disabled) { .rx__drug { display: block; font-size: var(--fs-18); - font-weight: 700; + font-weight: 600; } .rx__by { @@ -1457,7 +1466,7 @@ button.row-card:hover:not(:disabled) { .bubble p { padding: var(--s-3) var(--s-4); - border-radius: 18px; + border-radius: var(--r-tile); white-space: pre-wrap; overflow-wrap: anywhere; } @@ -1504,7 +1513,7 @@ button.row-card:hover:not(:disabled) { border-radius: var(--r-btn); background: var(--c-surface); font-weight: 600; - color: var(--c-navy); + color: var(--c-primary); } .qr:first-child { @@ -1560,10 +1569,12 @@ button.row-card:hover:not(:disabled) { /* ---------------------------------------------------------------- emergency */ .sosblock { + border: 1px solid var(--c-red-line); + border-left: 3px solid var(--c-red); display: grid; gap: var(--s-2); padding: var(--s-2); - border-radius: 18px; + border-radius: var(--r-tile); background: var(--c-red-soft); } @@ -1576,7 +1587,7 @@ button.row-card:hover:not(:disabled) { border: 0; background: none; color: var(--c-red-strong); - font-weight: 700; + font-weight: 600; font-size: var(--fs-16); text-align: left; } @@ -1629,7 +1640,7 @@ button.row-card:hover:not(:disabled) { .hotline--sm { padding: var(--s-2) var(--s-3); background: rgb(255 255 255 / 0.65); - border-radius: 12px; + border-radius: var(--r-tile); } .hotline__icon { @@ -1658,7 +1669,7 @@ button.row-card:hover:not(:disabled) { .hotline__phone { font-size: var(--fs-28); - font-weight: 700; + font-weight: 600; line-height: 1.1; color: var(--c-red-strong); } @@ -1704,14 +1715,14 @@ button.row-card:hover:not(:disabled) { margin: auto auto 0; padding: 0; border: 0; - border-radius: 24px 24px 0 0; + border-radius: 16px 16px 0 0; background: var(--c-surface); color: var(--c-text); } .sheet::backdrop, .modal::backdrop { - background: rgb(15 39 71 / 0.5); + background: rgb(33 59 56 / 0.35); } .sheet[open], @@ -1739,7 +1750,7 @@ button.row-card:hover:not(:disabled) { .sheet__title { font-size: var(--fs-20); - font-weight: 700; + font-weight: 600; } .sos { @@ -1755,7 +1766,7 @@ button.row-card:hover:not(:disabled) { display: grid; place-items: center; border-radius: 50%; - background: radial-gradient(circle, var(--c-red-soft) 55%, #fff6f6 56% 100%); + background: var(--c-red-soft); } .sos__btn { @@ -1790,12 +1801,14 @@ button.row-card:hover:not(:disabled) { .app { display: grid; - grid-template-columns: var(--sidebar-w) 1fr; + grid-template-columns: var(--sidebar-w) minmax(0, 1fr); } .tabbar, .only-phone, .screen > .sosblock { + border: 1px solid var(--c-red-line); + border-left: 3px solid var(--c-red); display: none; } @@ -1811,21 +1824,22 @@ button.row-card:hover:not(:disabled) { align-content: start; gap: var(--s-8); padding: var(--s-6) var(--s-4); - background: var(--c-navy); - color: #fff; + background: var(--c-surface); + border-right: 1px solid var(--c-border); + color: var(--c-text); } .sidebar__brand { display: flex; gap: var(--s-3); align-items: center; - color: #fff; + color: var(--c-text); text-decoration: none; } .sidebar__name { display: block; - font-weight: 700; + font-weight: 600; font-size: var(--fs-14); line-height: 1.2; } @@ -1833,7 +1847,7 @@ button.row-card:hover:not(:disabled) { .sidebar__tag { display: block; font-size: var(--fs-12); - color: #a9b9cf; + color: var(--c-text-3); } .sidebar__list { @@ -1852,7 +1866,7 @@ button.row-card:hover:not(:disabled) { border: 0; border-radius: var(--r-btn); background: none; - color: #c9d6e8; + color: var(--c-text-2); font-size: var(--fs-16); font-weight: 500; text-decoration: none; @@ -1860,25 +1874,26 @@ button.row-card:hover:not(:disabled) { } .sidebar__link:hover { - background: rgb(255 255 255 / 0.06); - color: #fff; + background: var(--c-tile); + color: var(--c-primary); } .sidebar__link.active { - background: rgb(255 255 255 / 0.12); - color: #fff; - font-weight: 700; + background: var(--c-primary-soft); + color: var(--c-primary); + font-weight: 600; } .sidebar__link .dot { position: static; margin-left: auto; - border-color: var(--c-navy); + border-color: var(--c-surface); } .app__main { display: grid; - grid-template-columns: minmax(0, 1fr) var(--rail-w); + grid-template-columns: minmax(0, 1fr); + align-content: start; gap: var(--s-6); max-width: 1320px; padding: var(--s-8) var(--s-8) var(--s-8) var(--s-10); @@ -1895,18 +1910,18 @@ button.row-card:hover:not(:disabled) { /* Tab screens and sign-in: the page content sits on one wide white card. */ .screen > .stack { padding: var(--s-8) var(--s-10); - border-radius: 24px; + border-radius: var(--r-tile); background: var(--c-surface); - box-shadow: 0 1px 2px rgb(15 39 71 / 0.06); + border: 1px solid var(--c-border); } /* Focus screens: question on the left, answers on the right. */ .focus, .done { padding: var(--s-8) var(--s-10) var(--s-10); - border-radius: 24px; + border-radius: var(--r-tile); background: var(--c-surface); - box-shadow: 0 1px 2px rgb(15 39 71 / 0.06); + border: 1px solid var(--c-border); } .done { @@ -1920,7 +1935,7 @@ button.row-card:hover:not(:disabled) { } .split { - grid-template-columns: minmax(0, 1.05fr) minmax(0, 1fr); + grid-template-columns: minmax(0, 1fr); gap: var(--s-12); align-items: start; } @@ -1932,7 +1947,7 @@ button.row-card:hover:not(:disabled) { .split__act { padding: var(--s-6); - border-radius: 20px; + border-radius: var(--r-tile); background: var(--c-tile); } @@ -1991,7 +2006,7 @@ button.row-card:hover:not(:disabled) { /* Today: dashboard. */ .dash { - grid-template-columns: minmax(0, 1.55fr) minmax(0, 1fr); + grid-template-columns: minmax(0, 1fr); gap: var(--s-6); align-items: start; } @@ -2003,19 +2018,18 @@ button.row-card:hover:not(:disabled) { .dash__main { padding: var(--s-6); - border-radius: 24px; + border-radius: var(--r-tile); background: var(--c-surface); - box-shadow: 0 1px 2px rgb(15 39 71 / 0.06); + border: 1px solid var(--c-border); } .dash__side .card { - border-color: transparent; - box-shadow: 0 1px 2px rgb(15 39 71 / 0.06); + border: 1px solid var(--c-border); } .grid2, .cols { - grid-template-columns: 1fr 1fr; + grid-template-columns: minmax(0, 1fr); align-items: start; } @@ -2028,7 +2042,7 @@ button.row-card:hover:not(:disabled) { } .rail { - position: sticky; + position: static; top: var(--s-8); display: grid; gap: var(--s-4); @@ -2036,10 +2050,12 @@ button.row-card:hover:not(:disabled) { } .railsos { + border: 1px solid var(--c-red-line); + border-left: 3px solid var(--c-red); display: grid; gap: var(--s-2); padding: var(--s-3); - border-radius: 20px; + border-radius: var(--r-tile); background: var(--c-red-soft); } @@ -2052,7 +2068,7 @@ button.row-card:hover:not(:disabled) { border: 0; background: none; color: var(--c-red-strong); - font-weight: 700; + font-weight: 600; text-align: left; } @@ -2081,7 +2097,7 @@ button.row-card:hover:not(:disabled) { .modal { max-width: 460px; margin: auto; - border-radius: 24px; + border-radius: var(--r-tile); } .composer { @@ -2118,13 +2134,13 @@ button.row-card:hover:not(:disabled) { .chip--trauma { background: var(--c-amber-soft); - color: #a86a00; + color: var(--c-amber); } .chip--alcohol, .chip--about { - background: var(--c-navy-soft); - color: var(--c-navy); + background: var(--c-primary-soft); + color: var(--c-primary); } .survey { @@ -2243,7 +2259,7 @@ button.row-card:hover:not(:disabled) { .drinks tbody th { white-space: nowrap; - color: var(--c-navy); + color: var(--c-primary); } /* diary: hours of sleep */ @@ -2280,8 +2296,8 @@ button.row-card:hover:not(:disabled) { outline: none; background: none; font-size: var(--fs-28); - font-weight: 700; - color: var(--c-navy); + font-weight: 600; + color: var(--c-primary); } .hours__field span { @@ -2309,7 +2325,7 @@ button.row-card:hover:not(:disabled) { gap: var(--s-4); width: 100%; padding: var(--s-3) var(--s-4); - border: 1px solid #cfe0f5; + border: 1px solid var(--c-border); border-radius: var(--r-tile); background: var(--c-blue-soft); text-align: left; @@ -2327,7 +2343,7 @@ button.row-card:hover:not(:disabled) { place-items: center; width: 56px; height: 56px; - border-radius: 14px; + border-radius: var(--r-btn); background: var(--c-surface); color: var(--c-blue); line-height: 1; @@ -2335,7 +2351,7 @@ button.row-card:hover:not(:disabled) { .effect__num { font-size: var(--fs-24); - font-weight: 700; + font-weight: 600; } .effect__unit { @@ -2404,7 +2420,7 @@ button.row-card:hover:not(:disabled) { gap: var(--s-3); margin: 0; font-size: var(--fs-18); - font-weight: 700; + font-weight: 600; } .drug__sub { @@ -2443,7 +2459,7 @@ button.row-card:hover:not(:disabled) { border: 3px solid var(--c-surface); border-radius: 50%; background: var(--c-teal); - box-shadow: 0 1px 3px rgb(15 39 71 / 25%); + box-shadow: 0 1px 3px rgb(33 59 56 / 20%); transform: translate(-50%, -50%); } @@ -2463,7 +2479,7 @@ button.row-card:hover:not(:disabled) { @media (min-width: 1024px) { .drug__grid { - grid-template-columns: 1fr 1fr; + grid-template-columns: minmax(0, 1fr); gap: var(--s-5); } @@ -2498,10 +2514,12 @@ button.row-card:hover:not(:disabled) { min-height: 100dvh; margin: 0 auto; padding: var(--s-10) var(--s-4); - align-content: center; + align-content: start; } .app--bare .screen > .sosblock { + border: 1px solid var(--c-red-line); + border-left: 3px solid var(--c-red); display: grid; } @@ -2527,7 +2545,7 @@ button.row-card:hover:not(:disabled) { .result__title { font-size: var(--fs-20); - font-weight: 700; + font-weight: 600; } .result__chips { @@ -2621,9 +2639,9 @@ button.row-card:hover:not(:disabled) { gap: var(--s-3); padding: var(--s-3) var(--s-3) var(--s-3) var(--s-4); border-radius: var(--r-tile); - background: var(--c-navy); + background: var(--c-primary); color: #fff; - box-shadow: 0 12px 32px rgb(15 39 71 / 0.25); + box-shadow: 0 12px 32px rgb(33 59 56 / 0.15); pointer-events: auto; animation: toast-in 200ms var(--ease); } @@ -2656,3 +2674,266 @@ button.row-card:hover:not(:disabled) { transform: translateY(-8px); } } + +/* ---------------------------------------------------------------- workspace frame */ + +.app__main, +.screen, +.screen > *, +.split > *, +.cols > *, +.dash > * { + min-width: 0; +} + +.workspace { + grid-column: 1 / -1; + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: var(--s-3); + margin: 0 max(var(--s-5), var(--safe-left)); + padding: calc(var(--s-4) + var(--safe-top)) 0 var(--s-4); + border-bottom: 1px solid var(--c-border); + color: var(--c-text-3); + font-size: var(--fs-13); +} + +.workspace__brand, +.workspace__profile { + display: inline-flex; + align-items: center; + gap: var(--s-2); +} + +.workspace__brand svg { + flex: none; +} + +.workspace__profile { + text-decoration: none; + color: var(--c-text); + font-weight: 500; +} + +.workspace__profile .avatar { + width: 34px; + height: 34px; + background: var(--c-teal-soft); + color: var(--c-primary); +} + +.workspace__tag { + font-size: var(--fs-12); +} + +.screen { + padding-top: var(--s-6); +} + +.head { + padding-bottom: var(--s-4); + border-bottom: 1px solid var(--c-border); +} + +.focus .head { + border-bottom: 0; + padding-bottom: 0; +} + +.tabbar__item.active { + background: var(--c-primary-soft); + box-shadow: inset 0 2px var(--c-primary); +} + +.btn--outline { + border-color: var(--c-border-strong); +} + +.btn--outline:hover:not(:disabled), +.btn--ghost:hover:not(:disabled), +.btn--soft:hover:not(:disabled), +.task:hover:not(:disabled), +.quick__btn:hover:not(:disabled) { + background: var(--c-primary-soft); + border-color: var(--c-border-strong); +} + +.composer:focus-within { + outline: 3px solid var(--c-focus); + outline-offset: 2px; +} + +.composer textarea { + min-width: 0; +} + +.log__row { + border: 0; + background: transparent; +} + +.log__row:hover:not(:disabled) { + background: var(--c-tile); +} + +.result { + border: 1px solid var(--c-border-strong); + border-left: 3px solid var(--c-teal); +} + +.notice--info { + border: 1px solid var(--c-border); +} + +.notice--warn, +.notice--danger { + border: 1px solid var(--c-red-line); + border-left: 3px solid var(--c-red); +} + +@media (max-width: 1023px) { + .screen > .stack, + .focus, + .done, + .dash__main { + padding: var(--s-5); + background: var(--c-surface); + border: 1px solid var(--c-border); + border-radius: var(--r-tile); + } + + .workspace { + max-width: 600px; + margin-inline: auto; + width: calc(100% - 40px); + } + + .workspace__tag { + display: none; + } +} + +@media (max-width: 480px) { + .screen > .stack, + .focus, + .done, + .dash__main { + padding: var(--s-4); + } + + .btn-row, + .quick, + .sosblock__lines { + grid-template-columns: minmax(0, 1fr); + } + + .signin__card { + padding: var(--s-6) var(--s-5); + } + + .task, + .effect { + flex-wrap: wrap; + } + + .task__text { + flex-basis: 55%; + } + + .signin__foot { + flex-wrap: wrap; + } + + .numscale__row { + gap: 3px; + } +} + +@media (min-width: 1024px) { + .workspace { + margin: 0; + min-height: 62px; + padding: 0 0 var(--s-5); + } + + .workspace:not(.workspace--bare) .workspace__brand svg { + display: none; + } + + .screen { + padding-top: 0; + } + + .sidebar { + display: flex; + flex-direction: column; + padding: var(--s-8) var(--s-5); + overflow-y: auto; + } + + .sidebar__brand > svg { + flex: none; + } + + .sidebar__note { + display: grid; + gap: var(--s-2); + margin-top: auto; + padding-top: var(--s-5); + border-top: 1px solid var(--c-border); + font-size: var(--fs-12); + line-height: 1.6; + color: var(--c-text-3); + } + + .sidebar__note strong { + color: var(--c-text); + font-weight: 500; + } + + .rail { + grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); + } + + .rail > * { + align-self: start; + } + + .screen > .stack, + .focus, + .done { + padding: var(--s-6); + } +} + +@media (min-width: 1200px) { + .dash { + grid-template-columns: minmax(0, 1.35fr) minmax(0, 1fr); + } + + .grid2, + .cols, + .drug__grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} + +@media (min-width: 1440px) { + .app__main { + grid-template-columns: minmax(0, 1fr) var(--rail-w); + } + + .rail { + position: sticky; + grid-template-columns: minmax(0, 1fr); + } +} + +/* Respect reduced motion for toasts defined after the earlier component rules. */ +@media (prefers-reduced-motion: reduce) { + .toast { + animation: none; + } +} diff --git a/web/src/theme/tokens.css b/web/src/theme/tokens.css index cc72e7b..ebb5c01 100644 --- a/web/src/theme/tokens.css +++ b/web/src/theme/tokens.css @@ -1,45 +1,45 @@ /* - * Design tokens — single source of colours, type and spacing (docs/mock, series 2). + * Shared visual language with dashboard/theme.py and the approved doctor workspace. * Capacitor wraps this same bundle; a React Native port maps these 1:1 to a theme object. */ :root { /* Ink & surfaces */ - --c-navy: #0f2747; /* primary buttons, headings, desktop sidebar */ - --c-navy-hover: #0a1d37; - --c-navy-soft: #e8eef6; - --c-text: #13294b; - --c-text-2: #4d5d73; - --c-text-3: #7a889b; - --c-page: #ffffff; - --c-page-desk: #f4f7fb; /* desktop canvas behind white panels */ + --c-primary: #285e4e; /* primary buttons and active navigation */ + --c-primary-hover: #204b3e; + --c-primary-soft: #edf3ee; + --c-text: #213b38; + --c-text-2: #526660; + --c-text-3: #63736f; + --c-page: #f6f7f3; + --c-page-desk: #f6f7f3; /* desktop canvas behind white panels */ --c-surface: #ffffff; - --c-tile: #f3f7fb; /* soft card fill */ - --c-border: #e2e9f1; - --c-border-strong: #c9d4e1; + --c-tile: #f4f6f2; /* soft card fill */ + --c-border: #e1e7e3; + --c-border-strong: #b4c6ba; - /* Selection & positive: teal */ - --c-teal: #17a08f; - --c-teal-strong: #0e7e71; - --c-teal-soft: #e3f5f2; + /* Selection & positive */ + --c-teal: #527f61; + --c-teal-strong: #38634b; + --c-teal-soft: #eef4ee; - /* Info: blue */ - --c-blue: #2f7fdb; - --c-blue-soft: #eaf3fd; + /* Informational surfaces */ + --c-blue: #38634b; + --c-blue-soft: #edf3ee; /* Help & crisis: red */ - --c-red: #e2383b; - --c-red-strong: #c62b2e; - --c-red-soft: #fdeded; - --c-red-line: #f7d3d3; + --c-red: #a83236; + --c-red-strong: #a83236; + --c-red-soft: #faeeee; + --c-red-line: #e7cbcb; /* Warning */ - --c-amber: #e69a12; - --c-amber-soft: #fff4dd; + --c-amber: #805714; + --c-amber-soft: #fbf3e4; - --c-focus: #2f7fdb; + --c-focus: #598d7a; - /* Type: Golos Text (OFL), bundled locally — works offline. */ - --font: "Golos Text", system-ui, -apple-system, "Segoe UI", sans-serif; + /* Same offline system stack as the doctor workspace. */ + --font: -apple-system, BlinkMacSystemFont, "Segoe UI", Arial, sans-serif; --fs-12: 0.75rem; --fs-13: 0.8125rem; --fs-14: 0.875rem; @@ -63,14 +63,14 @@ --s-12: 48px; /* Radii: tiles > buttons > chips */ - --r-tile: 16px; - --r-btn: 12px; - --r-chip: 999px; + --r-tile: 12px; + --r-btn: 8px; + --r-chip: 5px; --tap: 52px; --nav-h: 64px; - --sidebar-w: 232px; - --rail-w: 300px; + --sidebar-w: 228px; + --rail-w: 264px; --safe-top: env(safe-area-inset-top, 0px); --safe-bottom: env(safe-area-inset-bottom, 0px);