Merge branch 'feat/report-reaction'
lct-37: норматив реакции ДДС на доклад бригады
This commit is contained in:
commit
b66cf14e3f
15 changed files with 475 additions and 20 deletions
|
|
@ -53,6 +53,8 @@ class LessonCriteria(BaseModel):
|
|||
decision_time_limit_seconds: int = Field(default=30, ge=5, le=300)
|
||||
card_fill_time_limit_seconds: int = Field(default=180, ge=30, le=1800)
|
||||
dds_card_work_time_limit_seconds: int = Field(default=180, ge=30, le=1800)
|
||||
#: Сколько секунд после доклада бригады даётся на соответствующий статус.
|
||||
dds_report_reaction_limit_seconds: int = Field(default=45, ge=5, le=600)
|
||||
allowed_errors: int = Field(default=0, ge=0, le=50)
|
||||
require_correct_grammar: bool = True
|
||||
score_weights: dict[str, float] = Field(default_factory=dict)
|
||||
|
|
|
|||
|
|
@ -11,11 +11,14 @@
|
|||
привязывает статус к звонку или SIP: сведения можно получить по любому рабочему каналу.
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
from app.domain.statuses import (
|
||||
COMMENT_REQUIRED,
|
||||
PRIMARY,
|
||||
REFUSAL_COMMENT_REQUIRED,
|
||||
SERVICE_STATUS_LABELS,
|
||||
PhoneReportRecord,
|
||||
ServiceStatus,
|
||||
StatusEntry,
|
||||
current,
|
||||
|
|
@ -23,10 +26,102 @@ from app.domain.statuses import (
|
|||
from app.domain.taxonomy import Competency, ErrorCode, Finding, FindingSource
|
||||
from app.domain.events import Metric
|
||||
from app.domain.timers import GOST_REF
|
||||
from app.scoring.timing import TimeNorm, time_metric
|
||||
|
||||
MEMO_REF = "памятка «Работа на АРМ-112», раздел «Статусы реагирования»"
|
||||
|
||||
#: Статусы, означающие, что реагирование действительно шло.
|
||||
PROGRESS = (ServiceStatus.RESPONDING, ServiceStatus.ARRIVED, ServiceStatus.WORKING)
|
||||
|
||||
#: Статус, который диспетчер отмечает по докладу бригады этой фазы.
|
||||
REPORT_STATUS = {
|
||||
"dispatched": ServiceStatus.RESPONDING,
|
||||
"arrived": ServiceStatus.ARRIVED,
|
||||
"working": ServiceStatus.WORKING,
|
||||
"completed": ServiceStatus.COMPLETED,
|
||||
}
|
||||
REPORT_LABELS = {
|
||||
"dispatched": "о выезде",
|
||||
"arrived": "о прибытии",
|
||||
"working": "о начале работ",
|
||||
"completed": "о завершении работ",
|
||||
}
|
||||
#: Лимит реакции на доклад по умолчанию; занятие задаёт свой в критериях.
|
||||
REPORT_REACTION_MS = 45_000
|
||||
#: Реакция на доклад — норматив времени, как отработка карточки, но отметка
|
||||
#: D6 из памятки: опоздавший статус — тот же неполный ход работ.
|
||||
DDS_REPORT_REACTION = TimeNorm(
|
||||
key="dds_report_reaction",
|
||||
title="реакция на доклад бригады",
|
||||
summary="статус по докладу бригады отмечен с нарушением норматива",
|
||||
action="отметить статус по докладу",
|
||||
unmeasured="не отмечен",
|
||||
incomplete="не отмечен",
|
||||
code=ErrorCode.D6,
|
||||
source=FindingSource.DISPATCHER,
|
||||
ref=MEMO_REF,
|
||||
)
|
||||
#: Терминальный отказ: работ не было, поэтому неотмеченный по докладу статус
|
||||
#: не штрафуется ни отметкой, ни метрикой.
|
||||
TERMINAL_REFUSAL = {ServiceStatus.DECLINED, ServiceStatus.REFUSED}
|
||||
|
||||
|
||||
def report_reactions(
|
||||
marks: list[StatusEntry], reports: list[PhoneReportRecord],
|
||||
) -> list[tuple[PhoneReportRecord, int | None]]:
|
||||
"""Задержка статуса после каждого доклада бригады, мс; None — статус не отмечен.
|
||||
|
||||
Отсчёт — от серверного времени доклада. Статус, отмеченный раньше доклада,
|
||||
задержки не имеет: диспетчер узнал о ходе работ по другому каналу.
|
||||
"""
|
||||
result: list[tuple[PhoneReportRecord, int | None]] = []
|
||||
for report in reports:
|
||||
status = REPORT_STATUS.get(report.phase)
|
||||
if status is None:
|
||||
continue
|
||||
times = [mark.at for mark in marks if mark.status is status]
|
||||
if any(at <= report.at for at in times):
|
||||
result.append((report, 0))
|
||||
continue
|
||||
after = min(times, default=None)
|
||||
result.append((
|
||||
report,
|
||||
int((after - report.at).total_seconds() * 1000) if after is not None else None,
|
||||
))
|
||||
return result
|
||||
|
||||
|
||||
def report_reaction(
|
||||
service: str, marks: list[StatusEntry], reports: list[PhoneReportRecord], limit_ms: int,
|
||||
) -> tuple[Metric, Finding | None] | None:
|
||||
"""Метрика и отметка D6 по самой поздней реакции службы на доклады бригады.
|
||||
|
||||
Одна функция для отметок и для балла: иначе метрика провалится там,
|
||||
где отметки нет. None — реагировать было не на что.
|
||||
"""
|
||||
refused = current(marks, service) in TERMINAL_REFUSAL
|
||||
reactions = [(report, delay) for report, delay in report_reactions(marks, reports)
|
||||
if delay is not None or not refused]
|
||||
if not reactions:
|
||||
return None
|
||||
report, delay = max(reactions, key=lambda item: math.inf if item[1] is None else item[1])
|
||||
metric, finding = time_metric(DDS_REPORT_REACTION, delay, limit_ms, completed=True)
|
||||
label = SERVICE_STATUS_LABELS[REPORT_STATUS[report.phase]]
|
||||
detail = "отмечен не позже доклада" if delay == 0 else metric.fact
|
||||
fact = (f"статус «{label}» по докладу бригады «{report.crew}» "
|
||||
f"{REPORT_LABELS[report.phase]}: {detail}")
|
||||
if len(reactions) > 1:
|
||||
late = sum(item is None or item > limit_ms for _, item in reactions)
|
||||
fact += f"; с нарушением {late} из {len(reactions)} докладов"
|
||||
metric = metric.model_copy(update={
|
||||
"title": f"{service}: {metric.title}", "fact": fact, "service": service,
|
||||
})
|
||||
if finding is not None:
|
||||
finding = finding.model_copy(update={
|
||||
"summary": f"{service}: {finding.summary}", "fact": fact, "service": service,
|
||||
})
|
||||
return metric, finding
|
||||
|
||||
|
||||
def _finding(service: str, code: ErrorCode, summary: str, fact: str,
|
||||
norm: str | None = None) -> Finding:
|
||||
|
|
@ -37,7 +132,7 @@ def _finding(service: str, code: ErrorCode, summary: str, fact: str,
|
|||
summary=summary,
|
||||
fact=fact,
|
||||
norm=norm,
|
||||
ref="памятка «Работа на АРМ-112», раздел «Статусы реагирования»",
|
||||
ref=MEMO_REF,
|
||||
competency=(
|
||||
Competency.COMMUNICATION if code is ErrorCode.D5 else Competency.CARD
|
||||
),
|
||||
|
|
@ -93,6 +188,8 @@ def evaluate_dispatcher(
|
|||
reply_text: str = "",
|
||||
expected_decision: str = "accept",
|
||||
expected_decision_reason: str | None = None,
|
||||
phone_reports: list[PhoneReportRecord] | None = None,
|
||||
report_reaction_ms: int = REPORT_REACTION_MS,
|
||||
) -> list[Finding]:
|
||||
"""Отметки по работе диспетчера. Пустой список — работа без нарушений.
|
||||
|
||||
|
|
@ -264,15 +361,18 @@ def evaluate_dispatcher(
|
|||
# D6 — ход работ неполон к моменту закрытия карточки/занятия. В памятке
|
||||
# это приводит к повторным звонкам и скрывает от других служб факт реакции.
|
||||
# REFUSED — отдельный допустимый терминальный статус с обязательной причиной.
|
||||
reports = [report for report in phone_reports or () if report.service == service]
|
||||
missing_progress = [status for status in PROGRESS if status not in {m.status for m in marks}]
|
||||
if (latest not in {ServiceStatus.DECLINED, ServiceStatus.REFUSED}
|
||||
and (missing_progress or latest is not ServiceStatus.COMPLETED)):
|
||||
missing = ", ".join(SERVICE_STATUS_LABELS[status] for status in missing_progress)
|
||||
reported_done = any(report.phase == "completed" for report in reports)
|
||||
findings.append(
|
||||
_finding(
|
||||
service, ErrorCode.D6,
|
||||
f"{service}: ход реагирования не доведён до конца",
|
||||
fact=(f"не отмечены: {missing}" if missing else "карточка не закрыта"),
|
||||
fact=(f"не отмечены: {missing}" if missing else "карточка не закрыта")
|
||||
+ ("; бригада доложила о завершении работ" if reported_done else ""),
|
||||
norm=(
|
||||
"отметить по факту начало реагирования, прибытие, проведение работ "
|
||||
"и завершение; если работы не проводились — оформить отказ с причиной"
|
||||
|
|
@ -280,6 +380,11 @@ def evaluate_dispatcher(
|
|||
)
|
||||
)
|
||||
|
||||
# D6 — статус по докладу бригады отмечен позже лимита или не отмечен.
|
||||
reaction = report_reaction(service, marks, reports, report_reaction_ms)
|
||||
if reaction is not None and reaction[1] is not None:
|
||||
findings.append(reaction[1])
|
||||
|
||||
return findings
|
||||
|
||||
|
||||
|
|
@ -290,6 +395,7 @@ def dispatcher_metrics(
|
|||
expected_decision_reason: str | None = None,
|
||||
*,
|
||||
services: list[str] | None = None,
|
||||
report_reaction_ms: int = REPORT_REACTION_MS,
|
||||
) -> list[Metric]:
|
||||
"""Числовая часть оценки ДДС; каждый проверяемый шаг имеет факт и норму.
|
||||
|
||||
|
|
@ -319,6 +425,12 @@ def dispatcher_metrics(
|
|||
f"≤ {deadline_ms // 1000} с")
|
||||
if primary is None:
|
||||
continue
|
||||
# Метрика есть только там, где бригада докладывала: без докладов
|
||||
# реагировать не на что, и отсутствие звонков не штраф.
|
||||
reports = [report for report in getattr(state, "phone_reports", ()) if report.service == service]
|
||||
reaction = report_reaction(service, marks, reports, report_reaction_ms)
|
||||
if reaction is not None:
|
||||
metrics.append(reaction[0])
|
||||
expected_status = (ServiceStatus.ACCEPTED if expected_decision == "accept"
|
||||
else ServiceStatus.DECLINED)
|
||||
expected_label = "Принята" if expected_decision == "accept" else "Не принята"
|
||||
|
|
|
|||
|
|
@ -54,6 +54,8 @@ def to_csv(report: SessionReport) -> bytes:
|
|||
row("Занятие", "", "Режим", report.mode.value)
|
||||
row("Занятие", "", "Попытка", report.attempt)
|
||||
row("Критерии", "", "Лимит решения ДДС, с", report.criteria.decision_time_limit_seconds)
|
||||
row("Критерии", "", "Лимит реакции на доклад бригады, с",
|
||||
report.criteria.dds_report_reaction_limit_seconds)
|
||||
row("Критерии", "", "Допустимо ошибок", report.criteria.allowed_errors)
|
||||
row("Критерии", "", "Грамматика обязательна", "да" if report.criteria.require_correct_grammar else "нет")
|
||||
row("Критерии", "", "Переопределения весов", report.criteria.score_weights or "стандартные")
|
||||
|
|
@ -170,6 +172,7 @@ def to_pdf(report: SessionReport) -> bytes:
|
|||
("Режим", report.mode.value),
|
||||
("Попытка", report.attempt),
|
||||
("Лимит решения ДДС", f"{report.criteria.decision_time_limit_seconds} с"),
|
||||
("Лимит реакции на доклад бригады", f"{report.criteria.dds_report_reaction_limit_seconds} с"),
|
||||
("Допустимо ошибок", report.criteria.allowed_errors),
|
||||
("Грамматика обязательна", "да" if report.criteria.require_correct_grammar else "нет"),
|
||||
("Переопределения весов", report.criteria.score_weights or "стандартные"),
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ METRIC_MAP: dict[str, tuple[ErrorCode, Competency]] = {
|
|||
"dds_progress": (ErrorCode.D6, Competency.CARD),
|
||||
"dds_completion": (ErrorCode.D6, Competency.CARD),
|
||||
"dds_reply": (ErrorCode.D5, Competency.COMMUNICATION),
|
||||
"dds_report_reaction": (ErrorCode.D6, Competency.NORMS),
|
||||
"dds_grammar": (ErrorCode.D5, Competency.COMMUNICATION),
|
||||
"description_grammar": (ErrorCode.E4, Competency.COMMUNICATION),
|
||||
}
|
||||
|
|
@ -64,4 +65,5 @@ METRIC_WEIGHTS: dict[str, float] = {
|
|||
"description_grammar": 1.0,
|
||||
"card_fill_time": 1.5,
|
||||
"dds_work_time": 1.5,
|
||||
"dds_report_reaction": 1.5,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,8 +23,8 @@ def time_credit(elapsed_ms: int | None, limit_ms: int) -> float:
|
|||
|
||||
@dataclass(frozen=True)
|
||||
class TimeNorm:
|
||||
"""Формулировки норматива времени: карточка 112 и карточка ДДС различаются
|
||||
только словами, расчёт и отметка E3 у них общие."""
|
||||
"""Формулировки норматива времени: нормативы различаются словами и кодом
|
||||
отметки, расчёт вклада и формат факта у них общие."""
|
||||
|
||||
key: str
|
||||
title: str
|
||||
|
|
@ -32,6 +32,10 @@ class TimeNorm:
|
|||
action: str
|
||||
unmeasured: str
|
||||
incomplete: str
|
||||
code: ErrorCode = ErrorCode.E3
|
||||
source: FindingSource = FindingSource.TIMERS
|
||||
competency: Competency = Competency.NORMS
|
||||
ref: str = TIME_REF
|
||||
|
||||
|
||||
CARD_FILL_TIME = TimeNorm(
|
||||
|
|
@ -55,7 +59,7 @@ DDS_WORK_TIME = TimeNorm(
|
|||
def time_metric(
|
||||
norm: TimeNorm, elapsed_ms: int | None, limit_ms: int, *, completed: bool
|
||||
) -> tuple[Metric, Finding | None]:
|
||||
"""Метрика норматива и отметка E3, если он не выполнен.
|
||||
"""Метрика норматива и отметка (по умолчанию E3), если он не выполнен.
|
||||
|
||||
Незавершённая работа не получает временного вклада: быстрое, но брошенное
|
||||
заполнение не должно выглядеть скоростью.
|
||||
|
|
@ -64,13 +68,20 @@ def time_metric(
|
|||
fact = norm.unmeasured
|
||||
else:
|
||||
delta_ms = elapsed_ms - limit_ms
|
||||
# Превышение до полусекунды при округлении до целых читалось бы
|
||||
# как «45 с (+0 с)» при нормативе 45 с — тогда нужна десятая доля.
|
||||
precise = 0 < delta_ms <= 500
|
||||
|
||||
def seconds(ms: int) -> str:
|
||||
return f"{ms / 1000:.1f}" if precise else f"{round(ms / 1000)}"
|
||||
|
||||
if delta_ms > 0:
|
||||
deviation = f"+{round(delta_ms / 1000)} с сверх норматива"
|
||||
deviation = f"+{seconds(delta_ms)} с сверх норматива"
|
||||
elif delta_ms < 0:
|
||||
deviation = f"на {round(abs(delta_ms) / 1000)} с быстрее норматива"
|
||||
else:
|
||||
deviation = "точно в норматив"
|
||||
fact = f"{round(elapsed_ms / 1000)} с ({deviation})"
|
||||
fact = f"{seconds(elapsed_ms)} с ({deviation})"
|
||||
if not completed:
|
||||
fact = f"{norm.incomplete}; {fact}"
|
||||
norm_text = f"{norm.action} за {round(limit_ms / 1000)} с"
|
||||
|
|
@ -80,7 +91,7 @@ def time_metric(
|
|||
title=norm.title,
|
||||
fact=fact,
|
||||
norm=norm_text,
|
||||
ref=TIME_REF,
|
||||
ref=norm.ref,
|
||||
passed=passed,
|
||||
weight=METRIC_WEIGHTS[norm.key],
|
||||
credit=time_credit(elapsed_ms, limit_ms) if completed else 0.0,
|
||||
|
|
@ -88,12 +99,12 @@ def time_metric(
|
|||
if passed:
|
||||
return metric, None
|
||||
return metric, Finding(
|
||||
code=ErrorCode.E3,
|
||||
source=FindingSource.TIMERS,
|
||||
code=norm.code,
|
||||
source=norm.source,
|
||||
summary=norm.summary,
|
||||
fact=fact,
|
||||
norm=norm_text,
|
||||
ref=TIME_REF,
|
||||
competency=Competency.NORMS,
|
||||
ref=norm.ref,
|
||||
competency=norm.competency,
|
||||
metric_key=norm.key,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -48,6 +48,7 @@ def score_dds_card(state, card: DdsLiveCard) -> DdsCardRecord:
|
|||
services = state.card_services(card)
|
||||
decision_limit_ms = card.timers.limits[TimerCode.DDS_ACK]
|
||||
dds_decision = card.scenario.dds_decision
|
||||
reaction_ms = state.criteria.dds_report_reaction_limit_seconds * 1000
|
||||
findings = evaluate_dispatcher(
|
||||
entries=card.status_log,
|
||||
services=services,
|
||||
|
|
@ -57,10 +58,12 @@ def score_dds_card(state, card: DdsLiveCard) -> DdsCardRecord:
|
|||
reply_text=card.reply_text,
|
||||
expected_decision=dds_decision.expected,
|
||||
expected_decision_reason=dds_decision.reason,
|
||||
phone_reports=card.phone_reports,
|
||||
report_reaction_ms=reaction_ms,
|
||||
)
|
||||
metrics = dispatcher_metrics(
|
||||
card, decision_limit_ms, dds_decision.expected, dds_decision.reason,
|
||||
services=services,
|
||||
services=services, report_reaction_ms=reaction_ms,
|
||||
)
|
||||
weighted = GostResult(metrics=metrics, findings=findings)
|
||||
work_limit_ms = card.timers.limits[TimerCode.DDS_WORK]
|
||||
|
|
|
|||
|
|
@ -219,6 +219,7 @@ async def score_session(
|
|||
if live_card is not None:
|
||||
decision_limit_ms = live_card.timers.limits[TimerCode.DDS_ACK]
|
||||
services = list(snapshot.call_card_services)
|
||||
reaction_ms = snapshot.criteria.dds_report_reaction_limit_seconds * 1000
|
||||
result.findings.extend(evaluate_dispatcher(
|
||||
entries=live_card.status_log,
|
||||
services=services,
|
||||
|
|
@ -228,10 +229,12 @@ async def score_session(
|
|||
reply_text=live_card.reply_text,
|
||||
expected_decision=scenario.dds_decision.expected,
|
||||
expected_decision_reason=scenario.dds_decision.reason,
|
||||
phone_reports=live_card.phone_reports,
|
||||
report_reaction_ms=reaction_ms,
|
||||
))
|
||||
result.metrics.extend(dispatcher_metrics(
|
||||
live_card, decision_limit_ms, scenario.dds_decision.expected,
|
||||
scenario.dds_decision.reason, services=services,
|
||||
scenario.dds_decision.reason, services=services, report_reaction_ms=reaction_ms,
|
||||
))
|
||||
# Карточки ДДС уже взвешены каждая своим сценарием плюс настройкой
|
||||
# занятия. Веса первого сценария поверх них испортили бы остальные.
|
||||
|
|
|
|||
Loading…
Reference in a new issue