feat(админка): состояния costs, metrics и finance

This commit is contained in:
anor
2026-11-06 20:03:20 +10:00
parent 59c4741d98
commit 9f4af6137b
5 changed files with 70 additions and 15 deletions
+37 -11
View File
@@ -835,6 +835,7 @@ document.addEventListener('DOMContentLoaded',function(){applyThemeIcon();applyDe
<a href="#costs" onclick="return quickRange(29)">месяц</a> ·
<a href="#costs" onclick="return quickRange(364)">год</a></span>
<span id="costs-window" class="note"></span>
<span id="costs-updated" class="note" role="status"></span>
</div>
<h3>Сводка по моделям</h3>
<!-- Пометка о способе расчёта: без неё «₽ себестоимость» у зайки выглядит как счёт
@@ -870,6 +871,7 @@ document.addEventListener('DOMContentLoaded',function(){applyThemeIcon();applyDe
<input id="mx-days" type="number" min="1" max="366" value="14" style="width:90px"></label>
<button class="btn" onclick="loadMetrics()">Показать</button>
<span id="mx-note" class="note"></span>
<span id="mx-updated" class="note" role="status"></span>
</div>
<h3>Работа службы</h3>
<div id="mx-work" class="summary"></div>
@@ -892,6 +894,7 @@ document.addEventListener('DOMContentLoaded',function(){applyThemeIcon();applyDe
<label class="field">По дату<br>
<input id="fin-to" type="date" style="width:150px"></label>
<button class="btn" onclick="loadFinance()">Показать</button>
<span id="fin-updated" class="note" role="status"></span>
</div>
<div id="fin-totals" class="summary" style="margin:.4rem 0 .8rem"></div>
<table id="fin-months">
@@ -2074,16 +2077,15 @@ function quickRange(daysBack) {
let costsСерия = 0; // побеждает последний ЗАПРОШЕННЫЙ период, а не пришедший
async function loadCosts() {
const моя = ++costsСерия;
const win = document.getElementById('costs-window');
const upd = document.getElementById('costs-updated');
if (win) win.textContent = 'Загрузка…';
if (upd) upd.textContent = '';
try {
const r = await fetch('/api/admin/costs?' + costsQuery(), {headers: H});
const r = await запрос('/api/admin/costs?' + costsQuery());
// Ответ на уже отменённый запрос молча выбрасываем: прежде поздний ответ ложился
// последним, и цифры расходились с подписью периода (свод очереди 10.09.2026).
if (моя !== costsСерия) return;
if (!r.ok) {
const err = await r.json().catch(() => ({}));
document.getElementById('costs-window').textContent = err.detail || 'Не удалось построить отчёт';
return;
}
const d = await r.json();
if (моя !== costsСерия) return;
const t0 = d.totals;
@@ -2126,6 +2128,7 @@ async function loadCosts() {
(w.from || w.to)
? 'период: ' + (w.from || w.to) + ' — ' + (w.to || w.from) + (w.user ? ', ' + w.user : '')
: 'период: последние 14 дней (даты не заданы)' + (w.user ? ', ' + w.user : '');
if (upd) upd.textContent = 'обновлено ' + new Date().toLocaleTimeString('ru-RU', {hour:'2-digit', minute:'2-digit'});
// Сводка по моделям. Пустая цена печатается прочерком: «0 ₽» читается как «бесплатно».
const MODEL_NUM_COLS = [2, 3, 4, 5, 6, 7, 8, 9];
@@ -2185,7 +2188,14 @@ async function loadCosts() {
fillCells(tr, cells, [4, 5, 6, 7, 8, 9]);
t.appendChild(tr);
}
} catch (e) {}
} catch (e) {
if (моя !== costsСерия) return;
const totals = document.getElementById('costs-totals');
if (totals) totals.textContent = 'Не удалось загрузить расходы';
if (win) win.innerHTML = 'Не удалось построить отчёт: ' + esc(e.message || 'сеть')
+ ' <button type="button" class="btn-sm" onclick="loadCosts()">Повторить</button>';
if (upd) upd.textContent = 'ошибка загрузки';
}
}
loadCosts();
@@ -2259,13 +2269,18 @@ loadBillingSettings();
loadZaikaQuota();
// === Метрики работы и продукта ===
let metricsReq = 0;
async function loadMetrics() {
const my = ++metricsReq;
const days = Math.max(1, Math.min(366, parseInt(document.getElementById('mx-days').value, 10) || 14));
const note = document.getElementById('mx-note');
const upd = document.getElementById('mx-updated');
if (note) note.textContent = 'Загрузка…';
if (upd) upd.textContent = '';
try {
const r = await fetch('/api/admin/metrics?days=' + days, {headers: H});
if (!r.ok) { note.textContent = 'Не удалось получить метрики'; return; }
const r = await запрос('/api/admin/metrics?days=' + days);
const d = await r.json();
if (my !== metricsReq) return;
const w = d.work, p = d.product;
// Доля неудач без знаменателя не считается: прочерк честнее нуля.
const share = w.failure_share == null ? '—' : (w.failure_share * 100).toFixed(1).replace('.', ',') + ' %';
@@ -2318,9 +2333,13 @@ async function loadMetrics() {
fillCells(tr, [row.day, String(row.people), String(row.new)], [1, 2]);
t.appendChild(tr);
}
note.textContent = 'за последние ' + d.days + ' дней';
if (note) note.textContent = 'за последние ' + d.days + ' дней';
if (upd) upd.textContent = 'обновлено ' + new Date().toLocaleTimeString('ru-RU', {hour:'2-digit', minute:'2-digit'});
} catch (e) {
note.textContent = 'Не удалось получить метрики';
if (my !== metricsReq) return;
if (note) note.innerHTML = 'Не удалось получить метрики: ' + esc(e.message || 'сеть')
+ ' <button type="button" class="btn-sm" onclick="loadMetrics()">Повторить</button>';
if (upd) upd.textContent = 'ошибка загрузки';
}
}
loadMetrics();
@@ -2334,7 +2353,11 @@ async function loadFinance() {
if (to) p.set('to', to);
if (!from && !to) p.set('days', '180');
const box = document.getElementById('fin-totals');
const upd = document.getElementById('fin-updated');
if (box) box.textContent = 'Загрузка…';
if (upd) upd.textContent = '';
try {
await пропускГотов;
const r = await fetch('/api/admin/finance?' + p.toString(), {headers: H});
if (!r.ok) {
const err = await r.json().catch(() => ({}));
@@ -2382,11 +2405,14 @@ async function loadFinance() {
fillCells(tr, cells, [1, 2, 3, 4, 5, 6, 7, 8]);
tbl.appendChild(tr);
}
if (upd) upd.textContent = 'обновлено ' + new Date().toLocaleTimeString('ru-RU', {hour:'2-digit', minute:'2-digit'});
document.getElementById('fin-note').textContent = d.months.length
? 'Денежный поток = поступления минус наша себестоимость. Это не бухгалтерская прибыль: остатки на счетах клиентов — обязательство. Возвращённый платёж поступлением не считается. Прогоны без цены в себестоимость не входят.'
: 'За выбранный период ни поступлений, ни расходов не было.';
} catch (e) {
console.error('finance', e);
box.textContent = 'Не удалось загрузить финансовый итог';
if (upd) upd.textContent = 'ошибка загрузки';
}
}
loadFinance();