diff --git a/app/belki/history.py b/app/belki/history.py index 760ec36..e8a6f9e 100644 --- a/app/belki/history.py +++ b/app/belki/history.py @@ -32,7 +32,6 @@ class CalculationStore: """ self.database_url = database_url or "" self.sqlite_path = Path(sqlite_path) if sqlite_path else None - fetch_limit = 5000 if self.database_url.startswith(("postgres://", "postgresql://")): import psycopg self._psycopg = psycopg @@ -155,15 +154,26 @@ class CalculationStore: }) if sort_by not in {"escort_id", "escort_name", "kitten_id", "kitten_name"}: sort_by = "escort_id" - def sort_value(item: dict[str, Any]) -> Any: + def sort_value(item: dict[str, Any]) -> tuple[bool, int, int | str]: data = item["input"] if sort_by == "escort_id": - return data.get("escort_id", data.get("character_id")) - if sort_by == "escort_name": - return data.get("escort_name", data.get("character_name")) - return data.get(sort_by) - records.sort(key=lambda item: (sort_value(item) is None, sort_value(item) or ""), - reverse=descending) + value = data.get("escort_id", data.get("character_id")) + elif sort_by == "escort_name": + value = data.get("escort_name", data.get("character_name")) + else: + value = data.get(sort_by) + if value is None: + return True, 0, "" + if sort_by.endswith("_id"): + try: + return False, 0, int(value) + except (TypeError, ValueError): + # Existing records can predate API type normalization. Keep + # malformed legacy values visible rather than failing the + # entire privileged history view. + return False, 1, str(value) + return False, 0, str(value).casefold() + records.sort(key=sort_value, reverse=descending) return records[:limit] def delete_calculation(self, calculation_id: int) -> bool: diff --git a/structure_and_data.md b/structure_and_data.md index 21cdd52..e6af9f6 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -68,6 +68,7 @@ - 2026-08-25: `BelkiHTTPServer` supersedes the unbounded standard threaded server. It rejects oversized declared JSON before reading, times out a slow client after 15 seconds, and serves at most 32 concurrent connections. - 2026-08-25: long-lived authenticated admin refresh WebSockets now have a separate eight-connection pool, so they cannot consume all 32 request workers; additional connections receive an explicit temporary-unavailable response. - 2026-08-25: application validation now bounds names, attachment and feather rows, and descriptive text for both web and VK submissions. Stored attachment and review links must be HTTPS; the optional profile link is restricted to a real VK host. +- 2026-08-25: admin history sorting now tolerates legacy records whose IDs were stored as strings, preserving numeric order for valid IDs instead of failing the complete history view. - 2026-08-25: one-line VK/web recognition now gives explicit role labels priority over position. `сопровождающий`/`наставник`/`учитель` identify the escort, while `ученик`/`котёнок`/`бельчонок`/`подопечный` identify the ward; unlabeled pairs retain the original order-based fallback. - 2026-08-25: corrected Russian UX copy in the VK help and attachment flow; the web identity hint now accurately says that a manually completed pair applies only to the current calculation. - 2026-08-25: natural input normalizes Unicode spaces, dash variants, `ID`/`№` prefixes, spaced IDs, common date/time separators, and close role-label typos before extracting structured fields. Natasha was evaluated for Russian NER through Context7 but not added: game nicknames are better anchored by user-provided IDs and local role context than a generic person model. diff --git a/tests/test_history.py b/tests/test_history.py index a68a332..347badf 100644 --- a/tests/test_history.py +++ b/tests/test_history.py @@ -38,6 +38,18 @@ class CalculationHistoryTests(unittest.TestCase): self.assertFalse(store.delete_calculation(record_id)) self.assertNotIn(record_id, [row["id"] for row in store.list_calculations()]) + def test_admin_history_sorts_legacy_string_ids_without_type_errors(self) -> None: + with tempfile.TemporaryDirectory() as directory: + store = CalculationStore(sqlite_path=Path(directory) / "history.sqlite3") + for kitten_id in ("12", 2, "not-an-id"): + store.save( + actor_id=99, source="vk", + payload={"mode": "coaching", "escort_id": 1, "kitten_id": kitten_id}, + response={"mode": "coaching", "message": "расчёт", "result": {}}, + ) + 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"]) + if __name__ == "__main__": unittest.main()