feat(stove-api): expose estimate and operator controls

This commit is contained in:
anor
2026-11-26 20:22:55 +10:00
parent de624297ed
commit a98aa460d4
19 changed files with 1074 additions and 12 deletions
+4 -1
View File
@@ -8,6 +8,7 @@ import { CustomersPage } from '/static/admin2/pages/customers.js';
import { MoneyPage } from '/static/admin2/pages/money.js';
import { WorkPage } from '/static/admin2/pages/work.js';
import { SystemPage } from '/static/admin2/pages/system.js';
import { StoveApiPage } from '/static/admin2/pages/stove-api.js';
const html = htm.bind(h);
const TITLES = {
@@ -16,6 +17,7 @@ const TITLES = {
money: ["Деньги", "Поступления, поток и обязательства"],
work: ["Работа", "Очередь, прогоны и сбои"],
system: ["Система", "Здоровье службы и настройки"],
"stove-api": ["API печей", "Ключи, лимиты и история вызовов"],
};
const App = () => {
const [section, setSection] = useState(sectionFromPath(location.pathname));
@@ -78,7 +80,8 @@ const App = () => {
: section === 'customers' ? html`<${CustomersPage} />`
: section === 'money' ? html`<${MoneyPage} />`
: section === 'work' ? html`<${WorkPage} />`
: section === 'system' ? html`<${SystemPage} />` : html`
: section === 'system' ? html`<${SystemPage} />`
: section === 'stove-api' ? html`<${StoveApiPage} />` : html`
<section class="card" aria-labelledby="placeholder">
<h2 id="placeholder">Раздел готовится</h2>
<p>Данные и действия подключит следующий этап.</p>
+90
View File
@@ -0,0 +1,90 @@
import { h } from '/static/admin2/vendor/preact.module.js';
import { useEffect, useState } from '/static/admin2/vendor/hooks.module.js';
import htm from '/static/admin2/vendor/htm.module.js';
import { api } from '/static/admin2/api.js';
import { Table } from '/static/admin2/ui/table.js';
import { Loading } from '/static/admin2/ui/loading.js';
const html = htm.bind(h);
const base = '/api/admin/v2/stove-api';
export function StoveApiPage() {
const [data, setData] = useState(null);
const [error, setError] = useState('');
const [name, setName] = useState('');
const [note, setNote] = useState('');
const [secret, setSecret] = useState('');
const [selected, setSelected] = useState(null);
const load = () => api(base).then((d) => { setData(d); setError(''); })
.catch((e) => setError(e.message || 'API не отвечает'));
useEffect(() => { load(); const t = setInterval(load, 60000); return () => clearInterval(t); }, []);
const act = async (path, opts) => {
try { await api(path, opts); await load(); }
catch (e) { setError(e.message || 'Действие не выполнено'); }
};
const create = async (e) => {
e.preventDefault();
try {
const made = await api(base + '/keys', {method: 'POST', body: JSON.stringify({name, note})});
setSecret(made.secret);
setName(''); setNote(''); await load();
} catch (err) { setError(err.message || 'Ключ не создан'); }
};
const show = async (row) => {
try { setSelected(await api(base + '/requests/' + encodeURIComponent(row.request_id))); }
catch (e) { setError(e.message || 'Запрос не найден'); }
};
if (!data) return html`${error && html`<div role="alert" class="card error">${error}</div>`}<${Loading} />`;
return html`
${error && html`<div role="alert" class="card error">${error}</div>`}
<section class="card">
<h2>Состояние API</h2>
<p>${data.enabled ? 'Включено' : 'Выключено'} · неверных ключей за сутки: ${data.invalid_keys.count_24h}</p>
<button type="button" onClick=${() => act(base + '/enabled?enabled=' + (!data.enabled), {method: 'POST'})}>
${data.enabled ? 'Выключить API' : 'Включить API'}</button>
</section>
<section class="card">
<h2>Выдать ключ</h2>
<form onSubmit=${create}>
<label>Название <input value=${name} onInput=${(e) => setName(e.target.value)} required maxLength="100" /></label>
<label>Заметка <input value=${note} onInput=${(e) => setNote(e.target.value)} maxLength="500" /></label>
<button type="submit">Создать ключ</button>
</form>
${secret && html`<p role="status">Секрет виден только сейчас. Скопируйте и передайте владельцу защищённым способом:</p>
<code>${secret}</code><button type="button" onClick=${() => navigator.clipboard.writeText(secret)}>Скопировать</button>
<button type="button" onClick=${() => setSecret('')}>Скрыть</button>`}
</section>
<section class="card">
<h2>Ключи</h2>
<${Table} columns=${[
{key: 'name', label: 'Название'}, {key: 'key_prefix', label: 'Префикс'},
{key: 'calls_24h', label: 'Вызовов/сут'}, {key: 'limit_day', label: 'Лимит/сут'},
{key: 'ai_budget_rub_day', label: 'ИИ ₽/сут'},
{key: 'status', label: 'Статус', render: (r) => r.revoked_at ? 'отозван' : r.disabled ? 'отключён' : 'работает'},
{key: 'actions', label: 'Действия', render: (r) => r.revoked_at ? '' : html`
<button type="button" onClick=${() => act(base + '/keys/' + r.id + '/disabled?disabled=' + (!r.disabled), {method: 'POST'})}>${r.disabled ? 'Включить' : 'Отключить'}</button>
<button type="button" onClick=${() => {
const limit = Number(prompt('Новый лимит вызовов за сутки', String(r.limit_day)));
if (Number.isInteger(limit) && limit >= 0) act(base + '/keys/' + r.id + '/limits', {method: 'PATCH', body: JSON.stringify({limit_day: limit})});
}}>Лимит</button>
<button type="button" onClick=${() => {
const budget = Number(prompt('Новый бюджет ИИ, ₽ за сутки', String(r.ai_budget_rub_day)));
if (Number.isFinite(budget) && budget >= 0) act(base + '/keys/' + r.id + '/limits', {method: 'PATCH', body: JSON.stringify({ai_budget_rub_day: budget})});
}}>Бюджет ИИ</button>
<button type="button" onClick=${() => {
if (confirm('Отозвать ключ без восстановления?')) act(base + '/keys/' + r.id + '/revoke', {method: 'POST'});
}}>Отозвать</button>`},
]} rows=${data.keys.map((r) => ({...r, key: r.id}))} empty="Ключей пока нет" />
</section>
<section class="card">
<h2>Последние вызовы</h2>
<${Table} columns=${[
{key: 'ts', label: 'Когда'}, {key: 'key_id', label: 'Ключ'},
{key: 'request_id', label: 'Запрос'}, {key: 'http_status', label: 'HTTP'},
{key: 'error_code', label: 'Ошибка'}, {key: 'duration_ms', label: 'мс'},
]} rows=${data.history.map((r) => ({...r, key: r.id}))} onRowClick=${show} empty="Вызовов нет" />
${selected && html`<details open><summary>Запрос ${selected.request_id}</summary>
<pre>${JSON.stringify({request: selected.request, response: selected.response}, null, 2)}</pre>
<button type="button" onClick=${() => setSelected(null)}>Скрыть</button></details>`}
</section>`;
}
+1
View File
@@ -5,6 +5,7 @@ export const SECTIONS = [
["money", "Деньги", `${BASE}/money`],
["work", "Работа", `${BASE}/work`],
["system", "Система", `${BASE}/system`],
["stove-api", "API печей", `${BASE}/stove-api`],
];
export function sectionFromPath(pathname) {