import logging from dataclasses import dataclass from uuid import uuid4 import requests from django.conf import settings from apps.core.models import VoipConfiguration logger = logging.getLogger(__name__) @dataclass(frozen=True) class VoipCallResult: success: bool error: str = "" def place_voip_call(*, agent, customer, method): configuration = VoipConfiguration.load() if not configuration.voip_call_url: return VoipCallResult(False, "VOIP_CALL_URL تنظیم نشده است.") payload = { "method": method, "customer_number": customer.local_mobile, "metadata": { "agent_id": str(agent.public_id), "customer_id": str(customer.public_id), }, } if method == "ip_phone" and agent.voip_extension: payload["agent_extension"] = agent.voip_extension key_prefix = "internal" elif method == "mobile" and agent.voip_local_mobile: payload["agent_mobile"] = agent.voip_local_mobile key_prefix = "mobile" else: return VoipCallResult(False, "روش تماس انتخاب‌شده در دسترس نیست.") try: response = requests.post( configuration.voip_call_url, json=payload, headers={"Idempotency-Key": f"{key_prefix}-{uuid4().hex}"}, timeout=settings.INTEGRATION_HTTP_TIMEOUT_SECONDS, ) response.raise_for_status() if response.content: body = response.json() if not isinstance(body, dict) or body.get("success") is False: return VoipCallResult(False, "سرویس تماس درخواست را نپذیرفت.") return VoipCallResult(True) except (requests.RequestException, ValueError): logger.exception("VOIP click-to-call failed") return VoipCallResult(False, "خطا در ارتباط با سرویس تماس.")