feat(расходы): фильтры, сводка по моделям, время ответа и цена зайки по тарифам API

Страница расходов теперь смотрится за день, за интервал и по конкретному человеку.
Появилась сводка по моделям: токены отдельно вход-кэш-выход, деньги, кредиты подписки и
время ответа — среднее и суммарное, от подачи запроса до ответа модели (пишется по обоим
путям, старые строки остаются пустыми, а не нулевыми).

Цена зайки по её потокенным тарифам считается вдобавок к доле подписки, а не вместо неё:
за подписку мы платим не за токены, и подменять ею счёт нельзя. Пока годовая цена плана не
задана, себестоимость зайки берётся по тарифам, и основание расчёта видно в сводке.

Отдельная страница «Финансы»: поступления (успешные платежи, возвраты показаны рядом и
выручкой не считаются), себестоимость работы ИИ, прибыль и её доля. Ни одно среднее не
считается на нулевом делителе — прочерк вместо выдуманного числа.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RuEU1u9Rz24zmoy9TuvWc2
This commit is contained in:
anor
2026-09-09 21:58:10 +10:00
co-authored by Claude Opus 5
parent 87da1eaaa3
commit 36b8c3aa2f
11 changed files with 1184 additions and 41 deletions
+203 -1
View File
@@ -87,6 +87,7 @@ document.addEventListener('DOMContentLoaded',applyThemeIcon);
<a href="#files" onclick="return showPage('files')">Файлы</a>
<a href="#costs" onclick="return showPage('costs')">Расходы</a>
<a href="#payments" onclick="return showPage('payments')">Платежи</a>
<a href="#finance" onclick="return showPage('finance')">Финансы</a>
<a href="#" id="theme-toggle" onclick="toggleTheme();return false">🌙 Тёмная тема</a>
<a href="/" class="back">← Вернуться в чат</a>
<div class="app-version" style="position:absolute;bottom:.5rem;left:1rem;font-size:.65rem;color:#999"></div>
@@ -213,6 +214,28 @@ document.addEventListener('DOMContentLoaded',applyThemeIcon);
<!-- Пятичасовое окно подписки зайки: свой предел провайдера, к нашим рублям отношения
не имеет, но именно он первым остановит агентный путь. -->
<div id="zaika-quota" style="margin:.4rem 0 .8rem;font-size:.85rem;color:var(--muted)"></div>
<!-- Фильтры отчёта. Суммы «за 24 часа» выше им НЕ подчиняются: это другой вопрос,
и подмешать в них период значит соврать подписью. -->
<div style="margin:.4rem 0 .8rem;display:flex;gap:.6rem;align-items:flex-end;flex-wrap:wrap">
<label style="font-size:.8rem;color:var(--muted)">Пользователь<br>
<select id="costs-user" style="min-width:200px"><option value="">все</option></select></label>
<label style="font-size:.8rem;color:var(--muted)">С даты<br>
<input id="costs-from" type="date" style="width:150px"></label>
<label style="font-size:.8rem;color:var(--muted)">По дату<br>
<input id="costs-to" type="date" style="width:150px"></label>
<button onclick="applyCostsFilter()">Показать</button>
<button class="btn-secondary" onclick="resetCostsFilter()">Сбросить</button>
<span style="font-size:.8rem;color:var(--muted)">
<a href="#costs" onclick="return quickRange(0)">сегодня</a> ·
<a href="#costs" onclick="return quickRange(6)">неделя</a> ·
<a href="#costs" onclick="return quickRange(29)">месяц</a></span>
<span id="costs-window" style="font-size:.8rem;color:var(--muted)"></span>
</div>
<h3 style="font-size:.95rem;margin:.6rem 0 .3rem">Сводка по моделям</h3>
<table id="by-model">
<tr><th>Модель</th><th>Провайдер</th><th>Запросов</th><th>Токены (вход/кэш/выход)</th><th>Всего токенов</th><th>$</th><th>₽ себестоимость</th><th>₽ начислено</th><th>Кредиты</th><th>₽ по тарифам API</th><th>Время ответа</th></tr>
</table>
<h3 style="font-size:.95rem;margin:.9rem 0 .3rem">По дням</h3>
<table id="costs">
<tr><th>День</th><th>Пользователь</th><th>Путь</th><th>Провайдер</th><th>Запросов</th><th>Токены (in/out)</th><th>$</th><th>₽ себестоимость</th><th>₽ начислено</th><th>Кредиты</th></tr>
</table>
@@ -226,6 +249,23 @@ document.addEventListener('DOMContentLoaded',applyThemeIcon);
</table>
</div>
<!-- Финансовый итог: поступления и себестоимость обслуживания -->
<div class="page" id="page-finance">
<h2>Финансы</h2>
<div style="margin:.4rem 0 .8rem;display:flex;gap:.6rem;align-items:flex-end;flex-wrap:wrap">
<label style="font-size:.8rem;color:var(--muted)">С даты<br>
<input id="fin-from" type="date" style="width:150px"></label>
<label style="font-size:.8rem;color:var(--muted)">По дату<br>
<input id="fin-to" type="date" style="width:150px"></label>
<button onclick="loadFinance()">Показать</button>
</div>
<div id="fin-totals" style="margin:.4rem 0 .8rem;font-size:.9rem"></div>
<table id="fin-months">
<tr><th>Месяц</th><th>Поступления, ₽</th><th>Возвраты, ₽</th><th>Платящих</th><th>Себестоимость, ₽</th><th>Начислено людям, ₽</th><th>Прибыль, ₽</th><th>Запросов</th><th>Людей</th></tr>
</table>
<div id="fin-note" style="margin:.6rem 0;font-size:.8rem;color:var(--muted)"></div>
</div>
<!-- Invites -->
<div class="page" id="page-invites">
<h2>Приглашения</h2>
@@ -802,9 +842,55 @@ async function toggleTgVerify(cb) {
loadTgSwitch();
// === Расходы LLM ===
// Общие мелочи отчётов: деньги, время и «не знаем» вместо выдуманного нуля.
const rubOrDash = v => v == null ? '—' : v.toFixed(2).replace('.', ',');
function humanMs(ms) {
if (ms == null) return '—';
const s = Math.round(ms / 1000);
if (s < 60) return s + ' с';
const m = Math.floor(s / 60);
return m < 60 ? m + ' мин ' + (s % 60) + ' с' : Math.floor(m / 60) + ' ч ' + (m % 60) + ' мин';
}
function costsQuery() {
const p = new URLSearchParams();
const who = document.getElementById('costs-user').value;
const from = document.getElementById('costs-from').value;
const to = document.getElementById('costs-to').value;
if (who) p.set('user', who);
if (from) p.set('from', from);
if (to) p.set('to', to);
if (!from && !to) p.set('days', '14');
return p.toString();
}
function applyCostsFilter() { loadCosts(); }
function resetCostsFilter() {
document.getElementById('costs-user').value = '';
document.getElementById('costs-from').value = '';
document.getElementById('costs-to').value = '';
loadCosts();
}
function quickRange(daysBack) {
// Дни считаем по часам того, кто смотрит: «сегодня» — это его сегодня.
const end = new Date();
const start = new Date(end.getTime() - daysBack * 86400000);
const iso = d => d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0')
+ '-' + String(d.getDate()).padStart(2, '0');
document.getElementById('costs-from').value = iso(start);
document.getElementById('costs-to').value = iso(end);
loadCosts();
return false;
}
async function loadCosts() {
try {
const r = await fetch('/api/admin/costs?days=14', {headers: H});
const r = await fetch('/api/admin/costs?' + costsQuery(), {headers: H});
if (!r.ok) {
const err = await r.json().catch(() => ({}));
document.getElementById('costs-window').textContent = err.detail || 'Не удалось построить отчёт';
return;
}
const d = await r.json();
const t0 = d.totals;
// «0 ₽» и «рублей не знаем» — разные вещи: во втором случае так и пишем.
@@ -831,6 +917,62 @@ async function loadCosts() {
'За 24 ч: $' + (t0.agent_24h || 0).toFixed(3) + ' · ' + rub +
' · ' + (t0.credits_24h || 0).toFixed(0) + ' кредитов (глобальный кап $' +
t0.global_cap + '/день)' + week;
// Список людей для фильтра — только те, у кого в окне есть записи.
const sel = document.getElementById('costs-user');
const chosen = sel.value;
sel.innerHTML = '<option value="">все</option>';
for (const name of (d.usernames || [])) {
const o = document.createElement('option');
o.value = name; o.textContent = name;
sel.appendChild(o);
}
sel.value = chosen;
const w = d.window || {};
document.getElementById('costs-window').textContent =
(w.from || w.to)
? 'период: ' + (w.from || w.to) + ' — ' + (w.to || w.from) + (w.user ? ', ' + w.user : '')
: 'период: последние 14 дней' + (w.user ? ', ' + w.user : '');
// Сводка по моделям. Пустая цена печатается прочерком: «0 ₽» читается как «бесплатно».
const bm = document.getElementById('by-model');
bm.innerHTML = '<tr><th>Модель</th><th>Провайдер</th><th>Запросов</th><th>Токены (вход/кэш/выход)</th><th>Всего токенов</th><th>$</th><th>₽ себестоимость</th><th>₽ начислено</th><th>Кредиты</th><th>₽ по тарифам API</th><th>Время ответа</th></tr>';
for (const row of (d.by_model || [])) {
const cells = [row.model || '—', row.provider || '—', String(row.requests),
row.input_tokens + ' / ' + row.cache_tokens + ' / ' + row.output_tokens,
row.tokens.toLocaleString('ru-RU'),
row.cost_usd != null ? row.cost_usd.toFixed(4) : '—',
rubOrDash(row.cost_rub) + (row.cost_basis === 'api' ? ' (по тарифам)' : ''),
rubOrDash(row.price_rub) + (row.unpriced ? ' (ещё ' + row.unpriced + ' без цены)' : ''),
row.credits != null ? row.credits.toFixed(0) : '—',
rubOrDash(row.api_cost_rub),
humanMs(row.duration_avg_ms) + (row.timed ? ' в среднем · всего ' + humanMs(row.duration_sum_ms) : '')];
const tr = document.createElement('tr');
for (const c of cells) { const td = document.createElement('td'); td.textContent = c; tr.appendChild(td); }
bm.appendChild(tr);
}
if ((d.by_model || []).length) {
// Итог считает сервер: суммировать «или ноль» на странице значит нарисовать
// «0,00 ₽» там, где величины не было ни у одной строки (увидел на дев-версии).
const g = d.by_model_total || {};
const tr = document.createElement('tr');
tr.style.fontWeight = '600';
const cells = ['Всего', '', String(g.requests || 0), '',
(g.tokens || 0).toLocaleString('ru-RU'),
g.cost_usd != null ? g.cost_usd.toFixed(4) : '—',
rubOrDash(g.cost_rub), rubOrDash(g.price_rub)
+ (g.unpriced ? ' (ещё ' + g.unpriced + ' без цены)' : ''),
g.credits != null ? g.credits.toFixed(0) : '—', rubOrDash(g.api_cost_rub),
humanMs(g.duration_avg_ms)
+ (g.timed ? ' в среднем · всего ' + humanMs(g.duration_sum_ms) : '')];
for (const c of cells) { const td = document.createElement('td'); td.textContent = c; tr.appendChild(td); }
bm.appendChild(tr);
} else {
const tr = document.createElement('tr');
const td = document.createElement('td');
td.colSpan = 11; td.textContent = 'За выбранный период записей нет';
tr.appendChild(td); bm.appendChild(tr);
}
const t = document.getElementById('costs');
t.innerHTML = '<tr><th>День</th><th>Пользователь</th><th>Путь</th><th>Провайдер</th><th>Запросов</th><th>Токены (in/out)</th><th>$</th><th>₽ себестоимость</th><th>₽ начислено</th><th>Кредиты</th></tr>';
for (const row of d.daily) {
@@ -924,6 +1066,66 @@ async function saveBillingSettings() {
loadBillingSettings();
loadZaikaQuota();
// === Финансовый итог ===
async function loadFinance() {
const p = new URLSearchParams();
const from = document.getElementById('fin-from').value;
const to = document.getElementById('fin-to').value;
if (from) p.set('from', from);
if (to) p.set('to', to);
if (!from && !to) p.set('days', '180');
const box = document.getElementById('fin-totals');
try {
const r = await fetch('/api/admin/finance?' + p.toString(), {headers: H});
if (!r.ok) {
const err = await r.json().catch(() => ({}));
box.textContent = err.detail || 'Не удалось построить отчёт';
return;
}
const d = await r.json();
const t = d.totals;
// Поступлений пока нет вовсе — так и пишем. Нули в такой строке выглядят как
// «посчитали и вышло ноль», а это разные вещи.
const money = v => v == null ? '—' : v.toFixed(2).replace('.', ',') + ' ₽';
const share = t.margin_share == null ? '—' : (t.margin_share * 100).toFixed(1).replace('.', ',') + ' %';
box.innerHTML = '';
const lines = [
(t.revenue_rub > 0
? 'Поступления: ' + money(t.revenue_rub) + ' от ' + t.payers + ' плательщиков'
+ (t.revenue_per_payer != null ? ' (в среднем ' + money(t.revenue_per_payer) + ')' : '')
: 'Поступлений за период нет')
+ (t.refunded_rub > 0 ? ' · возвращено ' + money(t.refunded_rub) : ''),
'Себестоимость работы ИИ: ' + money(t.cost_rub)
+ (t.cost_per_person != null ? ' (на человека ' + money(t.cost_per_person) + ')' : '')
+ (t.unpriced ? ' · ещё ' + t.unpriced + ' прогонов без цены' : ''),
'Прибыль: ' + money(t.profit_rub) + ' · доля в поступлениях: ' + share,
'Работали: ' + t.requests + ' прогонов, ' + t.people + ' человек',
];
for (const line of lines) {
const div = document.createElement('div');
div.textContent = line;
box.appendChild(div);
}
const tbl = document.getElementById('fin-months');
tbl.innerHTML = '<tr><th>Месяц</th><th>Поступления, ₽</th><th>Возвраты, ₽</th><th>Платящих</th><th>Себестоимость, ₽</th><th>Начислено людям, ₽</th><th>Прибыль, ₽</th><th>Запросов</th><th>Людей</th></tr>';
for (const m of d.months) {
const profit = m.cost_rub == null ? null : m.revenue_rub - m.cost_rub;
const cells = [m.month, money(m.revenue_rub), m.refunded_rub ? money(m.refunded_rub) : '—',
String(m.payers), money(m.cost_rub), money(m.price_rub), money(profit),
String(m.requests), String(m.people)];
const tr = document.createElement('tr');
for (const c of cells) { const td = document.createElement('td'); td.textContent = c; tr.appendChild(td); }
tbl.appendChild(tr);
}
document.getElementById('fin-note').textContent = d.months.length
? 'Прибыль = поступления минус наша себестоимость. Возвращённый платёж поступлением не считается. Прогоны без цены в себестоимость не входят.'
: 'За выбранный период ни поступлений, ни расходов не было.';
} catch (e) {
box.textContent = 'Не удалось загрузить финансовый итог';
}
}
loadFinance();
// === Платежи ЮKassa ===
async function loadPayments() {
try {