fix(clinical): red flags, one crisis rule, callback after a crisis, one table of numbers
Clinical review of the questionnaires (ADR-013):
- Red-flag block first in stage 1 (config/instruments/red_flags.yaml); any «Да» stops the
questionnaire with an acute alert and the help screen of its category.
- One crisis rule: the crisis screen opens at a HIGH C-SSRS risk only; moderate stops and goes
to a psychiatrist (24 h as a guide), low is a flag with the safety plan. PHQ-9 item 9 with a
negative screener is a discrepancy flag; without a completed screener it asks the C-SSRS at once.
config/questionnaire.yaml: cssrs_positive_policy graded (C01).
- Every crisis leaves a callback task for the doctor on duty (post_crisis_call, one per patient)
and the app asks how the person is the next day, the safety plan one tap away.
- Routing: risk and flags first, scales second; PCL-5 >= 50 no longer means a priority
appointment (pcl5_severe is moderate on the dashboard too).
- Crisis numbers live only in config/texts/crisis.yaml; texts and the agent prompt refer to them
via {phone:<key>}. Fixes the children's helpline offered to adults by the chat agent.
Refs #92
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+2
-1
@@ -16,6 +16,7 @@ from app.api.schemas import (
|
||||
PatientListItem,
|
||||
SeriesPoint,
|
||||
)
|
||||
from app.core.safety import fill_phones
|
||||
from app.integrations.base import Prescription
|
||||
|
||||
TZ = ZoneInfo("Europe/Moscow")
|
||||
@@ -262,7 +263,7 @@ def andrey_card() -> PatientCard:
|
||||
"Что помогает: прогулка с собакой, душ",
|
||||
"Люди и места: брат Олег, спортзал",
|
||||
"Кому звонить: жена, сослуживец Миша",
|
||||
"Специалисты: д-р Смирнова, 8-800-2000-122, 112",
|
||||
fill_phones("Специалисты: д-р Смирнова, {phone:helpline}, 112"),
|
||||
"Безопасная среда: ружьё хранится у брата",
|
||||
],
|
||||
summary="За 13 дней: приверженность 12/13, эпизод намерения бросить на 5-й день (снят после звонка врача). "
|
||||
|
||||
@@ -13,7 +13,7 @@ from pydantic import BaseModel
|
||||
|
||||
from app.config import get_settings
|
||||
from app.core.cssrs_content import load_cssrs_russian
|
||||
from app.core.intake_questions import DIARY_PARTS, content, diary_config, texts
|
||||
from app.core.intake_questions import DIARY_PARTS, content, diary_config, red_flags, texts
|
||||
from app.core.scales import load_scale
|
||||
|
||||
Section = Literal["safety", "mood", "trauma", "alcohol", "about", "diary", "scale"]
|
||||
@@ -92,6 +92,9 @@ def catalog() -> Catalog:
|
||||
),
|
||||
)
|
||||
|
||||
flags = red_flags()
|
||||
add(FormInfo(id="red_flags", title="Вопросы о безопасности", section="safety"), [i["id"] for i in flags["items"]])
|
||||
|
||||
cssrs = load_cssrs_russian()
|
||||
add(FormInfo(id="cssrs", title=cssrs.title, section="safety"), ["cssrs_" + i.id for i in cssrs.items])
|
||||
|
||||
|
||||
@@ -53,11 +53,25 @@ def cssrs_answers(answers: dict) -> dict[str, int]:
|
||||
return {k.removeprefix("cssrs_"): v for k, v in answers.items() if k.startswith("cssrs_")}
|
||||
|
||||
|
||||
def red_flags() -> dict:
|
||||
return yaml.safe_load((get_settings().config_dir / "instruments/red_flags.yaml").read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def red_flag_category(item_id: str) -> str | None:
|
||||
return next((i["category"] for i in red_flags()["items"] if i["id"] == item_id), None)
|
||||
|
||||
|
||||
def next_intake(answers: dict, policy: IntakePolicy, sex: str | None) -> Question | None:
|
||||
"""Stage 1 in the fixed order of «Опросники для MVP»: PHQ-2, trauma filter → TSQ, RUS-AUDIT-S, C-SSRS screener,
|
||||
then the context questions; stage 2 (rest of PHQ-9, PCL-5, full RUS-AUDIT) only where stage 1 is positive.
|
||||
Items inside a scale keep the order of the source. The risk stop rules run after every answer (flows/intake.py),
|
||||
so a positive answer interrupts the questionnaire wherever it comes."""
|
||||
"""Stage 1: the red-flag block first (config/instruments/red_flags.yaml), then the fixed order of «Опросники
|
||||
для MVP»: PHQ-2, trauma filter → TSQ, RUS-AUDIT-S, C-SSRS screener, the context questions; stage 2 (rest of
|
||||
PHQ-9, PCL-5, full RUS-AUDIT) only where stage 1 is positive. Items inside a scale keep the order of the source.
|
||||
The risk stop rules run after every answer (flows/intake.py), so a positive answer interrupts the questionnaire
|
||||
wherever it comes."""
|
||||
flags = red_flags()
|
||||
for n, item in enumerate(flags["items"]):
|
||||
if item["id"] not in answers:
|
||||
text = (flags["intro"] + "\n\n" if n == 0 else "") + item["text"]
|
||||
return Question(item["id"], text, tuple((o["value"], o["label"]) for o in flags["options"]), "now")
|
||||
for item in ("phq9_1", "phq9_2"):
|
||||
if item not in answers:
|
||||
return scale_question("phq9", item)
|
||||
|
||||
@@ -12,6 +12,7 @@ import yaml
|
||||
from app.config import get_settings
|
||||
from app.core.intake_questions import content
|
||||
from app.core.questionnaire import IntakeDecision, IntakePolicy
|
||||
from app.core.safety import fill_phones
|
||||
|
||||
# Stage 1 finding → diary module of stage 2 (PTSD is the «veteran» module of the profile).
|
||||
FINDING_MODULE = {"depression_suspected": "depression", "ptsd_suspected": "veteran"}
|
||||
@@ -23,7 +24,7 @@ PCL5_IMPROVED_BELOW = 28
|
||||
|
||||
|
||||
def texts() -> dict[str, Any]:
|
||||
return yaml.safe_load((get_settings().config_dir / "texts/results.yaml").read_text(encoding="utf-8"))
|
||||
return yaml.safe_load(fill_phones((get_settings().config_dir / "texts/results.yaml").read_text(encoding="utf-8")))
|
||||
|
||||
|
||||
def render(interpretation: dict[str, Any]) -> str:
|
||||
|
||||
@@ -50,7 +50,6 @@ class IntakePolicy(BaseModel):
|
||||
phq9_specialist_at: int = Field(ge=0, le=27, strict=True)
|
||||
phq9_priority_at: int = Field(ge=0, le=27, strict=True)
|
||||
pcl5_specialist_at: int = Field(ge=0, le=80, strict=True)
|
||||
pcl5_priority_at: int = Field(ge=0, le=80, strict=True)
|
||||
pcl5_behavior_flag_at: int = Field(ge=0, le=4, strict=True)
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -65,8 +64,6 @@ class IntakePolicy(BaseModel):
|
||||
raise ValueError("choose a total threshold OR a zone for alcohol expansion")
|
||||
if not self.phq9_psychologist_at < self.phq9_specialist_at < self.phq9_priority_at:
|
||||
raise ValueError("PHQ-9 thresholds must be ordered")
|
||||
if self.pcl5_specialist_at >= self.pcl5_priority_at:
|
||||
raise ValueError("PCL-5 thresholds must be ordered")
|
||||
return self
|
||||
|
||||
|
||||
@@ -276,7 +273,9 @@ def evaluate_intake(
|
||||
if c.positive:
|
||||
flags.append("cssrs_positive")
|
||||
flags.extend(c.conflicts)
|
||||
if item9_positive or c.risk_lower_bound == "high":
|
||||
# One crisis rule (ADR-013): a high C-SSRS risk. Item 9 alone is a crisis only while the screener is not complete;
|
||||
# with a negative / low screener it is the «discrepancy» flag of the routing table, not the crisis screen.
|
||||
if c.risk_lower_bound == "high" or (item9_positive and not c.complete):
|
||||
return IntakeDecision(policy.version, "crisis", "crisis", (), tuple(flags), c.missing)
|
||||
if c.positive and policy.approval and policy.cssrs_positive_policy == "stop_any":
|
||||
return IntakeDecision(policy.version, "crisis", "crisis", (), tuple(flags), c.missing)
|
||||
@@ -327,9 +326,11 @@ def evaluate_intake(
|
||||
# PHQ-2-negative does not invent a PHQ-9 total; it simply does not trigger expansion.
|
||||
phq_total = phq.total if phq.complete else 0
|
||||
pcl_total = pcl.total if pcl.complete else 0
|
||||
# Risk and flags first, scales second (clinical review 2026-10-04). A high PCL-5 alone is not a reason for a
|
||||
# priority appointment: it goes to the planned specialist route.
|
||||
if c.risk == "moderate":
|
||||
primary = "urgent_psychiatrist"
|
||||
elif phq_total >= policy.phq9_priority_at or pcl_total >= policy.pcl5_priority_at:
|
||||
elif phq_total >= policy.phq9_priority_at:
|
||||
primary = "priority_psychiatrist"
|
||||
elif phq_total >= policy.phq9_specialist_at or pcl_total >= policy.pcl5_specialist_at:
|
||||
primary = "psychiatrist_or_psychotherapist"
|
||||
|
||||
@@ -395,6 +395,25 @@ def _crisis_cfg(path: Path = CRISIS_PATH) -> _CrisisCfg:
|
||||
return _CrisisCfg.model_validate(yaml.safe_load(path.read_text(encoding="utf-8")))
|
||||
|
||||
|
||||
_PHONE_REF = re.compile(r"\{phone:([a-z_]+)\}")
|
||||
|
||||
|
||||
def fill_phones(text: str, path: Path = CRISIS_PATH) -> str:
|
||||
"""Replace `{phone:<resource>}` with the number from the single table in config/texts/crisis.yaml.
|
||||
|
||||
Every patient text and prompt refers to the table instead of repeating a number, so a number is changed in one
|
||||
place. An unknown resource fails loudly: a wrong number on the crisis screen must never pass silently.
|
||||
"""
|
||||
resources = _crisis_cfg(path).resources
|
||||
|
||||
def number(m: re.Match[str]) -> str:
|
||||
if m.group(1) not in resources:
|
||||
raise ValueError(f"unknown crisis resource {m.group(1)!r}")
|
||||
return resources[m.group(1)].phone
|
||||
|
||||
return _PHONE_REF.sub(number, text)
|
||||
|
||||
|
||||
def _render(body: str, resources: list[CrisisResource], doctor_notified: str, grounding: str) -> str:
|
||||
lines = [body.strip(), ""]
|
||||
for r in resources:
|
||||
|
||||
@@ -14,6 +14,7 @@ from app.core.intake_questions import (
|
||||
diary_questions,
|
||||
group_answers,
|
||||
next_intake,
|
||||
red_flag_category,
|
||||
scale_question,
|
||||
texts,
|
||||
)
|
||||
@@ -27,6 +28,7 @@ from app.dialog.contracts import Button, Event, Reply
|
||||
from app.dialog.crisis import crisis_open, open_crisis
|
||||
from app.dialog.fsm import Step, on_enter, state, trigger
|
||||
from app.services import questionnaire as service
|
||||
from app.services.followup import schedule_post_crisis_call
|
||||
|
||||
|
||||
def allowed(ctx):
|
||||
@@ -105,6 +107,7 @@ async def urgent(ctx, row=None, *, code="help_now", categories=None):
|
||||
level=AlertLevel.ACUTE,
|
||||
params={"record_id": row.id if row else None, "flags": flags},
|
||||
)
|
||||
await schedule_post_crisis_call(ctx.session, ctx.token, ctx.now, source="questionnaire:" + code)
|
||||
step = open_crisis(ctx, categories or [], source="questionnaire:" + code)
|
||||
step.data["questionnaire_record"] = None
|
||||
step.data["intake_review_required"] = True
|
||||
@@ -113,6 +116,41 @@ async def urgent(ctx, row=None, *, code="help_now", categories=None):
|
||||
return step
|
||||
|
||||
|
||||
async def item9_discrepancy(ctx, row):
|
||||
profile = await ctx.profile()
|
||||
if profile:
|
||||
profile.enhanced_monitoring = True
|
||||
await service.alert(
|
||||
ctx.session,
|
||||
ctx.token,
|
||||
row.id + ":phq9_cssrs_discrepancy",
|
||||
"phq9_cssrs_discrepancy",
|
||||
ctx.now,
|
||||
level=AlertLevel.HIGH,
|
||||
params={"record_id": row.id},
|
||||
)
|
||||
row.details = {**row.details, "item9_flagged": True}
|
||||
|
||||
|
||||
async def item9_assessment(ctx, row):
|
||||
"""Thoughts of death in PHQ-9 item 9 → the C-SSRS screener at once; the screener's level decides (graded)."""
|
||||
await service.alert(
|
||||
ctx.session,
|
||||
ctx.token,
|
||||
row.id + ":item9_assessment",
|
||||
"phq9_item9_cssrs",
|
||||
ctx.now,
|
||||
level=AlertLevel.HIGH,
|
||||
params={"record_id": row.id},
|
||||
)
|
||||
await service.finish(ctx, row, "complete", extra={"stop_reason": "phq9_item9_cssrs"})
|
||||
profile = await ctx.profile()
|
||||
if profile:
|
||||
profile.enhanced_monitoring = True
|
||||
task = await service.queue_task(ctx.session, ctx.token, "cssrs_since_contact", row.id + ":cssrs", ctx.now)
|
||||
return await start(ctx, "cssrs_since_contact", task)
|
||||
|
||||
|
||||
async def manual_review(ctx, row, code):
|
||||
await service.finish(ctx, row, "review_required", extra={"stop_reason": code})
|
||||
await service.alert(
|
||||
@@ -135,9 +173,24 @@ async def advance(ctx, row):
|
||||
a = row.answers
|
||||
c = score_cssrs_recent(cssrs_answers(a))
|
||||
policy = load_policy()
|
||||
# PHQ-9 item 9 ≥1 — in the full scale or in the depression module of the diary — stops at once (stage 1 rule).
|
||||
if a.get("phq9_9", 0) > 0 or a.get("dphq_9", 0) > 0 or c.risk_lower_bound == "high":
|
||||
# Red flags (asked first): any «Да» stops the questionnaire with the help screen of its category.
|
||||
for item_id, value in a.items():
|
||||
if item_id.startswith("rf_") and value == 1:
|
||||
category = red_flag_category(item_id)
|
||||
return await urgent(ctx, row, code="red_flag_" + item_id[3:], categories=[category] if category else [])
|
||||
# One crisis rule for the whole app (ADR-013): the crisis screen opens at a HIGH C-SSRS risk only. Moderate →
|
||||
# stop + psychiatrist (about 24 h); low → flag, safety plan, continue.
|
||||
if c.risk_lower_bound == "high":
|
||||
return await urgent(ctx, row, code="suicide_signal")
|
||||
if a.get("dphq_9", 0) > 0 and row.kind in DIARY_KINDS:
|
||||
# Diary depression module, item 9 ≥1 → the C-SSRS right away («Этап 2»); its risk level decides.
|
||||
return await item9_assessment(ctx, row)
|
||||
if a.get("phq9_9", 0) > 0 and not c.complete:
|
||||
# Item 9 without a completed screener (only in a scheduled PHQ-9): assess the risk right away.
|
||||
return await item9_assessment(ctx, row)
|
||||
if a.get("phq9_9", 0) > 0 and not row.details.get("item9_flagged"):
|
||||
# Item 9 ≥1 with a negative / low C-SSRS = discrepancy (routing table): flag to the doctor, safety plan.
|
||||
await item9_discrepancy(ctx, row)
|
||||
if c.positive and policy.cssrs_positive_policy == "stop_any":
|
||||
return await urgent(ctx, row, code="cssrs_positive")
|
||||
if c.conflicts:
|
||||
@@ -165,7 +218,7 @@ async def advance(ctx, row):
|
||||
return await manual_review(ctx, row, "answer_conflict")
|
||||
if q:
|
||||
replies = [question_reply(row, q)]
|
||||
if c.complete and c.risk == "low" and not row.details.get("plan_shown"):
|
||||
if ((c.complete and c.risk == "low") or row.details.get("item9_flagged")) and not row.details.get("plan_shown"):
|
||||
from app.dialog.actions import safety_plan_reply
|
||||
|
||||
replies.insert(0, await safety_plan_reply(ctx))
|
||||
@@ -225,11 +278,12 @@ async def advance(ctx, row):
|
||||
if row.kind in ("phq9", "pcl5"):
|
||||
sid = row.kind
|
||||
total = extra["totals"][sid]["total"]
|
||||
priority = getattr(policy, sid + "_priority_at")
|
||||
# Only PHQ-9 has a priority threshold; PCL-5 alone never makes an appointment a priority.
|
||||
priority = getattr(policy, sid + "_priority_at", None)
|
||||
specialist = getattr(policy, sid + "_specialist_at")
|
||||
extra["route"] = (
|
||||
"priority_psychiatrist"
|
||||
if total >= priority
|
||||
if priority is not None and total >= priority
|
||||
else ("psychiatrist_or_psychotherapist" if total >= specialist else "review_with_treating_clinician")
|
||||
)
|
||||
earlier = [
|
||||
@@ -284,7 +338,13 @@ async def advance(ctx, row):
|
||||
return step
|
||||
from app.dialog.flows.core import menu_reply
|
||||
|
||||
return Step(replies=[menu_reply(ctx, shown)], next_state="idle", data={"questionnaire_record": None})
|
||||
replies = [menu_reply(ctx, shown)]
|
||||
if ((c.complete and c.risk == "low") or row.details.get("item9_flagged")) and not row.details.get("plan_shown"):
|
||||
# The safety plan is never skipped because the risk signal came with the last question.
|
||||
from app.dialog.actions import safety_plan_reply
|
||||
|
||||
replies.insert(0, await safety_plan_reply(ctx))
|
||||
return Step(replies=replies, next_state="idle", data={"questionnaire_record": None})
|
||||
|
||||
|
||||
# Diary flags that bring a full scale forward («Этап 2», p.4).
|
||||
|
||||
+3
-1
@@ -7,6 +7,7 @@ import yaml
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.config import get_settings
|
||||
from app.core.safety import fill_phones
|
||||
|
||||
|
||||
class _Strict(BaseModel):
|
||||
@@ -91,6 +92,7 @@ class ReachOutTexts(_Strict):
|
||||
silence: str
|
||||
missed_doses: str
|
||||
default: str
|
||||
after_crisis: str
|
||||
|
||||
|
||||
class VisitTexts(_Strict):
|
||||
@@ -120,4 +122,4 @@ def dialog_texts_path() -> Path:
|
||||
@lru_cache
|
||||
def load_dialog_texts(path: Path | None = None) -> DialogTexts:
|
||||
path = path or dialog_texts_path()
|
||||
return DialogTexts.model_validate(yaml.safe_load(path.read_text(encoding="utf-8")))
|
||||
return DialogTexts.model_validate(yaml.safe_load(fill_phones(path.read_text(encoding="utf-8"))))
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
"""System prompt of the chat agent (Russian). Prohibitions follow SPEC §7; grounding: answer only from tools."""
|
||||
|
||||
SYSTEM_PROMPT = """Ты — помощник пациента в сервисе сопровождения лечения между визитами к врачу. Пациент лечится у
|
||||
from app.core.safety import fill_phones
|
||||
|
||||
_SYSTEM_PROMPT = """Ты — помощник пациента в сервисе сопровождения лечения между визитами к врачу. Пациент лечится у
|
||||
психиатра; ты отвечаешь на его вопросы о состоянии, лечении и лекарствах.
|
||||
|
||||
Как работать:
|
||||
@@ -32,4 +34,7 @@ SYSTEM_PROMPT = """Ты — помощник пациента в сервисе
|
||||
|
||||
Стиль: по-русски, на «вы», спокойно и по-человечески, 3–6 коротких предложений, без markdown-заголовков.
|
||||
Если в вопросе есть признаки угрозы жизни — коротко скажи, что важно сразу позвонить 112 или на телефон
|
||||
доверия 8-800-2000-122, и что врач будет уведомлён."""
|
||||
доверия {phone:helpline}, и что врач будет уведомлён."""
|
||||
|
||||
# Numbers come from the single table config/texts/crisis.yaml.
|
||||
SYSTEM_PROMPT = fill_phones(_SYSTEM_PROMPT)
|
||||
|
||||
+12
-1
@@ -22,11 +22,13 @@ from app.db import repo
|
||||
from app.db.clinical import PatientProfile
|
||||
from app.db.intake import QuestionnaireTask
|
||||
from app.db.session import get_clinical_session
|
||||
from app.dialog.contracts import Event, Reply, get_engine
|
||||
from app.dialog.contracts import Button, Event, Reply, get_engine
|
||||
from app.dialog.texts import load_dialog_texts
|
||||
from app.integrations.base import integrations
|
||||
from app.scheduler import demo
|
||||
from app.services import monitoring
|
||||
from app.services import questionnaire as service
|
||||
from app.services.followup import next_day_check_due
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
_worker = None
|
||||
@@ -43,6 +45,15 @@ async def plan():
|
||||
state = await repo.get_dialog_state(session, profile.token)
|
||||
if not state or state.data.get("consent") is not True or state.data.get("adult") is not True:
|
||||
continue
|
||||
crisis = state.data.get("crisis")
|
||||
if next_day_check_due(crisis, now):
|
||||
# The day after a crisis the app asks how the person is, the safety plan one tap away.
|
||||
texts = load_dialog_texts()
|
||||
plan_button = Button(label=texts.safety_plan.title.rstrip(":"), data="safety_plan")
|
||||
await integrations.outbox.push(
|
||||
profile.token, [Reply(text=texts.reach_out.after_crisis, buttons=[[plan_button]], kind="question")]
|
||||
)
|
||||
state.data = {**state.data, "crisis": {**crisis, "followup_sent": now.isoformat()}}
|
||||
rows = await service.records(session, profile.token)
|
||||
initial = next((r for r in reversed(rows) if r.kind == "intake" and r.status == "complete"), None)
|
||||
if initial is None:
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Follow-up after a crisis (clinical review 2026-10-04: «план безопасности и звонок после кризиса — обязательно»).
|
||||
|
||||
Every crisis — from the safety lexicon, a rule (PHQ-9 item 9, C-SSRS high) or the questionnaire (red flags, high
|
||||
risk) — leaves a task for the doctor on duty: call the patient back, about 24 hours as a guide. The task is an alert
|
||||
on the dashboard; «позвонили» is its acknowledgement (`repo.ack_alert`, audited). One open task per patient: a
|
||||
repeated crisis signal does not pile up callbacks. On the next day the app itself asks how the person is, with the
|
||||
safety plan at hand (`app/scheduler/jobs.py`).
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.types import AlertLevel
|
||||
from app.db import repo
|
||||
from app.db.clinical import Alert
|
||||
|
||||
POST_CRISIS_CALL = "post_crisis_call"
|
||||
ON_DUTY = "on-duty"
|
||||
CALL_WITHIN = timedelta(hours=24) # a guide, not a guarantee
|
||||
NEXT_DAY_CHECK_AFTER = timedelta(hours=20)
|
||||
|
||||
|
||||
async def schedule_post_crisis_call(session: AsyncSession, token: str, now: datetime, *, source: str) -> Alert | None:
|
||||
if POST_CRISIS_CALL in await repo.open_alert_codes(session, token):
|
||||
return None
|
||||
return await repo.add_alert(
|
||||
session,
|
||||
token=token,
|
||||
level=AlertLevel.HIGH,
|
||||
code=POST_CRISIS_CALL,
|
||||
reason="Перезвонить пациенту после кризиса — дежурный специалист, ориентир 24 ч. Отметка «позвонили» — "
|
||||
"подтверждение этого сигнала.",
|
||||
ts=now,
|
||||
params={"due_at": (now + CALL_WITHIN).isoformat(), "assignee": ON_DUTY, "source": source},
|
||||
)
|
||||
|
||||
|
||||
def next_day_check_due(crisis: dict | None, now: datetime) -> bool:
|
||||
"""The day after a crisis the app asks how the person is — once per crisis episode."""
|
||||
if not crisis or not crisis.get("opened_at") or crisis.get("followup_sent"):
|
||||
return False
|
||||
return now - datetime.fromisoformat(crisis["opened_at"]) >= NEXT_DAY_CHECK_AFTER
|
||||
@@ -30,6 +30,7 @@ from app.db.audit import audit
|
||||
from app.db.session import get_clinical_session
|
||||
from app.integrations.base import integrations
|
||||
from app.services.contracts import register_monitoring
|
||||
from app.services.followup import schedule_post_crisis_call
|
||||
from app.services.snapshot import build_snapshot
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -93,6 +94,7 @@ class RuleMonitoring:
|
||||
ts=now,
|
||||
)
|
||||
notify.append((ON_DUTY_DOCTOR, level, action.reason_ru))
|
||||
await schedule_post_crisis_call(s, token, now, source=f"rule:{action.code}")
|
||||
await refresh_status(s, token)
|
||||
log.info("monitoring token=%s actions=%s", token, [a.code for a in actions])
|
||||
for doctor_id, level, text in notify:
|
||||
|
||||
Reference in New Issue
Block a user