Added apps
This commit is contained in:
1 parent
540c393258
commit
cfeee5a814
11 files changed
+548
-12
No files matched your search
@@ -0,0 +1,199 @@
|
||||
"""Заявки сообщества: валидация и отдельное хранилище очереди модерации."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
APPLICATION_TYPES = {
|
||||
"feather_donation": "Пожертвовать перо отряду",
|
||||
"kitten": "Стать бельчонком",
|
||||
"flying_squirrel": "Стать белкой-летягой",
|
||||
"curator": "Стать куратором",
|
||||
}
|
||||
|
||||
|
||||
class ApplicationError(ValueError):
|
||||
"""Понятная пользователю ошибка данных заявки."""
|
||||
|
||||
|
||||
def _positive_id(value: Any, label: str) -> int:
|
||||
try:
|
||||
result = int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ApplicationError(f"{label} должно быть числом") from exc
|
||||
if result <= 0:
|
||||
raise ApplicationError(f"{label} должно быть положительным")
|
||||
return result
|
||||
|
||||
|
||||
def validate_application(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Возвращает очищенную заявку и проверяет обязательные поля её типа."""
|
||||
if not isinstance(payload, dict):
|
||||
raise ApplicationError("Ожидалась заявка в формате JSON")
|
||||
application_type = str(payload.get("type", "")).strip()
|
||||
if application_type not in APPLICATION_TYPES:
|
||||
raise ApplicationError("Выберите тип заявки")
|
||||
name = str(payload.get("name", "")).strip()
|
||||
if not name:
|
||||
raise ApplicationError("Укажите имя персонажа")
|
||||
result: dict[str, Any] = {
|
||||
"type": application_type,
|
||||
"name": name,
|
||||
"character_id": _positive_id(payload.get("character_id"), "ID персонажа"),
|
||||
"attachments": [item for item in payload.get("attachments", []) if isinstance(item, dict)],
|
||||
"vk_link": str(payload.get("vk_link", "")).strip(),
|
||||
}
|
||||
if application_type == "kitten":
|
||||
if not result["attachments"]:
|
||||
raise ApplicationError("Для заявки в бельчата приложите скриншот активности")
|
||||
elif application_type == "flying_squirrel":
|
||||
practiced_before = payload.get("practiced_before")
|
||||
if not isinstance(practiced_before, bool):
|
||||
raise ApplicationError("Укажите, сдавали ли вы практику ранее")
|
||||
result["practiced_before"] = practiced_before
|
||||
result["practice_review_link"] = str(payload.get("practice_review_link", "")).strip()
|
||||
if practiced_before and not result["practice_review_link"]:
|
||||
raise ApplicationError("Приложите ссылку на комментарий с прошлой практики")
|
||||
elif application_type == "curator":
|
||||
if not result["attachments"]:
|
||||
raise ApplicationError("Для заявки куратором приложите скриншот ЛУ с дробью")
|
||||
elif application_type == "feather_donation":
|
||||
feathers = []
|
||||
for item in payload.get("feathers", []):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
color = str(item.get("color", "")).strip()
|
||||
source = str(item.get("source", "")).strip()
|
||||
if not color or not source:
|
||||
raise ApplicationError("Для каждого пера укажите цвет и источник добычи")
|
||||
amount = _positive_id(item.get("amount"), "Количество перьев")
|
||||
feathers.append({"color": color, "amount": amount, "source": source})
|
||||
if not feathers:
|
||||
raise ApplicationError("Добавьте хотя бы одно перо")
|
||||
result["feathers"] = feathers
|
||||
return result
|
||||
|
||||
|
||||
class ApplicationStore:
|
||||
"""Хранилище заявок в PostgreSQL production и SQLite для разработки."""
|
||||
|
||||
def __init__(self, database_url: str | None = None, sqlite_path: str | Path | None = None) -> None:
|
||||
self.database_url = database_url or ""
|
||||
self.sqlite_path = Path(sqlite_path) if sqlite_path else None
|
||||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||
import psycopg
|
||||
self._psycopg = psycopg
|
||||
self._ensure_postgres_schema()
|
||||
else:
|
||||
self.sqlite_path = self.sqlite_path or Path("data/belki.sqlite3")
|
||||
self.sqlite_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._ensure_sqlite_schema()
|
||||
|
||||
@classmethod
|
||||
def from_environment(cls) -> "ApplicationStore":
|
||||
return cls(os.getenv("BELKI_DATABASE_URL"), os.getenv("BELKI_HISTORY_DB", "data/belki.sqlite3"))
|
||||
|
||||
def _ensure_sqlite_schema(self) -> None:
|
||||
with sqlite3.connect(self.sqlite_path) as connection:
|
||||
connection.execute("""CREATE TABLE IF NOT EXISTS applications (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, actor_id INTEGER, reply_peer_id INTEGER,
|
||||
source TEXT NOT NULL, application_json TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending',
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, reviewed_at TEXT
|
||||
)""")
|
||||
try:
|
||||
connection.execute("ALTER TABLE applications ADD COLUMN notified_at TEXT")
|
||||
except sqlite3.OperationalError:
|
||||
pass
|
||||
|
||||
def _ensure_postgres_schema(self) -> None:
|
||||
with self._psycopg.connect(self.database_url) as connection:
|
||||
connection.execute("""CREATE TABLE IF NOT EXISTS belki_applications (
|
||||
id BIGSERIAL PRIMARY KEY, actor_id BIGINT, reply_peer_id BIGINT, source TEXT NOT NULL,
|
||||
application_json JSONB NOT NULL, status TEXT NOT NULL DEFAULT 'pending',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), reviewed_at TIMESTAMPTZ
|
||||
)""")
|
||||
connection.execute("ALTER TABLE belki_applications ADD COLUMN IF NOT EXISTS notified_at TIMESTAMPTZ")
|
||||
|
||||
def create(self, *, application: dict[str, Any], actor_id: int | None, reply_peer_id: int | None, source: str) -> int:
|
||||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||
from psycopg.types.json import Jsonb
|
||||
with self._psycopg.connect(self.database_url) as connection:
|
||||
row = connection.execute("""INSERT INTO belki_applications
|
||||
(actor_id, reply_peer_id, source, application_json) VALUES (%s, %s, %s, %s) RETURNING id""",
|
||||
(actor_id, reply_peer_id, source, Jsonb(application))).fetchone()
|
||||
return int(row[0])
|
||||
with sqlite3.connect(self.sqlite_path) as connection:
|
||||
cursor = connection.execute("""INSERT INTO applications
|
||||
(actor_id, reply_peer_id, source, application_json) VALUES (?, ?, ?, ?)""",
|
||||
(actor_id, reply_peer_id, source, json.dumps(application, ensure_ascii=False)))
|
||||
return int(cursor.lastrowid)
|
||||
|
||||
def list(self, *, status: str | None = None, limit: int = 500) -> list[dict[str, Any]]:
|
||||
if status not in (None, "pending", "accepted"):
|
||||
raise ApplicationError("Неизвестный статус заявки")
|
||||
limit = max(1, min(int(limit), 500))
|
||||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||
query = "SELECT id, actor_id, reply_peer_id, source, application_json, status, created_at, reviewed_at FROM belki_applications"
|
||||
params: tuple[Any, ...] = ()
|
||||
if status:
|
||||
query += " WHERE status = %s"; params = (status,)
|
||||
query += " ORDER BY created_at DESC LIMIT %s"; params += (limit,)
|
||||
with self._psycopg.connect(self.database_url) as connection:
|
||||
rows = connection.execute(query, params).fetchall()
|
||||
else:
|
||||
query = "SELECT id, actor_id, reply_peer_id, source, application_json, status, created_at, reviewed_at FROM applications"
|
||||
params: tuple[Any, ...] = ()
|
||||
if status:
|
||||
query += " WHERE status = ?"; params = (status,)
|
||||
query += " ORDER BY created_at DESC LIMIT ?"; params += (limit,)
|
||||
with sqlite3.connect(self.sqlite_path) as connection:
|
||||
rows = connection.execute(query, params).fetchall()
|
||||
return [{"id": row[0], "actor_id": row[1], "reply_peer_id": row[2], "source": row[3],
|
||||
"application": row[4] if isinstance(row[4], dict) else json.loads(row[4]), "status": row[5],
|
||||
"created_at": row[6].isoformat() if hasattr(row[6], "isoformat") else row[6],
|
||||
"reviewed_at": row[7].isoformat() if hasattr(row[7], "isoformat") else row[7]} for row in rows]
|
||||
|
||||
def accept(self, application_id: int) -> dict[str, Any] | None:
|
||||
if application_id <= 0:
|
||||
raise ApplicationError("ID заявки должно быть положительным")
|
||||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||
with self._psycopg.connect(self.database_url) as connection:
|
||||
row = connection.execute("""UPDATE belki_applications SET status = 'accepted', reviewed_at = NOW()
|
||||
WHERE id = %s AND status = 'pending'
|
||||
RETURNING id, actor_id, reply_peer_id, source, application_json, status, created_at, reviewed_at""", (application_id,)).fetchone()
|
||||
else:
|
||||
with sqlite3.connect(self.sqlite_path) as connection:
|
||||
cursor = connection.execute("UPDATE applications SET status = 'accepted', reviewed_at = CURRENT_TIMESTAMP WHERE id = ? AND status = 'pending'", (application_id,))
|
||||
if not cursor.rowcount:
|
||||
return None
|
||||
return next((item for item in self.list(limit=500) if item["id"] == application_id), None)
|
||||
if row is None:
|
||||
return None
|
||||
return {"id": row[0], "actor_id": row[1], "reply_peer_id": row[2], "source": row[3],
|
||||
"application": row[4], "status": row[5], "created_at": row[6].isoformat(), "reviewed_at": row[7].isoformat()}
|
||||
|
||||
def pending_notifications(self) -> list[dict[str, Any]]:
|
||||
"""Возвращает принятые VK-заявки, для которых ещё не отправлено уведомление."""
|
||||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||
with self._psycopg.connect(self.database_url) as connection:
|
||||
rows = connection.execute("""SELECT id, reply_peer_id, application_json FROM belki_applications
|
||||
WHERE status = 'accepted' AND notified_at IS NULL AND reply_peer_id IS NOT NULL""").fetchall()
|
||||
else:
|
||||
with sqlite3.connect(self.sqlite_path) as connection:
|
||||
rows = connection.execute("""SELECT id, reply_peer_id, application_json FROM applications
|
||||
WHERE status = 'accepted' AND notified_at IS NULL AND reply_peer_id IS NOT NULL""").fetchall()
|
||||
return [{"id": row[0], "reply_peer_id": row[1], "application": row[2] if isinstance(row[2], dict) else json.loads(row[2])} for row in rows]
|
||||
|
||||
def mark_notified(self, application_id: int) -> None:
|
||||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||
with self._psycopg.connect(self.database_url) as connection:
|
||||
connection.execute("UPDATE belki_applications SET notified_at = NOW() WHERE id = %s", (application_id,))
|
||||
else:
|
||||
with sqlite3.connect(self.sqlite_path) as connection:
|
||||
connection.execute("UPDATE applications SET notified_at = CURRENT_TIMESTAMP WHERE id = ?", (application_id,))
|
||||
Reference in new issue
Block a user