From e33de2114afcd9e5c4554c1ad7a8a1e3a0cea7e1 Mon Sep 17 00:00:00 2001 From: Nyan404 Date: Wed, 7 Oct 2026 21:47:37 +0300 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20=D0=BE=D1=82=D0=BC=D0=B5=D1=82=D0=BA=D1=83=20=D0=B2?= =?UTF-8?q?=D0=BD=D0=B5=D1=81=D0=B5=D0=BD=D0=BD=D1=8B=D1=85=20=D0=BE=D1=82?= =?UTF-8?q?=D1=87=D0=B5=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 1 + MEMORY.md | 4 ++++ app/belki/admin_filters.py | 4 ++++ app/belki/history.py | 25 +++++++++++++++++++++++-- app/main.py | 15 +++++++++++++++ project_mind_map.md | 4 ++++ structure_and_data.md | 1 + tests/test_admin_export.py | 6 ++++++ tests/test_history.py | 9 +++++++++ web/admin.html | 11 +++++++++-- 10 files changed, 76 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 447fb94..5262007 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,6 +20,7 @@ - For image/runtime changes, check the `Dockerfile`, Python entrypoint, static asset serving, and CI job together. - For k3s changes, validate YAML and current cluster inventory first; keep `KUBE_CONFIG_B64` masked/protected in GitLab. - Do not add unnecessary local build artifacts or temporary files to the repository. +- Admin report UI changes should cover both the persisted history flag and browser behavior: run the focused history/admin filter tests, Python compilation, `git diff --check`, and a JavaScript syntax check for `web/admin.html`. The report list defaults to the calendar current month; do not silently replace the existing sort order. ## Notes - VK scheduler lives in `app/belki/vk_scheduler.py`; use `BELKI_DATABASE_URL` in production and `BELKI_HISTORY_DB` for local SQLite checks. Keep mailing disabled until an administrator explicitly enables a conversation and schedule. diff --git a/MEMORY.md b/MEMORY.md index a0f9414..5d71b42 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -91,3 +91,7 @@ Inspection results persist the base score for the number of inspections and each # 2026-09-26: explicit edible catch catalogue `app/belki/domain.py` keeps an explicit `EDIBLE_CATCHES` set for one-point inspection catches. `Ящерица` and `Летучая мышь` are included and covered by `tests/test_belki.py`; the Krylan memo lists them in the edible catch table. + +# 2026-10-07: entered report state + +`app/belki/history.py` persists an administrative `entered` boolean with an idempotent SQLite/PostgreSQL schema migration. `/api/admin/calculations/{id}/entered` is session-protected and updates one report. `web/admin.html` defaults report history to the calendar current month, prepends an accessible checkbox/checkmark column, and dims rows after entry; sorting remains unchanged. diff --git a/app/belki/admin_filters.py b/app/belki/admin_filters.py index 5823fc8..a073fba 100644 --- a/app/belki/admin_filters.py +++ b/app/belki/admin_filters.py @@ -37,6 +37,10 @@ def period_bounds(period: str, date_from: str | None, date_to: str | None, *, no raise ValueError("Дата начала не может быть позже даты окончания") return start, end if period not in PERIODS: + if period == "current_month": + current = (now or datetime.now(timezone.utc)).astimezone(WEB_TIMEZONE) + start = current.replace(day=1, hour=0, minute=0, second=0, microsecond=0) + return start.astimezone(timezone.utc), current.astimezone(timezone.utc) raise ValueError("Неизвестный период") duration = PERIODS[period] if duration is None: diff --git a/app/belki/history.py b/app/belki/history.py index 8ffe2ae..cf09d29 100644 --- a/app/belki/history.py +++ b/app/belki/history.py @@ -92,6 +92,9 @@ class CalculationStore: created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP )""" ) + columns = {row[1] for row in connection.execute("PRAGMA table_info(calculations)")} + if "entered" not in columns: + connection.execute("ALTER TABLE calculations ADD COLUMN entered INTEGER NOT NULL DEFAULT 0") def _ensure_postgres_schema(self) -> None: """Создаёт таблицу belki_calculations в PostgreSQL, если её нет.""" @@ -108,6 +111,7 @@ class CalculationStore: created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() )""" ) + connection.execute("ALTER TABLE belki_calculations ADD COLUMN IF NOT EXISTS entered BOOLEAN NOT NULL DEFAULT FALSE") def save(self, *, actor_id: int | None, source: str, payload: dict[str, Any], response: dict[str, Any]) -> int: """ @@ -163,13 +167,13 @@ class CalculationStore: if self.database_url.startswith(("postgres://", "postgresql://")): with self._psycopg.connect(self.database_url) as connection: rows = connection.execute( - """SELECT id, actor_id, source, mode, input_json, result_json, message, created_at + """SELECT id, actor_id, source, mode, input_json, result_json, message, created_at, entered FROM belki_calculations ORDER BY created_at DESC LIMIT %s""", (fetch_limit,) ).fetchall() else: with sqlite3.connect(self.sqlite_path) as connection: rows = connection.execute( - """SELECT id, actor_id, source, mode, input_json, result_json, message, created_at + """SELECT id, actor_id, source, mode, input_json, result_json, message, created_at, entered FROM calculations ORDER BY created_at DESC LIMIT ?""", (fetch_limit,) ).fetchall() records = [] @@ -184,6 +188,7 @@ class CalculationStore: "id": row[0], "actor_id": row[1], "source": row[2], "mode": row[3], "input": input_data, "result": result_data, "message": message, "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"}: sort_by = "escort_id" @@ -210,6 +215,22 @@ class CalculationStore: records.sort(key=sort_value, reverse=descending) return records[:limit] + def set_entered(self, calculation_id: int, entered: bool) -> dict[str, Any] | None: + """Set the administrative entered flag and return the updated row.""" + if isinstance(calculation_id, bool) or not isinstance(calculation_id, int) or calculation_id <= 0: + raise ValueError("ID записи должен быть положительным целым числом") + if self.database_url.startswith(("postgres://", "postgresql://")): + with self._psycopg.connect(self.database_url) as connection: + row = connection.execute("UPDATE belki_calculations SET entered=%s WHERE id=%s RETURNING id", (entered, calculation_id)).fetchone() + if row is None: + return None + else: + with sqlite3.connect(self.sqlite_path) as connection: + cursor = connection.execute("UPDATE calculations SET entered=? WHERE id=?", (int(entered), calculation_id)) + if cursor.rowcount == 0: + return None + return next((item for item in self.list_calculations(limit=500) if item["id"] == calculation_id), None) + def delete_calculation(self, calculation_id: int) -> bool: """Delete one history row and report whether it existed.""" if isinstance(calculation_id, bool) or not isinstance(calculation_id, int) or calculation_id <= 0: diff --git a/app/main.py b/app/main.py index fd93c3b..2838d0c 100644 --- a/app/main.py +++ b/app/main.py @@ -669,6 +669,21 @@ class Handler(BaseHTTPRequestHandler): def do_PATCH(self) -> None: # noqa: N802 """Меняет статус новой заявки через PATCH API.""" parsed = urlparse(self.path) + entered_prefix = "/api/admin/calculations/" + if parsed.path.startswith(entered_prefix) and parsed.path.endswith("/entered"): + if not self._admin_authorized(): return + try: + calculation_id = int(parsed.path[len(entered_prefix):-len("/entered")].strip("/")) + payload = self._read_json_body() + item = history_store().set_entered(calculation_id, bool(payload.get("entered"))) + except (ApiError, ValueError) as exc: + self._json(400, {"error": str(exc)}) + return + if item is None: + self._json(404, {"error": "Запись не найдена"}) + else: + self._json(200, {"item": item}) + return if parsed.path.startswith("/api/admin/vk/conversations/") or parsed.path.startswith("/api/admin/vk/schedules/"): if not self._admin_authorized(): return try: diff --git a/project_mind_map.md b/project_mind_map.md index 3f27fce..e4ff95e 100644 --- a/project_mind_map.md +++ b/project_mind_map.md @@ -40,6 +40,8 @@ mindmap Applications web/admin.html Review and accept + Report entered checkbox + Current calendar month by default web/applications.html VK bot vk_bot.py @@ -61,11 +63,13 @@ mindmap Data PostgreSQL production calculations + calculations.entered admin flag applications sudoku_games export outbox identities and profiles SQLite local fallback + calculations.entered migration Private MinIO image storage belki-images bucket HAProxy front door 10.43.30.146:9000 diff --git a/structure_and_data.md b/structure_and_data.md index 47f5d0c..d304fcb 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -46,6 +46,7 @@ - Typed flows are: feather donation (amount/color/source rows), kitten (activity screenshot), flying squirrel (past practice and a review link when applicable), and curator (LU screenshot with fraction). VK uses `/заявка`, `/перо`, `/бельчонок`, `/летяга`, and `/куратор`; its context keyboard drives every selectable application branch, while users type only free-form values. The bot polls accepted VK applications every 15 seconds and notifies the original peer; web applications have no inferred VK recipient. - Google Sheets export is pre-wired but disabled by `BELKI_GOOGLE_EXPORT_ENABLED=0`. `ApplicationStore` records `application_created` and `application_accepted` snapshots in the PostgreSQL `belki_application_export_events` or SQLite `application_export_events` outbox. `GoogleSheetsExportService` sends FIFO JSON events only to an explicitly configured Google Apps Script Web App URL, retains failed events for retry, and is polled by the bot every 15 seconds when enabled. - The admin page uses a restrained light editorial table layout with a separate password gate, category tabs (all, осмотры, ЛУ, ЗУ, ПУ/уроки), responsive filters, client-side sorting across every visible column, cat/kitten selectors, sticky headings, and a keyboard-navigable photo gallery; behavior remains backed by the existing history API. +- 2026-10-07: admin report history defaults to the calendar current month (`current_month`), with older reports still available through the existing period/date controls. Each report has a persisted `entered` flag in PostgreSQL/SQLite; the admin table exposes an accessible checkbox in the leftmost column, adds a checkmark, and dims entered rows. `PATCH /api/admin/calculations/{id}/entered` updates the flag without changing sort order. - 2026-10-03: public calculator and `/admin` share an autumn visual layer: warm paper/ground tokens, amber-brown accents, subtle radial atmosphere, and seven CSS leaves with staggered fall motion. Leaves are decorative (`aria-hidden`, pointer-events disabled), stay behind content, and become static/faint under `prefers-reduced-motion`; no image or runtime dependency was added. - VK `messages.send` responses include a serialized context-aware keyboard; button payloads are translated back into the same dialog commands, while text commands remain supported. - Production k3s deployment (2026-08-16): namespace `belki` runs the Belki web calculator, VK bot, PostgreSQL 16, and the migrated cwshed Nginx gateway. The gateway keeps MetalLB IP `10.12.0.204`, serves the legacy CatWar site, and routes `/belki`, `/admin`, and `/api/*` to Belki web on `10.12.0.212`. Belki images are `reg.nyan404.ru/cwshed-clone/belki` and `reg.nyan404.ru/cwshed`; PostgreSQL is mirrored as `reg.nyan404.ru/library/postgres:16-alpine-amd64` because cluster nodes cannot pull Docker Hub directly. Registry pull credentials and runtime secrets are created out-of-band in the `belki` namespace. diff --git a/tests/test_admin_export.py b/tests/test_admin_export.py index f6dbfc5..34c7d0c 100644 --- a/tests/test_admin_export.py +++ b/tests/test_admin_export.py @@ -14,6 +14,12 @@ from app.main import BelkiHTTPServer, Handler class AdminFilterAndExportTests(unittest.TestCase): + def test_current_month_period_uses_calendar_month(self) -> None: + now = datetime(2026, 9, 1, 1, tzinfo=timezone.utc) + start, end = period_bounds("current_month", None, None, now=now) + self.assertEqual(start, datetime(2026, 8, 31, 21, tzinfo=timezone.utc)) + self.assertEqual(end, now) + def test_named_and_custom_periods_filter_records(self) -> None: now = datetime(2026, 9, 1, 12, tzinfo=timezone.utc) recent = {"created_at": "2026-09-01T11:30:00+00:00"} diff --git a/tests/test_history.py b/tests/test_history.py index 6617163..b804abe 100644 --- a/tests/test_history.py +++ b/tests/test_history.py @@ -70,6 +70,15 @@ class CalculationHistoryTests(unittest.TestCase): self.assertEqual(result["resource_points"][0]["points"], 7) self.assertEqual(record["message"], "Баллы осмотра: 50 балла.") + def test_admin_history_persists_entered_flag(self) -> None: + with tempfile.TemporaryDirectory() as directory: + store = CalculationStore(sqlite_path=Path(directory) / "history.sqlite3") + record_id = store.save(actor_id=1, source="web", payload={"mode": "coaching"}, response={"message": "готово", "result": {}}) + self.assertFalse(store.list_calculations()[0]["entered"]) + updated = store.set_entered(record_id, True) + self.assertTrue(updated["entered"]) + self.assertTrue(store.list_calculations()[0]["entered"]) + if __name__ == "__main__": unittest.main() diff --git a/web/admin.html b/web/admin.html index d5cfefe..f14479f 100644 --- a/web/admin.html +++ b/web/admin.html @@ -73,6 +73,11 @@ th { position: sticky; top: 0; z-index: 1; background: #f8f5f0; color: #69635d; font-size: .72rem; font-weight: 750; letter-spacing: .06em; text-transform: uppercase; white-space: nowrap; } tbody tr:last-child td { border-bottom: 0; } tbody tr:hover td { background: #fff8ef; } + tbody tr.entered td { background: #f1eee8; color: #8a847d; } + tbody tr.entered:hover td { background: #ebe7df; } + .entered-marker { display: inline-flex; align-items: center; gap: 7px; color: #827a70; font-size: .82rem; white-space: nowrap; } + .entered-marker input { min-width: 18px; width: 18px; height: 18px; margin: 0; accent-color: #5d7650; } + .entered-marker span { font-size: 1rem; line-height: 1; } td { color: #3d3935; font-size: .91rem; line-height: 1.45; } .id-cell { color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; } .person { min-width: 155px; } @@ -143,14 +148,14 @@ - + Скачать XLSX -
КотКотятаФотоДата (UTC+3)БаллыСообщениеАвторID
Загрузка истории…
+
ВнесеноКотКотятаФотоДата (UTC+3)БаллыСообщениеАвторID
Загрузка истории…