import { useState, useEffect, useRef } from 'react' import { notificationApi, referenceApi, usersApi } from '../api/client' import { ReferenceItem, User } from '../types' import { Plus, Trash2, Edit, Save, Bell, ChevronDown, Check, X } from 'lucide-react' interface Template { id: number name: string event_type: string channel: string subject_template: string body_template: string is_active: boolean send_to_initiator: boolean send_to_specialist: boolean send_to_group: boolean department_id: number | null specialist_ids: number[] } const eventTypes = [ { value: 'ticket_created', label: 'Создание заявки', description: 'При создании новой заявки' }, { value: 'ticket_reopened', label: 'Повторное открытие', description: 'При повторном открытии закрытой заявки' }, { value: 'ticket_initiator_reply', label: 'Ответ инициатора', description: 'Когда инициатор отвечает на заявку' }, { value: 'ticket_assigned', label: 'Назначение заявки', description: 'При назначении специалиста' }, { value: 'ticket_updated', label: 'Обновление заявки', description: 'При изменении статуса или приоритета' }, { value: 'ticket_closed', label: 'Закрытие заявки', description: 'При закрытии заявки' }, ] const channels = [ { value: 'email', label: 'Email' }, { value: 'sms', label: 'SMS' }, { value: 'both', label: 'Email + SMS' }, ] export default function NotificationTemplates() { const [templates, setTemplates] = useState([]) const [departments, setDepartments] = useState([]) const [specialists, setSpecialists] = useState([]) const [loading, setLoading] = useState(true) const [editingId, setEditingId] = useState(null) const [showForm, setShowForm] = useState(false) const [showSpecialistDropdown, setShowSpecialistDropdown] = useState(false) const specialistDropdownRef = useRef(null) const [formData, setFormData] = useState({ name: '', event_type: 'ticket_created', channel: 'email', subject_template: '', body_template: '', is_active: true, send_to_initiator: true, send_to_specialist: true, send_to_group: false, department_id: null as number | null, specialist_ids: [] as number[] }) useEffect(() => { loadTemplates() referenceApi.getDepartments().then(res => setDepartments(res.data)) usersApi.getSpecialists().then(res => setSpecialists(res.data)).catch(() => {}) }, []) useEffect(() => { const handleClick = (e: MouseEvent) => { if (specialistDropdownRef.current && !specialistDropdownRef.current.contains(e.target as Node)) { setShowSpecialistDropdown(false) } } document.addEventListener('mousedown', handleClick) return () => document.removeEventListener('mousedown', handleClick) }, []) const loadTemplates = () => { setLoading(true) notificationApi.getTemplates() .then(res => setTemplates(res.data)) .finally(() => setLoading(false)) } const handleSave = async () => { try { const payload = { ...formData, specialist_ids: formData.specialist_ids.length > 0 ? JSON.stringify(formData.specialist_ids) : null } if (editingId) { await notificationApi.updateTemplate(editingId, payload) } else { await notificationApi.createTemplate(payload) } setShowForm(false) setEditingId(null) resetForm() loadTemplates() } catch (err) { alert('Ошибка сохранения') } } const handleEdit = (template: Template) => { setEditingId(template.id) setFormData({ name: template.name, event_type: template.event_type, channel: template.channel, subject_template: template.subject_template, body_template: template.body_template, is_active: template.is_active, send_to_initiator: template.send_to_initiator, send_to_specialist: template.send_to_specialist, send_to_group: template.send_to_group, department_id: template.department_id, specialist_ids: template.specialist_ids || [] }) setShowForm(true) } const handleDelete = async (id: number) => { if (!confirm('Удалить шаблон?')) return try { await notificationApi.deleteTemplate(id) loadTemplates() } catch (err) { alert('Ошибка удаления') } } const resetForm = () => { setFormData({ name: '', event_type: 'ticket_created', channel: 'email', subject_template: '', body_template: '', is_active: true, send_to_initiator: true, send_to_specialist: true, send_to_group: false, department_id: null, specialist_ids: [] }) } const insertVariable = (variable: string, targetId: string) => { const el = document.getElementById(targetId) as HTMLInputElement | HTMLTextAreaElement if (!el) return const start = el.selectionStart || 0 const end = el.selectionEnd || 0 const isSubject = targetId === 'subject_template' const currentText = isSubject ? formData.subject_template : formData.body_template const newText = currentText.substring(0, start) + variable + currentText.substring(end) if (isSubject) { setFormData({ ...formData, subject_template: newText }) } else { setFormData({ ...formData, body_template: newText }) } setTimeout(() => { el.focus() el.setSelectionRange(start + variable.length, start + variable.length) }, 0) } const variables = [ { label: 'ID заявки', value: '{{ticket_id}}' }, { label: 'Тема', value: '{{ticket_subject}}' }, { label: 'Приоритет', value: '{{ticket_priority}}' }, { label: 'Статус', value: '{{ticket_status}}' }, { label: 'Инициатор', value: '{{initiator_name}}' }, { label: 'Email инициатора', value: '{{initiator_email}}' }, { label: 'Специалист', value: '{{specialist_name}}' }, { label: 'Email специалиста', value: '{{specialist_email}}' }, { label: 'URL заявки', value: '{{ticket_url}}' }, { label: 'Дата/время', value: '{{current_time}}' } ] const getEventLabel = (value: string) => eventTypes.find(e => e.value === value)?.label || value const getChannelLabel = (value: string) => channels.find(c => c.value === value)?.label || value const getDeptName = (id: number | null) => { if (!id) return '-' return departments.find(d => d.id === id)?.name || '-' } if (loading) return
Загрузка...
return (

Шаблоны уведомлений

{/* Template Form */} {showForm && (

{editingId ? 'Редактирование' : 'Новый шаблон'}

setFormData({ ...formData, name: e.target.value })} className="w-full px-3 py-2 border rounded-lg" placeholder="Название шаблона" />
setFormData({ ...formData, is_active: e.target.checked })} className="h-4 w-4 text-blue-600" />
{/* Variables - clickable for both subject and body */}
{variables.map(v => ( ))}
setFormData({ ...formData, subject_template: e.target.value })} className="w-full px-3 py-2 border rounded-lg" placeholder="Заявка #{{ticket_id}}: {{ticket_subject}}" />