Files
platform-project/modules/request-module/frontend/src/pages/NotificationTemplates.tsx
T
alex 6c86f0f571 TT-003: complete request-module integration into modular platform
- integrated request-module into module registry
- moved backend into modules/request-module
- added manifest.json and module.py
- implemented dynamic router mounting
- implemented dynamic static mounting
- removed direct dependencies from platform core
- verified startup with request-module
- verified startup without request-module
- added implementation_report_003.md
2026-08-06 16:31:27 +03:00

423 lines
20 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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<Template[]>([])
const [departments, setDepartments] = useState<ReferenceItem[]>([])
const [specialists, setSpecialists] = useState<User[]>([])
const [loading, setLoading] = useState(true)
const [editingId, setEditingId] = useState<number | null>(null)
const [showForm, setShowForm] = useState(false)
const [showSpecialistDropdown, setShowSpecialistDropdown] = useState(false)
const specialistDropdownRef = useRef<HTMLDivElement>(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 <div className="text-center py-8">Загрузка...</div>
return (
<div>
<div className="flex items-center justify-between mb-6">
<h2 className="text-2xl font-semibold flex items-center">
<Bell className="w-6 h-6 mr-2" /> Шаблоны уведомлений
</h2>
<button onClick={() => { resetForm(); setShowForm(true); }}
className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
<Plus className="w-4 h-4 mr-2" /> Новый шаблон
</button>
</div>
{/* Template Form */}
{showForm && (
<div className="bg-white rounded-lg shadow p-6 mb-6">
<h3 className="text-lg font-semibold mb-4">{editingId ? 'Редактирование' : 'Новый шаблон'}</h3>
<div className="grid grid-cols-2 gap-4 mb-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Название</label>
<input type="text" value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
className="w-full px-3 py-2 border rounded-lg" placeholder="Название шаблона" />
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Событие</label>
<select value={formData.event_type}
onChange={(e) => setFormData({ ...formData, event_type: e.target.value })}
className="w-full px-3 py-2 border rounded-lg">
{eventTypes.map(et => (
<option key={et.value} value={et.value}>{et.label} — {et.description}</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Канал</label>
<select value={formData.channel}
onChange={(e) => setFormData({ ...formData, channel: e.target.value })}
className="w-full px-3 py-2 border rounded-lg">
{channels.map(ch => <option key={ch.value} value={ch.value}>{ch.label}</option>)}
</select>
</div>
<div className="flex items-center">
<input type="checkbox" id="is_active" checked={formData.is_active}
onChange={(e) => setFormData({ ...formData, is_active: e.target.checked })} className="h-4 w-4 text-blue-600" />
<label htmlFor="is_active" className="ml-2 text-sm">Активен</label>
</div>
</div>
{/* Variables - clickable for both subject and body */}
<div className="mb-4 p-3 bg-gray-50 rounded-lg">
<label className="block text-xs font-medium text-gray-500 mb-2">
Переменные (нажмите для вставки в поле под курсором)
</label>
<div className="flex flex-wrap gap-2">
{variables.map(v => (
<button key={v.value} type="button"
onClick={() => {
const active = document.activeElement
const subjectEl = document.getElementById('subject_template')
if (active === subjectEl) {
insertVariable(v.value, 'subject_template')
} else {
insertVariable(v.value, 'body_template')
}
}}
className="px-2 py-1 text-xs bg-blue-50 text-blue-700 rounded hover:bg-blue-100 border border-blue-200">
{v.label}
</button>
))}
</div>
</div>
<div className="mb-4">
<label className="block text-sm font-medium text-gray-700 mb-1">Тема (Email)</label>
<input id="subject_template" type="text" value={formData.subject_template}
onChange={(e) => setFormData({ ...formData, subject_template: e.target.value })}
className="w-full px-3 py-2 border rounded-lg"
placeholder="Заявка #{{ticket_id}}: {{ticket_subject}}" />
</div>
<div className="mb-4">
<label className="block text-sm font-medium text-gray-700 mb-1">Текст шаблона</label>
<textarea id="body_template" value={formData.body_template}
onChange={(e) => setFormData({ ...formData, body_template: e.target.value })}
rows={6} className="w-full px-3 py-2 border rounded-lg"
placeholder="Создана новая заявка.&#10;&#10;Тема: {{ticket_subject}}&#10;Приоритет: {{ticket_priority}}" />
</div>
{/* Recipients */}
<div className="mb-4 p-3 bg-gray-50 rounded-lg">
<label className="block text-sm font-medium text-gray-700 mb-2">Получатели</label>
<div className="flex gap-4 flex-wrap items-start">
<label className="flex items-center">
<input type="checkbox" checked={formData.send_to_initiator}
onChange={(e) => setFormData({ ...formData, send_to_initiator: e.target.checked })}
className="h-4 w-4 text-blue-600 mr-2" />
Инициатор
</label>
<div className="flex flex-col gap-2">
<label className="flex items-center">
<input type="checkbox" checked={formData.send_to_specialist}
onChange={(e) => setFormData({ ...formData, send_to_specialist: e.target.checked })}
className="h-4 w-4 text-blue-600 mr-2" />
Специалист
</label>
{formData.send_to_specialist && (
<div className="relative ml-6" ref={specialistDropdownRef}>
<button type="button" onClick={() => setShowSpecialistDropdown(!showSpecialistDropdown)}
className="flex items-center gap-2 px-3 py-1.5 border rounded-lg text-sm bg-white hover:bg-gray-50 min-w-[220px]">
{formData.specialist_ids.length === 0 ? (
<span className="text-gray-500">Все специалисты</span>
) : (
<span className="text-gray-900">Выбрано: {formData.specialist_ids.length}</span>
)}
<ChevronDown className="w-4 h-4 ml-auto text-gray-400" />
</button>
{showSpecialistDropdown && (
<div className="absolute top-full left-0 mt-1 w-72 bg-white border rounded-lg shadow-lg z-50 max-h-60 overflow-y-auto">
<div className="px-3 py-2 border-b text-xs text-gray-500">
Если никого не выбрать — уведомление получат все специалисты из тикета
</div>
{specialists.map(s => {
const selected = formData.specialist_ids.includes(s.id)
return (
<button key={s.id} type="button"
onClick={() => {
setFormData({
...formData,
specialist_ids: selected
? formData.specialist_ids.filter(id => id !== s.id)
: [...formData.specialist_ids, s.id]
})
}}
className="flex items-center gap-2 w-full px-3 py-2 hover:bg-gray-50 text-left">
<div className={`w-4 h-4 border rounded flex items-center justify-center ${selected ? 'bg-blue-600 border-blue-600' : 'border-gray-300'}`}>
{selected && <Check className="w-3 h-3 text-white" />}
</div>
<span className="text-sm">{s.first_name} {s.last_name}</span>
<span className="text-xs text-gray-400 ml-auto">{s.email}</span>
</button>
)
})}
</div>
)}
{formData.specialist_ids.length > 0 && (
<div className="flex flex-wrap gap-1 mt-1 ml-1">
{formData.specialist_ids.map(id => {
const s = specialists.find(sp => sp.id === id)
if (!s) return null
return (
<span key={id} className="flex items-center gap-1 px-2 py-0.5 bg-blue-100 text-blue-700 rounded text-xs">
{s.first_name} {s.last_name}
<button type="button" onClick={() => setFormData({ ...formData, specialist_ids: formData.specialist_ids.filter(i => i !== id) })}>
<X className="w-3 h-3" />
</button>
</span>
)
})}
</div>
)}
</div>
)}
</div>
<label className="flex items-center">
<input type="checkbox" checked={formData.send_to_group}
onChange={(e) => setFormData({ ...formData, send_to_group: e.target.checked })}
className="h-4 w-4 text-blue-600 mr-2" />
Отдел (группа)
</label>
{formData.send_to_group && (
<select value={formData.department_id || ''}
onChange={(e) => setFormData({ ...formData, department_id: e.target.value ? Number(e.target.value) : null })}
className="px-3 py-1 border rounded-lg text-sm">
<option value="">Выберите отдел</option>
{departments.map(d => <option key={d.id} value={d.id}>{d.name}</option>)}
</select>
)}
</div>
</div>
<div className="flex justify-end gap-2">
<button onClick={() => { setShowForm(false); setEditingId(null); resetForm(); }} className="px-4 py-2 border rounded-lg">Отмена</button>
<button onClick={handleSave} className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
<Save className="w-4 h-4 mr-2 inline" /> Сохранить
</button>
</div>
</div>
)}
{/* Templates List */}
<div className="bg-white rounded-lg shadow overflow-hidden">
<table className="w-full">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Название</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Событие</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Канал</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Получатели</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Статус</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Действия</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200">
{templates.map((template) => (
<tr key={template.id} className="hover:bg-gray-50">
<td className="px-6 py-4 text-sm font-medium">{template.name}</td>
<td className="px-6 py-4">
<span className="px-2 py-1 text-xs rounded-full bg-purple-100 text-purple-800">
{getEventLabel(template.event_type)}
</span>
</td>
<td className="px-6 py-4 text-sm text-gray-500">{getChannelLabel(template.channel)}</td>
<td className="px-6 py-4 text-sm text-gray-500">
{template.send_to_initiator && <span className="inline-block mr-2">Инициатор</span>}
{template.send_to_specialist && (
<span className="inline-block mr-2">
Специалист{template.specialist_ids && template.specialist_ids.length > 0 ? ` (${template.specialist_ids.length})` : ''}
</span>
)}
{template.send_to_group && <span className="inline-block">Отдел: {getDeptName(template.department_id)}</span>}
</td>
<td className="px-6 py-4">
<span className={`px-2 py-1 text-xs rounded-full ${template.is_active ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'}`}>
{template.is_active ? 'Активен' : 'Неактивен'}
</span>
</td>
<td className="px-6 py-4">
<div className="flex gap-2">
<button onClick={() => handleEdit(template)} className="text-blue-500 hover:text-blue-700"><Edit className="w-4 h-4" /></button>
<button onClick={() => handleDelete(template.id)} className="text-red-500 hover:text-red-700"><Trash2 className="w-4 h-4" /></button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)
}