Хозяин 21.11.2026: «я тебе должен держать в голове все URL-ы старой админки?» — кнопка
возврата жила только на странице «Платежи» прежней админки. Теперь к строке зачисления
в счёте клиента прирастают платёж и остаток к возврату; кнопка «Вернуть N ₽» спрашивает
сумму и зовёт тот же рубеж /api/admin/topups/{id}/refund. После возврата кнопки нет.
Co-Authored-By: Claude Code <noreply@anthropic.com>
250 lines
15 KiB
JavaScript
250 lines
15 KiB
JavaScript
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 [own, setOwn] = useState(false);
|
||
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 [tabReload, setTabReload] = useState(0);
|
||
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);
|
||
setOwn(d && !Array.isArray(d) ? !!d.own : false);
|
||
})
|
||
.catch((e) => { if (alive) setError(e.message || 'Не удалось загрузить вкладку'); })
|
||
.finally(() => { if (alive) setLoading(false); });
|
||
return () => { alive = false; };
|
||
}, [tab, card, email, tabReload]);
|
||
|
||
// Возврат онлайн-пополнения прямо из карточки: сумму человек вписывает ту, что вернул
|
||
// в кабинете платёжки (кабинет о возврате сайту не сообщает), сервер проверит предел.
|
||
const refund = async (r) => {
|
||
const amount = prompt('Сколько вернули человеку ' + email + ' в кабинете платёжки, ₽?\n'
|
||
+ 'Вернуть можно до ' + rub(r.refundable_rub) + '; аннулируйте чек там же.',
|
||
String(r.refundable_rub));
|
||
if (amount === null || !amount.trim()) return;
|
||
setNotice('');
|
||
try {
|
||
await api('/api/admin/topups/' + r.topup_id + '/refund',
|
||
{method: 'POST', body: JSON.stringify({amount: amount.trim()})});
|
||
setNotice('Возврат ' + amount.trim() + ' ₽ записан');
|
||
setTabReload((n) => n + 1);
|
||
} catch (e) {
|
||
setNotice(e.message || 'Возврат не записан');
|
||
}
|
||
};
|
||
|
||
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`<${Loading} rows={2} />` : html`
|
||
<nav class="tabs">${TABS.map(([k, label]) => html`
|
||
<button type="button" key=${k} class=${k === tab ? 'tab active' : 'tab'}
|
||
onClick=${() => { setRows([]); setSummary(null); 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>Telegram</span><b>${телеграм(card.profile)}</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>` : tab === 'dialogs' ? html`<div class="table-wrap">${loading
|
||
? html`<${Loading} rows={2} />`
|
||
: rows.length === 0 ? html`<p class="note">Пусто.</p>`
|
||
: html`<table class="dialogs"><thead><tr><th>Был(а)</th><th class="num">Сообщений</th>
|
||
<th>Последний вопрос</th><th>Открыть</th></tr></thead>
|
||
<tbody>${rows.map((r) => html`
|
||
<tr key=${r.tab_id}><td>${when(r.last_ts)}</td><td class="num">${r.msg_count}</td>
|
||
<td title=${String(r.title || r.last_question || '')}>${вопрос(r)}</td>
|
||
<td><a href=${'/?tab=' + encodeURIComponent(r.tab_id) +
|
||
'&owner=' + encodeURIComponent(email)} target="_blank"
|
||
rel="noopener noreferrer">Открыть</a></td>
|
||
</tr>`)}</tbody></table>`}</div>`
|
||
: html`<div class="tab-body">
|
||
${!loading && tab === 'ledger' ? html`<p class="note">
|
||
${summary ? html`Баланс <b>${rub(summary.balance_rub)}</b> · внесено
|
||
${rub(summary.deposited_rub)} · израсходовано ${rub(summary.charged_rub)}`
|
||
: own ? 'Счёт не ведётся: владелец или служебная учётка'
|
||
: 'Счёт не заведён'}</p>` : null}
|
||
<div class="table-wrap">${loading
|
||
? html`<${Loading} rows={2} />`
|
||
: rows.length === 0 ? html`<p class="note">Пусто.</p>`
|
||
: tab === 'ledger' ? html`<table class="ledger"><thead><tr><th>Дата</th>
|
||
<th class="num">Сумма</th><th>Примечание</th><th>Кто</th></tr></thead>
|
||
<tbody>${rows.map((r) => html`
|
||
<tr key=${r.id}><td>${when(r.ts)}</td>
|
||
<td class=${'num ' + (r.amount_kop > 0 ? 'ok' : 'bad')}>${деньги(r.amount_kop)}</td>
|
||
<td>${r.comment || '—'}${r.reverses
|
||
? html`<br/><span class="sub">снимает №${r.reverses}</span>` : null}</td>
|
||
<td>${r.created_by === 'topup' ? 'онлайн-оплата' : (r.created_by || '—')}${r.topup_id && r.refundable_rub > 0 ? html`
|
||
<button type="button" style="margin-left:8px;padding:2px 8px;font-size:.72rem;border:1px solid var(--line);border-radius:7px;background:#fff;color:inherit;cursor:pointer"
|
||
onClick=${() => refund(r)}>Вернуть ${rub(r.refundable_rub)}</button>` : null}</td></tr>`)}</tbody></table>`
|
||
: tab === 'files' ? html`<table class="files"><thead><tr><th>Имя</th>
|
||
<th class="num">Размер</th><th>Изменён</th></tr></thead>
|
||
<tbody>${rows.map((r) => html`
|
||
<tr key=${r.name}><td>${r.name}</td><td class="num">${размер(r.size)}</td>
|
||
<td>${when(r.mtime)}</td></tr>`)}</tbody></table>`
|
||
: html`<table class="history"><thead><tr><th>Когда</th><th>Кто</th>
|
||
<th>Действие</th><th class="num">Итог</th></tr></thead>
|
||
<tbody>${rows.map((r) => html`
|
||
<tr key=${r.id}><td>${when(r.timestamp)}</td><td>${r.username || '—'}</td>
|
||
<td>${r.action}<br/><span class="sub">${[r.method, r.path].filter(Boolean).join(' ')}${r.detail ? ' · ' + r.detail : ''}</span></td>
|
||
<td class="num">${r.status_code == null ? '—' : r.status_code}</td></tr>`)}</tbody></table>`}
|
||
</div></div>`}
|
||
`}
|
||
</${Drawer}>`;
|
||
}
|