Добавление функциональности включения транскрипции разговора в поле "Заметки" карточки лида/контакта/клиента
This commit is contained in:
parent
88010e9dbf
commit
392a1637d5
|
|
@ -65,3 +65,4 @@ recordings_dir = "/home/ilgiz/projects/b24calls/data/bitrix24/recordings"
|
|||
download_recordings = true
|
||||
enrich_users = true
|
||||
timeout_seconds = 30.0
|
||||
max_note_chars = 8000
|
||||
|
|
|
|||
|
|
@ -0,0 +1,646 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime, timezone, tzinfo
|
||||
from hashlib import sha256
|
||||
from pathlib import Path
|
||||
from typing import Any, Mapping
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
|
||||
from .config import Bitrix24Config
|
||||
from .db.storage import CRMNoteSyncRecord, SQLiteStorage
|
||||
from .direction import direction_matches_filter, normalize_call_direction
|
||||
from .export.document import CallResultDocument
|
||||
from .sources.bitrix24 import (
|
||||
Bitrix24Error,
|
||||
Bitrix24RestClient,
|
||||
normalize_window,
|
||||
parse_bitrix24_datetime,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
NOTE_MODE_FULL_TRANSCRIPT = "full_transcript"
|
||||
NOTE_BEGIN_MARKER = "<<B24CALLS_SYNC v1 BEGIN>>"
|
||||
NOTE_END_MARKER = "<<B24CALLS_SYNC v1 END>>"
|
||||
|
||||
ENTITY_TYPE_IDS: dict[str, int] = {
|
||||
"LEAD": 1,
|
||||
"DEAL": 2,
|
||||
"CONTACT": 3,
|
||||
"COMPANY": 4,
|
||||
"QUOTE": 7,
|
||||
}
|
||||
|
||||
SYNC_BLOCK_PATTERN = re.compile(
|
||||
rf"(?ms)^{re.escape(NOTE_BEGIN_MARKER)}\n.*?^{re.escape(NOTE_END_MARKER)}\n?"
|
||||
)
|
||||
SYNC_AUDIO_ID_PATTERN = re.compile(r"^audio_file_id=(\d+)$", re.MULTILINE)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Bitrix24NoteSyncSelection:
|
||||
audio_file_id: int | None = None
|
||||
source_id: str | None = None
|
||||
start: date | datetime | None = None
|
||||
end: date | datetime | None = None
|
||||
direction: str = "all"
|
||||
limit: int | None = None
|
||||
dry_run: bool = False
|
||||
force: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Bitrix24NoteSyncEntry:
|
||||
audio_file_id: int
|
||||
source_id: str
|
||||
crm_entity_type: str | None
|
||||
crm_entity_id: str | None
|
||||
status: str
|
||||
message: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Bitrix24NoteSyncSummary:
|
||||
scanned: int = 0
|
||||
synced: int = 0
|
||||
dry_run: int = 0
|
||||
skipped_existing: int = 0
|
||||
skipped_missing_transcript: int = 0
|
||||
skipped_missing_crm_link: int = 0
|
||||
skipped_direction: int = 0
|
||||
skipped_length: int = 0
|
||||
skipped_unsupported_entity: int = 0
|
||||
failed: int = 0
|
||||
entries: tuple[Bitrix24NoteSyncEntry, ...] = field(default_factory=tuple)
|
||||
|
||||
|
||||
def _json_dumps(value: Any) -> str:
|
||||
return json.dumps(value, ensure_ascii=False, sort_keys=True, default=str)
|
||||
|
||||
|
||||
def _load_json(raw: str | None) -> dict[str, Any]:
|
||||
if not raw:
|
||||
return {}
|
||||
try:
|
||||
loaded = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
return {}
|
||||
return loaded if isinstance(loaded, dict) else {}
|
||||
|
||||
|
||||
def _system_timezone() -> tzinfo:
|
||||
return datetime.now().astimezone().tzinfo or timezone.utc
|
||||
|
||||
|
||||
def _normalize_datetime(value: date | datetime | None) -> datetime | None:
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
if value.tzinfo is None:
|
||||
return value.replace(tzinfo=_system_timezone())
|
||||
return value.astimezone(_system_timezone())
|
||||
return datetime.combine(value, datetime.min.time(), tzinfo=_system_timezone())
|
||||
|
||||
|
||||
def _parse_transcript_file(path: Path) -> CallResultDocument:
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
if not isinstance(payload, dict):
|
||||
raise Bitrix24Error(f"transcript artifact is not a JSON object: {path}")
|
||||
return CallResultDocument.from_payload(payload)
|
||||
|
||||
|
||||
def _find_bitrix24_call(value: Mapping[str, Any] | None) -> dict[str, Any]:
|
||||
if value is None:
|
||||
return {}
|
||||
stack: list[Any] = [value]
|
||||
while stack:
|
||||
current = stack.pop()
|
||||
if not isinstance(current, Mapping):
|
||||
continue
|
||||
nested = current.get("bitrix24_call")
|
||||
if isinstance(nested, Mapping):
|
||||
return dict(nested)
|
||||
for item in current.values():
|
||||
if isinstance(item, Mapping):
|
||||
stack.append(item)
|
||||
elif isinstance(item, list):
|
||||
stack.extend([child for child in item if isinstance(child, Mapping)])
|
||||
return {}
|
||||
|
||||
|
||||
def _extract_call_started_at(document: CallResultDocument, call_row: Mapping[str, Any] | None) -> datetime | None:
|
||||
if call_row is not None:
|
||||
started = parse_bitrix24_datetime(call_row.get("call_started_at"))
|
||||
if started is not None:
|
||||
return started
|
||||
source_metadata = document.source_metadata
|
||||
bitrix24_call = _find_bitrix24_call(source_metadata)
|
||||
return parse_bitrix24_datetime(bitrix24_call.get("CALL_START_DATE"))
|
||||
|
||||
|
||||
def _extract_bitrix24_call(document: CallResultDocument) -> dict[str, Any]:
|
||||
source_metadata = document.source_metadata
|
||||
return _find_bitrix24_call(source_metadata)
|
||||
|
||||
|
||||
def _extract_entity_type_id(entity_type: str) -> int | None:
|
||||
return ENTITY_TYPE_IDS.get(entity_type.upper())
|
||||
|
||||
|
||||
def _extract_comments(item: Mapping[str, Any]) -> str:
|
||||
value = item.get("comments")
|
||||
if value is None:
|
||||
return ""
|
||||
return str(value)
|
||||
|
||||
|
||||
def _transcript_sha256(text: str) -> str:
|
||||
return sha256(text.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _format_note_block(
|
||||
*,
|
||||
audio_file_id: int,
|
||||
source_type: str,
|
||||
source_id: str,
|
||||
crm_entity_type: str,
|
||||
crm_entity_id: str,
|
||||
note_mode: str,
|
||||
transcript_sha256: str,
|
||||
call_started_at: datetime | None,
|
||||
synced_at: datetime,
|
||||
transcript_text: str,
|
||||
) -> str:
|
||||
lines = [
|
||||
NOTE_BEGIN_MARKER,
|
||||
f"audio_file_id={audio_file_id}",
|
||||
f"source_type={source_type}",
|
||||
f"source_id={source_id}",
|
||||
f"crm_entity_type={crm_entity_type}",
|
||||
f"crm_entity_id={crm_entity_id}",
|
||||
f"note_mode={note_mode}",
|
||||
f"transcript_sha256={transcript_sha256}",
|
||||
f"call_started_at={call_started_at.isoformat() if call_started_at else ''}",
|
||||
f"synced_at={synced_at.isoformat()}",
|
||||
"---",
|
||||
transcript_text.strip(),
|
||||
NOTE_END_MARKER,
|
||||
]
|
||||
return "\n".join(lines).rstrip() + "\n"
|
||||
|
||||
|
||||
def _extract_audio_file_id_from_block(block: str) -> int | None:
|
||||
match = SYNC_AUDIO_ID_PATTERN.search(block)
|
||||
if match is None:
|
||||
return None
|
||||
try:
|
||||
return int(match.group(1))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _merge_sync_block(existing_comments: str, new_block: str, audio_file_id: int) -> str:
|
||||
if not existing_comments.strip():
|
||||
return new_block
|
||||
|
||||
parts: list[str] = []
|
||||
last_end = 0
|
||||
replaced = False
|
||||
for match in SYNC_BLOCK_PATTERN.finditer(existing_comments):
|
||||
parts.append(existing_comments[last_end : match.start()])
|
||||
block = match.group(0)
|
||||
block_audio_file_id = _extract_audio_file_id_from_block(block)
|
||||
if block_audio_file_id == audio_file_id:
|
||||
if not replaced:
|
||||
parts.append(new_block)
|
||||
replaced = True
|
||||
else:
|
||||
pass
|
||||
else:
|
||||
parts.append(block)
|
||||
last_end = match.end()
|
||||
parts.append(existing_comments[last_end:])
|
||||
merged = "".join(parts)
|
||||
if replaced:
|
||||
return merged.rstrip()
|
||||
|
||||
if merged.strip():
|
||||
separator = "" if merged.endswith("\n\n") else ("\n" if merged.endswith("\n") else "\n\n")
|
||||
return merged.rstrip() + separator + new_block
|
||||
return new_block
|
||||
|
||||
|
||||
def _load_transcript_row(
|
||||
storage: SQLiteStorage, audio_file_id: int
|
||||
) -> tuple[Mapping[str, Any], Path, CallResultDocument]:
|
||||
with storage.connect() as connection:
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT a.id AS audio_file_id,
|
||||
a.source_type,
|
||||
a.source_id,
|
||||
a.direction,
|
||||
a.validation_status,
|
||||
a.file_path AS audio_file_path,
|
||||
a.metadata_json AS audio_metadata_json,
|
||||
c.call_started_at,
|
||||
c.call_finished_at,
|
||||
ar.file_path AS transcript_file_path
|
||||
FROM audio_files AS a
|
||||
JOIN artifacts AS ar
|
||||
ON ar.audio_file_id = a.id
|
||||
AND ar.kind = 'transcript'
|
||||
AND ar.format = 'json'
|
||||
LEFT JOIN calls AS c
|
||||
ON c.id = a.call_id
|
||||
WHERE a.id = ?
|
||||
AND a.source_type = 'bitrix24'
|
||||
LIMIT 1
|
||||
""",
|
||||
(audio_file_id,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise Bitrix24Error(f"bitrix24 transcript artifact not found for audio_file_id={audio_file_id}")
|
||||
transcript_path = Path(str(row["transcript_file_path"]))
|
||||
if not transcript_path.exists():
|
||||
raise Bitrix24Error(f"transcript artifact file does not exist: {transcript_path}")
|
||||
document = _parse_transcript_file(transcript_path)
|
||||
return dict(row), transcript_path, document
|
||||
|
||||
|
||||
def _select_transcript_rows(
|
||||
storage: SQLiteStorage,
|
||||
*,
|
||||
direction: str,
|
||||
start: date | datetime | None,
|
||||
end: date | datetime | None,
|
||||
limit: int | None,
|
||||
) -> list[dict[str, Any]]:
|
||||
with storage.connect() as connection:
|
||||
rows = connection.execute(
|
||||
"""
|
||||
SELECT a.id AS audio_file_id,
|
||||
a.source_type,
|
||||
a.source_id,
|
||||
a.direction,
|
||||
a.validation_status,
|
||||
a.file_path AS audio_file_path,
|
||||
a.metadata_json AS audio_metadata_json,
|
||||
c.call_started_at,
|
||||
c.call_finished_at,
|
||||
ar.file_path AS transcript_file_path
|
||||
FROM audio_files AS a
|
||||
JOIN artifacts AS ar
|
||||
ON ar.audio_file_id = a.id
|
||||
AND ar.kind = 'transcript'
|
||||
AND ar.format = 'json'
|
||||
LEFT JOIN calls AS c
|
||||
ON c.id = a.call_id
|
||||
WHERE a.source_type = 'bitrix24'
|
||||
AND a.validation_status = 'done'
|
||||
ORDER BY COALESCE(c.call_started_at, a.updated_at) ASC, a.id ASC
|
||||
""",
|
||||
).fetchall()
|
||||
|
||||
start_dt: datetime | None = None
|
||||
end_dt: datetime | None = None
|
||||
if start is not None or end is not None:
|
||||
start_dt, end_dt = normalize_window(start, end)
|
||||
selected: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
item = dict(row)
|
||||
item_direction = normalize_call_direction(str(item.get("direction") or "unknown"))
|
||||
if not direction_matches_filter(item_direction, direction):
|
||||
continue
|
||||
|
||||
transcript_path = Path(str(item["transcript_file_path"]))
|
||||
if not transcript_path.exists():
|
||||
continue
|
||||
document = _parse_transcript_file(transcript_path)
|
||||
call_started_at = _extract_call_started_at(document, item)
|
||||
if start_dt is not None or end_dt is not None:
|
||||
if call_started_at is None:
|
||||
continue
|
||||
if start_dt is not None and call_started_at < start_dt:
|
||||
continue
|
||||
if end_dt is not None and call_started_at > end_dt:
|
||||
continue
|
||||
item["call_started_at_dt"] = call_started_at
|
||||
item["transcript_document"] = document
|
||||
item["transcript_path"] = transcript_path
|
||||
selected.append(item)
|
||||
if limit is not None and len(selected) >= limit:
|
||||
break
|
||||
return selected
|
||||
|
||||
|
||||
def _load_exact_selection(
|
||||
storage: SQLiteStorage,
|
||||
*,
|
||||
audio_file_id: int | None,
|
||||
source_id: str | None,
|
||||
) -> list[dict[str, Any]]:
|
||||
if audio_file_id is not None:
|
||||
row, transcript_path, document = _load_transcript_row(storage, audio_file_id)
|
||||
row["call_started_at_dt"] = _extract_call_started_at(document, row)
|
||||
row["transcript_document"] = document
|
||||
row["transcript_path"] = transcript_path
|
||||
return [row]
|
||||
|
||||
if source_id is None:
|
||||
return []
|
||||
|
||||
with storage.connect() as connection:
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT a.id AS audio_file_id,
|
||||
a.source_type,
|
||||
a.source_id,
|
||||
a.direction,
|
||||
a.validation_status,
|
||||
a.file_path AS audio_file_path,
|
||||
a.metadata_json AS audio_metadata_json,
|
||||
c.call_started_at,
|
||||
c.call_finished_at,
|
||||
ar.file_path AS transcript_file_path
|
||||
FROM audio_files AS a
|
||||
JOIN artifacts AS ar
|
||||
ON ar.audio_file_id = a.id
|
||||
AND ar.kind = 'transcript'
|
||||
AND ar.format = 'json'
|
||||
LEFT JOIN calls AS c
|
||||
ON c.id = a.call_id
|
||||
WHERE a.source_type = 'bitrix24'
|
||||
AND a.source_id = ?
|
||||
LIMIT 1
|
||||
""",
|
||||
(source_id,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return []
|
||||
item = dict(row)
|
||||
transcript_path = Path(str(item["transcript_file_path"]))
|
||||
document = _parse_transcript_file(transcript_path)
|
||||
item["call_started_at_dt"] = _extract_call_started_at(document, item)
|
||||
item["transcript_document"] = document
|
||||
item["transcript_path"] = transcript_path
|
||||
return [item]
|
||||
|
||||
|
||||
def _sync_single_note(
|
||||
*,
|
||||
storage: SQLiteStorage,
|
||||
client: Bitrix24RestClient,
|
||||
config: Bitrix24Config,
|
||||
row: Mapping[str, Any],
|
||||
force: bool,
|
||||
) -> Bitrix24NoteSyncEntry:
|
||||
audio_file_id = int(row["audio_file_id"])
|
||||
source_type = str(row["source_type"])
|
||||
source_id = str(row["source_id"])
|
||||
transcript_document = row["transcript_document"]
|
||||
assert isinstance(transcript_document, CallResultDocument)
|
||||
|
||||
transcript_text = transcript_document.transcript_text.strip()
|
||||
if not transcript_text:
|
||||
raise Bitrix24Error(f"empty transcript text for audio_file_id={audio_file_id}")
|
||||
|
||||
bitrix24_call = _extract_bitrix24_call(transcript_document)
|
||||
crm_entity_type = str(bitrix24_call.get("CRM_ENTITY_TYPE") or "").strip().upper()
|
||||
crm_entity_id = str(bitrix24_call.get("CRM_ENTITY_ID") or "").strip()
|
||||
if not crm_entity_type or not crm_entity_id:
|
||||
return Bitrix24NoteSyncEntry(
|
||||
audio_file_id=audio_file_id,
|
||||
source_id=source_id,
|
||||
crm_entity_type=crm_entity_type or None,
|
||||
crm_entity_id=crm_entity_id or None,
|
||||
status="skipped_missing_crm_link",
|
||||
message="CRM_ENTITY_TYPE or CRM_ENTITY_ID is missing in transcript metadata",
|
||||
)
|
||||
|
||||
entity_type_id = _extract_entity_type_id(crm_entity_type)
|
||||
if entity_type_id is None:
|
||||
return Bitrix24NoteSyncEntry(
|
||||
audio_file_id=audio_file_id,
|
||||
source_id=source_id,
|
||||
crm_entity_type=crm_entity_type,
|
||||
crm_entity_id=crm_entity_id,
|
||||
status="skipped_unsupported_entity",
|
||||
message=f"unsupported CRM entity type: {crm_entity_type}",
|
||||
)
|
||||
|
||||
transcript_sha = _transcript_sha256(transcript_text)
|
||||
note_mode = NOTE_MODE_FULL_TRANSCRIPT
|
||||
local_sync = storage.get_crm_note_sync(
|
||||
audio_file_id=audio_file_id,
|
||||
source_type=source_type,
|
||||
source_id=source_id,
|
||||
crm_entity_type=crm_entity_type,
|
||||
crm_entity_id=crm_entity_id,
|
||||
transcript_sha256=transcript_sha,
|
||||
note_mode=note_mode,
|
||||
)
|
||||
if local_sync is not None and not force:
|
||||
return Bitrix24NoteSyncEntry(
|
||||
audio_file_id=audio_file_id,
|
||||
source_id=source_id,
|
||||
crm_entity_type=crm_entity_type,
|
||||
crm_entity_id=crm_entity_id,
|
||||
status="skipped_existing",
|
||||
message="already synced locally",
|
||||
)
|
||||
|
||||
item_id = int(crm_entity_id)
|
||||
current_item = client.get_crm_item(entity_type_id, item_id)
|
||||
existing_comments = _extract_comments(current_item)
|
||||
call_started_at = row.get("call_started_at_dt")
|
||||
if not isinstance(call_started_at, datetime):
|
||||
call_started_at = _extract_call_started_at(transcript_document, row)
|
||||
|
||||
synced_at = datetime.now(tz=timezone.utc)
|
||||
new_block = _format_note_block(
|
||||
audio_file_id=audio_file_id,
|
||||
source_type=source_type,
|
||||
source_id=source_id,
|
||||
crm_entity_type=crm_entity_type,
|
||||
crm_entity_id=crm_entity_id,
|
||||
note_mode=note_mode,
|
||||
transcript_sha256=transcript_sha,
|
||||
call_started_at=call_started_at,
|
||||
synced_at=synced_at,
|
||||
transcript_text=transcript_text,
|
||||
)
|
||||
merged_comments = _merge_sync_block(existing_comments, new_block, audio_file_id)
|
||||
if merged_comments == existing_comments:
|
||||
storage.upsert_crm_note_sync(
|
||||
CRMNoteSyncRecord(
|
||||
audio_file_id=audio_file_id,
|
||||
source_type=source_type,
|
||||
source_id=source_id,
|
||||
crm_entity_type=crm_entity_type,
|
||||
crm_entity_id=crm_entity_id,
|
||||
note_mode=note_mode,
|
||||
transcript_sha256=transcript_sha,
|
||||
transcript_chars=len(transcript_text),
|
||||
comments_before_chars=len(existing_comments),
|
||||
comments_after_chars=len(existing_comments),
|
||||
remote_item=current_item,
|
||||
sync_status="skipped_existing",
|
||||
sync_message="remote comments already contained the sync block",
|
||||
)
|
||||
)
|
||||
return Bitrix24NoteSyncEntry(
|
||||
audio_file_id=audio_file_id,
|
||||
source_id=source_id,
|
||||
crm_entity_type=crm_entity_type,
|
||||
crm_entity_id=crm_entity_id,
|
||||
status="skipped_existing",
|
||||
message="remote comments already contained the sync block",
|
||||
)
|
||||
|
||||
if len(merged_comments) > config.max_note_chars:
|
||||
return Bitrix24NoteSyncEntry(
|
||||
audio_file_id=audio_file_id,
|
||||
source_id=source_id,
|
||||
crm_entity_type=crm_entity_type,
|
||||
crm_entity_id=crm_entity_id,
|
||||
status="skipped_length",
|
||||
message=(
|
||||
f"merged comments length {len(merged_comments)} exceeds max_note_chars "
|
||||
f"{config.max_note_chars}"
|
||||
),
|
||||
)
|
||||
|
||||
updated_item = client.update_crm_item(
|
||||
entity_type_id,
|
||||
item_id,
|
||||
{"comments": merged_comments},
|
||||
)
|
||||
storage.upsert_crm_note_sync(
|
||||
CRMNoteSyncRecord(
|
||||
audio_file_id=audio_file_id,
|
||||
source_type=source_type,
|
||||
source_id=source_id,
|
||||
crm_entity_type=crm_entity_type,
|
||||
crm_entity_id=crm_entity_id,
|
||||
note_mode=note_mode,
|
||||
transcript_sha256=transcript_sha,
|
||||
transcript_chars=len(transcript_text),
|
||||
comments_before_chars=len(existing_comments),
|
||||
comments_after_chars=len(merged_comments),
|
||||
remote_item=updated_item,
|
||||
sync_status="synced",
|
||||
sync_message="comments updated",
|
||||
)
|
||||
)
|
||||
return Bitrix24NoteSyncEntry(
|
||||
audio_file_id=audio_file_id,
|
||||
source_id=source_id,
|
||||
crm_entity_type=crm_entity_type,
|
||||
crm_entity_id=crm_entity_id,
|
||||
status="synced",
|
||||
message="comments updated",
|
||||
)
|
||||
|
||||
|
||||
def sync_bitrix24_notes(
|
||||
storage: SQLiteStorage,
|
||||
settings_bitrix24: Bitrix24Config,
|
||||
client: Bitrix24RestClient,
|
||||
*,
|
||||
selection: Bitrix24NoteSyncSelection,
|
||||
) -> Bitrix24NoteSyncSummary:
|
||||
try:
|
||||
if selection.audio_file_id is not None or selection.source_id is not None:
|
||||
candidates = _load_exact_selection(
|
||||
storage,
|
||||
audio_file_id=selection.audio_file_id,
|
||||
source_id=selection.source_id,
|
||||
)
|
||||
else:
|
||||
candidates = _select_transcript_rows(
|
||||
storage,
|
||||
direction=selection.direction,
|
||||
start=selection.start,
|
||||
end=selection.end,
|
||||
limit=selection.limit,
|
||||
)
|
||||
except Bitrix24Error as exc:
|
||||
if selection.audio_file_id is not None:
|
||||
audio_file_id = selection.audio_file_id
|
||||
else:
|
||||
audio_file_id = -1
|
||||
return Bitrix24NoteSyncSummary(
|
||||
failed=1,
|
||||
entries=(
|
||||
Bitrix24NoteSyncEntry(
|
||||
audio_file_id=audio_file_id,
|
||||
source_id=selection.source_id or "",
|
||||
crm_entity_type=None,
|
||||
crm_entity_id=None,
|
||||
status="failed",
|
||||
message=str(exc),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
entries: list[Bitrix24NoteSyncEntry] = []
|
||||
summary = {
|
||||
"scanned": 0,
|
||||
"synced": 0,
|
||||
"dry_run": 0,
|
||||
"skipped_existing": 0,
|
||||
"skipped_missing_transcript": 0,
|
||||
"skipped_missing_crm_link": 0,
|
||||
"skipped_direction": 0,
|
||||
"skipped_length": 0,
|
||||
"skipped_unsupported_entity": 0,
|
||||
"failed": 0,
|
||||
}
|
||||
|
||||
for row in candidates:
|
||||
summary["scanned"] += 1
|
||||
try:
|
||||
entry = _sync_single_note(
|
||||
storage=storage,
|
||||
client=client,
|
||||
config=settings_bitrix24,
|
||||
row=row,
|
||||
force=selection.force,
|
||||
dry_run=selection.dry_run,
|
||||
)
|
||||
except Bitrix24Error as exc:
|
||||
entry = Bitrix24NoteSyncEntry(
|
||||
audio_file_id=int(row["audio_file_id"]),
|
||||
source_id=str(row["source_id"]),
|
||||
crm_entity_type=None,
|
||||
crm_entity_id=None,
|
||||
status="failed",
|
||||
message=str(exc),
|
||||
)
|
||||
entries.append(entry)
|
||||
if entry.status == "synced":
|
||||
summary["synced"] += 1
|
||||
elif entry.status == "dry_run":
|
||||
summary["dry_run"] += 1
|
||||
elif entry.status in summary:
|
||||
summary[entry.status] += 1
|
||||
elif entry.status == "failed":
|
||||
summary["failed"] += 1
|
||||
|
||||
return Bitrix24NoteSyncSummary(
|
||||
scanned=summary["scanned"],
|
||||
synced=summary["synced"],
|
||||
dry_run=summary["dry_run"],
|
||||
skipped_existing=summary["skipped_existing"],
|
||||
skipped_missing_transcript=summary["skipped_missing_transcript"],
|
||||
skipped_missing_crm_link=summary["skipped_missing_crm_link"],
|
||||
skipped_direction=summary["skipped_direction"],
|
||||
skipped_length=summary["skipped_length"],
|
||||
skipped_unsupported_entity=summary["skipped_unsupported_entity"],
|
||||
failed=summary["failed"],
|
||||
entries=tuple(entries),
|
||||
)
|
||||
|
|
@ -104,6 +104,7 @@ class Bitrix24Config:
|
|||
download_recordings: bool = True
|
||||
enrich_users: bool = False
|
||||
timeout_seconds: float = 30.0
|
||||
max_note_chars: int = 8000
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
|
@ -591,6 +592,10 @@ def load_settings(
|
|||
os.environ.get("B24CALLS_BITRIX24_TIMEOUT_SECONDS"),
|
||||
float(bitrix24_section.get("timeout_seconds", 30.0)),
|
||||
),
|
||||
max_note_chars=_parse_int(
|
||||
os.environ.get("B24CALLS_BITRIX24_MAX_NOTE_CHARS"),
|
||||
int(bitrix24_section.get("max_note_chars", 8000)),
|
||||
),
|
||||
)
|
||||
|
||||
return Settings(
|
||||
|
|
|
|||
|
|
@ -88,3 +88,37 @@ CREATE TABLE IF NOT EXISTS artifacts (
|
|||
|
||||
CREATE INDEX IF NOT EXISTS idx_artifacts_audio_file
|
||||
ON artifacts(audio_file_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS crm_note_syncs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
audio_file_id INTEGER NOT NULL,
|
||||
source_type TEXT NOT NULL,
|
||||
source_id TEXT NOT NULL,
|
||||
crm_entity_type TEXT NOT NULL,
|
||||
crm_entity_id TEXT NOT NULL,
|
||||
note_mode TEXT NOT NULL DEFAULT 'full_transcript',
|
||||
transcript_sha256 TEXT NOT NULL,
|
||||
transcript_chars INTEGER NOT NULL,
|
||||
comments_before_chars INTEGER,
|
||||
comments_after_chars INTEGER,
|
||||
remote_item_json TEXT NOT NULL DEFAULT '{}',
|
||||
sync_status TEXT NOT NULL,
|
||||
sync_message TEXT,
|
||||
synced_at TEXT NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
updated_at TEXT NOT NULL DEFAULT (CURRENT_TIMESTAMP),
|
||||
UNIQUE(
|
||||
audio_file_id,
|
||||
source_type,
|
||||
source_id,
|
||||
crm_entity_type,
|
||||
crm_entity_id,
|
||||
transcript_sha256,
|
||||
note_mode
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_crm_note_syncs_audio_file
|
||||
ON crm_note_syncs(audio_file_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_crm_note_syncs_entity
|
||||
ON crm_note_syncs(crm_entity_type, crm_entity_id);
|
||||
|
|
|
|||
|
|
@ -85,6 +85,23 @@ class ArtifactRecord:
|
|||
metadata: Mapping[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CRMNoteSyncRecord:
|
||||
audio_file_id: int
|
||||
source_type: str
|
||||
source_id: str
|
||||
crm_entity_type: str
|
||||
crm_entity_id: str
|
||||
note_mode: str
|
||||
transcript_sha256: str
|
||||
transcript_chars: int
|
||||
sync_status: str
|
||||
comments_before_chars: int | None = None
|
||||
comments_after_chars: int | None = None
|
||||
remote_item: Mapping[str, Any] = field(default_factory=dict)
|
||||
sync_message: str | None = None
|
||||
|
||||
|
||||
class SQLiteStorage:
|
||||
"""Thin persistence layer around SQLite for the call pipeline."""
|
||||
|
||||
|
|
@ -479,6 +496,114 @@ class SQLiteStorage:
|
|||
(audio_file_id, kind, format),
|
||||
).fetchone()
|
||||
|
||||
def get_crm_note_sync(
|
||||
self,
|
||||
*,
|
||||
audio_file_id: int,
|
||||
source_type: str,
|
||||
source_id: str,
|
||||
crm_entity_type: str,
|
||||
crm_entity_id: str,
|
||||
transcript_sha256: str,
|
||||
note_mode: str,
|
||||
) -> sqlite3.Row | None:
|
||||
with self.connect() as connection:
|
||||
return connection.execute(
|
||||
"""
|
||||
SELECT * FROM crm_note_syncs
|
||||
WHERE audio_file_id = ?
|
||||
AND source_type = ?
|
||||
AND source_id = ?
|
||||
AND crm_entity_type = ?
|
||||
AND crm_entity_id = ?
|
||||
AND transcript_sha256 = ?
|
||||
AND note_mode = ?
|
||||
LIMIT 1
|
||||
""",
|
||||
(
|
||||
audio_file_id,
|
||||
source_type,
|
||||
source_id,
|
||||
crm_entity_type,
|
||||
crm_entity_id,
|
||||
transcript_sha256,
|
||||
note_mode,
|
||||
),
|
||||
).fetchone()
|
||||
|
||||
def upsert_crm_note_sync(self, record: CRMNoteSyncRecord) -> int:
|
||||
now = _utc_now()
|
||||
payload = (
|
||||
record.audio_file_id,
|
||||
record.source_type,
|
||||
record.source_id,
|
||||
record.crm_entity_type,
|
||||
record.crm_entity_id,
|
||||
record.note_mode,
|
||||
record.transcript_sha256,
|
||||
record.transcript_chars,
|
||||
record.comments_before_chars,
|
||||
record.comments_after_chars,
|
||||
_json_dumps(record.remote_item),
|
||||
record.sync_status,
|
||||
record.sync_message,
|
||||
now,
|
||||
now,
|
||||
)
|
||||
sql = """
|
||||
INSERT INTO crm_note_syncs (
|
||||
audio_file_id, source_type, source_id, crm_entity_type, crm_entity_id,
|
||||
note_mode, transcript_sha256, transcript_chars, comments_before_chars,
|
||||
comments_after_chars, remote_item_json, sync_status, sync_message,
|
||||
synced_at, updated_at
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(
|
||||
audio_file_id,
|
||||
source_type,
|
||||
source_id,
|
||||
crm_entity_type,
|
||||
crm_entity_id,
|
||||
transcript_sha256,
|
||||
note_mode
|
||||
) DO UPDATE SET
|
||||
transcript_chars = excluded.transcript_chars,
|
||||
comments_before_chars = excluded.comments_before_chars,
|
||||
comments_after_chars = excluded.comments_after_chars,
|
||||
remote_item_json = excluded.remote_item_json,
|
||||
sync_status = excluded.sync_status,
|
||||
sync_message = excluded.sync_message,
|
||||
synced_at = excluded.synced_at,
|
||||
updated_at = excluded.updated_at
|
||||
"""
|
||||
with self.connect() as connection:
|
||||
connection.execute(sql, payload)
|
||||
connection.commit()
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT id FROM crm_note_syncs
|
||||
WHERE audio_file_id = ?
|
||||
AND source_type = ?
|
||||
AND source_id = ?
|
||||
AND crm_entity_type = ?
|
||||
AND crm_entity_id = ?
|
||||
AND transcript_sha256 = ?
|
||||
AND note_mode = ?
|
||||
""",
|
||||
(
|
||||
record.audio_file_id,
|
||||
record.source_type,
|
||||
record.source_id,
|
||||
record.crm_entity_type,
|
||||
record.crm_entity_id,
|
||||
record.transcript_sha256,
|
||||
record.note_mode,
|
||||
),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise RuntimeError("SQLite did not return a CRM note sync id")
|
||||
return int(row["id"])
|
||||
|
||||
def update_audio_file_validation(
|
||||
self,
|
||||
audio_file_id: int,
|
||||
|
|
|
|||
|
|
@ -20,6 +20,8 @@ logger = logging.getLogger(__name__)
|
|||
VOXIMPLANT_STATISTIC_GET = "voximplant.statistic.get"
|
||||
DISK_FILE_GET = "disk.file.get"
|
||||
USER_GET = "user.get"
|
||||
CRM_ITEM_GET = "crm.item.get"
|
||||
CRM_ITEM_UPDATE = "crm.item.update"
|
||||
|
||||
HttpOpener = Callable[[urllib.request.Request, float], tuple[int, bytes]]
|
||||
Downloader = Callable[[str, Path, float, bool], int]
|
||||
|
|
@ -420,6 +422,103 @@ class Bitrix24RestClient:
|
|||
)
|
||||
return None
|
||||
|
||||
def get_crm_item(self, entity_type_id: int, item_id: int) -> dict[str, Any]:
|
||||
operation_started = time_module.perf_counter()
|
||||
logger.info(
|
||||
"Bitrix24 CRM item lookup started",
|
||||
extra={"entity_type_id": entity_type_id, "item_id": item_id},
|
||||
)
|
||||
response = self.call(
|
||||
CRM_ITEM_GET,
|
||||
{
|
||||
"entityTypeId": entity_type_id,
|
||||
"id": item_id,
|
||||
"useOriginalUfNames": "N",
|
||||
},
|
||||
)
|
||||
result = response.get("result")
|
||||
if not isinstance(result, dict):
|
||||
raise Bitrix24Error(f"{CRM_ITEM_GET} returned unexpected response shape")
|
||||
item = result.get("item")
|
||||
if isinstance(item, dict):
|
||||
logger.info(
|
||||
"Bitrix24 CRM item lookup completed",
|
||||
extra={
|
||||
"entity_type_id": entity_type_id,
|
||||
"item_id": item_id,
|
||||
"found": True,
|
||||
"duration_seconds": _elapsed_seconds(operation_started),
|
||||
},
|
||||
)
|
||||
return item
|
||||
logger.info(
|
||||
"Bitrix24 CRM item lookup completed",
|
||||
extra={
|
||||
"entity_type_id": entity_type_id,
|
||||
"item_id": item_id,
|
||||
"found": False,
|
||||
"duration_seconds": _elapsed_seconds(operation_started),
|
||||
},
|
||||
)
|
||||
return result
|
||||
|
||||
def update_crm_item(
|
||||
self, entity_type_id: int, item_id: int, fields: dict[str, Any]
|
||||
) -> dict[str, Any]:
|
||||
operation_started = time_module.perf_counter()
|
||||
payload: dict[str, Any] = {
|
||||
"entityTypeId": entity_type_id,
|
||||
"id": item_id,
|
||||
}
|
||||
for field_name, field_value in fields.items():
|
||||
payload[f"fields[{field_name}]"] = (
|
||||
json.dumps(field_value, ensure_ascii=False)
|
||||
if isinstance(field_value, (dict, list))
|
||||
else field_value
|
||||
)
|
||||
logger.info(
|
||||
"Bitrix24 CRM item update started",
|
||||
extra={
|
||||
"entity_type_id": entity_type_id,
|
||||
"item_id": item_id,
|
||||
"field_names": sorted(fields),
|
||||
},
|
||||
)
|
||||
response = self.call(CRM_ITEM_UPDATE, payload)
|
||||
result = response.get("result")
|
||||
if isinstance(result, dict):
|
||||
item = result.get("item")
|
||||
if isinstance(item, dict):
|
||||
logger.info(
|
||||
"Bitrix24 CRM item update completed",
|
||||
extra={
|
||||
"entity_type_id": entity_type_id,
|
||||
"item_id": item_id,
|
||||
"duration_seconds": _elapsed_seconds(operation_started),
|
||||
},
|
||||
)
|
||||
return item
|
||||
logger.info(
|
||||
"Bitrix24 CRM item update completed",
|
||||
extra={
|
||||
"entity_type_id": entity_type_id,
|
||||
"item_id": item_id,
|
||||
"duration_seconds": _elapsed_seconds(operation_started),
|
||||
},
|
||||
)
|
||||
return result
|
||||
if result is None:
|
||||
raise Bitrix24Error(f"{CRM_ITEM_UPDATE} returned unexpected response shape")
|
||||
logger.info(
|
||||
"Bitrix24 CRM item update completed",
|
||||
extra={
|
||||
"entity_type_id": entity_type_id,
|
||||
"item_id": item_id,
|
||||
"duration_seconds": _elapsed_seconds(operation_started),
|
||||
},
|
||||
)
|
||||
return {"result": result}
|
||||
|
||||
def _respect_rate_limit(self) -> None:
|
||||
if self.rate_limit_per_second <= 0:
|
||||
return
|
||||
|
|
|
|||
Loading…
Reference in New Issue