diff --git a/static/admin.html b/static/admin.html
index 2f6ddda..9f9cdfe 100644
--- a/static/admin.html
+++ b/static/admin.html
@@ -564,6 +564,12 @@ document.addEventListener('DOMContentLoaded',function(){applyThemeIcon();applyDe
Коэффициент цены (наценка), ×
+ Пополнение онлайн: от, ₽
+
+ до, ₽
+
+ Суммы-кнопки, ₽ через запятую
+
Сохранить
@@ -806,8 +812,9 @@ document.addEventListener('DOMContentLoaded',function(){applyThemeIcon();applyDe
Платежи
- Время Пользователь Тариф ₽ Статус ID ЮKassa
+ Время Пользователь Что ₽ Платёжка Номер у платёжки Статус Зачислено Возвращено Можно вернуть
+
Возврат делается в кабинете платёжки — там же аннулируйте чек. Потом нажмите «Возврат проведён» и впишите ту же сумму: запись на счёт человека придёт сама.
@@ -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 = 'Время Пользователь Тариф ₽ Статус ID ЮKassa ';
+ t.innerHTML = 'Время Пользователь Что ₽ Платёжка '
+ + 'Номер у платёжки Статус Зачислено Возвращено '
+ + 'Можно вернуть ';
+ 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) ===
diff --git a/static/chat.html b/static/chat.html
index 80744b6..8972b01 100644
--- a/static/chat.html
+++ b/static/chat.html
@@ -523,11 +523,30 @@ html { color-scheme: light; }
Часть ответов ещё не оценена — остаток может уточниться.
-
+
+ Пополнить счёт
Закрыть
+
+
+
+
Пополнить счёт
+
+
Своя сумма, ₽
+
+
Чек придёт на .
+
Оплата от физического лица. Организации — напишите на info@infosmeta.ru.
+
+
+ Отмена
+ Перейти к оплате
+
+
+
+
@@ -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');
diff --git a/static/stats.html b/static/stats.html
index 69d2633..5b3893f 100644
--- a/static/stats.html
+++ b/static/stats.html
@@ -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;
diff --git a/tests/test_topup_pages.py b/tests/test_topup_pages.py
index 92c853d..9881093 100644
--- a/tests/test_topup_pages.py
+++ b/tests/test_topup_pages.py
@@ -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():