feat(пополнение): кнопка и окно суммы в чате, ссылка на /stats, колонки и возврат в админке

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
anor
2026-10-28 14:57:27 +10:00
co-authored by Claude Opus 5.5
parent 289ce1ff1e
commit a157d9151c
4 changed files with 195 additions and 16 deletions
+55 -7
View File
@@ -564,6 +564,12 @@ document.addEventListener('DOMContentLoaded',function(){applyThemeIcon();applyDe
<input id="bs-price" type="text" style="width:120px" placeholder="15000"></label>
<label class="field">Коэффициент цены (наценка), ×<br>
<input id="bs-markup" type="text" style="width:80px" placeholder="1,5"></label>
<label class="field">Пополнение онлайн: от, ₽<br>
<input id="bs-topup-min" type="text" style="width:80px" placeholder="300"></label>
<label class="field">до, ₽<br>
<input id="bs-topup-max" type="text" style="width:90px" placeholder="20000"></label>
<label class="field">Суммы-кнопки, ₽ через запятую<br>
<input id="bs-topup-presets" type="text" style="width:170px" placeholder="500,1000,3000,5000"></label>
<button class="btn" onclick="saveBillingSettings()">Сохранить</button>
<span id="bs-note" class="note"></span>
</div>
@@ -806,8 +812,9 @@ document.addEventListener('DOMContentLoaded',function(){applyThemeIcon();applyDe
<div class="page" id="page-payments">
<h2>Платежи</h2>
<table id="payments">
<tr><th>Время</th><th>Пользователь</th><th>Тариф</th><th class="num">₽</th><th>Статус</th><th>ID ЮKassa</th></tr>
<tr><th>Время</th><th>Пользователь</th><th>Что</th><th class="num">₽</th><th>Платёжка</th><th>Номер у платёжки</th><th>Статус</th><th class="num">Зачислено</th><th class="num">Возвращено</th><th class="num">Можно вернуть</th><th></th></tr>
</table>
<p class="note">Возврат делается в кабинете платёжки — там же аннулируйте чек. Потом нажмите «Возврат проведён» и впишите ту же сумму: запись на счёт человека придёт сама.</p>
</div>
<!-- Метрики: четыре сигнала работы службы и продуктовая воронка -->
@@ -2037,6 +2044,11 @@ async function loadBillingSettings() {
document.getElementById('bs-plan').value = d.zai_plan || '';
document.getElementById('bs-price').value = d.zai_plan_price_rub_year || '';
document.getElementById('bs-markup').value = d.price_markup || '';
if (d.topup) {
document.getElementById('bs-topup-min').value = d.topup.min;
document.getElementById('bs-topup-max').value = d.topup.max;
document.getElementById('bs-topup-presets').value = d.topup.presets.join(',');
}
const rub4 = v => v.toFixed(4).replace('.', ',') + ' ₽';
// Причины независимы: курс нужен дипсику, план и цена подписки — зайке. Одна общая
// фраза на все случаи отправляла оператора чинить не то поле (поймал Хозяин 09.09.2026).
@@ -2060,7 +2072,10 @@ async function saveBillingSettings() {
const body = {usd_rub_rate: document.getElementById('bs-rate').value.trim(),
zai_plan: document.getElementById('bs-plan').value,
zai_plan_price_rub_year: document.getElementById('bs-price').value.trim(),
price_markup: document.getElementById('bs-markup').value.trim()};
price_markup: document.getElementById('bs-markup').value.trim(),
topup_min_rub: document.getElementById('bs-topup-min').value.trim(),
topup_max_rub: document.getElementById('bs-topup-max').value.trim(),
topup_presets: document.getElementById('bs-topup-presets').value.trim()};
// Пустое поле не отправляем: ручка меняет только присланное.
for (const k of Object.keys(body)) if (body[k] === '') delete body[k];
if (!Object.keys(body).length) { alert('Нечего сохранять'); return; }
@@ -2201,23 +2216,56 @@ async function loadFinance() {
}
loadFinance();
// === Платежи ЮKassa ===
// === Платежи: старые ЮKassa и пополнения онлайн ===
const PAY_STATUS = {new: 'создан', pending: 'ждёт оплаты', succeeded: 'оплачен', canceled: 'не оплачен',
failed: 'не создан', unapplied: 'оплачен, НЕ зачислен', refunded: 'возвращён'};
async function loadPayments() {
try {
const r = await запрос('/api/admin/payments?days=30');
const d = await r.json();
const t = document.getElementById('payments');
t.innerHTML = '<tr><th>Время</th><th>Пользователь</th><th>Тариф</th><th class="num">₽</th><th>Статус</th><th>ID ЮKassa</th></tr>';
t.innerHTML = '<tr><th>Время</th><th>Пользователь</th><th>Что</th><th class="num">₽</th><th>Платёжка</th>'
+ '<th>Номер у платёжки</th><th>Статус</th><th class="num">Зачислено</th><th class="num">Возвращено</th>'
+ '<th class="num">Можно вернуть</th><th></th></tr>';
const money = v => (v === null || v === undefined) ? '—' : Number(v).toLocaleString('ru-RU', {maximumFractionDigits: 2});
for (const p of d.payments) {
const tr = document.createElement('tr');
const topup = p.kind === 'topup';
const credited = topup && ['succeeded', 'refunded'].includes(p.status) ? p.amount_rub : 0;
// username/product — пользовательские данные → только textContent (не innerHTML)
const cells = [new Date(p.ts * 1000).toLocaleString('ru-RU'), p.username, p.product,
p.amount_rub, p.status, p.yk_payment_id || '—'];
fillCells(tr, cells, [3]);
const cells = [new Date(p.ts * 1000).toLocaleString('ru-RU'), p.username,
topup ? 'пополнение' : p.product, money(p.amount_rub), p.provider,
p.provider_id || '—', PAY_STATUS[p.status] || p.status,
topup ? money(credited) : '—', money(p.refunded_rub),
topup ? money(p.refundable_rub) : '—'];
fillCells(tr, cells, [3, 7, 8, 9]);
const td = document.createElement('td');
if (topup && p.status === 'succeeded') {
const btn = document.createElement('button');
btn.className = 'btn';
btn.textContent = 'Возврат проведён';
btn.onclick = () => topupRefund(p);
td.appendChild(btn);
}
tr.appendChild(td);
t.appendChild(tr);
}
} catch (e) {}
}
async function topupRefund(p) {
const left = p.amount_rub - p.refunded_rub;
const amount = prompt('Сколько вернули человеку ' + p.username + ' в кабинете платёжки, ₽?\n'
+ 'Остаток платежа ' + left.toLocaleString('ru-RU') + ' ₽; не потрачено со счёта '
+ Number(p.refundable_rub).toLocaleString('ru-RU') + ' ₽. Аннулируйте чек там же.',
String(p.refundable_rub || left));
if (amount === null || !amount.trim()) return;
const r = await fetch('/api/admin/topups/' + p.id + '/refund', {method: 'POST',
headers: {...H, 'Content-Type': 'application/json'}, body: JSON.stringify({amount: amount.trim()})});
let d = {};
try { d = await r.json(); } catch (e) {}
if (!r.ok) { alert(d.detail || ('Ответ сервера ' + r.status)); return; }
loadPayments();
}
loadPayments();
// === Files (admin) ===
+117 -5
View File
@@ -523,11 +523,30 @@ html { color-scheme: light; }
<div id="balance-window" style="font-size:.74rem;color:var(--text-muted);margin:6px 0;line-height:1.45"></div>
<div id="balance-price" style="font-size:.74rem;color:var(--text-muted);margin:6px 0;line-height:1.45"></div>
<div id="balance-unknown" style="display:none;font-size:.74rem;color:var(--accent);margin:6px 0;line-height:1.45">Часть ответов ещё не оценена — остаток может уточниться.</div>
<div style="display:flex;justify-content:flex-end;margin-top:10px">
<div style="display:flex;justify-content:flex-end;gap:8px;flex-wrap:wrap;margin-top:10px">
<button type="button" id="topup-open-btn" onclick="closeBalancePopover(); openTopupModal()" style="display:none;padding:5px 14px;font-size:.8rem;background:var(--accent);color:#fff;border:none;border-radius:7px;cursor:pointer;font-weight:600">Пополнить счёт</button>
<button type="button" onclick="closeBalancePopover()" style="padding:5px 12px;font-size:.8rem;background:transparent;border:1px solid var(--border);border-radius:7px;color:var(--text-muted);cursor:pointer">Закрыть</button>
</div>
</div>
<!-- Пополнение счёта онлайн: сумма → страница оплаты. Суммы и пределы приходят с сервера
(/api/limits → topup), сервер же и проверяет сумму. -->
<div id="topup-modal" role="dialog" aria-modal="true" aria-labelledby="topup-title" style="display:none;position:fixed;inset:0;z-index:2100;background:rgba(0,0,0,.35);align-items:center;justify-content:center;padding:16px">
<div style="background:var(--bg-card);border:1px solid var(--border);border-radius:12px;padding:16px 18px;box-shadow:0 8px 30px rgba(0,0,0,.22);width:100%;max-width:380px">
<div id="topup-title" style="font-size:.95rem;font-weight:600;color:var(--text)">Пополнить счёт</div>
<div id="topup-presets" style="display:grid;grid-template-columns:repeat(2,1fr);gap:8px;margin:12px 0"></div>
<label for="topup-amount" style="font-size:.78rem;color:var(--text-muted)">Своя сумма, ₽ <span id="topup-range"></span></label>
<input id="topup-amount" type="text" inputmode="decimal" autocomplete="off" style="width:100%;margin:4px 0 8px;padding:7px 9px;font-size:.9rem;border:1px solid var(--border);border-radius:7px;background:var(--bg);color:var(--text)">
<div id="topup-email" style="font-size:.74rem;color:var(--text-muted);line-height:1.45">Чек придёт на <span id="topup-email-addr"></span>.</div>
<div style="font-size:.74rem;color:var(--text-muted);line-height:1.45;margin-top:4px">Оплата от физического лица. Организации — напишите на info@infosmeta.ru.</div>
<div id="topup-error" role="alert" style="display:none;font-size:.78rem;color:var(--accent);margin-top:8px;line-height:1.4"></div>
<div style="display:flex;justify-content:flex-end;gap:8px;flex-wrap:wrap;margin-top:12px">
<button type="button" onclick="closeTopupModal()" style="padding:6px 12px;font-size:.82rem;background:transparent;border:1px solid var(--border);border-radius:7px;color:var(--text-muted);cursor:pointer">Отмена</button>
<button type="button" id="topup-go" onclick="goTopup()" style="padding:6px 14px;font-size:.82rem;background:var(--accent);color:#fff;border:none;border-radius:7px;cursor:pointer;font-weight:600">Перейти к оплате</button>
</div>
</div>
</div>
<!-- Оператор открыл чужой диалог: чтобы он не принял его за свой и не написал туда. -->
<div id="view-banner" role="status" style="display:none">
<span id="view-banner-text"></span>
@@ -1897,6 +1916,15 @@ async function loadLimits() {
if (!r.ok) return;
renderBalance(await r.json());
} catch (e) {}
// «Попробовать снова» со страницы результата оплаты ведёт сюда с ?topup=1.
try {
const q = new URLSearchParams(location.search);
if (q.get('topup') === '1' && lastBalance && lastBalance.topup) {
q.delete('topup');
history.replaceState(null, '', location.pathname + (q.toString() ? '?' + q : ''));
openTopupModal();
}
} catch (e) {}
}
// Какая ось ближе всего к исчерпанию — её и показываем, когда места мало.
@@ -1977,6 +2005,9 @@ function renderBalance(b) {
const ACCOUNT_PRICE_TEXT =
'Списывается цена каждого ответа: чем объёмнее разбор, тем дороже он стоит. Когда счёт ' +
'кончится, новые вопросы закроются до пополнения — напишите на info@infosmeta.ru.';
const ACCOUNT_PRICE_TEXT_TOPUP =
'Списывается цена каждого ответа: чем объёмнее разбор, тем дороже он стоит. Когда счёт ' +
'кончится, новые вопросы закроются до пополнения.';
function accountWindowText(b) {
const a = b.account;
const since = new Date(a.since * 1000).toLocaleDateString('ru-RU');
@@ -2021,10 +2052,11 @@ function openBalancePopover() {
}
if (b.read_only) {
// Ручной режим при живом счёте — решение оператора, «пополните счёт» тут было бы враньём.
// Блок пополнения сервер шлёт только при исчерпанном счёте без ручного режима.
document.getElementById('balance-window').textContent = (b.account && b.account.exhausted)
? 'Баланс исчерпан: на счёте ' + fmtRub(b.account.balance_rub) + '. Новые вопросы и ' +
'загрузка файлов закрыты, диалоги доступны для просмотра. Чтобы пополнить счёт, ' +
'напишите на info@infosmeta.ru.'
(b.topup ? 'нажмите «Пополнить счёт».' : 'напишите на info@infosmeta.ru.')
: 'Баланс исчерпан: новые вопросы ' +
'и загрузка файлов закрыты, диалоги доступны для просмотра. Чтобы продолжить работу, ' +
'напишите на info@infosmeta.ru.';
@@ -2033,8 +2065,10 @@ function openBalancePopover() {
}
if (b.account && !b.read_only && !b.trial) {
document.getElementById('balance-window').textContent = accountWindowText(b);
document.getElementById('balance-price').textContent = ACCOUNT_PRICE_TEXT;
document.getElementById('balance-price').textContent =
b.topup ? ACCOUNT_PRICE_TEXT_TOPUP : ACCOUNT_PRICE_TEXT;
}
document.getElementById('topup-open-btn').style.display = b.topup ? '' : 'none';
const badge = document.getElementById('balance-badge');
// Повторный клик по бейджу закрывает — иначе всплывашку убрать нечем.
if (pop.style.display !== 'none' && pop.style.display !== '') { closeBalancePopover(); return; }
@@ -2057,6 +2091,85 @@ function _balanceOutside(e) {
}
function _balanceEsc(e) { if (e.key === 'Escape') closeBalancePopover(); }
// === Пополнение счёта онлайн ===
let topupAmount = '';
function openTopupModal() {
const topup = lastBalance && lastBalance.topup;
if (!topup) return;
const box = document.getElementById('topup-presets');
box.textContent = '';
topupAmount = '';
for (const p of topup.presets) {
const btn = document.createElement('button');
btn.type = 'button';
btn.textContent = fmtRub(p);
btn.style.cssText = 'padding:8px;font-size:.88rem;background:transparent;border:1px solid var(--border);border-radius:7px;color:var(--text);cursor:pointer';
btn.onclick = () => {
topupAmount = String(p);
document.getElementById('topup-amount').value = '';
for (const other of box.children) other.style.borderColor = 'var(--border)';
btn.style.borderColor = 'var(--accent)';
};
box.appendChild(btn);
}
document.getElementById('topup-range').textContent =
'(от ' + fmtRub(topup.min) + ' до ' + fmtRub(topup.max) + ')';
const input = document.getElementById('topup-amount');
input.value = '';
input.oninput = () => {
topupAmount = '';
for (const other of box.children) other.style.borderColor = 'var(--border)';
};
let email = '';
try { email = _jwtPayload(token).sub || ''; } catch (e) {}
document.getElementById('topup-email-addr').textContent = email;
document.getElementById('topup-email').style.display = email ? '' : 'none';
document.getElementById('topup-error').style.display = 'none';
document.getElementById('topup-go').disabled = false;
document.getElementById('topup-modal').style.display = 'flex';
document.addEventListener('keydown', _topupEsc);
}
function closeTopupModal() {
document.getElementById('topup-modal').style.display = 'none';
document.removeEventListener('keydown', _topupEsc);
}
function _topupEsc(e) { if (e.key === 'Escape') closeTopupModal(); }
function _topupError(text) {
const el = document.getElementById('topup-error');
el.textContent = text;
el.style.display = '';
}
async function goTopup() {
const own = document.getElementById('topup-amount').value.trim();
const amount = own || topupAmount;
if (!amount) { _topupError('Выберите сумму или впишите свою.'); return; }
const go = document.getElementById('topup-go');
go.disabled = true;
try {
const r = await authFetch('/api/topups', {method: 'POST',
headers: {'Content-Type': 'application/json'}, body: JSON.stringify({amount: amount})});
if (!r.ok) { _topupError(await reasonOrText(r)); go.disabled = false; return; }
const d = await r.json();
// Страница результата берёт номер из адреса; это — запасной путь.
try { localStorage.setItem('last_topup_id', String(d.topup_id)); } catch (e) {}
location.href = d.pay_url;
} catch (e) {
_topupError('Не удалось связаться с сервером. Проверьте связь и попробуйте ещё раз.');
go.disabled = false;
}
}
// После отказа «баланс исчерпан»: кнопка пополнения прямо под отказом.
async function offerTopup(msgDiv) {
await loadLimits();
if (!msgDiv || !lastBalance || !lastBalance.topup) return;
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'copy-btn';
btn.textContent = 'Пополнить счёт';
btn.onclick = openTopupModal;
msgDiv.appendChild(btn);
}
// Цена ответа — отдельной строкой в конце пузыря. Кнопки идут блоками с margin-left:auto,
// поэтому строка встаёт под ними и ничего не задевает.
function attachCost(div, a) {
@@ -2241,8 +2354,7 @@ async function runChat(text, retried, готовыйПоток, внешнийCt
// последним стоит ответ, а чужой вопрос выше трогать нельзя.
const последний = [...document.querySelectorAll('#messages .msg')].pop();
if (последний && последний.classList.contains('msg-user')) последний.remove();
addMsg('error', await reasonOrText(r));
loadLimits(); // значок остатка тоже узнаёт про «баланс исчерпан»
offerTopup(addMsg('error', await reasonOrText(r))); // и значок узнаёт про «исчерпан»
// Только в пустое поле: набранное за время запроса не затираем. Событие ввода —
// чтобы штатный черновик сохранил вопрос и он пережил перезагрузку.
const поле = document.getElementById('msg-input');
+18 -3
View File
@@ -55,6 +55,7 @@ td.bar-cell { width: 38%; }
.bar { height: 10px; border-radius: 5px; background: var(--bar); min-width: 2px; }
.bar.zero { background: var(--border); }
.bad { color: var(--accent); font-weight: 600; }
.topup-link { display: inline-block; margin: .5rem 0; padding: .45rem .9rem; background: var(--accent, #c4463a); color: #fff; border-radius: 8px; text-decoration: none; font-weight: 600; font-size: .9rem; }
.deposits { list-style: none; margin-top: .4rem; font-variant-numeric: tabular-nums; }
.deposits li { padding: .2rem 0; border-bottom: 1px solid var(--border-light); font-size: .9rem; }
.state { padding: 1.5rem 0; text-align: center; color: var(--text-muted); }
@@ -210,10 +211,21 @@ function renderBalance(b) {
// Счёт (предоплата). «Списано со счёта» — по цене под ответами с первого взноса, а карточка
// «Потрачено за всё время» — вся история по нынешней цене: подписи разные, чтобы человек
// не складывал одно с другим.
function renderAccount(acc, deposits, readOnly) {
function topupLink() {
const a = el('a', 'topup-link', 'Пополнить счёт');
a.href = '/?topup=1';
return a;
}
function renderAccount(acc, deposits, readOnly, topup) {
const sec = document.getElementById('account');
const box = document.getElementById('account-body');
box.textContent = '';
if (!acc && topup) {
box.append(el('p', 'muted', 'Счёт ещё не пополнялся.'), topupLink());
sec.hidden = false;
return;
}
if (!acc) { sec.hidden = true; return; }
const since = new Date(acc.since * 1000).toLocaleDateString('ru-RU');
box.append(el('p', 'balance-line', 'На счёте: ' + rub(acc.balance_rub)));
@@ -221,8 +233,10 @@ function renderAccount(acc, deposits, readOnly) {
': ' + rub(acc.charged_rub)));
// Исчерпан — это уже сказано в блоке «Баланс» (read_only); второй раз не повторяем.
if (acc.exhausted && !readOnly) {
box.append(el('p', 'bad', 'Баланс исчерпан: новые вопросы закрыты до пополнения. Напишите на info@infosmeta.ru.'));
box.append(el('p', 'bad', 'Баланс исчерпан: новые вопросы закрыты до пополнения.' +
(topup ? '' : ' Напишите на info@infosmeta.ru.')));
}
if (topup) box.append(topupLink());
if (deposits && deposits.length) {
box.append(el('p', 'muted', 'Пополнения:'));
const ul = el('ul', 'deposits');
@@ -279,7 +293,8 @@ async function load() {
un.hidden = !s.unpriced;
if (s.unpriced) un.textContent = 'Цена ещё не посчитана у ' + s.unpriced + ' ответ(ов) — они в итог не вошли.';
renderBalance(res.body.limits || {});
renderAccount((res.body.limits || {}).account, res.body.deposits, (res.body.limits || {}).read_only);
renderAccount((res.body.limits || {}).account, res.body.deposits, (res.body.limits || {}).read_only,
(res.body.limits || {}).topup);
renderDays(s.days);
document.getElementById('state').hidden = true;
document.getElementById('content').hidden = false;
+5 -1
View File
@@ -49,9 +49,13 @@ def test_chat_offers_topup_on_refusal_and_after_return():
def test_stats_has_topup_link():
html = _read("stats.html")
link = html[html.index("function topupLink"):]
link = link[:link.index("\n}\n")]
assert "Пополнить счёт" in link and "/?topup=1" in link
fn = html[html.index("function renderAccount"):]
fn = fn[:fn.index("\n}\n")]
assert "Пополнить счёт" in fn and "/?topup=1" in fn and "topup" in fn
assert "if (topup) box.append(topupLink())" in fn and "!acc && topup" in fn
assert "(res.body.limits || {}).topup" in html
def test_admin_payments_columns_refund_and_settings():