Files
smeta-web/static/admin2/pages/customer.js
T

157 lines
8.7 KiB
JavaScript
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 { 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`<p class="error" role="alert">${error}</p>` : null}
${notice ? html`<${Toast} message=${notice} onUndo=${undoId ? undo : null}
onClose=${() => { setNotice(''); setUndoId(null); }} />` : null}
${!card ? html`<p class="note">Загрузка…</p>` : html`
<nav class="tabs">${TABS.map(([k, label]) => html`
<button type="button" key=${k} class=${k === tab ? 'tab active' : 'tab'}
onClick=${() => { setRows([]); setTab(k); }}>${label}</button>`)}</nav>
${!card.profile.deleted_at ? html`<div class="actions-bar">
<button type="button" disabled=${busy} onClick=${() => act('block',
{blocked: !card.profile.blocked}, card.profile.blocked ? 'Разблокирован' : 'Заблокирован')}>
${card.profile.blocked ? 'Разблокировать' : 'Заблокировать'}</button>
<button type="button" disabled=${busy} onClick=${() => act('read_only',
{read_only: !card.profile.read_only}, card.profile.read_only ? 'Работа открыта' : 'Только просмотр')}>
${card.profile.read_only ? 'Открыть работу' : 'Только просмотр'}</button>
<button type="button" disabled=${busy} onClick=${() => act('role',
{role: card.profile.role === 'admin' ? 'user' : 'admin'},
card.profile.role === 'admin' ? 'Теперь user' : 'Теперь admin')}>
${card.profile.role === 'admin' ? 'Сделать user' : 'Сделать admin'}</button>
<button type="button" disabled=${busy} onClick=${() => act('agent_access',
{agent_access: !card.profile.agent_access}, card.profile.agent_access ? 'Доступ снят' : 'Доступ выдан')}>
${card.profile.agent_access ? 'Снять агента' : 'Выдать агента'}</button>
<button type="button" disabled=${busy} onClick=${topup}>Внести</button>
<button type="button" disabled=${busy} onClick=${exportData}>Выгрузить</button>
<button type="button" disabled=${busy} onClick=${del}>Удалить</button>
</div>` : html`<div class="actions-bar">
<button type="button" disabled=${busy} onClick=${restore}>Восстановить</button>
</div>`}
${tab === 'overview' ? html`<div class="kv">
<div><span>Статус</span><b>${card.profile.deleted_at ? 'удалён' : card.profile.blocked ? 'заблокирован' : 'активен'}</b></div>
<div><span>Баланс</span><b>${rub(card.account && card.account.balance_rub)}</b></div>
<div><span>Доступ</span><b>${card.profile.agent_access ? 'агент' : 'справка'} · ${card.profile.agent_provider || 'по умолч.'}</b></div>
<div><span>Был(а)</span><b>${when(card.activity.last_seen)}</b></div>
<div><span>Сообщений</span><b>${card.activity.messages}</b></div>
<div><span>Файлов</span><b>${card.activity.files}${card.activity.files_capped ? '+' : ''}</b></div>
</div>` : html`<div class="tab-body">${loading
? html`<p class="note">Загрузка…</p>`
: rows.length === 0 ? html`<p class="note">Пусто.</p>`
: html`<pre class="json">${JSON.stringify(rows.slice(0, 20), null, 2)}</pre>`}</div>`}
`}
</${Drawer}>`;
}