Добавить отметку внесенных отчетов
This commit is contained in:
1 parent
623cf5ad3a
commit
e33de2114a
10 files changed
+76
-4
No files matched your search
@@ -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:
|
||||
|
||||
+23
-2
@@ -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:
|
||||
|
||||
+15
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user