diff --git a/MEMORY.md b/MEMORY.md
index 88dfb8a..96a118a 100644
--- a/MEMORY.md
+++ b/MEMORY.md
@@ -1,5 +1,7 @@
# MEMORY
+- 2026-10-10: `/admin` report rows default to creation date descending (newest first); `CalculationStore` supports the `created_at` sort key and the UI requests it explicitly.
+
- 2026-10-10 live: rotated `BELKI_ADMIN_PASSWORD` from ignored `.secrets/BELKI_ADMIN_PASSWORD`, restarted web and bot, and verified `/api/admin/calculations` returns 200 with the current value and 401 with an invalid value.
- 2026-10-10 live: image tag `67d505f` with the clickable points activity menu is deployed in k3s; runtime introspection of the new `belki-bot` pod confirmed the three `points:*` button payloads.
diff --git a/app/belki/history.py b/app/belki/history.py
index cf09d29..02dce91 100644
--- a/app/belki/history.py
+++ b/app/belki/history.py
@@ -155,6 +155,7 @@ class CalculationStore:
Возвращает записи истории для админ-панели.
Безопасная сортировка на уровне приложения (не SQL-инъекция):
+ - created_at — по дате создания
- escort_id, escort_name — по сопровождающему
- kitten_id, kitten_name — по котянку
@@ -190,12 +191,14 @@ class CalculationStore:
"created_at": row[7].isoformat() if hasattr(row[7], "isoformat") else row[7],
"entered": bool(row[8]),
})
- if sort_by not in {"escort_id", "escort_name", "kitten_id", "kitten_name"}:
+ if sort_by not in {"created_at", "escort_id", "escort_name", "kitten_id", "kitten_name"}:
sort_by = "escort_id"
def sort_value(item: dict[str, Any]) -> tuple[bool, int, int | str]:
"""Строит ключ, который сортирует числовые и текстовые значения предсказуемо."""
data = item["input"]
- if sort_by == "escort_id":
+ if sort_by == "created_at":
+ value = item["created_at"]
+ elif sort_by == "escort_id":
value = data.get("escort_id", data.get("character_id"))
elif sort_by == "escort_name":
value = data.get("escort_name", data.get("character_name"))
diff --git a/structure_and_data.md b/structure_and_data.md
index 01b6721..13b4584 100644
--- a/structure_and_data.md
+++ b/structure_and_data.md
@@ -20,6 +20,7 @@
- [`CONTRIBUTING.md`](./CONTRIBUTING.md): contribution and verification rules.
## Runtime / Deployment
+- 2026-10-10: admin report history now defaults to `created_at` descending (newest first) in both the browser table and API request. The history store accepts `created_at` as a safe sort key; the existing alternate sort controls remain available.
- 2026-10-10: rotated `BELKI_ADMIN_PASSWORD` in the existing namespace Secret from ignored `.secrets/BELKI_ADMIN_PASSWORD`, restarted `belki-web` and `belki-bot`, and verified the admin API returned HTTP 200 with the current value and HTTP 401 with an invalid value. The password itself is not stored in Git.
- 2026-10-10: deployed the clickable points activity menu and inflected activity aliases as image tag `67d505f`; `belki-bot`, web, and gateway rollouts completed successfully with new pods at zero restarts. Runtime verification inside the new bot pod exposed buttons `Прокачка`, `Тренировка`, `Осмотр` with `points:*` payloads.
- 2026-10-10: the VK points calculator now shows clickable `Прокачка`, `Тренировка`, and `Осмотр` buttons at the activity prompt. Text input accepts both nominative and accusative forms (`прокачка`/`прокачку`, `тренировка`/`тренировку`).
diff --git a/tests/test_history.py b/tests/test_history.py
index b804abe..da9c20c 100644
--- a/tests/test_history.py
+++ b/tests/test_history.py
@@ -1,5 +1,6 @@
import tempfile
import unittest
+import sqlite3
from pathlib import Path
from app.belki.history import CalculationStore
@@ -50,6 +51,17 @@ class CalculationHistoryTests(unittest.TestCase):
rows = store.list_calculations(sort_by="kitten_id", descending=False)
self.assertEqual([row["input"]["kitten_id"] for row in rows], [2, "12", "not-an-id"])
+ def test_admin_history_sorts_by_creation_date_newest_first(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ store = CalculationStore(sqlite_path=Path(directory) / "history.sqlite3")
+ first = store.save(actor_id=1, source="web", payload={"mode": "coaching"}, response={"message": "old", "result": {}})
+ second = store.save(actor_id=2, source="web", payload={"mode": "coaching"}, response={"message": "new", "result": {}})
+ with sqlite3.connect(store.sqlite_path) as connection:
+ connection.execute("UPDATE calculations SET created_at=? WHERE id=?", ("2026-10-10 10:00:00", first))
+ connection.execute("UPDATE calculations SET created_at=? WHERE id=?", ("2026-10-10 11:00:00", second))
+ rows = store.list_calculations(sort_by="created_at", descending=True)
+ self.assertEqual([row["id"] for row in rows], [second, first])
+
def test_admin_history_backfills_legacy_inspection_breakdown(self) -> None:
with tempfile.TemporaryDirectory() as directory:
store = CalculationStore(sqlite_path=Path(directory) / "history.sqlite3")
diff --git a/web/admin.html b/web/admin.html
index f14479f..0c08243 100644
--- a/web/admin.html
+++ b/web/admin.html
@@ -144,7 +144,7 @@
-
+
@@ -236,7 +236,7 @@
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'; const grouped = new Map(); (result.resource_points || []).forEach(resource => { const name = resource.name || resource[0] || 'Ресурс'; const amount = Number(resource.amount ?? resource[1] ?? 0); const points = Number(resource.points ?? resource[2] ?? 0); const key = name.trim().replace(/\s+/g, ' ').toLocaleLowerCase('ru-RU'); const current = grouped.get(key) || {name, amount: 0, points: 0}; current.amount += amount; current.points += points; grouped.set(key, current); }); const resourceTotal = [...grouped.values()].reduce((sum, resource) => sum + resource.points, 0); const resourceHeader = document.createElement('strong'); resourceHeader.textContent = `Итого по ресурсам: ${resourceTotal}`; details.append(resourceHeader); grouped.forEach(resource => { const perItem = resource.amount ? resource.points / resource.amount : 0; const line = document.createElement('span'); line.textContent = `${resource.name} ×${resource.amount}: ${resource.points} (${perItem}Б)`; details.append(line); }); if (result.inspection_points !== undefined) { const base = document.createElement('span'); base.textContent = `Баллы осмотра: ${result.inspection_points}`; details.append(base); } 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.
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: 'created_at', direction: 'desc', 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.
const applicationLabels = {feather_donation: 'Пожертвование перьев', kitten: 'Стать бельчонком', flying_squirrel: 'Стать белкой-летягой', curator: 'Стать куратором'};
// Extracts display fields from one application for the detail panel.