feat(admin): show inspection score breakdown
This commit is contained in:
1 parent
8241e84757
commit
0b1f2c1063
5 files changed
+25
-5
No files matched your search
@@ -78,3 +78,7 @@ The final gateway Dockerfile must copy `nginx.conf` into the release image, not
|
|||||||
# 2026-09-08: private MinIO image storage
|
# 2026-09-08: private MinIO image storage
|
||||||
|
|
||||||
`app/belki/image_host.py` now uses private distributed MinIO rather than `nyan.nyan404.ru`. The five internal S3 endpoints are tried in order for each operation; uploads are stored under an unguessable 128-bit object ID and public URLs resolve only through `https://cat.nyan404.ru/api/images/<id>`. Keep the MinIO bucket private. `belki-image-store` is a standalone out-of-band Secret with only `GetObject`/`PutObject` plus required `GetBucketLocation` for `belki-images`; never merge it into CI-recreated `belki-runtime` or commit credentials. Existing legacy img.nyan404.ru URLs remain stored as historical links and cannot be recovered by this change.
|
`app/belki/image_host.py` now uses private distributed MinIO rather than `nyan.nyan404.ru`. The five internal S3 endpoints are tried in order for each operation; uploads are stored under an unguessable 128-bit object ID and public URLs resolve only through `https://cat.nyan404.ru/api/images/<id>`. Keep the MinIO bucket private. `belki-image-store` is a standalone out-of-band Secret with only `GetObject`/`PutObject` plus required `GetBucketLocation` for `belki-images`; never merge it into CI-recreated `belki-runtime` or commit credentials. Existing legacy img.nyan404.ru URLs remain stored as historical links and cannot be recovered by this change.
|
||||||
|
|
||||||
|
# 2026-09-21: admin inspection score breakdown
|
||||||
|
|
||||||
|
Inspection results persist the base score for the number of inspections and each resource's calculated contribution in addition to the total. `/admin` displays these details in a dedicated `Баллы` column without changing the VK/public report text; legacy rows fall back to the stored total.
|
||||||
+9
-3
@@ -285,6 +285,8 @@ class InspectionReport:
|
|||||||
class InspectionResult:
|
class InspectionResult:
|
||||||
"""Результат расчёта баллов за осмотр."""
|
"""Результат расчёта баллов за осмотр."""
|
||||||
points: int
|
points: int
|
||||||
|
inspection_points: int = 0
|
||||||
|
resource_points: tuple[dict[str, int | str], ...] = field(default_factory=tuple)
|
||||||
|
|
||||||
|
|
||||||
def _inspection_resource_value(name: str) -> int:
|
def _inspection_resource_value(name: str) -> int:
|
||||||
@@ -325,6 +327,10 @@ def calculate_inspection(report: InspectionReport) -> InspectionResult:
|
|||||||
|
|
||||||
Формула: осмотры × 2 + сумма (количество × ценность_ресурса)
|
Формула: осмотры × 2 + сумма (количество × ценность_ресурса)
|
||||||
"""
|
"""
|
||||||
points = report.inspections * 2
|
inspection_points = report.inspections * 2
|
||||||
points += sum(amount * _inspection_resource_value(name) for name, amount in report.resources)
|
resource_points = tuple(
|
||||||
return InspectionResult(points=points)
|
{"name": name, "amount": amount, "points": amount * _inspection_resource_value(name)}
|
||||||
|
for name, amount in report.resources
|
||||||
|
)
|
||||||
|
points = inspection_points + sum(item["points"] for item in resource_points)
|
||||||
|
return InspectionResult(points=points, inspection_points=inspection_points, resource_points=resource_points)
|
||||||
@@ -119,6 +119,7 @@
|
|||||||
- 2026-08-25: mobile adaptation is a required acceptance criterion for all frontend changes; validate narrow-width layout, touch usability, focus/error states, and absence of horizontal overflow alongside desktop rendering.
|
- 2026-08-25: mobile adaptation is a required acceptance criterion for all frontend changes; validate narrow-width layout, touch usability, focus/error states, and absence of horizontal overflow alongside desktop rendering.
|
||||||
- 2026-08-25: `/belki` now applies a dedicated narrow-width layout: single-column forms and application types, full-width actions, compact panels/dialogs, 16px form text to avoid mobile browser zoom, and responsive tabs without horizontal overflow.
|
- 2026-08-25: `/belki` now applies a dedicated narrow-width layout: single-column forms and application types, full-width actions, compact panels/dialogs, 16px form text to avoid mobile browser zoom, and responsive tabs without horizontal overflow.
|
||||||
- 2026-08-25: removed unreferenced root-level legacy BBCode copies `belki.md`, `belki2.md`, and `belkifix.md`; the first two were byte-identical and the third differed only by a closing BBCode tag. They were neither served nor referenced by the calculator, bot, or documentation.
|
- 2026-08-25: removed unreferenced root-level legacy BBCode copies `belki.md`, `belki2.md`, and `belkifix.md`; the first two were byte-identical and the third differed only by a closing BBCode tag. They were neither served nor referenced by the calculator, bot, or documentation.
|
||||||
|
- 2026-09-21: `InspectionResult` now keeps the base inspection score and per-resource score entries alongside the total. The `/admin` report table renders these values in a dedicated `Баллы` column; older history rows still show their stored total when detailed fields are absent. The public report message remains unchanged.
|
||||||
# Обновление 2026-08-16: несколько котят
|
# Обновление 2026-08-16: несколько котят
|
||||||
|
|
||||||
Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`.
|
Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`.
|
||||||
|
|||||||
@@ -102,6 +102,11 @@ class ApiTests(unittest.TestCase):
|
|||||||
)
|
)
|
||||||
self.assertIn("осмотрел(-а) дупло 6 раз", response["message"])
|
self.assertIn("осмотрел(-а) дупло 6 раз", response["message"])
|
||||||
self.assertEqual(response["result"]["points"], 15)
|
self.assertEqual(response["result"]["points"], 15)
|
||||||
|
self.assertEqual(response["result"]["inspection_points"], 12)
|
||||||
|
self.assertEqual(response["result"]["resource_points"], (
|
||||||
|
{"name": "вьюнок", "amount": 2, "points": 2},
|
||||||
|
{"name": "паук", "amount": 1, "points": 1},
|
||||||
|
))
|
||||||
|
|
||||||
def test_bulk_inspection_payload_explains_missing_fields(self):
|
def test_bulk_inspection_payload_explains_missing_fields(self):
|
||||||
response = inspect_bulk_payload({"text": "/лу 15.08 11:00 11:20 | Белка [1] | Котёнок [2]"})
|
response = inspect_bulk_payload({"text": "/лу 15.08 11:00 11:20 | Белка [1] | Котёнок [2]"})
|
||||||
|
|||||||
+6
-2
@@ -74,6 +74,9 @@
|
|||||||
.photos img { display: block; width: 100%; height: 100%; object-fit: cover; }
|
.photos img { display: block; width: 100%; height: 100%; object-fit: cover; }
|
||||||
.photos button:hover { outline: 2px solid var(--accent); outline-offset: 2px; }
|
.photos button:hover { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||||
.message { max-width: 460px; margin: 0; white-space: pre-wrap; color: #514b45; font: inherit; font-size: .84rem; line-height: 1.5; }
|
.message { max-width: 460px; margin: 0; white-space: pre-wrap; color: #514b45; font: inherit; font-size: .84rem; line-height: 1.5; }
|
||||||
|
.points-cell { min-width: 170px; font-variant-numeric: tabular-nums; }
|
||||||
|
.points-details { display: grid; gap: 3px; color: var(--muted); font-size: .82rem; line-height: 1.35; }
|
||||||
|
.points-details strong { margin-top: 4px; color: var(--ink); font-size: .9rem; }
|
||||||
.delete { min-height: 34px; padding: 6px 10px; border-color: #d9b8b2; background: transparent; color: var(--danger); font-size: .82rem; }
|
.delete { min-height: 34px; padding: 6px 10px; border-color: #d9b8b2; background: transparent; color: var(--danger); font-size: .82rem; }
|
||||||
.delete:hover { border-color: var(--danger); background: #fff1ef; color: var(--danger); }
|
.delete:hover { border-color: var(--danger); background: #fff1ef; color: var(--danger); }
|
||||||
.empty { padding: 44px 20px; text-align: center; color: var(--muted); }
|
.empty { padding: 44px 20px; text-align: center; color: var(--muted); }
|
||||||
@@ -136,7 +139,7 @@
|
|||||||
<a id="reportsExport" class="export-link" href="/api/admin/calculations.xlsx">Скачать XLSX</a>
|
<a id="reportsExport" class="export-link" href="/api/admin/calculations.xlsx">Скачать XLSX</a>
|
||||||
</section>
|
</section>
|
||||||
<p class="error" id="error" role="alert"></p>
|
<p class="error" id="error" role="alert"></p>
|
||||||
<div class="table-wrap"><table><thead><tr><th>Кот</th><th>Котята</th><th>Фото</th><th>Дата (UTC+3)</th><th>Сообщение</th><th>Автор</th><th>ID</th><th></th></tr></thead><tbody id="rows"><tr><td class="empty" colspan="8">Загрузка истории…</td></tr></tbody></table></div>
|
<div class="table-wrap"><table><thead><tr><th>Кот</th><th>Котята</th><th>Фото</th><th>Дата (UTC+3)</th><th>Баллы</th><th>Сообщение</th><th>Автор</th><th>ID</th><th></th></tr></thead><tbody id="rows"><tr><td class="empty" colspan="9">Загрузка истории…</td></tr></tbody></table></div>
|
||||||
</section>
|
</section>
|
||||||
<section id="applicationsView" class="admin-section applications hidden" aria-labelledby="applicationsTitle"><header class="topbar"><div><h2 id="applicationsTitle">Заявки</h2><p class="intro">Новые обращения из VK-бота и веб-формы.</p></div><div class="record-count" id="applicationCount">Заявки не загружены</div></header><nav class="tabs" aria-label="Статус заявок"><button class="application-tab tab" type="button" data-status="pending" aria-selected="true">Новые</button><button class="application-tab tab" type="button" data-status="accepted" aria-selected="false">Принятые</button><button class="application-tab tab" type="button" data-status="" aria-selected="false">Все</button></nav><section class="controls" aria-label="Фильтры заявок"><label class="control-group">Период<select id="applicationPeriod"><option value="all">Вся история</option><option value="year">Последний год</option><option value="month">Последний месяц</option><option value="week">Последняя неделя</option><option value="day">Последние сутки</option><option value="12h">Последние 12 часов</option><option value="6h">Последние 6 часов</option><option value="4h">Последние 4 часа</option><option value="2h">Последние 2 часа</option><option value="1h">Последний час</option></select></label><label class="control-group">С даты<input id="applicationDateFrom" type="date"></label><label class="control-group">По дату<input id="applicationDateTo" type="date"></label><button id="loadApplications" type="button">Обновить</button><a id="applicationsExport" class="export-link" href="/api/admin/applications.xlsx">Скачать XLSX</a></section><div class="application-layout"><div id="applicationList" class="application-list"><p class="empty">Загрузка заявок…</p></div><article id="applicationDetail" class="application-detail"><p class="empty">Выберите заявку слева.</p></article></div></section>
|
<section id="applicationsView" class="admin-section applications hidden" aria-labelledby="applicationsTitle"><header class="topbar"><div><h2 id="applicationsTitle">Заявки</h2><p class="intro">Новые обращения из VK-бота и веб-формы.</p></div><div class="record-count" id="applicationCount">Заявки не загружены</div></header><nav class="tabs" aria-label="Статус заявок"><button class="application-tab tab" type="button" data-status="pending" aria-selected="true">Новые</button><button class="application-tab tab" type="button" data-status="accepted" aria-selected="false">Принятые</button><button class="application-tab tab" type="button" data-status="" aria-selected="false">Все</button></nav><section class="controls" aria-label="Фильтры заявок"><label class="control-group">Период<select id="applicationPeriod"><option value="all">Вся история</option><option value="year">Последний год</option><option value="month">Последний месяц</option><option value="week">Последняя неделя</option><option value="day">Последние сутки</option><option value="12h">Последние 12 часов</option><option value="6h">Последние 6 часов</option><option value="4h">Последние 4 часа</option><option value="2h">Последние 2 часа</option><option value="1h">Последний час</option></select></label><label class="control-group">С даты<input id="applicationDateFrom" type="date"></label><label class="control-group">По дату<input id="applicationDateTo" type="date"></label><button id="loadApplications" type="button">Обновить</button><a id="applicationsExport" class="export-link" href="/api/admin/applications.xlsx">Скачать XLSX</a></section><div class="application-layout"><div id="applicationList" class="application-list"><p class="empty">Загрузка заявок…</p></div><article id="applicationDetail" class="application-detail"><p class="empty">Выберите заявку слева.</p></article></div></section>
|
||||||
<section id="vkView" class="admin-section hidden" aria-labelledby="vkTitle">
|
<section id="vkView" class="admin-section hidden" aria-labelledby="vkTitle">
|
||||||
@@ -214,8 +217,9 @@
|
|||||||
function filteredItems() { return items.sort((a, b) => { const av = textForSort(a, sort.value), bv = textForSort(b, sort.value); const result = typeof av === 'number' && typeof bv === 'number' ? av - bv : String(av).localeCompare(String(bv), 'ru', {numeric: true, sensitivity: 'base'}); return direction.value === 'asc' ? result : -result; }); }
|
function filteredItems() { return items.sort((a, b) => { const av = textForSort(a, sort.value), bv = textForSort(b, sort.value); const result = typeof av === 'number' && typeof bv === 'number' ? av - bv : String(av).localeCompare(String(bv), 'ru', {numeric: true, sensitivity: 'base'}); return direction.value === 'asc' ? result : -result; }); }
|
||||||
// Rebuilds cat and kitten filter options from loaded records.
|
// Rebuilds cat and kitten filter options from loaded records.
|
||||||
function fillFilters() { const cats = new Map(), kittens = new Map(); items.forEach(item => { const input = item.input || {}; const person = personData(input); if (person.id) cats.set(String(person.id), person.name); kittenEntries(input).forEach(entry => { if (entry.id) kittens.set(String(entry.id), entry.name); }); }); const catValue = catFilter.value, kittenValue = kittenFilter.value; catFilter.replaceChildren(new Option('Все коты', '')); [...cats.entries()].sort((a,b) => a[1].localeCompare(b[1], 'ru')).forEach(([id,name]) => catFilter.add(new Option(`${name} [${id}]`, id))); kittenFilter.replaceChildren(new Option('Все котята', '')); [...kittens.entries()].sort((a,b) => a[1].localeCompare(b[1], 'ru')).forEach(([id,name]) => kittenFilter.add(new Option(`${name} [${id}]`, id))); if ([...catFilter.options].some(option => option.value === catValue)) catFilter.value = catValue; if ([...kittenFilter.options].some(option => option.value === kittenValue)) kittenFilter.value = kittenValue; }
|
function fillFilters() { const cats = new Map(), kittens = new Map(); items.forEach(item => { const input = item.input || {}; const person = personData(input); if (person.id) cats.set(String(person.id), person.name); kittenEntries(input).forEach(entry => { if (entry.id) kittens.set(String(entry.id), entry.name); }); }); const catValue = catFilter.value, kittenValue = kittenFilter.value; catFilter.replaceChildren(new Option('Все коты', '')); [...cats.entries()].sort((a,b) => a[1].localeCompare(b[1], 'ru')).forEach(([id,name]) => catFilter.add(new Option(`${name} [${id}]`, id))); kittenFilter.replaceChildren(new Option('Все котята', '')); [...kittens.entries()].sort((a,b) => a[1].localeCompare(b[1], 'ru')).forEach(([id,name]) => kittenFilter.add(new Option(`${name} [${id}]`, id))); if ([...catFilter.options].some(option => option.value === catValue)) catFilter.value = catValue; if ([...kittenFilter.options].some(option => option.value === kittenValue)) kittenFilter.value = kittenValue; }
|
||||||
|
function pointsCell(item) { const cell = document.createElement('td'); cell.className = 'points-cell'; const result = item.result || {}; if (item.mode !== 'inspection' || result.points === undefined) { cell.textContent = '—'; return cell; } const details = document.createElement('div'); details.className = 'points-details'; if (result.inspection_points !== undefined) { const base = document.createElement('span'); base.textContent = `Осмотры: ${result.inspection_points}`; details.append(base); } (result.resource_points || []).forEach(resource => { const line = document.createElement('span'); const name = resource.name || resource[0] || 'Ресурс'; const amount = resource.amount ?? resource[1] ?? 0; const points = resource.points ?? resource[2] ?? 0; line.textContent = `${amount > 0 ? '+' : ''}${amount} ${name}: ${points}`; details.append(line); }); const total = document.createElement('strong'); total.textContent = `Итого: ${result.points}`; details.append(total); cell.append(details); return cell; }
|
||||||
// Re-renders the report table, including empty and filtered states.
|
// Re-renders the report table, including empty and filtered states.
|
||||||
function render() { syncReportsExport(); rows.replaceChildren(); const visible = filteredItems(); recordCount.textContent = `${visible.length} записей`; if (!visible.length) { const row = document.createElement('tr'); const cell = document.createElement('td'); cell.className = 'empty'; cell.colSpan = 8; cell.textContent = 'По выбранным условиям записей нет.'; row.append(cell); rows.append(row); return; } visible.forEach(item => { const input = item.input || {}; const row = document.createElement('tr'); row.append(personCell(personData(input))); const kittenCell = document.createElement('td'); kittenCell.className = 'person'; kittenEntries(input).forEach(entry => { const strong = document.createElement('strong'); strong.textContent = entry.name; const small = document.createElement('span'); small.textContent = entry.id ? `[${entry.id}]` : 'ID не указан'; kittenCell.append(strong, small); }); if (!kittenCell.childElementCount) kittenCell.textContent = '—'; row.append(kittenCell, photoCell(input.attachments), (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = displayDate(item.created_at); return cell; })()); const message = document.createElement('td'); const pre = document.createElement('pre'); pre.className = 'message'; pre.textContent = item.message; message.append(pre); row.append(message, (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.actor_id || '—'; return cell; })(), (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.id; return cell; })()); const actions = document.createElement('td'); const remove = document.createElement('button'); remove.className = 'delete'; remove.type = 'button'; remove.textContent = 'Удалить'; remove.addEventListener('click', async () => { if (!window.confirm(`Удалить запись №${item.id}?`)) return; remove.disabled = true; try { const response = await fetch(`/api/admin/calculations/${encodeURIComponent(item.id)}`, {method: 'DELETE'}); const result = await response.json(); if (!response.ok) throw new Error(result.error || 'Не удалось удалить запись'); items = items.filter(entry => entry.id !== item.id); fillFilters(); render(); } catch (err) { error.textContent = err.message; remove.disabled = false; } }); actions.append(remove); row.append(actions); rows.append(row); }); }
|
function render() { syncReportsExport(); rows.replaceChildren(); const visible = filteredItems(); recordCount.textContent = `${visible.length} записей`; if (!visible.length) { const row = document.createElement('tr'); const cell = document.createElement('td'); cell.className = 'empty'; cell.colSpan = 9; cell.textContent = 'По выбранным условиям записей нет.'; row.append(cell); rows.append(row); return; } visible.forEach(item => { const input = item.input || {}; const row = document.createElement('tr'); row.append(personCell(personData(input))); const kittenCell = document.createElement('td'); kittenCell.className = 'person'; kittenEntries(input).forEach(entry => { const strong = document.createElement('strong'); strong.textContent = entry.name; const small = document.createElement('span'); small.textContent = entry.id ? `[${entry.id}]` : 'ID не указан'; kittenCell.append(strong, small); }); if (!kittenCell.childElementCount) kittenCell.textContent = '—'; row.append(kittenCell, photoCell(input.attachments), (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = displayDate(item.created_at); return cell; })(), pointsCell(item)); const message = document.createElement('td'); const pre = document.createElement('pre'); pre.className = 'message'; pre.textContent = item.message; message.append(pre); row.append(message, (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.actor_id || '—'; return cell; })(), (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.id; return cell; })()); const actions = document.createElement('td'); const remove = document.createElement('button'); remove.className = 'delete'; remove.type = 'button'; remove.textContent = 'Удалить'; remove.addEventListener('click', async () => { if (!window.confirm(`Удалить запись №${item.id}?`)) return; remove.disabled = true; try { const response = await fetch(`/api/admin/calculations/${encodeURIComponent(item.id)}`, {method: 'DELETE'}); const result = await response.json(); if (!response.ok) throw new Error(result.error || 'Не удалось удалить запись'); items = items.filter(entry => entry.id !== item.id); fillFilters(); render(); } catch (err) { error.textContent = err.message; remove.disabled = false; } }); actions.append(remove); row.append(actions); rows.append(row); }); }
|
||||||
async function load() { error.textContent = ''; loadButton.disabled = true; try { const query = queryFor(reportPeriod, reportDateFrom, reportDateTo, {sort: 'escort_name', direction: 'asc', limit: '500', category: activeCategory, cat: catFilter.value, kitten: kittenFilter.value}); const response = await fetch(`/api/admin/calculations?${query}`); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Не удалось загрузить историю'); items = data.items || []; fillFilters(); render(); } catch (err) { error.textContent = err.message; recordCount.textContent = 'История не загружена'; } finally { loadButton.disabled = false; } }
|
async function load() { error.textContent = ''; loadButton.disabled = true; try { const query = queryFor(reportPeriod, reportDateFrom, reportDateTo, {sort: 'escort_name', direction: 'asc', limit: '500', category: activeCategory, cat: catFilter.value, kitten: kittenFilter.value}); const response = await fetch(`/api/admin/calculations?${query}`); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Не удалось загрузить историю'); items = data.items || []; fillFilters(); render(); } catch (err) { error.textContent = err.message; recordCount.textContent = 'История не загружена'; } finally { loadButton.disabled = false; } }
|
||||||
// Loads report history from the admin API and refreshes filters/table.
|
// Loads report history from the admin API and refreshes filters/table.
|
||||||
const applicationLabels = {feather_donation: 'Пожертвование перьев', kitten: 'Стать бельчонком', flying_squirrel: 'Стать белкой-летягой', curator: 'Стать куратором'};
|
const applicationLabels = {feather_donation: 'Пожертвование перьев', kitten: 'Стать бельчонком', flying_squirrel: 'Стать белкой-летягой', curator: 'Стать куратором'};
|
||||||
|
|||||||
Reference in new issue
Block a user