new reporter module

This commit is contained in:
timur 2026-08-13 22:33:49 +05:00
parent b3f718a49e
commit cf25cd50f0
21 changed files with 445 additions and 5031 deletions

View File

@ -207,13 +207,33 @@ For systemd installations, use `voice-dashboard.service`. The default listener
is intentionally local-only. Put an authenticated HTTPS reverse proxy in front
of it before allowing access from other hosts.
### Daily DOCX report
At 08:00 local server time, `voice-reporter.timer` starts the one-shot
`voice-reporter.service`. It builds a report for the previous local calendar
day from `voice_categories` and `call_records`. The document follows the
management structure of `samples/report_sample2.docx` and is saved by default
as:
```text
/var/lib/voice-pipeline/reporter/YYYY-MM-DD/report.docx
```
Run `voice-pipeline reporter` to generate the previous day's report manually.
The output root can be overridden in `/etc/voice-pipeline/config.toml`:
```toml
[reporter]
output_root = "/var/lib/voice-pipeline/reporter"
```
`reload` supports four modes:
- `--list` shows matching calls without changing anything.
- `--reanalyze` resets selected calls back to `spooled` so analyzer can run again.
- `--recollect` deletes the selected calls from DB and spool so the collector can fetch them again.
- `--repair` scans for incomplete analyzer/reporter outputs and repairs them in one pass.
- `--repair --from-date YYYY-MM-DD` force-regenerates report_detail.html files and daily summary reports from the specified UTC date onward.
- `--repair` scans for incomplete analyzer outputs and repairs them.
- `--repair --from-date YYYY-MM-DD` also regenerates daily DOCX reports from the specified date onward.
## Collector behavior

View File

@ -253,8 +253,8 @@ device_preference = "auto"
# Reporter
# ---------------------------------------------------------------------------
[reporter]
# Days covered by each batch summary report.
summary_window_days = 1
# By default reports are saved next to spool_root: ../reporter/YYYY-MM-DD/report.docx
# output_root = "/var/lib/voice-pipeline/reporter"
# ---------------------------------------------------------------------------

View File

@ -84,7 +84,6 @@ where = ["src"]
include = ["voice_pipeline*", "collector*", "analyzer*", "reporter*", "importer*", "voice_category*", "web_dashboard*", "core*"]
[tool.setuptools.package-data]
reporter = ["templates/*.j2"]
web_dashboard = ["templates/*.j2", "static/*.css"]
[tool.ruff]

BIN
samples/report_sample2.docx Normal file

Binary file not shown.

View File

@ -294,7 +294,7 @@ class AnalyzerConfig(BaseModel):
class ReporterConfig(BaseModel):
summary_window_days: int = 1
output_root: Path | None = None
class ImporterConfig(BaseModel):

File diff suppressed because it is too large Load Diff

View File

@ -1,92 +0,0 @@
from __future__ import annotations
import json
from datetime import UTC, datetime
from typing import Any, cast
from sqlmodel import select
from core.db import get_session
from core.models import CallRecord, ReportSnapshot
from reporter.analytics import build_detail_context
def _ensure_utc(dt: datetime) -> datetime:
if dt.tzinfo is None:
return dt.replace(tzinfo=UTC)
return dt.astimezone(UTC)
def list_calls(
date_from: datetime | None = None,
date_to: datetime | None = None,
status: str | None = None,
) -> list[dict[str, Any]]:
with get_session() as session:
query = select(CallRecord)
if date_from is not None:
query = query.where(CallRecord.fetched_at >= _ensure_utc(date_from))
if date_to is not None:
query = query.where(CallRecord.fetched_at < _ensure_utc(date_to))
if status is not None:
query = query.where(CallRecord.status == status)
records = list(
session.exec(query.order_by(cast(Any, CallRecord.fetched_at))).all()
)
return [
{
"uniqueid": record.uniqueid,
"source": record.source,
"direction": record.direction,
"status": record.status,
"reporter_status": record.reporter_status,
"importer_status": record.importer_status,
"caller_phone": record.caller_phone,
"entity_type": record.entity_type,
"entity_id": record.entity_id,
"user_id": record.user_id,
}
for record in records
]
def get_call_detail(uniqueid: str) -> dict[str, Any] | None:
with get_session() as session:
record = session.exec(
select(CallRecord).where(CallRecord.uniqueid == uniqueid)
).first()
if record is None:
return None
return build_detail_context(record)
def get_report_snapshot(
report_type: str,
date_from: datetime,
date_to: datetime,
) -> dict[str, Any] | None:
with get_session() as session:
snapshot = session.exec(
select(ReportSnapshot)
.where(ReportSnapshot.report_type == report_type)
.where(ReportSnapshot.period_start == _ensure_utc(date_from))
.where(ReportSnapshot.period_end == _ensure_utc(date_to))
).first()
if snapshot is None:
return None
try:
payload: Any = json.loads(snapshot.payload_json)
except (TypeError, json.JSONDecodeError):
payload = snapshot.payload_json
return {
"report_type": snapshot.report_type,
"period_start": snapshot.period_start,
"period_end": snapshot.period_end,
"generated_at": snapshot.generated_at,
"output_path": snapshot.output_path,
"status": snapshot.status,
"call_count": snapshot.call_count,
"payload": payload,
"error": snapshot.error,
}

95
src/reporter/docx.py Normal file
View File

@ -0,0 +1,95 @@
# ruff: noqa: E501
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from xml.sax.saxutils import escape
from zipfile import ZIP_DEFLATED, ZipFile
@dataclass
class Document:
blocks: list[str] = field(default_factory=list)
def title(self, text: str) -> None:
self.blocks.append(_paragraph(text, style="Title"))
def heading(self, text: str, level: int = 1) -> None:
self.blocks.append(_paragraph(text, style=f"Heading{min(3, max(1, level))}"))
def paragraph(self, text: str) -> None:
self.blocks.append(_paragraph(text))
def table(self, headers: list[str], rows: list[list[object]]) -> None:
all_rows = [headers, *[[str(value) for value in row] for row in rows]]
columns = max(1, len(headers))
grid = "".join('<w:gridCol w:w="2400"/>' for _ in range(columns))
xml_rows = []
for row_index, row in enumerate(all_rows):
cells = []
for value in row:
fill = '<w:shd w:fill="D9EAF0"/>' if row_index == 0 else ""
bold = "<w:b/>" if row_index == 0 else ""
cells.append(
f'<w:tc><w:tcPr>{fill}</w:tcPr><w:p><w:r><w:rPr>{bold}</w:rPr>'
f'<w:t xml:space="preserve">{escape(str(value))}</w:t></w:r></w:p></w:tc>'
)
xml_rows.append(f"<w:tr>{''.join(cells)}</w:tr>")
self.blocks.append(
'<w:tbl><w:tblPr><w:tblBorders>'
'<w:top w:val="single" w:sz="4" w:color="B7C9D3"/>'
'<w:left w:val="single" w:sz="4" w:color="B7C9D3"/>'
'<w:bottom w:val="single" w:sz="4" w:color="B7C9D3"/>'
'<w:right w:val="single" w:sz="4" w:color="B7C9D3"/>'
'<w:insideH w:val="single" w:sz="4" w:color="D9E2E7"/>'
'<w:insideV w:val="single" w:sz="4" w:color="D9E2E7"/>'
f"</w:tblBorders></w:tblPr><w:tblGrid>{grid}</w:tblGrid>{''.join(xml_rows)}</w:tbl>"
)
def save(self, path: Path) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
document_xml = _DOCUMENT.format(body="".join(self.blocks))
with ZipFile(path, "w", ZIP_DEFLATED) as archive:
archive.writestr("[Content_Types].xml", _CONTENT_TYPES)
archive.writestr("_rels/.rels", _ROOT_RELS)
archive.writestr("word/document.xml", document_xml)
archive.writestr("word/styles.xml", _STYLES)
archive.writestr("word/_rels/document.xml.rels", _DOCUMENT_RELS)
return path
def _paragraph(text: str, style: str | None = None) -> str:
properties = f'<w:pPr><w:pStyle w:val="{style}"/></w:pPr>' if style else ""
return (
f'<w:p>{properties}<w:r><w:t xml:space="preserve">'
f"{escape(text)}</w:t></w:r></w:p>"
)
_CONTENT_TYPES = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="xml" ContentType="application/xml"/>
<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>
</Types>"""
_ROOT_RELS = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
</Relationships>"""
_DOCUMENT_RELS = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
</Relationships>"""
_DOCUMENT = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1134" w:right="850" w:bottom="1134" w:left="850"/></w:sectPr></w:body></w:document>"""
_STYLES = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Arial" w:hAnsi="Arial"/><w:sz w:val="20"/></w:rPr></w:rPrDefault></w:docDefaults>
<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>
<w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:basedOn w:val="Normal"/><w:rPr><w:b/><w:color w:val="173B4D"/><w:sz w:val="34"/></w:rPr></w:style>
<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:basedOn w:val="Normal"/><w:rPr><w:b/><w:color w:val="176B75"/><w:sz w:val="28"/></w:rPr></w:style>
<w:style w:type="paragraph" w:styleId="Heading2"><w:name w:val="heading 2"/><w:basedOn w:val="Normal"/><w:rPr><w:b/><w:color w:val="245B68"/><w:sz w:val="24"/></w:rPr></w:style>
<w:style w:type="paragraph" w:styleId="Heading3"><w:name w:val="heading 3"/><w:basedOn w:val="Normal"/><w:rPr><w:b/><w:sz w:val="22"/></w:rPr></w:style>
</w:styles>"""

View File

@ -1,301 +1,30 @@
from __future__ import annotations
"""reporter.main — Process 3 entry point.
Long-running systemd service. Polls the DB for calls with status=analyzed,
generates per-call HTML reports under reports_root, and at the end of each
UTC day generates a batch summary report.
"""
import time
from datetime import UTC, datetime
from typing import Any, cast
from sqlmodel import select
from __future__ import annotations
from datetime import date, datetime, timedelta
from core.config import load_config
from core.db import get_session, init_db
from core.db import init_db
from core.logger import configure_logging, get_logger
from core.models import (
AnalysisArtifact,
CallRecord,
CallStatus,
ReporterStatus,
)
from reporter.analytics import index_call
log = get_logger(__name__)
def _register_report_artifact(
session,
call_record_id: int,
uniqueid: str,
report_path,
) -> None:
from sqlmodel import select
existing = session.exec(
select(AnalysisArtifact).where(
AnalysisArtifact.call_record_id == call_record_id,
AnalysisArtifact.artifact_type == "report_detail",
)
).all()
for art in existing:
session.delete(art)
artifact = AnalysisArtifact(
call_record_id=call_record_id,
uniqueid=uniqueid,
artifact_type="report_detail",
file_path=str(report_path),
size_bytes=report_path.stat().st_size,
)
session.add(artifact)
def _report_detail_missing(record: CallRecord) -> bool:
return not record.report_detail_path.exists()
def repair_report_detail(record: CallRecord | None) -> None:
"""Regenerate missing per-call report files under reports_root."""
if record is None:
raise RuntimeError("CallRecord is required")
uid = record.uniqueid
call_start = time.monotonic()
log.info("Repairing missing report detail", uniqueid=uid)
try:
from reporter.report_detail import generate_detail_report
report_path = generate_detail_report(record)
with get_session() as session:
if record.id is None:
raise RuntimeError(f"CallRecord {record.uniqueid!r} has no id")
_register_report_artifact(session, record.id, uid, report_path)
rec = session.get(CallRecord, record.id)
if rec is None:
raise RuntimeError(f"CallRecord {record.uniqueid!r} disappeared")
rec.reporter_status = ReporterStatus.COMPLETED
rec.reporter_failure_count = 0
rec.reporter_error = None
if rec.reported_at is None:
rec.reported_at = datetime.now(UTC)
from reporter.report import generate_daily_report
log.info(
"Report detail repaired",
uniqueid=uid,
total_elapsed_s=round(time.monotonic() - call_start, 2),
)
except Exception as exc:
log.exception(
"Unhandled error during report repair",
uniqueid=uid,
error=str(exc),
elapsed_s=round(time.monotonic() - call_start, 2),
)
_mark_failed(record, str(exc))
# ---------------------------------------------------------------------------
# Per-call reporting
# ---------------------------------------------------------------------------
def report_call(record: CallRecord | None) -> None:
"""Generate the detail report and mark reporting completed.
log = get_logger(__name__)
def previous_local_day(now: datetime | None = None) -> date:
current = now or datetime.now().astimezone()
if current.tzinfo is None:
current = current.astimezone()
return current.date() - timedelta(days=1)
Reporter status transitions: pending/failed → processing → completed/failed.
Analyzer-owned ``status`` is not modified.
"""
if record is None:
raise RuntimeError("CallRecord is required")
uid = record.uniqueid
call_start = time.monotonic()
log.info("Reporting call START", uniqueid=uid)
# Mark as reporting
with get_session() as session:
rec = session.get(CallRecord, record.id)
if rec is None:
raise RuntimeError(f"CallRecord {record.uniqueid!r} disappeared")
rec.reporter_status = ReporterStatus.PROCESSING
try:
# 1. Generate per-call HTML report
from reporter.report_detail import generate_detail_report
step_t = time.monotonic()
report_path = generate_detail_report(record)
log.info(
"Step 1/2: detail report generated",
uniqueid=uid,
elapsed_s=round(time.monotonic() - step_t, 2),
)
with get_session() as session:
if record.id is None:
raise RuntimeError(f"CallRecord {record.uniqueid!r} has no id")
_register_report_artifact(session, record.id, uid, report_path)
# 2. Advance status to reported
with get_session() as session:
rec = session.get(CallRecord, record.id)
if rec is None:
raise RuntimeError(f"CallRecord {record.uniqueid!r} disappeared")
rec.reporter_status = ReporterStatus.COMPLETED
rec.reporter_failure_count = 0
rec.reporter_error = None
rec.reported_at = datetime.now(UTC)
log.info(
"Call reported COMPLETE",
uniqueid=uid,
total_elapsed_s=round(time.monotonic() - call_start, 2),
)
except Exception as exc:
log.exception(
"Unhandled error during reporting",
uniqueid=uid,
error=str(exc),
elapsed_s=round(time.monotonic() - call_start, 2),
)
_mark_failed(record, str(exc))
def _mark_failed(record: CallRecord, error: str) -> None:
with get_session() as session:
rec = session.get(CallRecord, record.id)
if rec is None:
raise RuntimeError(f"CallRecord {record.uniqueid!r} disappeared")
rec.reporter_failure_count = (rec.reporter_failure_count or 0) + 1
rec.reporter_error = error[:2000]
if rec.reporter_failure_count >= 3:
rec.reporter_status = ReporterStatus.DEAD_LETTER
log.error("Call moved to dead_letter (reporter)", uniqueid=record.uniqueid)
else:
rec.reporter_status = ReporterStatus.FAILED
# ---------------------------------------------------------------------------
# Daily summary trigger
# ---------------------------------------------------------------------------
def _should_generate_summary(last_summary_date: datetime | None) -> bool:
"""Return True once per UTC day."""
today = datetime.now(UTC).date()
if last_summary_date is None:
return True
return last_summary_date.date() < today
def _run_summary() -> None:
try:
from reporter.report_summary import generate_summary_report
path = generate_summary_report()
log.info("Daily summary report generated", path=str(path))
except Exception as exc:
log.error("Failed to generate summary report", error=str(exc))
# ---------------------------------------------------------------------------
# Main loop
# ---------------------------------------------------------------------------
def main() -> None:
cfg = load_config()
configure_logging(level=cfg.logging.level)
init_db()
log.info("Reporter service starting", poll_interval_s=cfg.schedule.poll_interval_s)
from core.daemon import GracefulExit
stop = GracefulExit()
last_summary_at: datetime | None = None
while not stop.requested:
# Fetch a batch of analyzed calls plus any reported calls missing report_detail.html
with get_session() as session:
pending = list(
session.exec(
select(CallRecord)
.where(
CallRecord.status == CallStatus.ANALYZED,
cast(Any, CallRecord.reporter_status).in_(
[ReporterStatus.PENDING, ReporterStatus.FAILED]
),
)
.order_by(cast(Any, CallRecord.analyzed_at))
.limit(10)
).all()
)
repair = list(
session.exec(
select(CallRecord)
.where(
CallRecord.reporter_status == ReporterStatus.COMPLETED
)
.order_by(cast(Any, CallRecord.reported_at))
.limit(20)
).all()
)
repair = [record for record in repair if _report_detail_missing(record)]
did_work = False
if pending:
did_work = True
log.info("Reporting batch", count=len(pending))
for record in pending:
if stop.requested:
log.info("Shutdown requested; finishing current batch")
break
try:
index_call(record)
report_call(record)
except Exception as exc:
log.exception(
"Fatal error in report_call",
uniqueid=record.uniqueid,
error=str(exc),
)
if repair and not stop.requested:
did_work = True
log.info("Repairing missing report artifacts", count=len(repair))
for record in repair:
if stop.requested:
log.info("Shutdown requested; finishing current batch")
break
try:
index_call(record)
repair_report_detail(record)
except Exception as exc:
log.exception(
"Fatal error in repair_report_detail",
uniqueid=record.uniqueid,
error=str(exc),
)
if not did_work:
log.debug(
"No analyzed calls; sleeping", seconds=cfg.schedule.poll_interval_s
)
# Daily summary — generate once per UTC day
if not stop.requested and _should_generate_summary(last_summary_at):
_run_summary()
last_summary_at = datetime.now(UTC)
if not stop.requested:
stop.sleep(cfg.schedule.poll_interval_s)
log.info("Reporter shutting down cleanly")
if __name__ == "__main__":
main()
report_day = previous_local_day()
output = generate_daily_report(report_day)
log.info("Daily DOCX report generated", report_day=report_day.isoformat(), path=str(output))
if __name__ == "__main__":
main()

View File

@ -1,35 +0,0 @@
from __future__ import annotations
from core.models import (
AnalysisArtifact,
CallDirection,
CallEmotion,
CallIdentityMap,
CallRecommendation,
CallRecord,
CallScore,
CallSource,
CallStatus,
CallTurn,
EntityType,
IngestionStatus,
ReportJob,
ReportSnapshot,
)
__all__ = [
"AnalysisArtifact",
"CallDirection",
"CallEmotion",
"CallIdentityMap",
"CallRecord",
"CallRecommendation",
"CallScore",
"CallSource",
"CallStatus",
"CallTurn",
"EntityType",
"IngestionStatus",
"ReportJob",
"ReportSnapshot",
]

175
src/reporter/report.py Normal file
View File

@ -0,0 +1,175 @@
# ruff: noqa: E501
from __future__ import annotations
from collections import Counter, defaultdict
from datetime import UTC, date, datetime, time, timedelta
from pathlib import Path
from statistics import median
from sqlmodel import select
from core.config import get_config
from core.db import get_session
from core.models import CallRecord, VoiceCategory
from reporter.docx import Document
def _period(day: date) -> tuple[datetime, datetime]:
tz = datetime.now().astimezone().tzinfo
start = datetime.combine(day, time.min, tzinfo=tz).astimezone(UTC)
end = datetime.combine(day + timedelta(days=1), time.min, tzinfo=tz).astimezone(UTC)
return start, end
def load_rows(day: date) -> list[tuple[VoiceCategory, CallRecord]]:
start, end = _period(day)
with get_session() as session:
return list(
session.exec(
select(VoiceCategory, CallRecord)
.join(CallRecord, VoiceCategory.call_record_id == CallRecord.id)
.where(CallRecord.fetched_at >= start, CallRecord.fetched_at < end)
.order_by(CallRecord.fetched_at) # type: ignore[arg-type]
).all()
)
def output_path(day: date) -> Path:
cfg = get_config()
root = cfg.reporter.output_root or (cfg.storage.spool_root.parent / "reporter")
return root / day.isoformat() / "report.docx"
def _rate(value: int, total: int) -> str:
return f"{value / total * 100:.1f}%" if total else "0.0%"
def _distribution(values: list[str]) -> list[list[object]]:
counts = Counter(values)
total = len(values)
return [[label, count, _rate(count, total)] for label, count in counts.most_common()]
def _manager_rows(rows: list[tuple[VoiceCategory, CallRecord]]) -> list[list[object]]:
grouped: dict[str, list[VoiceCategory]] = defaultdict(list)
for category, _ in rows:
grouped[category.user_name or category.user_id].append(category)
result = []
for manager, calls in grouped.items():
total = len(calls)
result.append(
[
manager,
total,
f"{sum(c.duration_s for c in calls) / 60:.1f}",
f"{sum(c.quality_score for c in calls) / total:.1f}",
_rate(sum(c.scorecard_greeting == "yes" for c in calls), total),
_rate(sum(c.scorecard_identified_need == "yes" for c in calls), total),
_rate(sum(c.scorecard_defined_next_step == "yes" for c in calls), total),
_rate(sum(c.requires_attention for c in calls), total),
]
)
return sorted(result, key=lambda item: (-int(item[1]), str(item[0])))
def build_report(day: date, rows: list[tuple[VoiceCategory, CallRecord]]) -> Document:
categories = [category for category, _ in rows]
records = [record for _, record in rows]
total = len(rows)
durations = [category.duration_s for category in categories]
attention = sum(category.requires_attention for category in categories)
repeated = Counter(record.caller_phone for record in records if record.caller_phone)
repeated = Counter({phone: count for phone, count in repeated.items() if count > 1})
doc = Document()
doc.title("Сводный отчёт по анализу голосовых переговоров менеджеров с клиентами")
doc.paragraph(f"Отчётный период: {day.strftime('%d.%m.%Y')}. Сформирован по данным voice_category и call_records.")
doc.heading("1. Управленческое резюме")
if total:
common_category, common_count = Counter(c.category for c in categories).most_common(1)[0]
doc.paragraph(
f"Обработано {total} звонков общей длительностью {sum(durations) / 60:.1f} мин. "
f"Средняя длительность — {sum(durations) / total:.1f} сек.; требуют внимания "
f"{attention} звонков ({_rate(attention, total)}). Наиболее частая категория — "
f"{common_category} ({common_count}, {_rate(common_count, total)})."
)
else:
doc.paragraph("За отчётный день категоризированные звонки отсутствуют.")
doc.heading("2. Методика формирования отчёта")
doc.paragraph("Показатели рассчитаны по категоризированным звонкам, попавшим в предыдущий локальный календарный день. Использованы классификация, scorecard, семантические признаки, метаданные звонка и данные менеджера/клиента.")
doc.heading("3. Количественная структура массива")
doc.table(["Показатель", "Значение"], [
["Количество звонков", total],
["Суммарная длительность, мин.", f"{sum(durations) / 60:.1f}" if total else "0.0"],
["Средняя длительность, сек.", f"{sum(durations) / total:.1f}" if total else "0.0"],
["Медианная длительность, сек.", f"{median(durations):.1f}" if total else "0.0"],
["Средний quality score", f"{sum(c.quality_score for c in categories) / total:.1f}" if total else "0.0"],
["Уникальных менеджеров", len({c.user_id for c in categories})],
["Уникальных клиентских номеров", len({r.caller_phone for r in records if r.caller_phone})],
])
for number, title, values in (
("3.1", "Категории звонков", [c.category for c in categories]),
("3.2", "Тональность", [c.sentiment for c in categories]),
("3.3", "Риск отношений", [c.relationship_risk for c in categories]),
("3.4", "Язык распознавания", [c.language for c in categories]),
):
doc.heading(f"{number}. {title}", 2)
doc.table(["Группа", "Количество", "Доля"], _distribution(values))
doc.heading("4. Количественные показатели по менеджерам")
doc.table(["Менеджер", "Звонков", "Мин.", "Q-score", "Приветствие", "Потребность", "Next step", "Внимание"], _manager_rows(rows))
doc.heading("5. Темы и проблематика по менеджерам")
problem_rows = []
for manager in sorted({c.user_name or c.user_id for c in categories}):
calls = [c for c in categories if (c.user_name or c.user_id) == manager]
reasons = Counter(reason for call in calls for reason in call.attention_reasons)
problem_rows.append([manager, ", ".join(reason for reason, _ in reasons.most_common(3)) or "Не выявлено"])
doc.table(["Менеджер", "Основные проблемные темы"], problem_rows)
doc.heading("6. Ожидания, проблемы и запросы клиентов")
intents = Counter(value for c in categories for value in c.client_intents)
contacts = Counter(value for c in categories for value in c.contact_reasons)
doc.heading("6.1. Ранжирование ожиданий и запросов клиентов", 2)
doc.table(["Ожидание / запрос", "Количество", "Доля звонков"], [[value, count, _rate(count, total)] for value, count in intents.most_common()])
doc.heading("6.2. Причины обращения", 2)
doc.table(["Причина", "Количество", "Доля звонков"], [[value, count, _rate(count, total)] for value, count in contacts.most_common()])
doc.heading("7. Карта возражений")
objections: Counter[str] = Counter()
for category in categories:
for objection in category.objections:
if isinstance(objection, dict):
objections[str(objection.get("type") or "Не указано")] += 1
else:
objections[str(objection)] += 1
doc.table(["Возражение", "Количество", "Доля звонков"], [[value, count, _rate(count, total)] for value, count in objections.most_common()])
doc.heading("8. Профили клиентов по сегментам")
doc.table(["Сегмент", "Количество", "Доля"], _distribution([c.client_segment for c in categories]))
doc.heading("9. Готовность менеджеров к переговорам")
doc.table(["Уровень", "Количество", "Доля"], _distribution([c.manager_readiness for c in categories]))
doc.heading("10. Тренды взаимодействия с клиентами")
doc.table(["Результат звонка", "Количество", "Доля"], _distribution([c.call_result for c in categories]))
doc.heading("11. Как компания выглядит в глазах клиентов")
doc.table(["Восприятие", "Количество", "Доля"], _distribution([c.company_perception for c in categories]))
doc.heading("12. Рекомендации и мероприятия по устранению недостатков")
recommendations = Counter(reason for c in categories for reason in c.attention_reasons)
if recommendations:
for reason, count in recommendations.most_common(10):
doc.paragraph(f"• {reason}: разобрать {count} звонков и определить корректирующее действие с ответственным менеджером.")
else:
doc.paragraph("Критические повторяющиеся причины внимания не выявлены.")
doc.heading("13. Перечень звонков, требующих внимания")
doc.table(["Дата и время", "ID звонка", "Менеджер", "Клиент", "Категория", "Причины"], [
[record.fetched_at.astimezone().strftime("%d.%m.%Y %H:%M"), category.uniqueid, category.user_name or category.user_id, category.client_name or record.caller_phone or "—", category.category, ", ".join(category.attention_reasons) or "Требуется проверка"]
for category, record in rows if category.requires_attention
])
doc.heading("14. Приложение: повторные клиентские номера")
doc.table(["Номер", "Количество звонков"], [[phone, count] for phone, count in repeated.most_common()])
return doc
def generate_daily_report(day: date) -> Path:
rows = load_rows(day)
return build_report(day, rows).save(output_path(day))

View File

@ -1,83 +0,0 @@
from __future__ import annotations
"""reporter.report_detail — Generate a per-call HTML report.
Reads transcript.json and script_analysis.json from the analyzer artifacts directory,
renders them with a Jinja2 template, and writes report_detail.html under reports_root.
"""
import json
from pathlib import Path
from core.logger import get_logger
from core.models import CallRecord
from reporter.analytics import build_detail_context
log = get_logger(__name__)
# Resolve the templates directory relative to this file
_TEMPLATES_DIR = Path(__file__).parent / "templates"
def _load_json(path: Path) -> list | dict | None:
if not path.exists():
return None
try:
return json.loads(path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError) as exc:
log.warning("Failed to load JSON artifact", path=str(path), error=str(exc))
return None
def _format_duration(seconds: int | None) -> str:
if seconds is None:
return "—"
minutes, secs = divmod(seconds, 60)
return f"{minutes}:{secs:02d}"
def _format_timestamp(start_s: float) -> str:
minutes, seconds = divmod(int(start_s), 60)
return f"{minutes:02d}:{seconds:02d}"
def generate_detail_report(record: CallRecord) -> Path:
"""Render report_detail.html for *record* and write it under reports_root.
Returns the path to the generated HTML file.
"""
from jinja2 import Environment, FileSystemLoader, select_autoescape
env = Environment(
loader=FileSystemLoader(str(_TEMPLATES_DIR)),
autoescape=select_autoescape(["html"]),
)
env.filters["format_timestamp"] = _format_timestamp
env.filters["format_duration"] = _format_duration
context = build_detail_context(record)
context.setdefault("record", record)
context.setdefault("duration_fmt", _format_duration(record.duration_s))
context.setdefault("score_color", _score_color(context.get("score")))
template = env.get_template("report_detail.html.j2")
html = template.render(**context)
output_path = record.report_detail_path
output_path.parent.mkdir(parents=True, exist_ok=True)
tmp = output_path.with_suffix(".tmp")
tmp.write_text(html, encoding="utf-8")
tmp.rename(output_path)
log.info("Detail report written", uniqueid=record.uniqueid, path=str(output_path))
return output_path
def _score_color(score: int | None) -> str:
if score is None:
return "#888"
if score >= 80:
return "#2d8a4e" # green
if score >= 60:
return "#d97706" # amber
return "#dc2626" # red

View File

@ -1,172 +0,0 @@
from __future__ import annotations
"""reporter.report_summary — Generate a batch summary report."""
import json
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import Any
from sqlmodel import select
from core.config import get_config
from core.db import get_session
from core.logger import get_logger
from core.models import CallRecord, ReporterStatus
from reporter.analytics import build_summary_metrics, upsert_snapshot
log = get_logger(__name__)
_TEMPLATES_DIR = Path(__file__).parent / "templates"
def _ensure_utc(dt: datetime) -> datetime:
if dt.tzinfo is None:
return dt.replace(tzinfo=UTC)
return dt.astimezone(UTC)
def _report_timestamp(record: CallRecord) -> datetime:
timestamp = record.reported_at or record.analyzed_at or record.fetched_at
return _ensure_utc(timestamp)
def _load_analysis(record: Any) -> dict[str, Any] | None:
path = getattr(record, "analysis_path", None)
if path is None or not Path(path).exists():
return None
try:
payload = json.loads(Path(path).read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
return None
return payload if isinstance(payload, dict) else None
def _load_transcript(record: Any) -> list[dict[str, Any]]:
path = getattr(record, "transcript_path", None)
if path is None or not Path(path).exists():
return []
try:
payload = json.loads(Path(path).read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
return []
if isinstance(payload, dict):
turns = payload.get("turns", [])
return turns if isinstance(turns, list) else []
return payload if isinstance(payload, list) else []
def _aggregate(records) -> dict[str, Any]:
return build_summary_metrics(list(records))
def generate_summary_report(
date_from: datetime | None = None,
date_to: datetime | None = None,
) -> Path:
"""Generate a batch summary report covering [date_from, date_to)."""
cfg = get_config()
if date_to is None:
date_to = datetime.now(UTC).replace(hour=0, minute=0, second=0, microsecond=0)
else:
date_to = _ensure_utc(date_to)
if date_from is None:
date_from = date_to - timedelta(days=cfg.reporter.summary_window_days)
else:
date_from = _ensure_utc(date_from)
log.info(
"Generating summary report",
date_from=date_from.isoformat(),
date_to=date_to.isoformat(),
)
with get_session() as session:
all_records = session.exec(select(CallRecord)).all()
records = [
record
for record in all_records
if record.report_detail_path.exists()
and date_from <= _report_timestamp(record) < date_to
]
if not records:
records = [
record
for record in all_records
if record.reporter_status == ReporterStatus.COMPLETED
and date_from <= _report_timestamp(record) < date_to
]
previous_from = date_from - (date_to - date_from)
previous_to = date_from
previous_records = [
record
for record in all_records
if record.report_detail_path.exists()
and previous_from <= _report_timestamp(record) < previous_to
]
if not previous_records:
previous_records = [
record
for record in all_records
if record.reporter_status == ReporterStatus.COMPLETED
and previous_from <= _report_timestamp(record) < previous_to
]
log.info(
"Calls in window",
count=len(records),
previous_count=len(previous_records),
)
metrics = build_summary_metrics(list(records), previous_records=list(previous_records))
from jinja2 import Environment, FileSystemLoader, select_autoescape
env = Environment(
loader=FileSystemLoader(str(_TEMPLATES_DIR)),
autoescape=select_autoescape(["html"]),
)
context = {
"date_from": date_from,
"date_to": date_to,
"previous_date_from": previous_from,
"previous_date_to": previous_to,
"metrics": metrics,
"records": records,
"generated_at": datetime.now(UTC),
}
template = env.get_template("report_summary.html.j2")
html = template.render(**context)
cfg.storage.reports_root.mkdir(parents=True, exist_ok=True)
date_str = date_from.strftime("%Y-%m-%d")
output_path = cfg.storage.reports_root / f"summary_{date_str}.html"
tmp = output_path.with_suffix(".tmp")
tmp.write_text(html, encoding="utf-8")
tmp.rename(output_path)
upsert_snapshot(
report_type="summary",
date_from=date_from,
date_to=date_to,
output_path=output_path,
payload={
"metrics": metrics,
"records": [rec.uniqueid for rec in records],
"previous_records": [rec.uniqueid for rec in previous_records],
},
status="done",
call_count=metrics["total_calls"],
)
log.info(
"Summary report written", path=str(output_path), calls=metrics["total_calls"]
)
return output_path

View File

@ -1,414 +0,0 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}Voice Pipeline Report{% endblock %}</title>
<style>
*, *::before, *::after { box-sizing: border-box; }
:root {
--bg: #f4efe8;
--surface: #fffdf9;
--surface-alt: #f8f1e8;
--border: #dfd3c5;
--text: #201a15;
--muted: #6d6258;
--accent: #9a3412;
--accent-soft: #fde9dc;
--good: #17603a;
--good-bg: #ddf4e4;
--warn: #9a6700;
--warn-bg: #fff1cc;
--bad: #a61b1b;
--bad-bg: #fde2e1;
--neutral: #4a5565;
--neutral-bg: #e8edf3;
--ink: #2f251d;
--shadow: 0 12px 32px rgba(54, 35, 15, 0.08);
}
body {
margin: 0;
background:
radial-gradient(circle at top left, rgba(154, 52, 18, 0.10), transparent 24rem),
radial-gradient(circle at top right, rgba(23, 96, 58, 0.08), transparent 20rem),
var(--bg);
color: var(--text);
font-family: Georgia, "Times New Roman", serif;
font-size: 15px;
line-height: 1.55;
padding: 24px 16px 48px;
}
.container {
max-width: 1160px;
margin: 0 auto;
}
.report-shell {
background: rgba(255, 253, 249, 0.86);
border: 1px solid rgba(223, 211, 197, 0.8);
border-radius: 28px;
box-shadow: var(--shadow);
overflow: hidden;
backdrop-filter: blur(10px);
}
.report-header {
padding: 32px 36px 24px;
background:
linear-gradient(135deg, rgba(154, 52, 18, 0.96), rgba(93, 33, 12, 0.92)),
var(--accent);
color: #fff8f1;
}
.eyebrow {
font-family: "Trebuchet MS", "Segoe UI", sans-serif;
font-size: 12px;
letter-spacing: 0.12em;
text-transform: uppercase;
opacity: 0.8;
margin-bottom: 10px;
}
.report-header h1 {
margin: 0;
font-size: 34px;
line-height: 1.1;
font-weight: 700;
}
.report-header .meta {
margin-top: 12px;
color: rgba(255, 248, 241, 0.82);
font-family: "Trebuchet MS", "Segoe UI", sans-serif;
font-size: 13px;
line-height: 1.5;
}
.content {
padding: 28px 28px 20px;
}
.section {
margin-bottom: 22px;
padding: 22px 24px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 22px;
box-shadow: 0 8px 22px rgba(54, 35, 15, 0.03);
}
.section-title {
margin: 0 0 12px;
font-size: 20px;
font-weight: 700;
color: var(--ink);
}
.section-subtitle {
margin: 0 0 16px;
color: var(--muted);
font-family: "Trebuchet MS", "Segoe UI", sans-serif;
font-size: 13px;
}
.grid-2 {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16px;
}
.grid-3 {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 16px;
}
.grid-4 {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 16px;
}
.kpi-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
gap: 14px;
}
.kpi-card {
background: linear-gradient(180deg, rgba(255,255,255,0.9), rgba(248,241,232,0.86));
border: 1px solid var(--border);
border-radius: 18px;
padding: 16px 18px;
min-height: 118px;
}
.kpi-label {
color: var(--muted);
font-family: "Trebuchet MS", "Segoe UI", sans-serif;
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.06em;
}
.kpi-value {
margin-top: 10px;
font-size: 34px;
line-height: 1;
font-weight: 700;
color: var(--ink);
}
.kpi-note {
margin-top: 8px;
color: var(--muted);
font-size: 13px;
font-family: "Trebuchet MS", "Segoe UI", sans-serif;
}
.executive-list {
margin: 0;
padding-left: 20px;
}
.executive-list li + li {
margin-top: 8px;
}
.badge {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 4px 10px;
border-radius: 999px;
font-family: "Trebuchet MS", "Segoe UI", sans-serif;
font-size: 12px;
font-weight: 700;
letter-spacing: 0.02em;
}
.badge.good { background: var(--good-bg); color: var(--good); }
.badge.warn { background: var(--warn-bg); color: var(--warn); }
.badge.bad { background: var(--bad-bg); color: var(--bad); }
.badge.neutral { background: var(--neutral-bg); color: var(--neutral); }
.callout {
border-radius: 18px;
padding: 16px 18px;
font-family: "Trebuchet MS", "Segoe UI", sans-serif;
}
.callout.good { background: var(--good-bg); color: var(--good); }
.callout.warn { background: var(--warn-bg); color: var(--warn); }
.callout.bad { background: var(--bad-bg); color: var(--bad); }
.callout.neutral { background: var(--neutral-bg); color: var(--neutral); }
table {
width: 100%;
border-collapse: collapse;
font-family: "Trebuchet MS", "Segoe UI", sans-serif;
font-size: 13px;
}
thead th {
padding: 10px 12px;
text-align: left;
text-transform: uppercase;
letter-spacing: 0.05em;
font-size: 11px;
color: var(--muted);
border-bottom: 1px solid var(--border);
}
tbody td {
padding: 12px;
vertical-align: top;
border-top: 1px solid rgba(223, 211, 197, 0.7);
}
tbody tr:first-child td {
border-top: none;
}
tbody tr:nth-child(odd) td {
background: rgba(248, 241, 232, 0.38);
}
.mini-list {
margin: 0;
padding-left: 18px;
}
.mini-list li + li {
margin-top: 6px;
}
.pill-list {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.pill {
display: inline-flex;
align-items: center;
padding: 5px 9px;
background: var(--surface-alt);
border: 1px solid var(--border);
border-radius: 999px;
font-family: "Trebuchet MS", "Segoe UI", sans-serif;
font-size: 12px;
color: var(--ink);
}
.distribution {
display: flex;
flex-direction: column;
gap: 10px;
}
.distribution-row {
display: grid;
grid-template-columns: 140px 1fr 52px;
gap: 12px;
align-items: center;
font-family: "Trebuchet MS", "Segoe UI", sans-serif;
font-size: 13px;
}
.distribution-track {
position: relative;
height: 12px;
background: #efe4d8;
border-radius: 999px;
overflow: hidden;
}
.distribution-fill {
position: absolute;
inset: 0 auto 0 0;
background: linear-gradient(90deg, rgba(154,52,18,0.88), rgba(222,116,55,0.88));
border-radius: 999px;
}
.split-card {
display: flex;
flex-direction: column;
gap: 12px;
padding: 16px 18px;
border-radius: 18px;
border: 1px solid var(--border);
background: linear-gradient(180deg, rgba(248,241,232,0.45), rgba(255,255,255,0.95));
}
.label-value {
display: grid;
grid-template-columns: 180px 1fr;
gap: 10px;
font-family: "Trebuchet MS", "Segoe UI", sans-serif;
font-size: 13px;
padding: 8px 0;
border-top: 1px solid rgba(223, 211, 197, 0.7);
}
.label-value:first-child {
border-top: none;
padding-top: 0;
}
.label-value .label {
color: var(--muted);
}
.transcript {
display: flex;
flex-direction: column;
gap: 10px;
}
.segment {
display: grid;
grid-template-columns: 58px 1fr;
gap: 14px;
padding: 14px 16px;
border: 1px solid var(--border);
border-radius: 18px;
background: rgba(255,255,255,0.84);
}
.segment.agent { border-left: 5px solid #9a3412; }
.segment.customer { border-left: 5px solid #17603a; }
.segment-ts {
font-family: "Trebuchet MS", "Segoe UI", sans-serif;
font-size: 12px;
color: var(--muted);
padding-top: 2px;
}
.segment-speaker {
font-family: "Trebuchet MS", "Segoe UI", sans-serif;
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--muted);
margin-bottom: 6px;
}
.segment-text {
white-space: pre-wrap;
}
.report-footer {
padding: 0 28px 24px;
color: var(--muted);
font-family: "Trebuchet MS", "Segoe UI", sans-serif;
font-size: 12px;
text-align: center;
}
@media print {
body {
padding: 0;
background: #fff;
}
.report-shell {
border: none;
box-shadow: none;
}
}
@media (max-width: 860px) {
.grid-2, .grid-3, .grid-4 {
grid-template-columns: 1fr;
}
.content, .report-header {
padding-left: 20px;
padding-right: 20px;
}
.distribution-row {
grid-template-columns: 1fr;
}
.label-value {
grid-template-columns: 1fr;
}
.segment {
grid-template-columns: 1fr;
}
}
</style>
</head>
<body>
<div class="container">
<div class="report-shell">
{% block content %}{% endblock %}
<div class="report-footer">
Generated by voice-pipeline{% if generated_at is defined %} · {{ generated_at.strftime('%Y-%m-%d %H:%M UTC') }}{% endif %}
</div>
</div>
</div>
</body>
</html>

View File

@ -1,279 +0,0 @@
{% extends "base.html.j2" %}
{% block title %}Детальный отчёт — {{ record.uniqueid }}{% endblock %}
{% block content %}
<div class="report-header">
<div class="eyebrow">Forensic Call Card</div>
<h1>Детальный отчёт по разговору</h1>
<div class="meta">
UNIQUEID {{ record.uniqueid }} · {{ record.source | capitalize }} · {{ (record.direction or "unknown") | capitalize }}<br>
Длительность {{ duration_fmt }} · Менеджер {{ manager_label }} · Клиент {{ customer_label }}
</div>
</div>
<div class="content">
<section class="section">
<h2 class="section-title">Итоговые KPI звонка</h2>
<p class="section-subtitle">Эти показатели используются и в сводном отчёте, и в оценке конкретного разговора.</p>
<div class="grid-2" style="margin-bottom:16px;">
<div class="callout {% if quality_bucket.key == 'high' %}good{% elif quality_bucket.key == 'medium' %}warn{% elif quality_bucket.key == 'low' %}bad{% else %}neutral{% endif %}">
<strong>{{ quality_bucket.label }}</strong><br>
{% if score is not none %}Score {{ score }}/100{% else %}Score отсутствует{% endif %}
</div>
<div class="callout {% if requires_attention %}bad{% else %}good{% endif %}">
<strong>{% if requires_attention %}Требует внимания{% else %}Вне приоритетной зоны{% endif %}</strong><br>
{% if attention_reasons %}{{ attention_reasons | join(", ") }}{% else %}Высокорисковые сигналы не выявлены.{% endif %}
</div>
</div>
<div class="kpi-grid">
{% for item in call_kpis %}
<div class="kpi-card">
<div class="kpi-label">{{ item.label }}</div>
<div class="kpi-value" style="font-size:30px;">{{ item.value }}</div>
</div>
{% endfor %}
</div>
</section>
<section class="section">
<h2 class="section-title">Как звонок влияет на сводный отчёт</h2>
<p class="section-subtitle">Связка между call-level evidence и summary aggregation.</p>
<div class="split-card">
{% for row in summary_link_rows %}
<div class="label-value">
<div class="label">{{ row.label }}</div>
<div><strong>{{ row.value }}</strong><br><span style="color:var(--muted);">{{ row.detail }}</span></div>
</div>
{% endfor %}
</div>
</section>
<section class="section">
<h2 class="section-title">Сигналы риска и причины внимания</h2>
<p class="section-subtitle">Флаги формируются из тех же derived metrics, что и списки проблемных звонков в summary.</p>
{% if risk_flags %}
<div class="grid-2">
{% for flag in risk_flags %}
<div class="callout {% if flag.severity == 'high' %}bad{% elif flag.severity == 'medium' %}warn{% else %}neutral{% endif %}">
<strong>{{ flag.label }}</strong><br>
{{ flag.detail }}
</div>
{% endfor %}
</div>
{% else %}
<div class="callout good">Высокорисковые сигналы не выявлены.</div>
{% endif %}
</section>
<section class="section">
<h2 class="section-title">Контекст и привязка в CRM</h2>
<p class="section-subtitle">Участники разговора и Bitrix/CRM linkage для трассировки и последующих действий.</p>
<div class="grid-2">
<div class="label-value"><div class="label">Статус решения</div><div>{{ semantic_analysis.resolution_status or "unknown" }}</div></div>
<div class="label-value"><div class="label">Уровень риска</div><div>{{ semantic_analysis.risk_level or "low" }}</div></div>
<div class="label-value"><div class="label">Стадия конфликта</div><div>{{ semantic_analysis.conflict_stage or "none" }}</div></div>
<div class="label-value"><div class="label">Стадия отношений</div><div>{{ semantic_analysis.relationship_stage or "unknown" }}</div></div>
<div class="split-card">
<div class="kpi-label">Участники</div>
{% for role in ["caller", "callee", "agent", "customer"] %}
{% set participant = participant_details.get(role) %}
{% if participant %}
<div class="label-value">
<div class="label">{{ role }}</div>
<div>
<strong>{{ participant.name or "unknown" }}</strong><br>
speaker={{ participant.speaker or "unknown" }}
{% if participant.phone %}<br>phone={{ participant.phone }}{% endif %}
{% if participant.user_id %}<br>user_id={{ participant.user_id }}{% endif %}
{% if participant.entity_type or participant.entity_id %}
<br>entity={{ participant.entity_type or "unknown" }} {{ participant.entity_id or "" }}
{% endif %}
</div>
</div>
{% endif %}
{% endfor %}
<div class="label-value"><div class="label">Статус решения</div><div>{{ semantic_analysis.resolution_status or "unknown" }}</div></div>
<div class="label-value"><div class="label">Уровень риска</div><div>{{ semantic_analysis.risk_level or "low" }}</div></div>
<div class="label-value"><div class="label">Стадия конфликта</div><div>{{ semantic_analysis.conflict_stage or "none" }}</div></div>
<div class="label-value"><div class="label">Стадия отношений</div><div>{{ semantic_analysis.relationship_stage or "unknown" }}</div></div>
</div>
<div class="split-card">
<div class="kpi-label">Bitrix linkage</div>
<div class="label-value"><div class="label">CRM activity</div><div>{{ bitrix_linkage.crm_activity_id or "—" }}</div></div>
<div class="label-value"><div class="label">Entity</div><div>{{ bitrix_linkage.entity_type or "—" }}{% if bitrix_linkage.entity_id %} #{{ bitrix_linkage.entity_id }}{% endif %}</div></div>
<div class="label-value"><div class="label">Portal user</div><div>{{ bitrix_linkage.employee_user_id or "—" }}</div></div>
<div class="label-value"><div class="label">External call</div><div>{{ bitrix_linkage.external_call_id or "—" }}</div></div>
<div class="label-value"><div class="label">Voximplant call</div><div>{{ bitrix_linkage.voximplant_call_id or "—" }}</div></div>
<div class="label-value"><div class="label">Index status</div><div>{{ index_status or "—" }}</div></div>
</div>
</div>
</section>
<section class="section">
<h2 class="section-title">Разбор разговора</h2>
<p class="section-subtitle">Скрипт, проблемы, рекомендации и эмоциональный профиль по конкретному кейсу.</p>
<div class="grid-2">
<div class="split-card">
<div class="kpi-label">Вывод и problem flags</div>
<p style="margin:0;">{{ summary or "Нет текстового вывода." }}</p>
<div class="pill-list" style="margin-top:12px;">
{% for label in problem_labels %}
<span class="pill">{{ label }}</span>
{% else %}
<span class="pill">problem flags не выявлены</span>
{% endfor %}
</div>
<div class="kpi-label" style="margin-top:16px;">Бизнес-риски</div>
<div class="pill-list">
{% for item in semantic_analysis.business_risks %}
<span class="pill">{{ item }}</span>
{% else %}
<span class="pill">нет данных</span>
{% endfor %}
</div>
</div>
<div class="split-card">
<div class="kpi-label">Эмоциональный профиль</div>
<div class="label-value"><div class="label">Доминирующая эмоция</div><div>{{ dominant_emotion }}</div></div>
{% for speaker, emotions in speaker_emotions.items() %}
<div class="label-value">
<div class="label">{{ speaker }}</div>
<div class="pill-list">
{% for emotion, count in emotions.items() %}
<span class="pill">{{ emotion }}: {{ count }}</span>
{% endfor %}
</div>
</div>
{% endfor %}
</div>
</div>
{% if analysis and analysis.checklist %}
<div class="split-card" style="margin-top:16px;">
<div class="kpi-label">Script adherence</div>
{% for item in analysis.checklist %}
<div class="label-value">
<div class="label">{{ item.item }}</div>
<div>
<span class="badge {% if item.passed %}good{% else %}bad{% endif %}">{{ "passed" if item.passed else "failed" }}</span>
{% if item.evidence %}<br><span style="color:var(--muted);">«{{ item.evidence }}»</span>{% endif %}
</div>
</div>
{% endfor %}
</div>
{% endif %}
{% if recommendations %}
<div class="split-card" style="margin-top:16px;">
<div class="kpi-label">Рекомендации</div>
<ul class="mini-list">
{% for item in recommendations %}
<li><strong>{{ item.text }}</strong>{% if item.detail %}<br><span style="color:var(--muted);">{{ item.detail }}</span>{% endif %}</li>
{% endfor %}
</ul>
</div>
{% endif %}
</section>
<section class="section">
<h2 class="section-title">Семантические признаки для сводного отчёта</h2>
<p class="section-subtitle">Эти поля напрямую питают главы summary и должны быть прозрачны на уровне одного звонка.</p>
<div class="grid-2">
<div class="split-card">
<div class="label-value"><div class="label">Категория звонка</div><div>{{ semantic_analysis.call_category or "unknown" }}</div></div>
<div class="label-value"><div class="label">Сегмент клиента</div><div>{{ semantic_analysis.customer_segment or "unknown" }}</div></div>
<div class="label-value"><div class="label">Готовность менеджера</div><div>{{ semantic_analysis.manager_readiness or "unknown" }}</div></div>
<div class="label-value"><div class="label">Восприятие компании</div><div>{{ semantic_analysis.company_perception or "unknown" }}</div></div>
</div>
<div class="split-card">
<div class="kpi-label">Причины perception</div>
<div class="pill-list">
{% for item in semantic_analysis.company_perception_reasons %}
<span class="pill">{{ item }}</span>
{% else %}
<span class="pill">нет данных</span>
{% endfor %}
</div>
</div>
</div>
<div class="grid-3" style="margin-top:16px;">
<div class="split-card">
<div class="kpi-label">Ожидания клиента</div>
<ul class="mini-list">
{% for item in semantic_analysis.client_expectations %}
<li>{{ item }}</li>
{% else %}
<li>нет данных</li>
{% endfor %}
</ul>
</div>
<div class="split-card">
<div class="kpi-label">Проблемы и запросы</div>
<ul class="mini-list">
{% for item in semantic_analysis.client_problems %}
<li>{{ item }}</li>
{% else %}
<li>нет данных</li>
{% endfor %}
{% for item in semantic_analysis.client_requests %}
<li>{{ item }}</li>
{% else %}
{% endfor %}
</ul>
</div>
<div class="split-card">
<div class="label-value">
<div class="label">Возражения / барьеры</div>
<div class="pill-list">
{% for item in semantic_analysis.objections_or_barriers %}
<span class="pill">{{ item }}</span>
{% else %}
<span class="pill">нет данных</span>
{% endfor %}
</div>
</div>
<div class="label-value">
<div class="label">Рекомендуемые действия</div>
<div class="pill-list">
{% for item in semantic_analysis.improvement_actions %}
<span class="pill">{{ item }}</span>
{% else %}
<span class="pill">нет данных</span>
{% endfor %}
</div>
</div>
</div>
</div>
<div class="split-card" style="margin-top:16px;">
<div class="kpi-label">Следующее действие</div>
<div class="label-value"><div class="label">Ответственный</div><div>{{ semantic_analysis.next_action_owner or "unknown" }}</div></div>
<div class="label-value"><div class="label">Приоритет</div><div>{{ semantic_analysis.next_action_priority or "normal" }}</div></div>
<div class="label-value"><div class="label">Действие</div><div>{{ semantic_analysis.next_action_text or "нет данных" }}</div></div>
</div>
</section>
<section class="section">
<h2 class="section-title">Таймлайн и полная транскрипция</h2>
<p class="section-subtitle">Полный разбор реплик остаётся доступен, но подчинён аналитическим секциям.</p>
<div class="transcript">
{% for seg in transcript_timeline %}
<div class="segment {{ seg.speaker }}">
<div class="segment-ts">{{ seg.timestamp }}</div>
<div>
<div class="segment-speaker">
{{ seg.speaker }}
{% if seg.emotion and seg.emotion != "neutral" %}
<span class="badge neutral">{{ seg.emotion }}</span>
{% endif %}
</div>
<div class="segment-text">{{ seg.text }}</div>
</div>
</div>
{% else %}
<div class="callout neutral">Сегменты транскрипции отсутствуют.</div>
{% endfor %}
</div>
</section>
</div>
{% endblock %}

View File

@ -1,411 +0,0 @@
{% extends "base.html.j2" %}
{% block title %}Сводный отчёт — {{ date_from.strftime('%Y-%m-%d') }}{% endblock %}
{% block content %}
<div class="report-header">
<div class="eyebrow">Management Summary</div>
<h1>Сводный отчёт по звонкам</h1>
<div class="meta">
Период: {{ date_from.strftime('%Y-%m-%d') }} — {{ date_to.strftime('%Y-%m-%d') }}<br>
Сравнение: {{ previous_date_from.strftime('%Y-%m-%d') }} — {{ previous_date_to.strftime('%Y-%m-%d') }}<br>
Источник: analyzer artifacts + reporter analytics
</div>
</div>
<div class="content">
<section class="section">
<h2 class="section-title">Управленческое резюме</h2>
<p class="section-subtitle">Краткие выводы для руководства по текущему окну наблюдения.</p>
{% if metrics.executive_summary %}
<ol class="executive-list">
{% for item in metrics.executive_summary %}
<li>{{ item }}</li>
{% endfor %}
</ol>
{% else %}
<p>Нет данных для управленческого резюме.</p>
{% endif %}
<div class="kpi-grid" style="margin-top:16px;">
{% for card in metrics.kpi_cards %}
<div class="kpi-card">
<div class="kpi-label">{{ card.label }}</div>
<div class="kpi-value">{{ card.value }}</div>
</div>
{% endfor %}
</div>
</section>
<section class="section">
<h2 class="section-title">9. Риски и конфликтные звонки</h2>
<p class="section-subtitle">Бизнес-риски, конфликтные сигналы и очередь follow-up по insights.</p>
<div class="grid-2">
<div class="split-card">
<div class="kpi-label">Риски</div>
<ul class="mini-list">
{% for row in metrics.risk_breakdown.rows %}
<li>{{ row.name }} — {{ row.count }} ({{ row.share }}%)</li>
{% else %}
<li>нет данных</li>
{% endfor %}
</ul>
</div>
<div class="split-card">
<div class="kpi-label">Follow-up queue</div>
<ul class="mini-list">
{% for item in metrics.follow_up_queue["items"][:8] %}
<li>{{ item.owner }} / {{ item.priority }} — {{ item.action }}</li>
{% else %}
<li>нет данных</li>
{% endfor %}
</ul>
</div>
</div>
</section>
<section class="section">
<h2 class="section-title">1. Количественные показатели по менеджерам</h2>
<p class="section-subtitle">Звонки, score, compliance, сигналы внимания и семантические паттерны по каждому менеджеру.</p>
{% if metrics.manager_quantitative_metrics.rows %}
<table>
<thead>
<tr>
<th>Менеджер</th>
<th>Звонки</th>
<th>Scored</th>
<th>Средний score</th>
<th>Compliance</th>
<th>Attention</th>
<th>Low quality</th>
<th>Readiness</th>
<th>Топ возражения</th>
<th>Топ ожидания</th>
</tr>
</thead>
<tbody>
{% for row in metrics.manager_quantitative_metrics.rows %}
<tr>
<td>{{ row.user_id }}</td>
<td>{{ row.calls }}</td>
<td>{{ row.scored_calls }}</td>
<td>{{ row.avg_score if row.avg_score is not none else "—" }}</td>
<td>{{ row.compliance_rate if row.compliance_rate is not none else "—" }}{% if row.compliance_rate is not none %}%{% endif %}</td>
<td>{{ row.attention_calls }}</td>
<td>{{ row.low_quality_calls }}</td>
<td>
high {{ row.readiness_distribution.high }},
medium {{ row.readiness_distribution.medium }},
low {{ row.readiness_distribution.low }}
</td>
<td>{{ row.top_objections | join(", ") if row.top_objections else "нет данных" }}</td>
<td>{{ row.top_expectations | join(", ") if row.top_expectations else "нет данных" }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>Нет данных по менеджерам.</p>
{% endif %}
</section>
<section class="section">
<h2 class="section-title">2. Количество звонков</h2>
<p class="section-subtitle">Объём звонков, длительность, mix по направлениям и сравнение с предыдущим окном.</p>
<div class="grid-3">
<div class="split-card">
<div class="kpi-label">Текущий период</div>
<div class="label-value"><div class="label">Всего звонков</div><div>{{ metrics.call_volume_overview.total_calls }}</div></div>
<div class="label-value"><div class="label">Scored calls</div><div>{{ metrics.call_volume_overview.scored_calls }}</div></div>
<div class="label-value"><div class="label">Attention rate</div><div>{{ metrics.call_volume_overview.attention_rate_pct }}%</div></div>
</div>
<div class="split-card">
<div class="kpi-label">Длительность</div>
<div class="label-value"><div class="label">Общая</div><div>{{ metrics.call_volume_overview.total_duration_fmt }}</div></div>
<div class="label-value"><div class="label">Средняя</div><div>{{ metrics.call_volume_overview.avg_duration_fmt }}</div></div>
<div class="label-value"><div class="label">Медианная</div><div>{{ metrics.call_volume_overview.median_duration_fmt }}</div></div>
</div>
<div class="split-card">
<div class="kpi-label">Направления</div>
{% for direction, count in metrics.call_volume_overview.direction_distribution.items() %}
<div class="label-value"><div class="label">{{ direction }}</div><div>{{ count }}</div></div>
{% else %}
<p>Нет данных.</p>
{% endfor %}
</div>
</div>
<table style="margin-top:16px;">
<thead>
<tr>
<th>Показатель</th>
<th>Текущий</th>
<th>Предыдущий</th>
<th>Δ</th>
</tr>
</thead>
<tbody>
{% for label, item in metrics.call_volume_overview.comparison.items() %}
<tr>
<td>{{ label }}</td>
<td>{{ item.current if item.current is not none else "—" }}</td>
<td>{{ item.previous if item.previous is not none else "—" }}</td>
<td>{{ item.delta if item.delta is not none else "—" }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</section>
<section class="section">
<h2 class="section-title">3. Категории звонков</h2>
<p class="section-subtitle">Распределение по нормализованным категориям из semantic analysis.</p>
{% if metrics.call_category_breakdown.rows %}
<table>
<thead>
<tr>
<th>Категория</th>
<th>Звонки</th>
<th>Доля</th>
<th>Пред. период</th>
<th>Δ звонков</th>
<th>Пример</th>
</tr>
</thead>
<tbody>
{% for row in metrics.call_category_breakdown.rows %}
<tr>
<td>{{ row.name }}</td>
<td>{{ row.count }}</td>
<td>{{ row.share }}%</td>
<td>{{ row.previous_count }}</td>
<td>{{ row.delta_count }}</td>
<td>{{ row.example_summary or "—" }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>Нет данных по категориям звонков.</p>
{% endif %}
</section>
<section class="section">
<h2 class="section-title">4. Ожидания, проблемы и запросы клиентов</h2>
<p class="section-subtitle">Повторяющиеся ожидания клиента, болевые точки и явные запросы.</p>
<div class="grid-3">
<div class="split-card">
<div class="kpi-label">Ожидания</div>
<ul class="mini-list">
{% for row in metrics.client_expectations_and_needs.expectations %}
<li>{{ row.name }} — {{ row.count }} ({{ row.share }}%)</li>
{% else %}
<li>нет данных</li>
{% endfor %}
</ul>
</div>
<div class="split-card">
<div class="kpi-label">Проблемы</div>
<ul class="mini-list">
{% for row in metrics.client_expectations_and_needs.problems %}
<li>{{ row.name }} — {{ row.count }} ({{ row.share }}%)</li>
{% else %}
<li>нет данных</li>
{% endfor %}
</ul>
</div>
<div class="split-card">
<div class="kpi-label">Запросы</div>
<ul class="mini-list">
{% for row in metrics.client_expectations_and_needs.requests %}
<li>{{ row.name }} — {{ row.count }} ({{ row.share }}%)</li>
{% else %}
<li>нет данных</li>
{% endfor %}
</ul>
</div>
</div>
</section>
<section class="section">
<h2 class="section-title">5. Частотность возражений/барьеров</h2>
<p class="section-subtitle">Ключевые барьеры в диалогах и доля звонков, где они возникали.</p>
<div class="callout {% if metrics.objection_frequency.share_pct >= 30 %}warn{% else %}neutral{% endif %}">
Звонки с возражениями: {{ metrics.objection_frequency.calls_with_objections }} ({{ metrics.objection_frequency.share_pct }}%)
</div>
{% if metrics.objection_frequency.rows %}
<table style="margin-top:16px;">
<thead>
<tr>
<th>Возражение / барьер</th>
<th>Частота</th>
<th>Доля</th>
<th>Пред. период</th>
<th>Δ</th>
</tr>
</thead>
<tbody>
{% for row in metrics.objection_frequency.rows %}
<tr>
<td>{{ row.name }}</td>
<td>{{ row.count }}</td>
<td>{{ row.share }}%</td>
<td>{{ row.previous_count }}</td>
<td>{{ row.delta_count }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>Возражения и барьеры не выделены.</p>
{% endif %}
</section>
<section class="section">
<h2 class="section-title">6. Профили клиентов по сегментам</h2>
<p class="section-subtitle">Сегменты клиентов, объём, средний score и типовые темы внутри сегмента.</p>
{% if metrics.customer_segments.rows %}
<table>
<thead>
<tr>
<th>Сегмент</th>
<th>Звонки</th>
<th>Доля</th>
<th>Средний score</th>
<th>Топ категории</th>
<th>Топ проблемы</th>
</tr>
</thead>
<tbody>
{% for row in metrics.customer_segments.rows %}
<tr>
<td>{{ row.segment }}</td>
<td>{{ row.calls }}</td>
<td>{{ row.share }}%</td>
<td>{{ row.avg_score if row.avg_score is not none else "—" }}</td>
<td>{{ row.top_categories | join(", ") if row.top_categories else "нет данных" }}</td>
<td>{{ row.top_problems | join(", ") if row.top_problems else "нет данных" }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>Сегментация клиентов недоступна.</p>
{% endif %}
</section>
<section class="section">
<h2 class="section-title">7. Готовность менеджеров к переговорам</h2>
<p class="section-subtitle">Распределение readiness по звонкам и связь с результатами менеджеров.</p>
<div class="grid-2">
<div class="split-card">
<div class="kpi-label">Распределение readiness</div>
<ul class="mini-list">
{% for row in metrics.manager_readiness.rows %}
<li>{{ row.name }} — {{ row.count }} ({{ row.share }}%)</li>
{% else %}
<li>нет данных</li>
{% endfor %}
</ul>
</div>
<div class="split-card">
<div class="kpi-label">Связь с менеджерами</div>
<ul class="mini-list">
{% for row in metrics.manager_readiness.manager_rows[:5] %}
<li>{{ row.user_id }}: high {{ row.readiness_distribution.high }}, medium {{ row.readiness_distribution.medium }}, low {{ row.readiness_distribution.low }}</li>
{% else %}
<li>нет данных</li>
{% endfor %}
</ul>
</div>
</div>
</section>
<section class="section">
<h2 class="section-title">8. Тренды взаимодействия с клиентами</h2>
<p class="section-subtitle">Сравнение текущего окна с предыдущим периодом такой же длины.</p>
<table>
<thead>
<tr>
<th>Показатель</th>
<th>Текущий</th>
<th>Предыдущий</th>
<th>Δ</th>
</tr>
</thead>
<tbody>
{% for item in metrics.interaction_trends.window_comparison %}
<tr>
<td>{{ item.label }}</td>
<td>{{ item.current if item.current is not none else "—" }}</td>
<td>{{ item.previous if item.previous is not none else "—" }}</td>
<td>{{ item.delta if item.delta is not none else "—" }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</section>
<section class="section">
<h2 class="section-title">9. Как компания выглядит в глазах клиентов</h2>
<p class="section-subtitle">Восприятие компании клиентами и типовые причины негативных или смешанных оценок.</p>
<div class="grid-2">
<div class="split-card">
<div class="kpi-label">Распределение perception</div>
<ul class="mini-list">
{% for row in metrics.company_perception.rows %}
<li>{{ row.name }} — {{ row.count }} ({{ row.share }}%)</li>
{% else %}
<li>нет данных</li>
{% endfor %}
</ul>
</div>
<div class="split-card">
<div class="kpi-label">Причины perception</div>
<ul class="mini-list">
{% for row in metrics.company_perception.reasons %}
<li>{{ row.name }} — {{ row.count }}</li>
{% else %}
<li>нет данных</li>
{% endfor %}
</ul>
</div>
</div>
</section>
<section class="section">
<h2 class="section-title">10. Рекомендации и мероприятия по устранению недостатков</h2>
<p class="section-subtitle">Агрегированные меры по процессам, менеджерам и клиентским сценариям.</p>
<div class="grid-3">
<div class="split-card">
<div class="kpi-label">Процессы</div>
<ul class="mini-list">
{% for row in metrics.improvement_program.process_actions %}
<li>{{ row.action }} — {{ row.count }}</li>
{% else %}
<li>нет данных</li>
{% endfor %}
</ul>
</div>
<div class="split-card">
<div class="kpi-label">Менеджеры</div>
<ul class="mini-list">
{% for row in metrics.improvement_program.manager_actions %}
<li>{{ row.action }} — {{ row.count }}</li>
{% else %}
<li>нет данных</li>
{% endfor %}
</ul>
</div>
<div class="split-card">
<div class="kpi-label">Клиентские сценарии</div>
<ul class="mini-list">
{% for row in metrics.improvement_program.client_scenario_actions %}
<li>{{ row.action }} — {{ row.count }}</li>
{% else %}
<li>нет данных</li>
{% endfor %}
</ul>
</div>
</div>
</section>
</div>
{% endblock %}

View File

@ -104,11 +104,9 @@ Modes:
the voximplant checkpoint is rewound so the selected day is
eligible for collection again.
--repair Scan the DB for calls with incomplete analyzer/reporter outputs
and heal them in one pass. Analyzer outputs are regenerated
first, then missing per-call HTML reports are rebuilt. When
--from-date is supplied, all report_detail.html files and daily
summary reports from that UTC date onward are regenerated.
--repair Scan the DB for calls with incomplete analyzer outputs.
When --from-date is supplied, daily DOCX reports from that
date onward are regenerated after analyzer repair.
--list Show matching calls without changing anything.
@ -401,33 +399,29 @@ def _do_recollect(records, rewind_day=None) -> None:
print(" systemctl start voice-collector.service")
def _do_repair(records, from_day=None) -> None:
"""Heal incomplete analyzer/reporter outputs in a single pass."""
def _do_repair(records, from_day=None) -> None:
"""Heal incomplete analyzer outputs and optionally rebuild daily reports."""
from analyzer.main import _analysis_outputs_missing, process_call
from core.config import get_config
from reporter.main import _report_detail_missing, repair_report_detail
cfg = get_config()
expect_analysis = bool(cfg.analyzer.script_files)
if from_day is not None:
analyzer_targets = []
reporter_targets = list(records)
else:
analyzer_targets = [
rec for rec in records if _analysis_outputs_missing(rec, expect_analysis)
]
reporter_targets = [rec for rec in records if _report_detail_missing(rec)]
if from_day is not None:
analyzer_targets = []
else:
analyzer_targets = [
rec for rec in records if _analysis_outputs_missing(rec, expect_analysis)
]
if not analyzer_targets and not reporter_targets:
print("No incomplete analyzer/reporter outputs found.")
return
if not analyzer_targets and from_day is None:
print("No incomplete analyzer outputs found.")
return
print(
"Found "
f"{len(analyzer_targets)} analyzer repair target(s) and "
f"{len(reporter_targets)} reporter repair target(s)."
f"{len(analyzer_targets)} analyzer repair target(s)."
)
if analyzer_targets:
@ -449,58 +443,20 @@ def _do_repair(records, from_day=None) -> None:
print(f"Analyzer repair complete: {fixed}/{len(analyzer_targets)} healed.")
if from_day is None:
reporter_targets = [
rec
for rec in reporter_targets
if not _analysis_outputs_missing(rec, expect_analysis)
]
if reporter_targets and analyzer_targets:
print(
"\nReporter repair will only run for calls with analyzer outputs present."
)
if reporter_targets:
if from_day is None:
print("\nHealing reporter outputs...")
else:
print(
"\nForce-regenerating reporter outputs "
f"from {from_day.isoformat()} onward..."
)
fixed = 0
for rec in reporter_targets:
try:
repair_report_detail(rec)
fixed += 1
print(f" ✓ {rec.uniqueid} report_detail.html repaired")
except Exception as exc:
print(f" ✗ {rec.uniqueid} reporter repair failed: {exc}")
if from_day is None:
print(f"Reporter repair complete: {fixed}/{len(reporter_targets)} healed.")
else:
print(
"Reporter force regeneration complete: "
f"{fixed}/{len(reporter_targets)} rebuilt."
)
if from_day is not None:
if from_day is not None:
_regenerate_summaries_from(from_day)
def _regenerate_summaries_from(start_day) -> None:
from datetime import UTC, datetime, timedelta
from reporter.report_summary import generate_summary_report
def _regenerate_summaries_from(start_day) -> None:
from datetime import UTC, datetime, timedelta
from reporter.report import generate_daily_report
today = datetime.now(UTC).date()
current = start_day
regenerated = 0
while current <= today:
day_start = datetime(current.year, current.month, current.day, tzinfo=UTC)
day_end = day_start + timedelta(days=1)
generate_summary_report(date_from=day_start, date_to=day_end)
generate_daily_report(current)
regenerated += 1
current += timedelta(days=1)

View File

@ -40,6 +40,7 @@ fi
echo "==> Creating data directories"
mkdir -p \
"${DATA_DIR}/spool" \
"${DATA_DIR}/reporter" \
"${DATA_DIR}/reports" \
"${DATA_DIR}/analyzer-artifacts" \
"${DATA_DIR}/category" \
@ -93,6 +94,7 @@ for unit in \
voice-category.timer \
voice-dashboard.service \
voice-reporter.service \
voice-reporter.timer \
voice-importer.service
do
cp "${SCRIPT_DIR}/${unit}" "${UNIT_DIR}/"
@ -114,11 +116,12 @@ echo "==> Reloading systemd"
systemctl daemon-reload
echo "==> Enabling units"
systemctl disable --now voice-reporter.service 2>/dev/null || true
systemctl enable voice-collector.timer
systemctl enable voice-analyzer.timer
systemctl enable voice-category.timer
systemctl enable voice-dashboard.service
systemctl enable voice-reporter.service
systemctl enable voice-reporter.timer
systemctl enable voice-importer.service
# ── Summary ────────────────────────────────────────────────────────────────
@ -135,14 +138,14 @@ echo " systemctl start voice-collector.timer"
echo " systemctl start voice-analyzer.timer"
echo " systemctl start voice-category.timer"
echo " systemctl start voice-dashboard.service"
echo " systemctl start voice-reporter.service"
echo " systemctl start voice-reporter.timer"
echo " systemctl start voice-importer.service"
echo ""
echo " Check status:"
echo " systemctl status voice-collector.timer"
echo " systemctl status voice-analyzer.timer"
echo " systemctl status voice-dashboard.service"
echo " systemctl status voice-reporter.service"
echo " systemctl status voice-reporter.timer"
echo " systemctl status voice-importer.service"
echo ""
echo " Live logs:"

View File

@ -1,64 +1,32 @@
[Unit]
Description=Voice Pipeline — Reporter (long-running)
Documentation=file:/etc/voice-pipeline/config.toml
After=network-online.target
Wants=network-online.target
# Restart rate-limit: give up after 5 restarts in 5 minutes
StartLimitIntervalSec=300
StartLimitBurst=5
# Reporter reads artifacts written by the analyzer; start after it
After=voice-analyzer.service
[Service]
Type=simple
User=voice-pipeline
Group=voice-pipeline
# ── Environment ────────────────────────────────────────────────────────────
Environment=VOICE_PIPELINE_CONFIG=/etc/voice-pipeline/config.toml
# EnvironmentFile=/etc/voice-pipeline/secrets.env
# ── Process ────────────────────────────────────────────────────────────────
WorkingDirectory=/opt/voice-pipeline
ExecStart=/opt/voice-pipeline/venv/bin/voice-pipeline reporter
# ── Restart policy ─────────────────────────────────────────────────────────
Restart=on-failure
RestartSec=15s
# ── Logging ────────────────────────────────────────────────────────────────
StandardOutput=journal
StandardError=journal
SyslogIdentifier=voice-reporter
# ── Timeouts ───────────────────────────────────────────────────────────────
TimeoutStartSec=60s
# Bitrix24 API calls + Jinja2 rendering are fast; allow 60 s to flush
TimeoutStopSec=60s
# ── Resource limits ────────────────────────────────────────────────────────
# Reporter is lightweight — Jinja2 + JSON + httpx
MemoryMax=256M
CPUQuota=30%
LimitNOFILE=1024
# ── Security hardening ─────────────────────────────────────────────────────
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ReadOnlyPaths=/opt/voice-pipeline
# Needs to write reports/ and read spool/ — both under the data dir
ReadWritePaths=/var/lib/voice-pipeline
ReadOnlyPaths=/etc/voice-pipeline
ProtectHome=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
SystemCallFilter=@system-service @network-io @file-system
SystemCallErrorNumber=EPERM
RestrictRealtime=true
RestrictSUIDSGID=true
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
[Install]
WantedBy=multi-user.target
[Unit]
Description=Voice Pipeline - Daily DOCX report for the previous day
Documentation=file:/etc/voice-pipeline/config.toml
After=network-online.target postgresql.service voice-category.service
Wants=network-online.target
[Service]
Type=oneshot
User=voice-pipeline
Group=voice-pipeline
Environment=VOICE_PIPELINE_CONFIG=/etc/voice-pipeline/config.toml
WorkingDirectory=/opt/voice-pipeline
ExecStart=/opt/voice-pipeline/venv/bin/voice-pipeline reporter
StandardOutput=journal
StandardError=journal
SyslogIdentifier=voice-reporter
TimeoutStartSec=300
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ReadOnlyPaths=/opt/voice-pipeline /etc/voice-pipeline
ReadWritePaths=/var/lib/voice-pipeline
ProtectHome=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
RestrictRealtime=true
RestrictSUIDSGID=true
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
MemoryMax=256M
CPUQuota=30%
LimitNOFILE=1024

View File

@ -0,0 +1,11 @@
[Unit]
Description=Generate the daily voice report at 08:00
[Timer]
OnCalendar=*-*-* 08:00:00
Persistent=true
AccuracySec=1min
Unit=voice-reporter.service
[Install]
WantedBy=timers.target

View File

@ -1,364 +1,68 @@
from __future__ import annotations
import json
from datetime import UTC, datetime, timedelta
from pathlib import Path
from unittest.mock import MagicMock
from datetime import UTC, date, datetime
from types import SimpleNamespace
from zipfile import ZipFile
def _write_json(path: Path, data: object) -> None:
path.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
def _row(uniqueid: str, *, attention: bool = False):
category = SimpleNamespace(
uniqueid=uniqueid,
duration_s=120,
quality_score=80.0,
user_id="5",
user_name="Иван",
category="sale",
sentiment="negative" if attention else "positive",
relationship_risk="high" if attention else "low",
language="ru",
scorecard_greeting="yes",
scorecard_identified_need="yes",
scorecard_defined_next_step="no",
requires_attention=attention,
attention_reasons=["нет следующего шага"] if attention else [],
client_intents=["получить информацию"],
contact_reasons=["консультация"],
objections=[{"type": "нет времени"}] if attention else [],
client_segment="Розница",
manager_readiness="medium",
call_result="successful_contact",
company_perception="рабочее",
client_name="Клиент",
)
record = SimpleNamespace(
fetched_at=datetime(2026, 8, 12, 10, 0, tzinfo=UTC),
caller_phone="+79000000000",
)
return category, record
def _make_transcript(tmp_path: Path) -> Path:
transcript = {
"CALL_ID": "test-uid",
"MESSAGES": [
{"SIDE": "User", "START_TIME": 0, "STOP_TIME": 3, "MESSAGE": "Hello, how can I help?"},
{"SIDE": "Client", "START_TIME": 3, "STOP_TIME": 6, "MESSAGE": "I have a billing issue."},
{"SIDE": "User", "START_TIME": 6, "STOP_TIME": 10, "MESSAGE": "I'll sort that for you."},
{"SIDE": "Client", "START_TIME": 10, "STOP_TIME": 13, "MESSAGE": "Thank you very much."},
],
}
p = tmp_path / "transcript.json"
_write_json(p, transcript)
return p
def test_daily_docx_contains_sample_sections(tmp_path, monkeypatch):
from reporter.report import build_report, output_path
config = SimpleNamespace(
reporter=SimpleNamespace(output_root=None),
storage=SimpleNamespace(spool_root=tmp_path / "spool"),
)
monkeypatch.setattr("reporter.report.get_config", lambda: config)
day = date(2026, 8, 12)
path = build_report(day, [_row("call-1"), _row("call-2", attention=True)]).save(
output_path(day)
)
assert path == tmp_path / "reporter" / "2026-08-12" / "report.docx"
assert path.is_file()
with ZipFile(path) as archive:
xml = archive.read("word/document.xml").decode()
assert "Сводный отчёт" in xml
assert "4. Количественные показатели по менеджерам" in xml
assert "13. Перечень звонков, требующих внимания" in xml
assert "call-2" in xml
def _make_analysis(tmp_path: Path, score: int = 80) -> Path:
data = {
"script_id": "inbound_v1",
"score": score,
"summary": "Agent handled the call professionally.",
"bitrix_summary": f"Score {score}/100. Passed 2/3. Agent handled the call professionally.",
"passed_count": 2,
"total_count": 3,
"semantic_analysis": {
"call_category": "billing",
"client_expectations": ["Resolve billing issue quickly"],
"client_problems": ["Billing mismatch"],
"client_requests": ["Confirm corrected invoice"],
"objections_or_barriers": ["Does not want repeated callbacks"],
"customer_segment": "existing_client",
"manager_readiness": "high" if score >= 70 else "low",
"company_perception": "positive" if score >= 70 else "mixed",
"company_perception_reasons": ["Agent responded clearly"],
"improvement_actions": ["Confirm next step explicitly"],
},
"checklist": [
{"item": "Greet with name", "passed": True, "evidence": "Hello, how can I help?"},
{"item": "Resolve issue", "passed": True, "evidence": "I'll sort that"},
{"item": "Confirm closure", "passed": False, "evidence": None},
],
}
p = tmp_path / "analysis.json"
_write_json(p, data)
return p
def test_reporter_uses_previous_local_day():
from reporter.main import previous_local_day
def _make_insights(tmp_path: Path, score: int = 80) -> Path:
data = {
"artifact_kind": "semantic_insights",
"version": "v1",
"degraded": False,
"executive_summary": "Клиент уточняет вопрос по биллингу и ожидает быстрое решение.",
"call_classification": {
"primary_category": "billing",
"secondary_categories": ["follow_up"],
"intent": "Подтвердить корректный счет",
"resolution_status": "resolved" if score >= 70 else "callback_required",
},
"customer_needs": {
"expectations": ["Быстро решить вопрос"],
"requests": ["Подтвердить корректный счет"],
"complaints": ["Ошибка в начислении"],
"objections": ["Не хочет повторных звонков"],
"pain_points": ["Несовпадение в счете"],
},
"agent_compliance": {
"script_fit": "high" if score >= 70 else "low",
"detected_script_type": "inbound_v1",
"compliance_gaps": ["Подтвердить следующий шаг"],
"strong_moves": ["Агент быстро объяснил решение"],
},
"risk_assessment": {
"conflict_detected": score < 70,
"conflict_stage": "open" if score < 70 else "none",
"business_risks": ["refund"] if score < 70 else [],
"risk_level": "high" if score < 70 else "low",
"risk_rationale": "Есть риск перерастания жалобы." if score < 70 else "Существенных рисков нет.",
},
"customer_profile": {
"business_segment": "smb",
"relationship_stage": "existing_customer",
"industry_hint": "retail",
},
"next_best_action": {
"owner": "agent",
"action": "Подтвердить клиенту закрытие вопроса в CRM.",
"due_priority": "high" if score < 70 else "normal",
},
}
p = tmp_path / "insights.json"
_write_json(p, data)
return p
class TestReportDetailHelpers:
def test_format_duration(self):
from reporter.report_detail import _format_duration
assert _format_duration(90) == "1:30"
assert _format_duration(0) == "0:00"
assert _format_duration(3661) == "61:01"
def test_format_timestamp(self):
from reporter.report_detail import _format_timestamp
assert _format_timestamp(0.0) == "00:00"
assert _format_timestamp(65.9) == "01:05"
def test_score_color(self):
from reporter.report_detail import _score_color
assert _score_color(85) == "#2d8a4e"
assert _score_color(65) == "#d97706"
assert _score_color(40) == "#dc2626"
class TestReporterCompatibility:
def test_reporter_accepts_new_emotion_artifact_format(self):
from reporter.analytics import _emotion_distribution, _emotion_dominant, _emotion_per_speaker
payload = {
"utterances_total": 12,
"emotions": {
"neutral": {"total": 12, "share": 1.0, "by_speaker": {"agent": 6, "customer": 6}}
},
}
assert _emotion_distribution(payload) == {"neutral": 12}
assert _emotion_per_speaker(payload) == {"agent": {"neutral": 6}, "customer": {"neutral": 6}}
assert _emotion_dominant(payload, {"neutral": 12}) == "neutral"
def test_reporter_falls_back_to_artifact_context_for_bitrix_identity(self):
from reporter.analytics import _normalize_identity
record = MagicMock()
record.uniqueid = "uid-1"
record.source = "bitrix24"
record.direction = "inbound"
record.user_id = None
record.entity_type = None
record.entity_id = None
record.caller_phone = None
transcript = {
"CALL_ID": "vx-001",
"MESSAGES": [],
"artifact_context": {
"external_call_id": "ext-001",
"voximplant_call_id": "vx-001",
"crm_activity_id": "act-001",
"crm_entity_type": "LEAD",
"crm_entity_id": "501",
"caller_phone": "+79990001122",
"bitrix_fields": {
"CRM_ACTIVITY_ID": "act-001",
"CRM_ENTITY_TYPE": "LEAD",
"CRM_ENTITY_ID": "501",
},
},
}
identity = _normalize_identity(record, {}, {}, transcript, {})
assert identity["crm_activity_id"] == "act-001"
assert identity["entity_type"] == "LEAD"
assert identity["entity_id"] == "501"
assert identity["caller_phone"] == "+79990001122"
class TestAggregate:
def _make_record(
self,
tmp_path: Path,
user_id: str,
score: int | None = None,
direction: str = "inbound",
transcript_override: dict[str, object] | None = None,
):
uid_dir = tmp_path / f"uid_{user_id}_{score}_{direction}"
uid_dir.mkdir(exist_ok=True)
if transcript_override is None:
_make_transcript(uid_dir)
else:
_write_json(uid_dir / "transcript.json", transcript_override)
if score is not None:
_make_analysis(uid_dir, score=score)
_make_insights(uid_dir, score=score or 80)
rec = MagicMock()
rec.uniqueid = f"uid_{user_id}_{score}_{direction}"
rec.source = "bitrix24"
rec.user_id = user_id
rec.direction = direction
rec.status = "reported"
rec.caller_phone = "+79990001122"
rec.entity_type = "CONTACT"
rec.entity_id = "999"
rec.duration_s = 13
rec.transcript_path = uid_dir / "transcript.json"
rec.analysis_path = uid_dir / "analysis.json"
rec.meta_path = uid_dir / "meta.json"
rec.conversation_path = uid_dir / "conversation.json"
rec.emotion_path = uid_dir / "emotion.json"
rec.insights_path = uid_dir / "insights.json"
rec.spool_path = uid_dir
rec.report_detail_path = uid_dir / "report_detail.html"
_write_json(rec.meta_path, {"direction": direction, "caller_phone": "+79990001122"})
_write_json(
rec.conversation_path,
{
"artifact_context": {
"crm_activity_id": "act-1",
"crm_entity_type": "CONTACT",
"crm_entity_id": "999",
"user_id": user_id,
"caller_phone": "+79990001122",
}
},
)
_write_json(rec.emotion_path, {"distribution": {"positive": 1, "neutral": 3}})
return rec
def test_empty(self):
from reporter.report_summary import _aggregate
result = _aggregate([])
assert result["total_calls"] == 0
assert result["avg_score"] is None
assert result["attention_calls"] == []
assert "manager_quantitative_metrics" in result
def test_scores_averaged(self, tmp_path: Path):
from reporter.report_summary import _aggregate
records = [
self._make_record(tmp_path, "u1", score=80),
self._make_record(tmp_path, "u1", score=60),
self._make_record(tmp_path, "u2", score=70),
]
result = _aggregate(records)
assert result["total_calls"] == 3
assert result["avg_score"] == 70.0
assert result["scored_calls"] == 3
assert result["median_score"] == 70.0
def test_per_agent_breakdown(self, tmp_path: Path):
from reporter.report_summary import _aggregate
records = [
self._make_record(tmp_path, "u1", score=90),
self._make_record(tmp_path, "u1", score=70),
self._make_record(tmp_path, "u2", score=50),
]
result = _aggregate(records)
agents = {a["user_id"]: a for a in result["agents"]}
assert agents["u1"]["calls"] == 2
assert agents["u1"]["avg_score"] == 80.0
assert result["manager_quantitative_metrics"]["rows"]
def test_summary_contains_new_section_payloads(self, tmp_path: Path):
from reporter.analytics import build_summary_metrics
current = [
self._make_record(tmp_path, "u1", score=90),
self._make_record(tmp_path, "u2", score=55),
]
previous = [self._make_record(tmp_path, "u3", score=70)]
result = build_summary_metrics(current, previous_records=previous)
assert result["call_category_breakdown"]["rows"]
assert result["client_expectations_and_needs"]["expectations"]
assert "rows" in result["objection_frequency"]
assert "rows" in result["customer_segments"]
assert "rows" in result["risk_breakdown"]
assert "items" in result["follow_up_queue"]
assert "rows" in result["manager_readiness"]
assert result["interaction_trends"]["window_comparison"]
assert "all_actions" in result["improvement_program"]
class TestReporterContexts:
def test_detail_context_contains_summary_linked_fields(self, tmp_path: Path):
from reporter.analytics import build_detail_context
helper = TestAggregate()
record = helper._make_record(tmp_path, "u42", score=78)
context = build_detail_context(record)
assert context["call_kpis"]
assert context["summary_link_rows"]
assert context["quality_bucket"]["label"]
assert "bitrix_linkage" in context
assert context["transcript_timeline"]
assert context["semantic_analysis"]["call_category"] == "billing"
assert context["semantic_analysis"]["customer_segment"] == "smb"
assert context["semantic_analysis"]["next_action_text"]
def test_summary_and_detail_templates_render_new_sections(self, tmp_path: Path):
from jinja2 import Environment, FileSystemLoader, select_autoescape
from reporter.analytics import build_detail_context, build_summary_metrics
from reporter.report_detail import _TEMPLATES_DIR as templates_dir
helper = TestAggregate()
record = helper._make_record(tmp_path, "u77", score=55)
summary_metrics = build_summary_metrics([record])
detail_context = build_detail_context(record)
env = Environment(
loader=FileSystemLoader(str(templates_dir)),
autoescape=select_autoescape(["html"]),
)
summary_html = env.get_template("report_summary.html.j2").render(
date_from=datetime.now(UTC) - timedelta(days=1),
date_to=datetime.now(UTC),
previous_date_from=datetime.now(UTC) - timedelta(days=2),
previous_date_to=datetime.now(UTC) - timedelta(days=1),
metrics=summary_metrics,
records=[record],
generated_at=datetime.now(UTC),
)
detail_html = env.get_template("report_detail.html.j2").render(
**detail_context,
generated_at=datetime.now(UTC),
)
assert "Управленческое резюме" in summary_html
assert "Количественные показатели по менеджерам" in summary_html
assert "Ожидания, проблемы и запросы клиентов" in summary_html
assert "Как компания выглядит в глазах клиентов" in summary_html
assert "Как звонок влияет на сводный отчёт" in detail_html
assert "Семантические признаки для сводного отчёта" in detail_html
assert "Таймлайн и полная транскрипция" in detail_html
class TestShouldGenerateSummary:
def test_none_always_true(self):
from reporter.main import _should_generate_summary
assert _should_generate_summary(None) is True
def test_today_is_false(self):
from reporter.main import _should_generate_summary
now = datetime.now(UTC)
assert _should_generate_summary(now) is False
def test_yesterday_is_true(self):
from reporter.main import _should_generate_summary
yesterday = datetime.now(UTC) - timedelta(days=1)
assert _should_generate_summary(yesterday) is True
assert previous_local_day(datetime(2026, 8, 13, 8, 0).astimezone()) == date(
2026, 8, 12
)