feat: add sent report history lookup

This commit is contained in:
nyan404 committed 2026-10-18 18:56:23 +03:00
1 parent 546fa37fce
commit 3ebab303a5
12 files changed
+393 -18

No files matched your search

+90 -14
View File
@@ -177,20 +177,7 @@ class CalculationStore:
"""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 = []
for row in rows:
input_data = row[4] if isinstance(row[4], dict) else json.loads(row[4])
result_data = row[5] if isinstance(row[5], dict) or row[5] is None else json.loads(row[5])
result_data = _restore_inspection_breakdown(input_data, result_data)
message = row[6]
if input_data.get("mode") == "inspection" and isinstance(result_data, dict) and "points" in result_data:
message = re.sub(r"Баллы осмотра:\s*[-+]?\d+", f"Баллы осмотра: {result_data['points']}", message)
records.append({
"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]),
})
records = self._records_from_rows(rows)
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]:
@@ -218,6 +205,95 @@ class CalculationStore:
records.sort(key=sort_value, reverse=descending)
return records[:limit]
@staticmethod
def _validate_lookup_id(value: int, label: str) -> int:
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
raise ValueError(f"{label} должен быть положительным целым числом")
return value
def list_vk_reports(self, actor_id: int, *, limit: int = 100) -> list[dict[str, Any]]:
"""Return the latest saved reports submitted by one VK user."""
actor_id = self._validate_lookup_id(actor_id, "ID отправителя")
limit = max(1, min(int(limit), 100))
modes = ("coaching", "training", "inspection")
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 actor_id = %s AND source = 'vk' AND mode = ANY(%s)
ORDER BY created_at DESC, id DESC LIMIT %s""",
(actor_id, list(modes), limit),
).fetchall()
else:
placeholders = ",".join("?" for _ in modes)
with sqlite3.connect(self.sqlite_path) as connection:
rows = connection.execute(
f"""SELECT id, actor_id, source, mode, input_json, result_json, message, created_at, entered
FROM calculations
WHERE actor_id = ? AND source = 'vk' AND mode IN ({placeholders})
ORDER BY created_at DESC, id DESC LIMIT ?""",
(actor_id, *modes, limit),
).fetchall()
return self._records_from_rows(rows)
def list_character_reports(self, character_id: int, *, limit: int = 100) -> list[dict[str, Any]]:
"""Return recent reports containing a character in any participant role."""
character_id = self._validate_lookup_id(character_id, "ID кота")
limit = max(1, min(int(limit), 100))
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 mode = ANY(%s) AND (
input_json->>'escort_id' = %s OR input_json->>'kitten_id' = %s
OR input_json->>'character_id' = %s
OR EXISTS (
SELECT 1 FROM jsonb_array_elements(
CASE WHEN jsonb_typeof(input_json->'extra_kittens') = 'array'
THEN input_json->'extra_kittens' ELSE '[]'::jsonb END
) AS extra(value) WHERE extra.value->>1 = %s
)
) ORDER BY created_at DESC, id DESC LIMIT %s""",
(["coaching", "training", "inspection"], str(character_id), str(character_id), str(character_id), str(character_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 mode IN ('coaching', 'training', 'inspection') AND (
CAST(json_extract(input_json, '$.escort_id') AS TEXT) = ?
OR CAST(json_extract(input_json, '$.kitten_id') AS TEXT) = ?
OR CAST(json_extract(input_json, '$.character_id') AS TEXT) = ?
OR EXISTS (
SELECT 1 FROM json_each(input_json, '$.extra_kittens') AS extra
WHERE CAST(json_extract(extra.value, '$[1]') AS TEXT) = ?
)
) ORDER BY created_at DESC, id DESC LIMIT ?""",
(str(character_id), str(character_id), str(character_id), str(character_id), limit),
).fetchall()
return self._records_from_rows(rows)
@staticmethod
def _records_from_rows(rows: list[tuple[Any, ...]]) -> list[dict[str, Any]]:
records = []
for row in rows:
input_data = row[4] if isinstance(row[4], dict) else json.loads(row[4])
result_data = row[5] if isinstance(row[5], dict) or row[5] is None else json.loads(row[5])
result_data = _restore_inspection_breakdown(input_data, result_data)
message = row[6]
if input_data.get("mode") == "inspection" and isinstance(result_data, dict) and "points" in result_data:
message = re.sub(r"Баллы осмотра:\s*[-+]?\d+", f"Баллы осмотра: {result_data['points']}", message)
records.append({
"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]),
})
return records
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: