merge: пополнение счёта и Robokassa в текущую ветку

Конфликты сведены: таблицы topups рядом с админскими, старая таблица
платежей сохраняет CSV и получает колонки пополнений, окно остатка —
ссылка на цены и кнопка пополнения; тесты 404 и админской таблицы
приведены к текущим ответам с request_id.

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
anor
2026-11-20 23:06:59 +10:00
co-authored by Claude Code
19 changed files with 2947 additions and 93 deletions
+124 -5
View File
@@ -749,11 +749,30 @@ html { color-scheme: light; }
<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="font-size:.74rem;margin:6px 0;line-height:1.45"><a href="/static/pricing.html" target="_blank" rel="noopener" style="color:var(--accent)">Стоимость услуг и как считается цена</a></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>
@@ -2244,12 +2263,26 @@ function fmtWhen(epoch) {
return d.toLocaleDateString('ru-RU', {day: '2-digit', month: '2-digit'}) + ' в ' + fmtTime(epoch);
}
async function loadLimits() {
let limitsLoading = null;
function loadLimits() {
limitsLoading = _loadLimits();
return limitsLoading;
}
async function _loadLimits() {
try {
const r = await authFetch(API + '/api/limits');
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) {}
}
// Какая ось ближе всего к исчерпанию — её и показываем, когда места мало.
@@ -2330,6 +2363,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');
@@ -2374,10 +2410,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.';
@@ -2386,8 +2423,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; }
@@ -2410,6 +2449,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 limitsLoading;
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) {
@@ -2598,8 +2716,9 @@ async function runChat(text, retried, готовыйПоток, внешнийCt
// последним стоит ответ, а чужой вопрос выше трогать нельзя.
const последний = [...document.querySelectorAll('#messages .msg')].pop();
if (последний && последний.classList.contains('msg-user')) последний.remove();
addMsg('error', await reasonOrText(r));
const отказ = addMsg('error', await reasonOrText(r));
loadLimits(); // значок остатка тоже узнаёт про «баланс исчерпан»
offerTopup(отказ);
// Только в пустое поле: набранное за время запроса не затираем. Событие ввода —
// чтобы штатный черновик сохранил вопрос и он пережил перезагрузку.
const поле = document.getElementById('msg-input');