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
+23
-2
@@ -205,6 +205,24 @@ class CalculationStore:
|
||||
records.sort(key=sort_value, reverse=descending)
|
||||
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
|
||||
def _validate_lookup_id(value: int, label: str) -> int:
|
||||
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
||||
@@ -300,7 +318,8 @@ class CalculationStore:
|
||||
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()
|
||||
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:
|
||||
return None
|
||||
else:
|
||||
@@ -308,7 +327,9 @@ class CalculationStore:
|
||||
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)
|
||||
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:
|
||||
"""Delete one history row and report whether it existed."""
|
||||
|
||||
+20
-1
@@ -494,6 +494,23 @@ class Handler(BaseHTTPRequestHandler):
|
||||
response.close()
|
||||
response.release_conn()
|
||||
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 not self._admin_authorized():
|
||||
return
|
||||
@@ -746,7 +763,9 @@ class Handler(BaseHTTPRequestHandler):
|
||||
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")))
|
||||
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:
|
||||
self._json(400, {"error": str(exc)})
|
||||
return
|
||||
|
||||
Reference in new issue
Block a user