merge: пополнение счёта и Robokassa в текущую ветку
Конфликты сведены: таблицы topups рядом с админскими, старая таблица платежей сохраняет CSV и получает колонки пополнений, окно остатка — ссылка на цены и кнопка пополнения; тесты 404 и админской таблицы приведены к текущим ответам с request_id. Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
+67
-13
@@ -596,6 +596,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>
|
||||
@@ -707,9 +713,13 @@ document.addEventListener('DOMContentLoaded',function(){applyThemeIcon();applyDe
|
||||
"Токены (вход/выход)": "Сколько модель прочитала и сколько написала за день. Токены из кэша здесь не показаны — они есть в сводке по моделям."
|
||||
},
|
||||
"payments": {
|
||||
"Тариф": "Что куплено. agent-month — агентные функции на 30 дней.",
|
||||
"Статус": "pending — ждёт оплаты; succeeded — оплачен, доступ продлён; canceled — отменён; refunded — деньги возвращены.",
|
||||
"ID ЮKassa": "Номер платежа в кабинете ЮKassa — по нему платёж находится у них при сверке."
|
||||
"Что": "Пополнение — онлайн-пополнение счёта; agent-month — старый тариф ЮKassa (агентные функции на 30 дней).",
|
||||
"Платёжка": "Через какую платёжку прошёл платёж.",
|
||||
"Номер у платёжки": "Номер платежа в кабинете платёжки — по нему платёж находится у них при сверке и возврате.",
|
||||
"Статус": "Ждёт оплаты — человек ушёл платить; оплачен — деньги зачислены на счёт; не оплачен — отменён или брошен; оплачен, НЕ зачислен — сумма не сошлась или учётки нет, разобрать вручную; возвращён — деньги вернули целиком.",
|
||||
"Зачислено": "Сколько записано на счёт человека по этому платежу.",
|
||||
"Возвращено": "Сколько уже вернули по этому платежу (возврат делается в кабинете платёжки).",
|
||||
"Можно вернуть": "Подсказка: меньшее из остатка платежа и остатка на счёте. Вернуть больше можно, но счёт уйдёт в минус и работа закроется."
|
||||
},
|
||||
"mx-latency": {
|
||||
"Задержка, медиана": "Половина ответов пришла быстрее этого времени, половина — медленнее. Обычный, а не худший случай.",
|
||||
@@ -859,9 +869,12 @@ document.addEventListener('DOMContentLoaded',function(){applyThemeIcon();applyDe
|
||||
<div class="page" id="page-payments">
|
||||
<h2>Платежи</h2>
|
||||
<div class="toolbar"><button type="button" class="btn-sm" onclick="downloadCsv('/api/admin/export/payments.csv?days=30', 'payments.csv')">CSV</button> <span id="payments-updated" class="note" role="status"></span></div>
|
||||
<div class="table-wrap">
|
||||
<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>
|
||||
</div>
|
||||
<p class="note">Возврат делается в кабинете платёжки — там же аннулируйте чек. Потом нажмите «Возврат проведён» и впишите ту же сумму: запись на счёт человека придёт сама.</p>
|
||||
</div>
|
||||
|
||||
<!-- Метрики: четыре сигнала работы службы и продуктовая воронка -->
|
||||
@@ -2264,6 +2277,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).
|
||||
@@ -2287,7 +2305,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; }
|
||||
@@ -2450,35 +2471,68 @@ async function loadFinance() {
|
||||
}
|
||||
loadFinance();
|
||||
|
||||
// === Платежи ЮKassa ===
|
||||
const PAY_HEAD = '<tr><th>Время</th><th>Пользователь</th><th>Тариф</th><th class="num">₽</th><th>Статус</th><th>ID ЮKassa</th></tr>';
|
||||
// === Платежи: старые ЮKassa и пополнения онлайн ===
|
||||
const PAY_HEAD = '<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 PAY_STATUS = {new: 'создан', pending: 'ждёт оплаты', succeeded: 'оплачен', canceled: 'не оплачен',
|
||||
failed: 'не создан', unapplied: 'оплачен, НЕ зачислен', refunded: 'возвращён'};
|
||||
async function loadPayments() {
|
||||
const t = document.getElementById('payments');
|
||||
const upd = document.getElementById('payments-updated');
|
||||
if (!t) return;
|
||||
t.innerHTML = PAY_HEAD + '<tr><td colspan="6" class="dim">Загрузка…</td></tr>';
|
||||
t.innerHTML = PAY_HEAD + '<tr><td colspan="11" class="dim">Загрузка…</td></tr>';
|
||||
try {
|
||||
const r = await запрос('/api/admin/payments?days=30');
|
||||
const d = await r.json();
|
||||
t.innerHTML = PAY_HEAD;
|
||||
const money = v => (v === null || v === undefined) ? '—' : Number(v).toLocaleString('ru-RU', {maximumFractionDigits: 2});
|
||||
if (!d.payments.length) {
|
||||
t.insertAdjacentHTML('beforeend', '<tr class="row-empty"><td colspan="6">Платежей за 30 дней нет</td></tr>');
|
||||
t.insertAdjacentHTML('beforeend', '<tr class="row-empty"><td colspan="11">Платежей за 30 дней нет</td></tr>');
|
||||
}
|
||||
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);
|
||||
}
|
||||
if (upd) upd.textContent = 'обновлено ' + new Date().toLocaleTimeString('ru-RU', {hour:'2-digit', minute:'2-digit'});
|
||||
} catch (e) {
|
||||
t.innerHTML = PAY_HEAD + '<tr><td colspan="6" class="bad">Не удалось загрузить платежи: '
|
||||
t.innerHTML = PAY_HEAD + '<tr><td colspan="11" class="bad">Не удалось загрузить платежи: '
|
||||
+ esc(e.message || 'сеть') + ' <button type="button" class="btn-sm" onclick="loadPayments()">Повторить</button></td></tr>';
|
||||
if (upd) upd.textContent = 'ошибка загрузки';
|
||||
}
|
||||
}
|
||||
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) ===
|
||||
|
||||
+124
-5
@@ -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');
|
||||
|
||||
+79
-31
@@ -8,12 +8,16 @@
|
||||
:root { --bg: #f5f0eb; --card: #fff; --text: #3a3a3a; --muted: #6b6b6b; --accent: #c4463a; --border: #d4c5b2; --radius: 10px; --green: #2d8a56; }
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); min-height: 100vh; display: flex; align-items: center; justify-content: center; }
|
||||
.card { background: var(--card); border-radius: var(--radius); padding: 2rem; width: 380px; box-shadow: 0 2px 12px rgba(0,0,0,.08); text-align: center; }
|
||||
.card { background: var(--card); border-radius: var(--radius); padding: 2rem; width: 380px; max-width: calc(100vw - 32px); box-shadow: 0 2px 12px rgba(0,0,0,.08); text-align: center; }
|
||||
h1 { font-size: 1.2rem; margin-bottom: .3rem; }
|
||||
.subtitle { color: var(--muted); font-size: .85rem; margin-bottom: 1.5rem; }
|
||||
.status { font-size: .95rem; margin-bottom: 1.2rem; line-height: 1.45; }
|
||||
.status.ok { color: var(--green); font-weight: 600; }
|
||||
.status.fail { color: var(--accent); }
|
||||
.hint { color: var(--muted); font-size: .85rem; margin: -.6rem 0 1.2rem; line-height: 1.4; }
|
||||
.btns { display: flex; flex-direction: column; gap: .5rem; }
|
||||
.btns .ghost { background: transparent; color: var(--text); border: 1px solid var(--border); }
|
||||
.btns .ghost:hover { background: var(--bg); }
|
||||
.spinner { width: 28px; height: 28px; margin: 0 auto 1rem; border: 3px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .9s linear infinite; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
button { width: 100%; padding: .7rem; background: var(--accent); color: #fff; border: none; border-radius: var(--radius); font-size: .95rem; font-weight: 600; cursor: pointer; }
|
||||
@@ -35,52 +39,96 @@ html { color-scheme: light; }
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<h1>Оплата</h1>
|
||||
<h1>Пополнение счёта</h1>
|
||||
<p class="subtitle">Сметный ИИ-ассистент</p>
|
||||
<div class="spinner" id="spinner"></div>
|
||||
<div class="status" id="status">Проверяем оплату…</div>
|
||||
<button onclick="window.location.href='/'">Вернуться в чат</button>
|
||||
<div class="status" id="status">Проверяем платёж…</div>
|
||||
<p class="hint" id="hint" hidden></p>
|
||||
<div class="btns">
|
||||
<button id="retry" class="ghost" hidden onclick="window.location.href='/?topup=1'">Попробовать снова</button>
|
||||
<button onclick="window.location.href='/'">Вернуться в чат</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Страница — ТОЛЬКО UX: поллинг статуса СВОЕГО платежа. Доступ выдаёт сервер
|
||||
// (вебхук/сверка), даже если эту страницу закрыть — оплата не потеряется.
|
||||
// Страница — только показ: деньги зачисляют уведомление платёжки и сверка на сервере,
|
||||
// даже если эту страницу закрыть. Опрос своего платежа раз в 3 с до 2 минут.
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
// payment_id: из query (если положили в return_url вручную) или из localStorage —
|
||||
// кнопка «Оплатить» сохраняет его перед редиректом на ЮKassa.
|
||||
const paymentId = params.get('payment_id') || localStorage.getItem('last_payment_id') || '';
|
||||
const token = localStorage.getItem('token') || '';
|
||||
let topupId = params.get('t') || '';
|
||||
try { if (!topupId) topupId = localStorage.getItem('last_topup_id') || ''; } catch (e) {}
|
||||
// Старые платежи (до пополнения): payment_id → прежняя ручка статуса.
|
||||
let legacyId = params.get('payment_id') || '';
|
||||
try { if (!topupId && !legacyId) legacyId = localStorage.getItem('last_payment_id') || ''; } catch (e) {}
|
||||
let token = '';
|
||||
try { token = localStorage.getItem('token') || ''; } catch (e) {}
|
||||
const statusEl = document.getElementById('status');
|
||||
const hintEl = document.getElementById('hint');
|
||||
const spinnerEl = document.getElementById('spinner');
|
||||
const UNKNOWN = 'Не удалось проверить платёж. Если деньги списались — они появятся на счёте ' +
|
||||
'в течение часа; если нет — напишите на info@infosmeta.ru.';
|
||||
const WAITING = 'Банк ещё подтверждает платёж. Деньги появятся на счёте сами, страницу можно закрыть.';
|
||||
let tries = 0;
|
||||
|
||||
function show(text, cls) {
|
||||
statusEl.textContent = text;
|
||||
statusEl.className = 'status' + (cls ? ' ' + cls : '');
|
||||
if (cls) spinnerEl.style.display = 'none';
|
||||
function rub(v) {
|
||||
return Number(v).toLocaleString('ru-RU', {minimumFractionDigits: 0, maximumFractionDigits: 2}) + ' ₽';
|
||||
}
|
||||
|
||||
async function poll() {
|
||||
if (!paymentId) { show('Платёж не найден. Если вы оплатили — доступ включится автоматически в течение нескольких минут.', 'fail'); return; }
|
||||
if (!token) { show('Вы не вошли в систему. Войдите — статус оплаты обновится автоматически.', 'fail'); return; }
|
||||
function show(text, cls, hint) {
|
||||
statusEl.textContent = text;
|
||||
statusEl.className = 'status' + (cls ? ' ' + cls : '');
|
||||
if (cls !== undefined) spinnerEl.style.display = 'none';
|
||||
hintEl.hidden = !hint;
|
||||
hintEl.textContent = hint || '';
|
||||
}
|
||||
|
||||
async function pollTopup() {
|
||||
if (!token) { show(UNKNOWN, 'fail', 'Войдите на сайт — состояние платежа обновится.'); return; }
|
||||
try {
|
||||
const r = await fetch('/api/payments/status?payment_id=' + encodeURIComponent(paymentId),
|
||||
{headers: {'Authorization': 'Bearer ' + token}});
|
||||
if (r.status === 401) { show('Сессия истекла. Войдите заново — оплата не потеряется.', 'fail'); return; }
|
||||
if (!r.ok) { show('Платёж не найден. Если деньги списались — доступ включится автоматически.', 'fail'); return; }
|
||||
const d = await r.json();
|
||||
if (d.status === 'succeeded') { show('Оплата прошла! Агентные функции активированы.', 'ok'); return; }
|
||||
if (d.status === 'canceled') { show('Оплата не завершена (отменена или отклонена). Деньги не списаны.', 'fail'); return; }
|
||||
if (d.status === 'refunded') { show('По этому платежу оформлен возврат.', 'fail'); return; }
|
||||
const r = await fetch('/api/topups/' + encodeURIComponent(topupId),
|
||||
{headers: {'Authorization': 'Bearer ' + token}, cache: 'no-store'});
|
||||
if (r.status === 401 || r.status === 404 || r.status === 400) { show(UNKNOWN, 'fail'); return; }
|
||||
if (r.ok) {
|
||||
const d = await r.json();
|
||||
if (d.status === 'succeeded') {
|
||||
try { localStorage.removeItem('last_topup_id'); } catch (e) {}
|
||||
show('Зачислено ' + rub(d.amount_rub) + '.', 'ok',
|
||||
d.balance_rub === null || d.balance_rub === undefined ? '' : 'На счёте ' + rub(d.balance_rub));
|
||||
return;
|
||||
}
|
||||
if (d.status === 'canceled') {
|
||||
document.getElementById('retry').hidden = false;
|
||||
show('Оплата не прошла, деньги не списаны.', 'fail');
|
||||
return;
|
||||
}
|
||||
if (d.status === 'refunded') { show('По этому платежу оформлен возврат.', 'fail'); return; }
|
||||
if (d.status === 'failed') { show(UNKNOWN, 'fail'); return; }
|
||||
show(WAITING);
|
||||
}
|
||||
} catch (e) { /* сеть моргнула — следующая попытка */ }
|
||||
tries++;
|
||||
if (tries >= 40) { // ~2 минуты: вебхук мог задержаться — доберёт фоновая сверка
|
||||
show('Оплата ещё обрабатывается. Доступ включится автоматически — можно вернуться в чат.', '');
|
||||
return;
|
||||
}
|
||||
setTimeout(poll, 3000);
|
||||
if (tries >= 40) { show(WAITING, ''); return; }
|
||||
setTimeout(pollTopup, 3000);
|
||||
}
|
||||
poll();
|
||||
|
||||
async function pollLegacy() {
|
||||
if (!token) { show(UNKNOWN, 'fail'); return; }
|
||||
try {
|
||||
const r = await fetch('/api/payments/status?payment_id=' + encodeURIComponent(legacyId),
|
||||
{headers: {'Authorization': 'Bearer ' + token}});
|
||||
if (!r.ok) { show(UNKNOWN, 'fail'); return; }
|
||||
const d = await r.json();
|
||||
if (d.status === 'succeeded') { show('Оплата прошла.', 'ok'); return; }
|
||||
if (d.status === 'canceled') { show('Оплата не прошла, деньги не списаны.', 'fail'); return; }
|
||||
if (d.status === 'refunded') { show('По этому платежу оформлен возврат.', 'fail'); return; }
|
||||
} catch (e) {}
|
||||
tries++;
|
||||
if (tries >= 40) { show(WAITING, ''); return; }
|
||||
setTimeout(pollLegacy, 3000);
|
||||
}
|
||||
|
||||
if (topupId) pollTopup();
|
||||
else if (legacyId) pollLegacy();
|
||||
else show(UNKNOWN, 'fail');
|
||||
</script>
|
||||
<!-- Переключатель темы — тот же на всех страницах (сказал Хозяин 18.11) -->
|
||||
<style>
|
||||
|
||||
+20
-4
@@ -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); }
|
||||
@@ -182,7 +183,8 @@ function renderBalance(b) {
|
||||
b.read_only ? 'Баланс' : (b.trial ? 'Пробный доступ' : 'Остаток на сутки');
|
||||
if (b.read_only) {
|
||||
box.append(el('p', 'balance-line', 'Баланс исчерпан: новые вопросы закрыты, диалоги доступны для просмотра. ' +
|
||||
'Чтобы продолжить, напишите на info@infosmeta.ru.'));
|
||||
(b.topup ? 'Чтобы продолжить, нажмите «Пополнить счёт» в блоке «Счёт».'
|
||||
: 'Чтобы продолжить, напишите на info@infosmeta.ru.')));
|
||||
return;
|
||||
}
|
||||
if (b.trial) {
|
||||
@@ -210,10 +212,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 +234,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 +294,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;
|
||||
|
||||
Reference in New Issue
Block a user