Add API for pending reports
This commit is contained in:
1 parent
bb21a767d7
commit
10d214ef56
7 files changed
+127
-3
No files matched your search
@@ -20,6 +20,7 @@
|
|||||||
- For web UI work, use the project-local `.codex/skills/frontend-craft`, `.codex/skills/frontend-design`, and `.codex/skills/ui-ux-pro-max` instructions: establish a deliberate visual direction, preserve accessibility and interaction quality, then inspect the rendered result.
|
- For web UI work, use the project-local `.codex/skills/frontend-craft`, `.codex/skills/frontend-design`, and `.codex/skills/ui-ux-pro-max` instructions: establish a deliberate visual direction, preserve accessibility and interaction quality, then inspect the rendered result.
|
||||||
|
|
||||||
## Validation
|
## Validation
|
||||||
|
- External report polling: run `python -m unittest tests.test_pending_reports tests.test_history -q`. Pending pages are filtered in SQL before pagination; reset the cursor for every polling cycle, and preserve the shared `entered` flag and admin authorization.
|
||||||
- Frontend regression: `node tests/browser/calculator.cjs` against a separately started isolated server at `http://127.0.0.1:8876` (override `BELKI_TEST_URL` only with another loopback URL). Use the remote test zone when exposed; it was unavailable on 2026-11-14. Playwright is test tooling, not a runtime dependency: use the bundled Node/Playwright returned by `load_workspace_dependencies`, setting `NODE_PATH` to its `node_modules` and optionally `CHROMIUM_PATH` to the browser executable. The suite closes its browser/contexts and intercepts weather and admin fixtures; real calculation requests require the normal Python dependencies.
|
- Frontend regression: `node tests/browser/calculator.cjs` against a separately started isolated server at `http://127.0.0.1:8876` (override `BELKI_TEST_URL` only with another loopback URL). Use the remote test zone when exposed; it was unavailable on 2026-11-14. Playwright is test tooling, not a runtime dependency: use the bundled Node/Playwright returned by `load_workspace_dependencies`, setting `NODE_PATH` to its `node_modules` and optionally `CHROMIUM_PATH` to the browser executable. The suite closes its browser/contexts and intercepts weather and admin fixtures; real calculation requests require the normal Python dependencies.
|
||||||
- For a local fallback, create a temporary venv and install existing `requirements.txt`, then launch `python -m app.main` with `BELKI_DATABASE_URL=`, `BELKI_HOST=127.0.0.1`, `BELKI_PORT=8876`, and temporary absolute paths for `BELKI_HISTORY_DB` and `BELKI_IDENTITIES_DB`. Never reuse production stores. `BELKI_SCREENSHOT_DIR` optionally saves browser screenshots outside Git. Stop the server and remove the temporary venv, SQLite files, caches and screenshots after review.
|
- For a local fallback, create a temporary venv and install existing `requirements.txt`, then launch `python -m app.main` with `BELKI_DATABASE_URL=`, `BELKI_HOST=127.0.0.1`, `BELKI_PORT=8876`, and temporary absolute paths for `BELKI_HISTORY_DB` and `BELKI_IDENTITIES_DB`. Never reuse production stores. `BELKI_SCREENSHOT_DIR` optionally saves browser screenshots outside Git. Stop the server and remove the temporary venv, SQLite files, caches and screenshots after review.
|
||||||
- Browser coverage includes native radio arrow keys, report invalidation on edits/mode changes, delayed responses/double submissions, clipboard denial, dialog focus/Escape, section URLs/Back, both application entry points, admin filters/default sort and gallery. Keep API/data contracts intact: training points are a number, coaching kitten points are an array. Do not restore stale prepared reports when a calculation response arrives after an edit.
|
- Browser coverage includes native radio arrow keys, report invalidation on edits/mode changes, delayed responses/double submissions, clipboard denial, dialog focus/Escape, section URLs/Back, both application entry points, admin filters/default sort and gallery. Keep API/data contracts intact: training points are a number, coaching kitten points are an array. Do not restore stale prepared reports when a calculation response arrives after an edit.
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
# MEMORY
|
# MEMORY
|
||||||
|
|
||||||
|
- 2026-11-17: the external report integration polls `/api/admin/calculations/pending` and acknowledges through the admin `entered` flag; it shares the admin credential and privileges. A poll starts from the beginning each time to rediscover unmarked or concurrently committed records; clients deduplicate by report ID. The local change is not evidence of deployment.
|
||||||
|
|
||||||
- 2026-10-21: static review found CVE-2026-109618 / CVE-2026-109619 not actionable for the declared Python/Nginx/PostgreSQL stack, which has no PHP request runtime. Evidence and limits are in `structure_and_data.md`; this does not attest to live containers or external infrastructure. Recheck if PHP is introduced or deployment differs.
|
- 2026-10-21: static review found CVE-2026-109618 / CVE-2026-109619 not actionable for the declared Python/Nginx/PostgreSQL stack, which has no PHP request runtime. Evidence and limits are in `structure_and_data.md`; this does not attest to live containers or external infrastructure. Recheck if PHP is introduced or deployment differs.
|
||||||
|
|
||||||
- 2026-10-18: Russian copy is addressed to CatWar faction members. Website instructions, VK help/dialog prompts, and identity lookup messages use plain wording while retaining game terms and existing report formats. Feather input examples intentionally retain the dash separator accepted by the parser; dates/time ranges and empty table markers are also preserved.
|
- 2026-10-18: Russian copy is addressed to CatWar faction members. Website instructions, VK help/dialog prompts, and identity lookup messages use plain wording while retaining game terms and existing report formats. Feather input examples intentionally retain the dash separator accepted by the parser; dates/time ranges and empty table markers are also preserved.
|
||||||
|
|||||||
@@ -65,6 +65,14 @@ python3 -m app.belki.vk_bot
|
|||||||
|
|
||||||
Админская история доступна по адресу `/admin`. Она защищена заголовком пароля, показывает отдельные столбцы кота-сопровождающего и котёнка, по умолчанию сортирует по коту и позволяет удалять записи после подтверждения. Пароль задаётся через `BELKI_ADMIN_PASSWORD` в `.env` (для Kubernetes — в Secret); без него API админки отключено.
|
Админская история доступна по адресу `/admin`. Она защищена заголовком пароля, показывает отдельные столбцы кота-сопровождающего и котёнка, по умолчанию сортирует по коту и позволяет удалять записи после подтверждения. Пароль задаётся через `BELKI_ADMIN_PASSWORD` в `.env` (для Kubernetes — в Secret); без него API админки отключено.
|
||||||
|
|
||||||
|
### API невнесённых отчётов
|
||||||
|
|
||||||
|
Отдельный серверный сервис может опрашивать `GET /api/admin/calculations/pending` и передавать отчёты человеку. Требуется заголовок `X-Admin-Password` со значением `BELKI_ADMIN_PASSWORD` (или действующая cookie админской сессии). Этот пароль предоставляет доступ ко всей админке: храните его только на сервере и передавайте только по HTTPS, не размещайте в браузерном коде.
|
||||||
|
|
||||||
|
Ответ: `{"items": [...], "next_after_id": 123}`. В `items` те же поля, что в истории админки: `id`, `actor_id`, `source`, `mode`, `input`, `result`, `message`, `created_at`, `entered`. Выдаются все ещё не внесённые записи, включая старые, по возрастанию ID. `limit` — от 1 до 500, по умолчанию 100; для следующей страницы передайте `after_id` из `next_after_id`. Если `next_after_id` равен `null`, текущий обход закончен. Каждый новый опрос начинайте без `after_id`: отметку могут снять, а запись — сохраниться во время обхода. Повторная выдача невнесённой записи ожидаема; используйте её `id` для дедупликации у получателя.
|
||||||
|
|
||||||
|
После внесения человеком отправьте `PATCH /api/admin/calculations/{id}/entered` с тем же заголовком, `Content-Type: application/json` и телом `{"entered": true}`. Повторный запрос безопасен. Чтобы снять отметку, отправьте `{"entered": false}`. Ответ содержит обновлённую запись в поле `item`; несуществующий ID возвращает 404, неверные параметры — 400, отсутствие доступа — 401. Это общая отметка с `/admin`; простое получение или просмотр отчёта её не меняет. Успешный запрос подтверждает только сохранение отметки, а не само внесение во внешнюю систему.
|
||||||
|
|
||||||
## Структура
|
## Структура
|
||||||
|
|
||||||
- `app/belki/domain.py` — расчётное ядро без инфраструктурных зависимостей;
|
- `app/belki/domain.py` — расчётное ядро без инфраструктурных зависимостей;
|
||||||
|
|||||||
+23
-2
@@ -205,6 +205,24 @@ class CalculationStore:
|
|||||||
records.sort(key=sort_value, reverse=descending)
|
records.sort(key=sort_value, reverse=descending)
|
||||||
return records[:limit]
|
return records[:limit]
|
||||||
|
|
||||||
|
def list_pending_calculations(self, *, after_id: int = 0, limit: int = 100) -> list[dict[str, Any]]:
|
||||||
|
"""Return unentered calculations in ID order, without the admin view's scan limit."""
|
||||||
|
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, entered
|
||||||
|
FROM belki_calculations WHERE entered = FALSE AND id > %s ORDER BY id LIMIT %s""",
|
||||||
|
(after_id, 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, entered
|
||||||
|
FROM calculations WHERE entered = 0 AND id > ? ORDER BY id LIMIT ?""",
|
||||||
|
(after_id, limit),
|
||||||
|
).fetchall()
|
||||||
|
return self._records_from_rows(rows)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _validate_lookup_id(value: int, label: str) -> int:
|
def _validate_lookup_id(value: int, label: str) -> int:
|
||||||
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
||||||
@@ -300,7 +318,8 @@ class CalculationStore:
|
|||||||
raise ValueError("ID записи должен быть положительным целым числом")
|
raise ValueError("ID записи должен быть положительным целым числом")
|
||||||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||||
with self._psycopg.connect(self.database_url) as connection:
|
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()
|
row = connection.execute("""UPDATE belki_calculations SET entered=%s WHERE id=%s
|
||||||
|
RETURNING id, actor_id, source, mode, input_json, result_json, message, created_at, entered""", (entered, calculation_id)).fetchone()
|
||||||
if row is None:
|
if row is None:
|
||||||
return None
|
return None
|
||||||
else:
|
else:
|
||||||
@@ -308,7 +327,9 @@ class CalculationStore:
|
|||||||
cursor = connection.execute("UPDATE calculations SET entered=? WHERE id=?", (int(entered), calculation_id))
|
cursor = connection.execute("UPDATE calculations SET entered=? WHERE id=?", (int(entered), calculation_id))
|
||||||
if cursor.rowcount == 0:
|
if cursor.rowcount == 0:
|
||||||
return None
|
return None
|
||||||
return next((item for item in self.list_calculations(limit=500) if item["id"] == calculation_id), None)
|
row = connection.execute("""SELECT id, actor_id, source, mode, input_json, result_json, message, created_at, entered
|
||||||
|
FROM calculations WHERE id = ?""", (calculation_id,)).fetchone()
|
||||||
|
return self._records_from_rows([row])[0]
|
||||||
|
|
||||||
def delete_calculation(self, calculation_id: int) -> bool:
|
def delete_calculation(self, calculation_id: int) -> bool:
|
||||||
"""Delete one history row and report whether it existed."""
|
"""Delete one history row and report whether it existed."""
|
||||||
|
|||||||
+20
-1
@@ -494,6 +494,23 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
response.close()
|
response.close()
|
||||||
response.release_conn()
|
response.release_conn()
|
||||||
return
|
return
|
||||||
|
if path == "/api/admin/calculations/pending":
|
||||||
|
if not self._admin_authorized():
|
||||||
|
return
|
||||||
|
query = parse_qs(urlparse(self.path).query, keep_blank_values=True)
|
||||||
|
try:
|
||||||
|
after_id = int(query.get("after_id", ["0"])[0])
|
||||||
|
limit = int(query.get("limit", ["100"])[0])
|
||||||
|
if not 0 <= after_id <= 9223372036854775807 or not 1 <= limit <= 500:
|
||||||
|
raise ValueError
|
||||||
|
except ValueError:
|
||||||
|
self._json(400, {"error": "after_id должен быть неотрицательным, limit — от 1 до 500"})
|
||||||
|
return
|
||||||
|
records = history_store().list_pending_calculations(after_id=after_id, limit=limit + 1)
|
||||||
|
has_more = len(records) > limit
|
||||||
|
records = records[:limit]
|
||||||
|
self._json(200, {"items": records, "next_after_id": records[-1]["id"] if has_more else None})
|
||||||
|
return
|
||||||
if path == "/api/admin/calculations":
|
if path == "/api/admin/calculations":
|
||||||
if not self._admin_authorized():
|
if not self._admin_authorized():
|
||||||
return
|
return
|
||||||
@@ -746,7 +763,9 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
try:
|
try:
|
||||||
calculation_id = int(parsed.path[len(entered_prefix):-len("/entered")].strip("/"))
|
calculation_id = int(parsed.path[len(entered_prefix):-len("/entered")].strip("/"))
|
||||||
payload = self._read_json_body()
|
payload = self._read_json_body()
|
||||||
item = history_store().set_entered(calculation_id, bool(payload.get("entered")))
|
if not isinstance(payload.get("entered"), bool):
|
||||||
|
raise ValueError("Поле entered должно быть boolean")
|
||||||
|
item = history_store().set_entered(calculation_id, payload["entered"])
|
||||||
except (ApiError, ValueError) as exc:
|
except (ApiError, ValueError) as exc:
|
||||||
self._json(400, {"error": str(exc)})
|
self._json(400, {"error": str(exc)})
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
# Structure and Data
|
# Structure and Data
|
||||||
|
|
||||||
|
## External report polling — 2026-11-17
|
||||||
|
|
||||||
|
- `GET /api/admin/calculations/pending` reads unentered history directly from SQLite/PostgreSQL in ascending ID order with cursor pagination. `PATCH /api/admin/calculations/{id}/entered` updates the same flag as the admin UI and returns the actual row regardless of history size. The existing admin password/session authorizes both; no separate integration identity exists. See README for the contract and polling semantics. Changes are local until deployed.
|
||||||
|
|
||||||
## Calculator and related UI guidance pass — 2026-11-14
|
## Calculator and related UI guidance pass — 2026-11-14
|
||||||
|
|
||||||
- `web/calculator.html` keeps the existing warm palette and typography. Section navigation now uses real links with `aria-current` and browser history; calculation mode uses a native radio group with built-in arrow-key behavior. File inputs, repeatable kitten fields, quick input and output have accessible labels/focus; dialogs retain native modal focus and Escape handling. No new runtime dependencies or polyfills were required.
|
- `web/calculator.html` keeps the existing warm palette and typography. Section navigation now uses real links with `aria-current` and browser history; calculation mode uses a native radio group with built-in arrow-key behavior. File inputs, repeatable kitten fields, quick input and output have accessible labels/focus; dialogs retain native modal focus and Escape handling. No new runtime dependencies or polyfills were required.
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import http.client
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
import threading
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from app.belki.history import CalculationStore
|
||||||
|
from app.main import BelkiHTTPServer, Handler
|
||||||
|
|
||||||
|
|
||||||
|
class PendingReportsTests(unittest.TestCase):
|
||||||
|
def test_external_poll_and_acknowledgement(self):
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
store = CalculationStore(sqlite_path=Path(directory) / 'history.sqlite3')
|
||||||
|
ids = [store.save(actor_id=1, source='web', payload={'mode': 'training'},
|
||||||
|
response={'message': str(i), 'result': {}}) for i in range(503)]
|
||||||
|
server = BelkiHTTPServer(('127.0.0.1', 0), Handler)
|
||||||
|
worker = threading.Thread(target=server.serve_forever, daemon=True)
|
||||||
|
worker.start()
|
||||||
|
|
||||||
|
def request(method, path, body=None, authorized=True):
|
||||||
|
connection = http.client.HTTPConnection('127.0.0.1', server.server_port)
|
||||||
|
headers = {'Connection': 'close'}
|
||||||
|
if authorized:
|
||||||
|
headers['X-Admin-Password'] = 'test-password'
|
||||||
|
if body is not None:
|
||||||
|
headers['Content-Type'] = 'application/json'
|
||||||
|
body = json.dumps(body)
|
||||||
|
connection.request(method, path, body=body, headers=headers)
|
||||||
|
response = connection.getresponse()
|
||||||
|
result = response.status, json.loads(response.read())
|
||||||
|
connection.close()
|
||||||
|
return result
|
||||||
|
|
||||||
|
try:
|
||||||
|
with patch.dict(os.environ, {'BELKI_ADMIN_PASSWORD': 'test-password'}), patch('app.main.history_store', return_value=store):
|
||||||
|
self.assertEqual(request('GET', '/api/admin/calculations/pending', authorized=False)[0], 401)
|
||||||
|
self.assertEqual(request('PATCH', f'/api/admin/calculations/{ids[0]}/entered', {'entered': True}, False)[0], 401)
|
||||||
|
status, page = request('GET', '/api/admin/calculations/pending?limit=2')
|
||||||
|
self.assertEqual(status, 200)
|
||||||
|
self.assertEqual([item['id'] for item in page['items']], ids[:2])
|
||||||
|
self.assertEqual(page['next_after_id'], ids[1])
|
||||||
|
status, updated = request('PATCH', f'/api/admin/calculations/{ids[0]}/entered', {'entered': True})
|
||||||
|
self.assertEqual(status, 200)
|
||||||
|
self.assertTrue(updated['item']['entered'])
|
||||||
|
self.assertEqual(request('PATCH', f'/api/admin/calculations/{ids[0]}/entered', {'entered': True})[0], 200)
|
||||||
|
self.assertEqual(request('PATCH', f'/api/admin/calculations/{ids[1]}/entered', {'entered': 'false'})[0], 400)
|
||||||
|
self.assertEqual(request('PATCH', '/api/admin/calculations/99999/entered', {'entered': True})[0], 404)
|
||||||
|
self.assertEqual(request('GET', '/api/admin/calculations/pending?limit=0')[0], 400)
|
||||||
|
self.assertEqual(request('GET', '/api/admin/calculations/pending?after_id=-1')[0], 400)
|
||||||
|
self.assertEqual(request('GET', '/api/admin/calculations/pending?after_id=9223372036854775808')[0], 400)
|
||||||
|
_, page = request('GET', f'/api/admin/calculations/pending?after_id={ids[-2]}')
|
||||||
|
self.assertEqual([item['id'] for item in page['items']], ids[-1:])
|
||||||
|
self.assertIsNone(page['next_after_id'])
|
||||||
|
_, page = request('GET', '/api/admin/calculations/pending?limit=1')
|
||||||
|
self.assertEqual(page['items'][0]['id'], ids[1])
|
||||||
|
request('PATCH', f'/api/admin/calculations/{ids[0]}/entered', {'entered': False})
|
||||||
|
self.assertFalse(store.list_calculations(limit=1, sort_by='created_at', descending=False)[0]['entered'])
|
||||||
|
finally:
|
||||||
|
server.shutdown()
|
||||||
|
server.server_close()
|
||||||
|
worker.join(timeout=2)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user