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'; import { Loading } from '/static/admin2/ui/loading.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', 'История']]; // Длинный вопрос режем с многоточием: иначе обрыв выглядит как поломка, а полный // текст открывается в самом диалоге по ссылке «Открыть». const вопрос = (r) => { const t = String(r.title || r.last_question || ''); return t.length > 140 ? t.slice(0, 140).trimEnd() + '…' : t; }; // Счёт приходит в копейках: человеку показываем рубли и знак — куда деньги. const деньги = (kop) => kop == null ? '—' : (kop > 0 ? '+' : '') + (kop / 100).toLocaleString('ru-RU', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + ' ₽'; // Что показать оператору про Telegram: доказанное ботом (@имя или номер чата) важнее // вписанного руками — то всего лишь заявка (решение 18.11.2026). const телеграм = (p) => { if (p.tg_verified) { if (p.tg_username) return '@' + p.tg_username + ' · подтверждён'; if (p.tg_chat_id) return 'id ' + p.tg_chat_id + ' · подтверждён'; return 'подтверждён'; } return p.telegram ? p.telegram + ' — не подтверждён' : '—'; }; const размер = (b) => b == null ? '—' : b < 1024 ? b + ' Б' : b < 1048576 ? Math.round(b / 1024) + ' КБ' : (b / 1048576).toLocaleString('ru-RU', {minimumFractionDigits: 1, maximumFractionDigits: 1}) + ' МБ'; export function CustomerDrawer({ email, onClose, onDeleted, onChanged }) { const [card, setCard] = useState(null); const [tab, setTab] = useState('overview'); const [rows, setRows] = useState([]); const [summary, setSummary] = useState(null); 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) return; setRows(Array.isArray(d) ? d : (d.items || d.entries || [])); // Счёт отдаёт ещё и сводку (баланс, взносы, расход) — показываем строкой над таблицей. setSummary(d && !Array.isArray(d) ? (d.account || null) : null); }) .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`<${Loading} rows={2} />` : html` ${!card.profile.deleted_at ? html`` : html``} ${tab === 'overview' ? html`Пусто.
` : html`| Был(а) | Сообщений | Последний вопрос | Открыть |
|---|---|---|---|
| ${when(r.last_ts)} | ${r.msg_count} | ${вопрос(r)} | Открыть |
${summary ? html`Баланс ${rub(summary.balance_rub)} · внесено ${rub(summary.deposited_rub)} · израсходовано ${rub(summary.charged_rub)}` : 'Счёт не заведён'}
` : null}Пусто.
` : tab === 'ledger' ? html`| Дата | Сумма | Примечание | Кто |
|---|---|---|---|
| ${when(r.ts)} | 0 ? 'ok' : 'bad')}>${деньги(r.amount_kop)} | ${r.comment || '—'}${r.reverses
? html` снимает №${r.reverses}` : null} |
${r.created_by || '—'} |
| Имя | Размер | Изменён |
|---|---|---|
| ${r.name} | ${размер(r.size)} | ${when(r.mtime)} |
| Когда | Кто | Действие | Итог |
|---|---|---|---|
| ${when(r.timestamp)} | ${r.username || '—'} | ${r.action} ${[r.method, r.path].filter(Boolean).join(' ')}${r.detail ? ' · ' + r.detail : ''} |
${r.status_code == null ? '—' : r.status_code} |