import { h } from '/static/admin2/vendor/preact.module.js'; import { useEffect, useRef, useState } from '/static/admin2/vendor/hooks.module.js'; import htm from '/static/admin2/vendor/htm.module.js'; import { api } from '/static/admin2/api.js'; import { Drawer } from '/static/admin2/ui/drawer.js'; import { Toast } from '/static/admin2/ui/toast.js'; const html = htm.bind(h); const rub = (v) => v == null ? '—' : Number(v).toLocaleString('ru-RU', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + ' ₽'; const when = (ts) => ts ? new Date(ts * 1000).toLocaleString('ru-RU') : '—'; const TABS = [['overview', 'Обзор'], ['dialogs', 'Диалоги'], ['ledger', 'Счёт'], ['files', 'Файлы'], ['history', 'История']]; export function CustomerDrawer({ email, onClose, onDeleted, onChanged }) { const [card, setCard] = useState(null); const [tab, setTab] = useState('overview'); const [rows, setRows] = useState([]); const [error, setError] = useState(''); const [loading, setLoading] = useState(false); const [reload, setReload] = useState(0); const [undoId, setUndoId] = useState(null); const [notice, setNotice] = useState(''); const [busy, setBusy] = useState(false); const prevEmail = useRef(email); useEffect(() => { let alive = true; const switched = prevEmail.current !== email; prevEmail.current = email; setCard(null); setError(''); if (switched) { setTab('overview'); setRows([]); } setLoading(false); api('/api/admin/v2/customers/' + encodeURIComponent(email)) .then((d) => { if (alive) setCard(d); }) .catch((e) => { if (alive) setError(e.message || 'Не удалось загрузить'); }); return () => { alive = false; }; }, [email, reload]); useEffect(() => { if (tab === 'overview' || !card) return; let alive = true; const suffix = {dialogs: 'dialogs', ledger: 'ledger', files: 'files', history: 'history'}[tab]; setError(''); setLoading(true); api('/api/admin/v2/customers/' + encodeURIComponent(email) + '/' + suffix) .then((d) => { if (alive) setRows(d.items || d.entries || d); }) .catch((e) => { if (alive) setError(e.message || 'Не удалось загрузить вкладку'); }) .finally(() => { if (alive) setLoading(false); }); return () => { alive = false; }; }, [tab, card, email]); const act = async (action, value, label) => { setBusy(true); setNotice(''); setUndoId(null); try { const r = await api('/api/admin/v2/customers/' + encodeURIComponent(email) + '/action', {method: 'POST', body: JSON.stringify({action, value})}); setUndoId(r.id); setNotice(label); setReload((n) => n + 1); } catch (e) { setNotice(e.message || 'Не выполнено'); } finally { setBusy(false); } }; const undo = async () => { if (!undoId) return; setBusy(true); try { await api('/api/admin/v2/actions/' + undoId + '/undo', {method: 'POST'}); setNotice('Отменено'); setUndoId(null); setReload((n) => n + 1); } catch (e) { setNotice(e.message || 'Не удалось отменить'); } finally { setBusy(false); } }; const topup = async () => { const amount = prompt('Сумма взноса, ₽', '1000'); if (!amount) return; setBusy(true); setNotice(''); try { const rid = (crypto && crypto.randomUUID) ? crypto.randomUUID() : String(Date.now()); await api('/api/admin/v2/customers/' + encodeURIComponent(email) + '/topup', {method: 'POST', body: JSON.stringify({amount, request_id: rid})}); setNotice('Взнос записан'); setReload((n) => n + 1); } catch (e) { setNotice(e.message || 'Взнос не записан'); } finally { setBusy(false); } }; const exportData = async () => { setBusy(true); try { const r = await fetch('/api/admin/v2/customers/' + encodeURIComponent(email) + '/export', {headers: {Authorization: 'Bearer ' + (localStorage.getItem('token') || '')}}); if (!r.ok) throw new Error('Ошибка ' + r.status); const url = URL.createObjectURL(await r.blob()); const a = document.createElement('a'); a.href = url; a.download = 'export.zip'; a.click(); URL.revokeObjectURL(url); } catch (e) { setNotice(e.message || 'Не удалось выгрузить'); } finally { setBusy(false); } }; const del = async () => { if (!confirm('Удалить учётку ' + email + '? Переписка и файлы останутся, адрес освободится.')) return; setBusy(true); setNotice(''); try { await api('/api/admin/v2/customers/' + encodeURIComponent(email) + '/delete', {method: 'POST'}); onDeleted && onDeleted(card ? card.profile.email : email); } catch (e) { setNotice(e.message || 'Не удалось удалить'); } finally { setBusy(false); } }; const restore = async () => { setBusy(true); setNotice(''); try { await api('/api/admin/v2/customers/' + encodeURIComponent(email) + '/restore', {method: 'POST'}); onChanged && onChanged(); } catch (e) { setNotice(e.message || 'Не удалось восстановить'); } finally { setBusy(false); } }; const title = card ? card.profile.email : 'Карточка клиента'; return html` <${Drawer} title=${title} onClose=${onClose}> ${error ? html`
${error}
` : null} ${notice ? html`<${Toast} message=${notice} onUndo=${undoId ? undo : null} onClose=${() => { setNotice(''); setUndoId(null); }} />` : null} ${!card ? html`Загрузка…
` : html` ${!card.profile.deleted_at ? html`` : html``} ${tab === 'overview' ? html`Загрузка…
` : rows.length === 0 ? html`Пусто.
` : html`${JSON.stringify(rows.slice(0, 20), null, 2)}`}