Files
ACORE/apps/asterisk_connector/views.py
T

51 lines
1.9 KiB
Python

import time
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.utils.html import escape
from django.views.decorators.http import require_POST
from apps.employees.models import Employee
from .services import TelephonyError, originate_between
CALL_COOLDOWN_SEC = 3
def _notice(ok: bool, text: str, status: int = 200) -> HttpResponse:
color = 'var(--color-primary)' if ok else 'var(--color-destructive)'
html = (
f'<div role="status" style="background:var(--color-card); color:var(--color-foreground);'
f'border:1px solid {color}; border-radius:var(--radius); padding:0.75rem 1rem;'
f'box-shadow:0 8px 24px rgb(0 0 0/0.12); max-width:22rem; font-size:0.875rem;">'
f'{escape(text)}</div>'
)
response = HttpResponse(html, status=status)
response['HX-Retarget'] = '#telephony-notice'
response['HX-Reswap'] = 'innerHTML'
return response
@login_required
@require_POST
def originate_call_view(request):
raw_id = (request.POST.get('employee_id') or '').strip()
if not raw_id.isdigit():
return _notice(False, 'Не указан сотрудник.', status=400)
now = time.time()
last = request.session.get('ami_last_call_at') or 0
if now - float(last) < CALL_COOLDOWN_SEC:
return _notice(False, 'Подождите секунду перед следующим звонком.', status=429)
request.session['ami_last_call_at'] = now
callee = get_object_or_404(Employee, pk=int(raw_id), is_active=True)
try:
originate_between(request.user, callee)
except TelephonyError as exc:
return _notice(False, str(exc), status=400)
label = callee.internal_number
return _notice(True, f'Звонок на {callee.short_name} ({label}). Возьмите свою трубку.')