Complete incident selection and 112 to DDS workflow
This commit is contained in:
parent
0526b11f91
commit
68dd83c7c2
21 changed files with 281 additions and 56 deletions
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
]
|
||||
|
|
|
|||
|
|
@ -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))
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -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):
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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(),
|
||||
|
|
|
|||
|
|
@ -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
|
||||
#: Чьё это занятие. Проставляется при запуске, когда курсант известен
|
||||
|
|
|
|||
Loading…
Reference in a new issue