Complete incident selection and 112 to DDS workflow

This commit is contained in:
andreysk0304 2026-09-21 20:10:57 +03:00
commit 68dd83c7c2
21 changed files with 281 additions and 56 deletions

View file

@ -26,7 +26,7 @@ async def groups() -> dict:
@router.get("/signs")
async def signs(prefix: list[str] = Query(default=[])) -> dict:
async def signs(prefix: list[str] = Query(default=[]), group: int | None = None) -> dict:
"""Значения следующего признака при уже выбранных.
Пустой `prefix` — значения первого уровня. Возвращается и найденное
@ -34,10 +34,10 @@ async def signs(prefix: list[str] = Query(default=[])) -> dict:
он классифицировал, до того, как отправит карточку.
"""
level = len(prefix) + 1
found = ekp.by_signs(prefix) if prefix else None
found = ekp.by_signs(prefix, group) if prefix else None
return {
"level": level,
"values": ekp.signs_at_level(level, prefix) if level <= 3 else [],
"values": ekp.signs_at_level(level, prefix, group) if level <= 3 else [],
"incident": (
{
"code": found.code,

View file

@ -17,6 +17,7 @@ from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.auth import audit, require
from app.domain import ekp
from app.db.base import get_session
from app.domain.roles import Role
from app.scenarios import store
@ -131,6 +132,11 @@ async def listing() -> list[dict]:
"topics": scenario.topics,
"modes": scenario.modes,
"dds": scenario.ground_truth.dds.value if scenario.ground_truth.dds else None,
"ticket": scenario.ticket,
"position": scenario.position,
"ekp_group": (ekp.incident(scenario.ground_truth.incident_code).group
if scenario.ground_truth.incident_code
and ekp.incident(scenario.ground_truth.incident_code) else None),
}
for scenario in store.all_scenarios()
]

View file

@ -100,25 +100,37 @@ async def _handle(session_id: UUID, state, event) -> None:
code=ErrorKind.UNSUPPORTED_EVENT, message="Действие недоступно в этом упражнении",
))
return
if state.exercise is Exercise.CARD and state.dispatched_card is not None:
hub.to_trainee(session_id, ErrorEvent(
code=ErrorKind.UNSUPPORTED_EVENT,
message="Карточка уже передана в ДДС и не может быть изменена",
))
return
match event.type:
case "card.submit":
state.kio.registered_at = state.started_at or now_utc()
state.kio.response_status = ResponseStatus.TRANSFERRED
state.dispatched_card = state.kio.model_copy(deep=True)
state.dispatched_at = now_utc()
state.ended_at = state.dispatched_at
state.end_reason = CallEndReason.COMPLETE
hub.stop_ticker(session_id)
if state.handoff_to_dds:
state.on_event("dds.dispatch")
else:
state.ended_at = state.dispatched_at
state.end_reason = CallEndReason.COMPLETE
hub.stop_ticker(session_id)
hub.to_station(session_id, state.card_received_event())
hub.to_station(session_id, StationState(snapshot=state.station_snapshot()))
hub.to_observers(session_id, KioState(kio=state.kio))
hub.to_trainee(session_id, CallEnded(reason=CallEndReason.COMPLETE))
hub.to_observers(session_id, SessionEnded(reason=CallEndReason.COMPLETE))
if hub.journal:
await hub.journal.session_ended(
session_id, state.ended_at, CallEndReason.COMPLETE.value
)
await finish(session_id, state)
if state.handoff_to_dds:
hub.to_observers(session_id, state.snapshot())
else:
hub.to_observers(session_id, SessionEnded(reason=CallEndReason.COMPLETE))
if hub.journal:
await hub.journal.session_ended(
session_id, state.ended_at, CallEndReason.COMPLETE.value
)
await finish(session_id, state)
case "call.answer":
state.on_event("call.answer")
state.started_at = now_utc()
@ -295,7 +307,7 @@ async def call(ws: WebSocket, session_id: UUID) -> None:
from app.api.ws.control import card_briefing
hub.to_trainee(session_id, card_briefing(state))
if state.ended:
if state.ended or state.dispatched_card is not None:
hub.to_trainee(session_id, CallEnded(reason=state.end_reason or CallEndReason.COMPLETE))
if state.score is not None:
hub.to_trainee(session_id, ScoreReady(session_id=session_id))

View file

@ -72,10 +72,17 @@ def card_briefing(state: SessionState) -> CardBriefing:
required_fields=([field for field in state.required_fields if field != "dds"]
if scenario.ground_truth.incident_code else list(state.required_fields)),
card=state.kio,
handoff_to_dds=state.handoff_to_dds,
)
async def _start(session_id: UUID, event, who=None) -> None:
if event.handoff_to_dds and event.exercise is not Exercise.CARD:
hub.to_observers(session_id, ErrorEvent(
code=ErrorKind.SCENARIO_INVALID,
message="Передача в ДДС доступна только для текстовой карточки 112",
))
return
scenario = store.get(event.scenario_id)
if scenario is None:
hub.to_observers(
@ -118,6 +125,7 @@ async def _start(session_id: UUID, event, who=None) -> None:
level=scenario.level.value,
mode=event.mode,
exercise=event.exercise,
handoff_to_dds=event.handoff_to_dds,
scenario=scenario.model_copy(deep=True),
required_fields=scenario.required_fields,
trainee_name=event.trainee,
@ -188,12 +196,12 @@ async def _stop(session_id: UUID) -> None:
if state.exercise in {Exercise.DDS, Exercise.CARD}:
from app.session.finish import finish
if state.exercise is Exercise.DDS:
if state.exercise is Exercise.DDS or state.handoff_to_dds and state.dispatched_card is not None:
hub.to_station(session_id, SessionEnded(reason=CallEndReason.INSTRUCTOR))
else:
hub.to_trainee(session_id, CallEnded(reason=CallEndReason.INSTRUCTOR))
await finish(session_id, state)
if state.exercise is Exercise.DDS:
if state.exercise is Exercise.DDS or state.handoff_to_dds and state.dispatched_card is not None:
hub.to_station(session_id, ScoreReady(session_id=session_id))
if hub.journal:
await hub.journal.session_ended(session_id, state.ended_at, CallEndReason.INSTRUCTOR.value)

View file

@ -86,7 +86,7 @@ async def _handle(session_id: UUID, state, event) -> None:
_error(session_id, "Служба отсутствует в списке оповещения карточки")
return
phase = REPORT_FOR_STATUS.get(event.status)
if state.exercise is Exercise.DDS and phase is not None and not any(
if (state.exercise is Exercise.DDS or state.handoff_to_dds) and phase is not None and not any(
report.service == event.service and report.phase == phase
for report in state.phone_reports
):
@ -144,7 +144,7 @@ async def _handle(session_id: UUID, state, event) -> None:
state.dds_log.append(("phone.dial", now_utc(), crew))
hub.to_station(session_id, PhoneReport(**report.model_dump()))
case "card.reply":
if state.exercise is not Exercise.DDS or not state.dispatched_card or (
if (state.exercise is not Exercise.DDS and not state.handoff_to_dds) or not state.dispatched_card or (
event.card_id != state.dispatched_card.card_id
):
_error(session_id, "Ответ относится не к текущей карточке")
@ -168,7 +168,7 @@ async def _handle(session_id: UUID, state, event) -> None:
else:
await _finish_dds(session_id, state)
case "station.finish":
if state.exercise is not Exercise.DDS:
if state.exercise is not Exercise.DDS and not state.handoff_to_dds:
_error(session_id, "Операторское занятие завершается после звонка 112")
return
await _finish_dds(session_id, state)

View file

@ -95,12 +95,12 @@ def _by_code() -> dict[str, Incident]:
@lru_cache(maxsize=1)
def _by_signs() -> dict[tuple[str, ...], Incident]:
def _by_signs() -> dict[tuple[int, tuple[str, ...]], Incident]:
"""Признаки → строка классификатора. Нормализуем регистр: методист пишет
«Жилой дом», книга — «жилой дом», и это одно и то же."""
table: dict[tuple[str, ...], Incident] = {}
table: dict[tuple[int, tuple[str, ...]], Incident] = {}
for incident in reference().incidents:
table.setdefault(tuple(sign.lower() for sign in incident.signs), incident)
table.setdefault((incident.group, tuple(sign.lower() for sign in incident.signs)), incident)
return table
@ -108,10 +108,14 @@ def incident(code: str) -> Incident | None:
return _by_code().get(code)
def by_signs(signs: list[str]) -> Incident | None:
def by_signs(signs: list[str], group: int | None = None) -> Incident | None:
"""Комбинация признаков → происшествие. Порядок признаков значим:
в книге это три уровня, а не множество."""
return _by_signs().get(tuple(sign.strip().lower() for sign in signs if sign.strip()))
key = tuple(sign.strip().lower() for sign in signs if sign.strip())
if group is not None:
return _by_signs().get((group, key))
return next((item for (item_group, item_signs), item in _by_signs().items()
if item_signs == key), None)
def groups() -> list[IncidentGroup]:
@ -146,7 +150,7 @@ def notify_list(code: str, modifiers: list[str] | None = None) -> list[str]:
return service_names(indexes)
def signs_at_level(level: int, prefix: list[str] | None = None) -> list[str]:
def signs_at_level(level: int, prefix: list[str] | None = None, group: int | None = None) -> list[str]:
"""Значения признака уровня 1–3 при уже выбранных предыдущих.
Это источник выпадающих списков в карточке: выбрал «жилой дом» — во втором
@ -155,6 +159,8 @@ def signs_at_level(level: int, prefix: list[str] | None = None) -> list[str]:
chosen = [sign.strip().lower() for sign in (prefix or [])]
values: list[str] = []
for item in reference().incidents:
if group is not None and item.group != group:
continue
if len(item.signs) < level or item.signs[0].lower() == HIDDEN_SIGN:
continue
if [sign.lower() for sign in item.signs[: len(chosen)]] != chosen:

View file

@ -128,6 +128,7 @@ class CardBriefing(BaseModel):
text: str
required_fields: list[str]
card: KIO | None = None
handoff_to_dds: bool = False
class CallStarted(BaseModel):
@ -424,6 +425,7 @@ class ScenarioStart(BaseModel):
group_id: str | None = None
mode: SessionMode
exercise: Exercise = Exercise.CALL
handoff_to_dds: bool = False
class DirectorInject(BaseModel):

View file

@ -104,6 +104,7 @@ class KIO(BaseModel):
# Происшествие. Оператор проставляет признаки, остальное считает система
# по ЕКП (domain/ekp.py) — службу он не выбирает.
incident_group: int | None = None
signs: list[str] = Field(default_factory=list, max_length=3)
incident_code: str | None = Field(default=None, description="Код ЕКП по признакам")
incident_type: IncidentType | None = None
@ -163,7 +164,7 @@ def missing_fields(card: KIO, required: list[str]) -> list[str]:
#: те же «признаки», только не про тип происшествия, а про обстоятельства:
#: пострадавшие поднимают скорую, газификация — МОСГАЗ (domain/ekp.py).
MODIFIER_FIELDS: frozenset[str] = frozenset(
{"signs", "victims_count", "life_threat", "evacuation_needed", "fire.gasified"}
{"incident_group", "signs", "victims_count", "life_threat", "evacuation_needed", "fire.gasified"}
)
@ -189,7 +190,7 @@ def derive_incident(card: KIO) -> KIO:
"""
from app.domain import ekp
found = ekp.by_signs(card.signs)
found = ekp.by_signs(card.signs, card.incident_group)
keys = modifiers(card)
data = card.model_dump()
data["incident_code"] = found.code if found else None

View file

@ -2,6 +2,7 @@
import re
from app.domain import ekp
from app.domain.kio import KIO, ResponseStatus
from app.scenarios.schema import Scenario
from app.session.state import SessionState, now_utc
@ -25,6 +26,8 @@ def prepare_card(state: SessionState, scenario: Scenario) -> None:
address=truth.address or address_fact or None,
floor=floor.group(1) if floor else None,
incident_type=truth.incident_type, incident_code=truth.incident_code,
incident_group=(ekp.incident(truth.incident_code).group
if truth.incident_code and ekp.incident(truth.incident_code) else None),
dds=truth.dds, signs=list(scenario.signs),
notify=list(truth.notify) or ([fallback[service]] if service in fallback else []),
victims_count=truth.victims,

View file

@ -126,7 +126,9 @@ async def finish(session_id: UUID, state) -> None:
# Работа диспетчера — вторая роль и вторая таксономия. Отметки D1–D6 идут
# рядом с E1–E6, а не вместо: в живой цепочке 112 → ДДС в одном занятии
# участвуют оба (docs/spec/DATASET.md#статусы-реагирования).
if state.dispatched_card is not None and state.exercise is Exercise.CALL:
if state.dispatched_card is not None and (
state.exercise is Exercise.CALL or state.handoff_to_dds
):
dispatcher_findings = evaluate_dispatcher(
entries=state.status_log,
services=state.notified_services(),

View file

@ -71,6 +71,8 @@ class SessionState:
level: str
mode: SessionMode
exercise: Exercise = Exercise.CALL
#: После заполнения КИО занятие продолжится на АРМ ДДС, а не завершится.
handoff_to_dds: bool = False
required_fields: list[str] = field(default_factory=list)
trainee_name: str | None = None
#: Чьё это занятие. Проставляется при запуске, когда курсант известен

View file

@ -36,12 +36,13 @@ def read_until(socket, wanted):
raise AssertionError(f"событие {wanted} не пришло")
def start(client):
def start(client, *, handoff_to_dds=False):
session_id = uuid4()
context = client.websocket_connect(f"/ws/control/{session_id}")
control = context.__enter__()
control.send_json({"type": "scenario.start", "scenario_id": "fire-apartment-l2",
"trainee": "Иванов", "mode": "training", "exercise": "card"})
"trainee": "Иванов", "mode": "training", "exercise": "card",
"handoff_to_dds": handoff_to_dds})
wait_for(lambda: hub.get(session_id))
return session_id, context
@ -123,3 +124,53 @@ def test_incomplete_card_has_only_card_findings(client):
assert report["reference_questions"] == []
finally:
control.__exit__(None, None, None)
def test_filled_112_card_continues_as_dds_in_the_same_lesson(client):
session_id, control = start(client, handoff_to_dds=True)
try:
with client.websocket_connect(f"/ws/call/{session_id}") as trainee:
briefing = read_until(trainee, "card.briefing")
assert briefing["handoff_to_dds"] is True
trainee.send_json({"type": "kio.patch", "fields": {
"address": "улица Ленина, 14", "incident_type": "fire",
"victims_count": 2, "description": "горит балкон",
"signs": ["жилой дом", "балкон", "открытое пламя"],
}})
wait_for(lambda: hub.get(session_id).kio.incident_code)
trainee.send_json({"type": "card.submit"})
assert read_until(trainee, "call.ended")["reason"] == "complete"
state = hub.get(session_id)
assert state.dispatched_card is not None and not state.ended
assert state.score is None
trainee.send_json({"type": "kio.patch", "fields": {"address": "поздняя правка"}})
assert "передана" in read_until(trainee, "error")["message"]
with client.websocket_connect(f"/ws/call/{session_id}") as late:
assert read_until(late, "card.briefing")["card"]["address"] == "улица Ленина, 14"
assert read_until(late, "call.ended")["reason"] == "complete"
with client.websocket_connect(f"/ws/station/{session_id}") as station:
assert read_until(station, "card.received")["card"]["address"] == "улица Ленина, 14"
snapshot = read_until(station, "station.state")["snapshot"]
service = snapshot["services"][0]
crew = next(item for item in snapshot["crew_options"] if item.startswith(service + " — "))
station.send_json({"type": "card.status", "service": service, "status": "accepted"})
read_until(station, "station.state")
station.send_json({"type": "crew.select", "crew": crew})
read_until(station, "station.state")
station.send_json({"type": "phone.dial"})
assert read_until(station, "phone.report")["phase"] == "dispatched"
read_until(station, "station.state")
station.send_json({"type": "card.status", "service": service, "status": "responding"})
read_until(station, "station.state")
station.send_json({"type": "station.finish"})
read_until(station, "score.ready")
score = wait_for(lambda: hub.get(session_id).score)
assert hub.get(session_id).ended
keys = {item["key"] for item in score["metrics"]}
assert {"address", "incident_signs", "dds_primary", "dds_contact"} <= keys
assert score["score_auto"] < 100
finally:
control.__exit__(None, None, None)

View file

@ -5,9 +5,11 @@
"""
import pytest
from pathlib import Path
from app.domain import ekp
from app.domain.kio import KIO, derive_incident
from app.scenarios.loader import load_library
def test_reference_loads_whole_book():
@ -20,6 +22,20 @@ def test_reference_loads_whole_book():
assert all(incident.type for incident in reference.incidents), "код без итогового типа"
def test_all_customer_ticket_cards_are_complete_and_classified():
cards = [scenario for scenario in load_library(Path(__file__).resolve().parents[2] / "scenarios")
if scenario.ticket is not None]
assert len(cards) == 96
assert {scenario.ticket for scenario in cards} == set(range(1, 33))
for ticket in range(1, 33):
assert {scenario.position for scenario in cards if scenario.ticket == ticket} == {1, 2, 3}
assert all(scenario.facts and scenario.signs and scenario.ground_truth.address
and scenario.ground_truth.victims is not None
and scenario.ground_truth.incident_code
and ekp.incident(scenario.ground_truth.incident_code)
for scenario in cards)
def test_signs_give_the_code_from_the_book():
found = ekp.by_signs(["жилой дом", "подъезд", "открытое пламя"])
assert found is not None
@ -40,6 +56,20 @@ def test_next_level_narrows_by_previous():
assert "мусор" not in second, "«мусор» относится к улице, а не к жилому дому"
def test_category_filters_all_three_incident_choices_and_card_derivation():
fire = ekp.by_signs(["жилой дом", "балкон", "открытое пламя"])
assert fire is not None
other_group = next(group.id for group in ekp.groups() if group.id != fire.group)
assert ekp.by_signs(fire.signs, fire.group) == fire
assert ekp.by_signs(fire.signs, other_group) is None
assert fire.signs[0] in ekp.signs_at_level(1, group=fire.group)
assert fire.signs[1] in ekp.signs_at_level(2, fire.signs[:1], group=fire.group)
assert fire.signs[2] in ekp.signs_at_level(3, fire.signs[:2], group=fire.group)
card = derive_incident(KIO(incident_group=fire.group, signs=fire.signs))
assert card.incident_code == fire.code
assert derive_incident(KIO(incident_group=other_group, signs=fire.signs)).incident_code is None
def test_service_rows_hidden_from_operator_are_not_offered():
"""Часть строк книги существует ради интеграции и оператору не показывается."""
assert all(ekp.HIDDEN_SIGN not in sign.lower() for sign in ekp.signs_at_level(1))