Complete DDS training workflow and delivery package
This commit is contained in:
parent
68dd83c7c2
commit
4c4b91064f
229 changed files with 11969 additions and 1024 deletions
|
|
@ -33,14 +33,15 @@ from app.domain.events import (
|
|||
)
|
||||
from app.domain.events import BgStart
|
||||
from app.scenarios import store
|
||||
from app.session.finish import finish, release_score
|
||||
from app.session.finish import finish, refresh_archived_report, release_score
|
||||
from app.api.auth import principal_of
|
||||
from app.domain.roles import Role
|
||||
from app.session.hub import hub
|
||||
from app.session.state import now_utc
|
||||
from app.domain.kio import ResponseStatus
|
||||
from app.voice.models import get_voice_models
|
||||
from app.voice.models import TTS_RATE, get_voice_models
|
||||
from app.voice.pipeline import VoiceSession
|
||||
from app.voice.recording import start_recording
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
|
|
@ -62,6 +63,8 @@ def _on_audio(session_id: UUID, state, frame: bytes) -> None:
|
|||
session_id, len(frame), FRAME_BYTES)
|
||||
return
|
||||
state.audio_frames += 1
|
||||
if state.recorder is not None:
|
||||
state.recorder.add_pcm(frame, sample_rate=16_000)
|
||||
if state.voice is not None:
|
||||
state.voice.feed(frame)
|
||||
if state.audio_frames % FRAMES_PER_LOG == 0:
|
||||
|
|
@ -138,6 +141,8 @@ async def _handle(session_id: UUID, state, event) -> None:
|
|||
hub.to_observers(session_id, state.snapshot())
|
||||
if hub.journal:
|
||||
await hub.journal.session_started(session_id, state.started_at)
|
||||
if state.recorder is None:
|
||||
state.recorder = start_recording(session_id)
|
||||
_start_voice(session_id, state)
|
||||
|
||||
case "kio.patch":
|
||||
|
|
@ -220,6 +225,7 @@ async def _handle(session_id: UUID, state, event) -> None:
|
|||
await hub.journal.self_assessment(
|
||||
session_id, event.missed, event.comment, now_utc()
|
||||
)
|
||||
await refresh_archived_report(session_id, state)
|
||||
# Оценка могла быть готова раньше самооценки — теперь её можно отдать.
|
||||
await release_score(session_id, state)
|
||||
|
||||
|
|
@ -237,6 +243,8 @@ async def _handle(session_id: UUID, state, event) -> None:
|
|||
)
|
||||
await finish(session_id, state)
|
||||
|
||||
await hub.checkpoint(session_id)
|
||||
|
||||
|
||||
def _start_voice(session_id: UUID, state) -> None:
|
||||
"""Голос включается, когда курсант снял трубку: звонящий сразу кричит первую реплику."""
|
||||
|
|
@ -244,13 +252,18 @@ def _start_voice(session_id: UUID, state) -> None:
|
|||
scenario = store.get(state.scenario_id)
|
||||
if models is None or scenario is None or state.voice is not None:
|
||||
return
|
||||
def send_audio(pcm: bytes) -> None:
|
||||
if state.recorder is not None:
|
||||
state.recorder.add_pcm(pcm, sample_rate=TTS_RATE)
|
||||
hub.to_trainee(session_id, pcm)
|
||||
|
||||
state.voice = VoiceSession(
|
||||
session_id=session_id,
|
||||
state=state,
|
||||
models=models,
|
||||
send_event=lambda event: hub.to_trainee(session_id, event),
|
||||
send_observer=lambda event: hub.to_observers(session_id, event),
|
||||
send_audio=lambda pcm: hub.to_trainee(session_id, pcm),
|
||||
send_audio=send_audio,
|
||||
journal=hub.journal,
|
||||
)
|
||||
if scenario.background:
|
||||
|
|
|
|||
|
|
@ -8,43 +8,43 @@
|
|||
преподавателю, уходит на его же сокет `observe`.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import math
|
||||
from uuid import UUID, uuid4
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
||||
from pydantic import TypeAdapter, ValidationError
|
||||
|
||||
from app.domain.events import (
|
||||
CallEndReason,
|
||||
CallEnded,
|
||||
ErrorEvent,
|
||||
ErrorKind,
|
||||
ScoreReady,
|
||||
CallIncoming,
|
||||
CardBriefing,
|
||||
Exercise,
|
||||
StationState,
|
||||
InstructorToServer,
|
||||
InstructorNoteShown,
|
||||
ModeSet,
|
||||
ReferenceStarted,
|
||||
SessionEnded,
|
||||
)
|
||||
import asyncio
|
||||
|
||||
from app.dialog.factory import build_caller
|
||||
from app.api.auth import audit, principal_of
|
||||
from app.dialog.director import apply as apply_directive
|
||||
from app.dialog.director import mood_of
|
||||
from app.dialog.factory import build_caller
|
||||
from app.dialog.persona import PersonaState
|
||||
from app.dialog.runtime import get_embedder
|
||||
from app.dialog.slots import SlotMachine
|
||||
from app.scenarios import store
|
||||
from app.api.auth import audit, principal_of
|
||||
from app.domain.events import (
|
||||
CallEnded,
|
||||
CallEndReason,
|
||||
CallIncoming,
|
||||
CardBriefing,
|
||||
ErrorEvent,
|
||||
ErrorKind,
|
||||
Exercise,
|
||||
InstructorNoteShown,
|
||||
InstructorToServer,
|
||||
ModeSet,
|
||||
ReferenceStarted,
|
||||
ScoreReady,
|
||||
SessionEnded,
|
||||
StationState,
|
||||
)
|
||||
from app.domain.roles import Role
|
||||
from app.domain.timers import TimerCode
|
||||
from app.scenarios import store
|
||||
from app.session.dds import prepare_queue
|
||||
from app.session.hub import hub
|
||||
from app.session.state import SessionState, now_utc
|
||||
from app.session.dds import prepare_card
|
||||
from app.voice.models import get_voice_models
|
||||
from app.voice.pipeline import FILLERS, prefetch
|
||||
|
||||
|
|
@ -93,10 +93,10 @@ async def _start(session_id: UUID, event, who=None) -> None:
|
|||
|
||||
scenario_ids = event.scenario_ids or [event.scenario_id]
|
||||
if event.exercise is Exercise.DDS:
|
||||
if not scenario_ids or scenario_ids[0] != event.scenario_id or len(scenario_ids) > 10:
|
||||
if not scenario_ids or scenario_ids[0] != event.scenario_id or len(scenario_ids) > 96:
|
||||
hub.to_observers(session_id, ErrorEvent(
|
||||
code=ErrorKind.SCENARIO_INVALID,
|
||||
message="Очередь ДДС должна начинаться с scenario_id и содержать не более 10 карточек",
|
||||
message="Очередь ДДС должна начинаться с scenario_id и содержать не более 96 карточек",
|
||||
))
|
||||
return
|
||||
scenarios = [store.get(scenario_id) for scenario_id in scenario_ids]
|
||||
|
|
@ -110,10 +110,19 @@ async def _start(session_id: UUID, event, who=None) -> None:
|
|||
|
||||
attempt = 1
|
||||
recorded_trainee_id = event.trainee_id
|
||||
recorded_service = None
|
||||
if hub.journal:
|
||||
attempt, recorded_trainee_id = await hub.journal.start_lesson(
|
||||
session_id, scenario.id, event.mode.value, event.trainee, event.trainee_id
|
||||
)
|
||||
try:
|
||||
attempt, recorded_trainee_id, recorded_service = await hub.journal.start_lesson(
|
||||
session_id, scenario.id, event.mode.value, event.trainee, event.trainee_id,
|
||||
owner_login=who.login if who is not None else None,
|
||||
)
|
||||
except PermissionError:
|
||||
hub.to_observers(session_id, ErrorEvent(
|
||||
code=ErrorKind.FORBIDDEN,
|
||||
message="Занятие создано другим преподавателем",
|
||||
))
|
||||
return
|
||||
|
||||
# Занятие собирается целиком и только потом регистрируется: иначе
|
||||
# наблюдатель, подключившийся в эту щель, увидит полусобранное состояние
|
||||
|
|
@ -124,23 +133,35 @@ async def _start(session_id: UUID, event, who=None) -> None:
|
|||
scenario_title=scenario.title,
|
||||
level=scenario.level.value,
|
||||
mode=event.mode,
|
||||
owner_login=who.login if who is not None else None,
|
||||
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,
|
||||
trainee_id=recorded_trainee_id,
|
||||
dds_service=recorded_service or event.dds_service,
|
||||
attempt=attempt,
|
||||
criteria=event.criteria,
|
||||
)
|
||||
state.timers.limits[TimerCode.DDS_ACK] = event.criteria.decision_time_limit_seconds * 1000
|
||||
if event.exercise is Exercise.CALL:
|
||||
embedder = get_embedder()
|
||||
if embedder is not None:
|
||||
state.slots = SlotMachine(state.scenario, embedder)
|
||||
state.persona = PersonaState(state.scenario.persona)
|
||||
state.caller = build_caller(scenario.id)
|
||||
state.caller = build_caller(
|
||||
scenario.id,
|
||||
use_pregenerated=scenario.tree.pregenerated,
|
||||
)
|
||||
elif event.exercise is Exercise.DDS:
|
||||
state.dds_scenarios = [item.model_copy(deep=True) for item in scenarios]
|
||||
prepare_card(state, state.dds_scenarios[0])
|
||||
prepare_queue(
|
||||
state,
|
||||
state.dds_scenarios,
|
||||
arrival_interval_seconds=event.dds_arrival_interval_seconds,
|
||||
max_waiting=event.dds_max_waiting,
|
||||
)
|
||||
state.started_at = state.dispatched_at
|
||||
else:
|
||||
state.started_at = now_utc()
|
||||
|
|
@ -155,13 +176,19 @@ async def _start(session_id: UUID, event, who=None) -> None:
|
|||
if models is not None:
|
||||
asyncio.create_task(prefetch(models, [scenario.first_line, *FILLERS.values()]))
|
||||
state.on_event("call.incoming")
|
||||
await hub.checkpoint(session_id)
|
||||
hub.start_ticker(session_id)
|
||||
if who is not None:
|
||||
# Запуск занятия меняет чужой результат — значит попадает в журнал
|
||||
# аудита (ТЗ, хранение не менее шести месяцев).
|
||||
asyncio.create_task(
|
||||
audit(who.login, who.role.value, "lesson.start", str(session_id),
|
||||
f"{scenario.id}, режим {event.mode.value}, курсант {event.trainee}")
|
||||
# Сохраняем до продолжения сценария, чтобы завершение процесса не
|
||||
# потеряло событие. ФИО курсанта в долгоживущий журнал не дублируем.
|
||||
await audit(
|
||||
who.login,
|
||||
who.role.value,
|
||||
"lesson.start",
|
||||
str(session_id),
|
||||
f"{scenario.id}, режим {event.mode.value}",
|
||||
)
|
||||
|
||||
if event.exercise is Exercise.CALL:
|
||||
|
|
@ -191,18 +218,22 @@ async def _stop(session_id: UUID) -> None:
|
|||
return
|
||||
state.ended_at = now_utc()
|
||||
state.end_reason = CallEndReason.INSTRUCTOR
|
||||
if state.voice is not None:
|
||||
await state.voice.close()
|
||||
hub.stop_ticker(session_id)
|
||||
hub.to_observers(session_id, SessionEnded(reason=CallEndReason.INSTRUCTOR))
|
||||
if state.exercise in {Exercise.DDS, Exercise.CARD}:
|
||||
from app.session.finish import finish
|
||||
from app.session.finish import finish
|
||||
|
||||
if state.exercise in {Exercise.DDS, Exercise.CARD}:
|
||||
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 or state.handoff_to_dds and state.dispatched_card is not None:
|
||||
hub.to_station(session_id, ScoreReady(session_id=session_id))
|
||||
else:
|
||||
hub.to_trainee(session_id, CallEnded(reason=CallEndReason.INSTRUCTOR))
|
||||
await finish(session_id, state)
|
||||
if hub.journal:
|
||||
await hub.journal.session_ended(session_id, state.ended_at, CallEndReason.INSTRUCTOR.value)
|
||||
|
||||
|
|
@ -236,6 +267,21 @@ async def control(ws: WebSocket, session_id: UUID) -> None:
|
|||
)
|
||||
continue
|
||||
|
||||
existing_state = hub.get(session_id)
|
||||
if event.type == "scenario.start":
|
||||
if existing_state is not None:
|
||||
hub.to_observers(session_id, ErrorEvent(
|
||||
code=ErrorKind.FORBIDDEN,
|
||||
message="Для нового занятия создайте новый номер сессии",
|
||||
))
|
||||
continue
|
||||
elif existing_state is None or existing_state.owner_login != who.login:
|
||||
hub.to_observers(session_id, ErrorEvent(
|
||||
code=ErrorKind.FORBIDDEN,
|
||||
message="Это занятие принадлежит другому преподавателю",
|
||||
))
|
||||
continue
|
||||
|
||||
match event.type:
|
||||
case "scenario.start":
|
||||
await _start(session_id, event, who)
|
||||
|
|
@ -315,7 +361,7 @@ async def control(ws: WebSocket, session_id: UUID) -> None:
|
|||
if result.needs_network:
|
||||
hub.to_observers(session_id, ErrorEvent(
|
||||
code=ErrorKind.DIRECTIVE_NEEDS_NETWORK,
|
||||
message="Свободный текст требует LLM: офлайн доступны только кнопки",
|
||||
message="Свободный текст требует локально запущенной модели; без неё доступны кнопки",
|
||||
))
|
||||
continue
|
||||
state.directives.append(event.directive)
|
||||
|
|
@ -338,5 +384,6 @@ async def control(ws: WebSocket, session_id: UUID) -> None:
|
|||
message=f"{event.type} ещё не реализовано",
|
||||
),
|
||||
)
|
||||
await hub.checkpoint(session_id)
|
||||
except WebSocketDisconnect:
|
||||
return
|
||||
|
|
|
|||
|
|
@ -10,23 +10,41 @@
|
|||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
||||
from pydantic import TypeAdapter, ValidationError
|
||||
|
||||
from app.domain.events import (
|
||||
CallEndReason, ErrorEvent, ErrorKind, Exercise, PhoneReport, ScoreReady,
|
||||
SessionEnded, StationState, StationToServer,
|
||||
)
|
||||
from app.domain.statuses import PRIMARY, PhoneReportRecord, ServiceStatus, StatusError, current
|
||||
from app.api.auth import principal_of
|
||||
from app.domain.events import (
|
||||
CallEndReason,
|
||||
ErrorEvent,
|
||||
ErrorKind,
|
||||
Exercise,
|
||||
PhoneLine,
|
||||
PhoneReport,
|
||||
ScoreReady,
|
||||
SessionEnded,
|
||||
StationState,
|
||||
StationToServer,
|
||||
)
|
||||
from app.domain.roles import Role
|
||||
from app.domain.statuses import (
|
||||
PRIMARY,
|
||||
SERVICE_STATUS_LABELS,
|
||||
PhoneCallPending,
|
||||
PhoneLineRecord,
|
||||
PhoneReportRecord,
|
||||
ServiceStatus,
|
||||
StatusError,
|
||||
current,
|
||||
)
|
||||
from app.scoring.grammar import assess
|
||||
from app.session.dds import deliver_due_cards
|
||||
from app.session.finish import finish, score_current_dds
|
||||
from app.session.hub import hub
|
||||
from app.session.state import now_utc
|
||||
from app.session.finish import finish
|
||||
from app.session.finish import score_current_dds
|
||||
from app.session.dds import prepare_card
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
|
|
@ -34,24 +52,85 @@ router = APIRouter()
|
|||
_adapter = TypeAdapter(StationToServer)
|
||||
|
||||
REPORT_PHASES = ("dispatched", "arrived", "working", "completed")
|
||||
REPORT_TEXT = {
|
||||
"dispatched": "Бригада выехала к месту происшествия.",
|
||||
"arrived": "Бригада прибыла на место происшествия.",
|
||||
"working": "Бригада приступила к проведению работ.",
|
||||
"completed": "Работы завершены, бригада освобождена.",
|
||||
REQUIRED_STATUS = {
|
||||
"dispatched": ServiceStatus.ACCEPTED,
|
||||
"arrived": ServiceStatus.RESPONDING,
|
||||
"working": ServiceStatus.ARRIVED,
|
||||
"completed": ServiceStatus.WORKING,
|
||||
}
|
||||
REPORT_FOR_STATUS = {
|
||||
ServiceStatus.RESPONDING: "dispatched",
|
||||
ServiceStatus.ARRIVED: "arrived",
|
||||
ServiceStatus.WORKING: "working",
|
||||
ServiceStatus.COMPLETED: "completed",
|
||||
STATUS_AT_OR_AFTER = {
|
||||
"dispatched": {ServiceStatus.ACCEPTED, ServiceStatus.RESPONDING,
|
||||
ServiceStatus.ARRIVED, ServiceStatus.WORKING},
|
||||
"arrived": {ServiceStatus.RESPONDING, ServiceStatus.ARRIVED, ServiceStatus.WORKING},
|
||||
"working": {ServiceStatus.ARRIVED, ServiceStatus.WORKING},
|
||||
"completed": {ServiceStatus.WORKING, ServiceStatus.COMPLETED},
|
||||
}
|
||||
|
||||
|
||||
def _error(session_id: UUID, message: str) -> None:
|
||||
hub.to_station(session_id, ErrorEvent(code=ErrorKind.UNSUPPORTED_EVENT, message=message))
|
||||
|
||||
|
||||
def _line(session_id: UUID, state, speaker: str, text: str) -> None:
|
||||
call = state.phone_pending
|
||||
if call is None:
|
||||
return
|
||||
line = PhoneLineRecord(service=call.service, crew=call.crew,
|
||||
speaker=speaker, text=text, at=now_utc())
|
||||
state.phone_lines.append(line)
|
||||
state.dds_log.append((f"phone.line.{speaker}", line.at, f"{call.crew}: {text}"))
|
||||
hub.to_station(session_id, PhoneLine(**line.model_dump()))
|
||||
|
||||
|
||||
def _address_matches(expected: str | None, supplied: str) -> bool:
|
||||
"""Не даём сообщить бригаде другой номер дома/другую улицу."""
|
||||
if not expected:
|
||||
return bool(supplied.strip())
|
||||
numbers = re.findall(r"\d+", expected)
|
||||
spoken_numbers = re.findall(r"\d+", supplied)
|
||||
words = re.findall(r"[а-яё]{4,}", expected.casefold())
|
||||
spoken_words = re.findall(r"[а-яё]{4,}", supplied.casefold())
|
||||
return (all(number in spoken_numbers for number in numbers)
|
||||
and any(word[:4] == spoken[:4] for word in words for spoken in spoken_words))
|
||||
|
||||
|
||||
def _incident_matches(state, supplied: str) -> bool:
|
||||
text = supplied.casefold()
|
||||
# Описание часто начинается с адреса: его нельзя считать совпадением
|
||||
# характера происшествия. Берём только название сценария и признаки ЕКП.
|
||||
source = " ".join((state.scenario_title, " ".join(state.kio.signs)))
|
||||
anchors = {word[:4] for word in re.findall(r"[а-яё]{5,}", source.casefold())}
|
||||
return len(supplied.strip()) >= 8 and any(anchor in text for anchor in anchors)
|
||||
|
||||
|
||||
def _has_purpose(text: str, stems: tuple[str, ...]) -> bool:
|
||||
normalized = text.casefold()
|
||||
return len(text.strip()) >= 8 and any(stem in normalized for stem in stems)
|
||||
|
||||
|
||||
def _report_text(phase: str, crew: str, address: str) -> str:
|
||||
match phase:
|
||||
case "dispatched":
|
||||
return f"{crew}: вызов по адресу {address} принят, выезжаем. О прибытии доложу."
|
||||
case "arrived":
|
||||
return f"{crew}: прибыли по адресу {address}. Уточняем обстановку на месте."
|
||||
case "working":
|
||||
return f"{crew}: обстановка уточнена, приступили к работам. Сообщим о завершении."
|
||||
case _:
|
||||
return f"{crew}: работы завершены. Дальнейшая помощь от нашей бригады не требуется."
|
||||
|
||||
|
||||
def _finish_phone_call(session_id: UUID, state) -> None:
|
||||
call = state.phone_pending
|
||||
assert call is not None
|
||||
text = _report_text(call.phase, call.crew, state.dispatched_card.address or "из карточки")
|
||||
_line(session_id, state, "crew", text)
|
||||
report = PhoneReportRecord(service=call.service, crew=call.crew,
|
||||
phase=call.phase, text=text, at=now_utc())
|
||||
state.phone_reports.append(report)
|
||||
state.dds_log.append(("phone.report", now_utc(), f"{call.crew}: {call.phase}"))
|
||||
state.phone_pending = None
|
||||
hub.to_station(session_id, PhoneReport(**report.model_dump()))
|
||||
|
||||
|
||||
async def _finish_dds(session_id: UUID, state) -> None:
|
||||
state.ended_at = now_utc()
|
||||
state.end_reason = CallEndReason.COMPLETE
|
||||
|
|
@ -75,22 +154,15 @@ async def _handle(session_id: UUID, state, event) -> None:
|
|||
# диспетчер один и выбирать службу не из чего.
|
||||
state.on_event("card.ack")
|
||||
state.dds_log.append(("card.ack", now_utc(), None))
|
||||
services = state.notified_services()
|
||||
services = state.managed_services()
|
||||
if services:
|
||||
try:
|
||||
state.set_service_status(services[0], ServiceStatus.ACCEPTED)
|
||||
except StatusError:
|
||||
pass # статус уже стоит: повторное нажатие ничего не меняет
|
||||
case "card.status":
|
||||
if event.service not in state.notified_services():
|
||||
_error(session_id, "Служба отсутствует в списке оповещения карточки")
|
||||
return
|
||||
phase = REPORT_FOR_STATUS.get(event.status)
|
||||
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
|
||||
):
|
||||
_error(session_id, f"Статус «{event.status.value}» требует доклада бригады")
|
||||
if event.service not in state.managed_services():
|
||||
_error(session_id, "Можно менять статусы только своей ДДС")
|
||||
return
|
||||
try:
|
||||
state.set_service_status(
|
||||
|
|
@ -116,33 +188,73 @@ async def _handle(session_id: UUID, state, event) -> None:
|
|||
):
|
||||
_error(session_id, "После первого доклада бригаду этой службы менять нельзя")
|
||||
return
|
||||
if state.phone_pending is not None:
|
||||
_error(session_id, "Завершите текущий разговор перед сменой бригады")
|
||||
return
|
||||
state.crew_selected = event.crew
|
||||
state.crew_assignments[service] = event.crew
|
||||
state.dds_log.append(("crew.select", now_utc(), event.crew))
|
||||
case "phone.dial":
|
||||
if state.phone_pending is not None:
|
||||
_error(session_id, "Разговор уже идёт: передайте сведения или завершите звонок")
|
||||
return
|
||||
crew = state.crew_selected
|
||||
service = state.crew_service(crew) if crew else None
|
||||
if service is None:
|
||||
_error(session_id, "Сначала выберите бригаду")
|
||||
return
|
||||
if current(state.status_log, service) not in {
|
||||
ServiceStatus.ACCEPTED, ServiceStatus.RESPONDING,
|
||||
ServiceStatus.ARRIVED, ServiceStatus.WORKING,
|
||||
}:
|
||||
_error(session_id, "Сначала примите карточку этой службы")
|
||||
return
|
||||
previous = [report for report in state.phone_reports if report.service == service]
|
||||
if len(previous) >= len(REPORT_PHASES):
|
||||
_error(session_id, "Все доклады этой бригады уже получены")
|
||||
return
|
||||
phase = REPORT_PHASES[len(previous)]
|
||||
report = PhoneReportRecord(
|
||||
service=service, crew=crew, phase=phase,
|
||||
text=REPORT_TEXT[phase], at=now_utc(),
|
||||
)
|
||||
state.phone_reports.append(report)
|
||||
required = REQUIRED_STATUS[phase]
|
||||
if current(state.status_log, service) not in STATUS_AT_OR_AFTER[phase]:
|
||||
_error(session_id, f"Перед звонком нужен статус «{SERVICE_STATUS_LABELS[required]}» этой службы")
|
||||
return
|
||||
state.phone_pending = PhoneCallPending(service=service, crew=crew, phase=phase)
|
||||
state.dds_log.append(("phone.dial", now_utc(), crew))
|
||||
hub.to_station(session_id, PhoneReport(**report.model_dump()))
|
||||
greeting = (f"{crew}, старший группы на связи. Назовите адрес, характер происшествия "
|
||||
"и что требуется от бригады."
|
||||
if phase == "dispatched" else
|
||||
f"{crew}, старший группы на связи. Слушаю ваш запрос по карточке.")
|
||||
_line(session_id, state, "crew", greeting)
|
||||
case "phone.brief":
|
||||
call = state.phone_pending
|
||||
if call is None or call.phase != "dispatched":
|
||||
_error(session_id, "Сначала соединитесь со старшим группы для передачи вызова")
|
||||
return
|
||||
if not _address_matches(state.dispatched_card.address, event.address):
|
||||
_error(session_id, "Проверьте адрес: улица и номер дома должны совпадать с карточкой")
|
||||
return
|
||||
if not _incident_matches(state, event.incident):
|
||||
_error(session_id, "Уточните характер происшествия по данным карточки")
|
||||
return
|
||||
if not _has_purpose(event.request, ("выезд", "выех", "направ", "прибыт",
|
||||
"реагир", "помощ", "подтверд", "долож")):
|
||||
_error(session_id, "Сформулируйте задачу: выезд, помощь или доклад бригады")
|
||||
return
|
||||
_line(session_id, state, "dispatcher", f"Адрес: {event.address.strip()}. "
|
||||
f"Происшествие: {event.incident.strip()}. {event.request.strip()}")
|
||||
_finish_phone_call(session_id, state)
|
||||
case "phone.check":
|
||||
call = state.phone_pending
|
||||
if call is None or call.phase == "dispatched":
|
||||
_error(session_id, "Сначала передайте вызов, затем запросите обстановку")
|
||||
return
|
||||
if not _has_purpose(event.text, ("обстанов", "статус", "прибыл", "доех",
|
||||
"выех", "работ", "заверш", "мест",
|
||||
"ход", "сообщ", "долож", "уточн")):
|
||||
_error(session_id, "Спросите обстановку, прибытие или ход работ по карточке")
|
||||
return
|
||||
_line(session_id, state, "dispatcher", event.text.strip())
|
||||
_finish_phone_call(session_id, state)
|
||||
case "phone.hangup":
|
||||
if state.phone_pending is None:
|
||||
_error(session_id, "Нет активного разговора")
|
||||
return
|
||||
state.dds_log.append(("phone.hangup", now_utc(), state.phone_pending.crew))
|
||||
state.phone_pending = None
|
||||
case "card.reply":
|
||||
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
|
||||
|
|
@ -150,7 +262,18 @@ async def _handle(session_id: UUID, state, event) -> None:
|
|||
_error(session_id, "Ответ относится не к текущей карточке")
|
||||
return
|
||||
state.reply_text = event.text
|
||||
state.reply_grammar = await assess(event.text)
|
||||
state.reply_log.append((now_utc(), event.text))
|
||||
case "card.open":
|
||||
if state.exercise is not Exercise.DDS or not state.activate_dds_card(event.card_id):
|
||||
_error(session_id, "Карточка отсутствует в текущей очереди")
|
||||
return
|
||||
hub.to_station(session_id, state.card_received_event())
|
||||
# CardReceived carries the contents, while StationState carries
|
||||
# the status journal and current queue. Send both on every switch
|
||||
# so the newly opened card cannot briefly inherit the previous
|
||||
# card's status snapshot until the next periodic tick.
|
||||
hub.to_station(session_id, StationState(snapshot=state.station_snapshot()))
|
||||
case "card.next":
|
||||
if state.exercise is not Exercise.DDS or not state.dispatched_card or (
|
||||
event.card_id != state.dispatched_card.card_id
|
||||
|
|
@ -161,11 +284,32 @@ async def _handle(session_id: UUID, state, event) -> None:
|
|||
_error(session_id, "Эта карточка уже завершена")
|
||||
return
|
||||
state.dds_completed.append(score_current_dds(state))
|
||||
if state.dds_card_index + 1 < len(state.dds_scenarios):
|
||||
state.dds_card_index += 1
|
||||
prepare_card(state, state.dds_scenarios[state.dds_card_index])
|
||||
completed_index = state.dds_card_index
|
||||
state.dds_live_cards = [
|
||||
item for item in state.dds_live_cards if item.card_id != event.card_id
|
||||
]
|
||||
remaining = sorted(state.dds_live_cards, key=lambda item: item.original_index)
|
||||
if remaining:
|
||||
following = next(
|
||||
(item for item in remaining if item.original_index > completed_index),
|
||||
remaining[0],
|
||||
)
|
||||
state.activate_dds_card(following.card_id, capture=False)
|
||||
hub.to_station(session_id, state.card_received_event())
|
||||
else:
|
||||
# Keep the lesson alive if selected cards have not arrived yet.
|
||||
# The next delivery may become the active card immediately or
|
||||
# after its configured interval; no completed card is reused.
|
||||
state.dds_active_card_id = None
|
||||
state.dispatched_card = None
|
||||
state.dispatched_at = None
|
||||
state.dds_card_index = completed_index
|
||||
active_before_delivery = state.dds_active_card_id
|
||||
deliver_due_cards(state)
|
||||
if state.dds_active_card_id and state.dds_active_card_id != active_before_delivery:
|
||||
hub.to_station(session_id, state.card_received_event())
|
||||
hub.to_station(session_id, StationState(snapshot=state.station_snapshot()))
|
||||
if not state.dds_live_cards and len(state.dds_completed) >= len(state.dds_scenarios):
|
||||
await _finish_dds(session_id, state)
|
||||
case "station.finish":
|
||||
if state.exercise is not Exercise.DDS and not state.handoff_to_dds:
|
||||
|
|
@ -173,9 +317,11 @@ async def _handle(session_id: UUID, state, event) -> None:
|
|||
return
|
||||
await _finish_dds(session_id, state)
|
||||
case "card.bounce":
|
||||
# Карточка вернулась: в разборе это E6 с конкретной причиной.
|
||||
state.bounced_fields = list(event.missing_fields)
|
||||
state.dds_log.append(("card.bounce", now_utc(), event.comment))
|
||||
_error(
|
||||
session_id,
|
||||
"ДДС не проверяет заполнение карточки: замечания передаёт служба контроля 112",
|
||||
)
|
||||
return
|
||||
case "zone.decision":
|
||||
state.on_event("zone.decision")
|
||||
state.dds_log.append(("zone.decision", now_utc(), "в зоне" if event.in_zone else "не в зоне"))
|
||||
|
|
@ -186,6 +332,8 @@ async def _handle(session_id: UUID, state, event) -> None:
|
|||
state.on_event("crew.arrived")
|
||||
state.kio = state.kio.model_copy(update={"arrival_at": event.at})
|
||||
state.dds_log.append(("crew.arrived", now_utc(), None))
|
||||
state.capture_active_dds()
|
||||
await hub.checkpoint(session_id)
|
||||
hub.to_station(session_id, StationState(snapshot=state.station_snapshot()))
|
||||
hub.to_observers(session_id, state.snapshot())
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue