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,))
|
||||
+145
-4
@@ -4,6 +4,8 @@ import json
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime
|
||||
from typing import Any, Iterator
|
||||
from urllib.parse import urlencode
|
||||
@@ -13,6 +15,7 @@ from .api import ApiError, calculate_payload
|
||||
from .history import CalculationStore
|
||||
from .image_host import ImageHostClient
|
||||
from .identity import Identity, IdentityDirectory
|
||||
from .applications import APPLICATION_TYPES, ApplicationError, ApplicationStore, validate_application
|
||||
|
||||
"""
|
||||
Обработка VK-бота:
|
||||
@@ -425,18 +428,133 @@ class VkApiClient:
|
||||
))
|
||||
|
||||
|
||||
class ApplicationDialog:
|
||||
"""Небольшой пошаговый опросник для заявок, не смешанный с расчётами."""
|
||||
|
||||
_commands = {
|
||||
"/перо": "feather_donation", "/пожертвовать": "feather_donation",
|
||||
"/бельчонок": "kitten", "/бельчата": "kitten",
|
||||
"/летяга": "flying_squirrel", "/белка-летяга": "flying_squirrel",
|
||||
"/куратор": "curator",
|
||||
}
|
||||
|
||||
def __init__(self, identities: IdentityDirectory, store: ApplicationStore) -> None:
|
||||
self.identities, self.store = identities, store
|
||||
self.states: dict[int, dict[str, Any]] = {}
|
||||
|
||||
def active(self, actor_id: int) -> bool:
|
||||
return actor_id in self.states
|
||||
|
||||
def queue_attachments(self, actor_id: int, attachments: list[dict[str, Any]]) -> None:
|
||||
if actor_id in self.states:
|
||||
target = self.states[actor_id].setdefault("attachments", [])
|
||||
target.extend(attachments)
|
||||
del target[:-10]
|
||||
|
||||
@staticmethod
|
||||
def _menu() -> str:
|
||||
return ("Какую заявку хотите подать?\n"
|
||||
"• /перо — пожертвовать перо отряду\n"
|
||||
"• /бельчонок — стать бельчонком\n"
|
||||
"• /летяга — стать белкой-летягой\n"
|
||||
"• /куратор — стать куратором")
|
||||
|
||||
def _start(self, actor_id: int, application_type: str) -> str:
|
||||
profile = self.identities.profile(actor_id=actor_id)
|
||||
state: dict[str, Any] = {"type": application_type, "attachments": []}
|
||||
if profile:
|
||||
state.update(name=profile.name, character_id=profile.character_id)
|
||||
self.states[actor_id] = state
|
||||
if not profile:
|
||||
return "Укажите имя и ID персонажа: Имя [12345]."
|
||||
return self._next(state)
|
||||
|
||||
@staticmethod
|
||||
def _next(state: dict[str, Any]) -> str:
|
||||
kind = state["type"]
|
||||
if kind == "feather_donation":
|
||||
return "Перечислите перья через запятую: количество цвет — источник добычи.\nНапример: 2 синие — личные запасы, 1 чёрное — осмотр дупла."
|
||||
if kind == "kitten":
|
||||
return "Пришлите скриншот активности. Когда закончите, напишите «готово»."
|
||||
if kind == "curator":
|
||||
return "Пришлите скриншот ЛУ с дробью. Когда закончите, напишите «готово»."
|
||||
if "vk_link" not in state:
|
||||
return "Пришлите ссылку на страницу VK или напишите «нет»."
|
||||
if "practiced_before" not in state:
|
||||
return "Сдавали практику ранее? Ответьте «да» или «нет»."
|
||||
if state["practiced_before"] and "practice_review_link" not in state:
|
||||
return "Пришлите ссылку на комментарий ответственного/куратора с прошлой практики."
|
||||
return ""
|
||||
|
||||
@staticmethod
|
||||
def _parse_feathers(text: str) -> list[dict[str, Any]]:
|
||||
feathers = []
|
||||
for part in text.split(","):
|
||||
match = re.fullmatch(r"\s*(\d+)\s+(.+?)\s*[—-]\s*(.+?)\s*", part)
|
||||
if not match:
|
||||
raise ApplicationError("Не смог разобрать перья. Используйте: 2 синие — личные запасы")
|
||||
feathers.append({"amount": int(match.group(1)), "color": match.group(2), "source": match.group(3)})
|
||||
return feathers
|
||||
|
||||
def _save(self, actor_id: int, peer_id: int, state: dict[str, Any]) -> str:
|
||||
application = validate_application(state)
|
||||
application_id = self.store.create(application=application, actor_id=actor_id, reply_peer_id=peer_id, source="vk")
|
||||
self.states.pop(actor_id, None)
|
||||
return f"Заявка №{application_id} отправлена на рассмотрение. Я напишу сюда, когда её примут."
|
||||
|
||||
def handle(self, actor_id: int, peer_id: int, text: str) -> str | None:
|
||||
command = text.strip().lower()
|
||||
if command in ("/заявка", "/заявки"):
|
||||
return self._menu()
|
||||
if command in self._commands:
|
||||
return self._start(actor_id, self._commands[command])
|
||||
state = self.states.get(actor_id)
|
||||
if state is None:
|
||||
return None
|
||||
if command in ("/отмена", "отмена"):
|
||||
self.states.pop(actor_id, None)
|
||||
return "Заявка отменена."
|
||||
try:
|
||||
if "name" not in state:
|
||||
state["name"], state["character_id"] = _person(text)
|
||||
self.identities.remember_profile(actor_id=actor_id, name=state["name"], character_id=state["character_id"])
|
||||
return self._next(state)
|
||||
if state["type"] == "feather_donation":
|
||||
state["feathers"] = self._parse_feathers(text)
|
||||
return self._save(actor_id, peer_id, state)
|
||||
if state["type"] in ("kitten", "curator"):
|
||||
if command != "готово":
|
||||
return "Пришлите скриншот, затем напишите «готово»."
|
||||
return self._save(actor_id, peer_id, state)
|
||||
if "vk_link" not in state:
|
||||
state["vk_link"] = "" if command in ("нет", "неа", "-") else text.strip()
|
||||
return self._next(state)
|
||||
if "practiced_before" not in state:
|
||||
if command not in ("да", "нет"):
|
||||
return "Ответьте «да» или «нет»."
|
||||
state["practiced_before"] = command == "да"
|
||||
return self._next(state) if state["practiced_before"] else self._save(actor_id, peer_id, state)
|
||||
state["practice_review_link"] = text.strip()
|
||||
return self._save(actor_id, peer_id, state)
|
||||
except ApplicationError as exc:
|
||||
return str(exc)
|
||||
|
||||
|
||||
class BelkiBot:
|
||||
"""Основной класс бота, обрабатывающий события VK."""
|
||||
def __init__(self, client: VkApiClient, group_id: int) -> None:
|
||||
"""Инициализация бота с клиентом VK и ID группы."""
|
||||
self.client = client
|
||||
self.group_id = group_id
|
||||
identities = IdentityDirectory.from_environment(persistent=True)
|
||||
self.dialog = BelkiDialog(
|
||||
IdentityDirectory.from_environment(persistent=True),
|
||||
identities,
|
||||
onboarding=True,
|
||||
calculation_store=CalculationStore.from_environment(),
|
||||
attachment_mirror=ImageHostClient().mirror,
|
||||
)
|
||||
self.application_store = ApplicationStore.from_environment()
|
||||
self.application_dialog = ApplicationDialog(identities, self.application_store)
|
||||
|
||||
def response_for_text(self, text: str) -> str:
|
||||
"""Обработка текстового сообщения и возврат ответа."""
|
||||
@@ -465,9 +583,26 @@ class BelkiBot:
|
||||
photos = extract_photo_attachments(message)
|
||||
if photos:
|
||||
self.dialog.queue_attachments(sender, photos)
|
||||
self.application_dialog.queue_attachments(sender, photos)
|
||||
if text:
|
||||
response = self.dialog.handle(int(peer_id), text, user_id=sender)
|
||||
self.client.send(int(peer_id), response, keyboard=self.dialog.keyboard_for(sender))
|
||||
response = self.application_dialog.handle(sender, int(peer_id), text)
|
||||
if response is None:
|
||||
response = self.dialog.handle(int(peer_id), text, user_id=sender)
|
||||
keyboard = self.dialog.keyboard_for(sender)
|
||||
else:
|
||||
keyboard = None
|
||||
self.client.send(int(peer_id), response, keyboard=keyboard)
|
||||
|
||||
def notify_accepted_applications(self) -> None:
|
||||
"""Отправляет пользователям принятые админом заявки и отмечает доставку."""
|
||||
for item in self.application_store.pending_notifications():
|
||||
application = item["application"]
|
||||
label = APPLICATION_TYPES.get(application.get("type"), "Заявка")
|
||||
try:
|
||||
self.client.send(int(item["reply_peer_id"]), f"Ваша заявка «{label}» принята. Спасибо!")
|
||||
except (VkError, OSError):
|
||||
continue
|
||||
self.application_store.mark_notified(int(item["id"]))
|
||||
|
||||
@staticmethod
|
||||
def _button_text(message: dict[str, Any]) -> str | None:
|
||||
@@ -483,7 +618,7 @@ class BelkiBot:
|
||||
value = payload.get("command") if isinstance(payload, dict) else payload
|
||||
return {
|
||||
"menu:lu": "/лу", "menu:zu": "/зу", "menu:training": "/урок",
|
||||
"menu:inspection": "/осмотр", "menu:help": "/help", "menu:cancel": "/отмена",
|
||||
"menu:inspection": "/осмотр", "menu:help": "/help", "menu:cancel": "/отмена", "menu:application": "/заявка",
|
||||
"quick:today": "__today__", "quick:no_resources": "без ресурсов",
|
||||
"place:hollow": "дупло", "place:crevice": "расщелина",
|
||||
"skill:lu": "ЛУ", "skill:zu": "ЗУ",
|
||||
@@ -515,6 +650,11 @@ class BelkiBot:
|
||||
|
||||
def run_forever(self) -> None:
|
||||
"""Бесконечный цикл обработки событий."""
|
||||
def notification_loop() -> None:
|
||||
while True:
|
||||
self.notify_accepted_applications()
|
||||
time.sleep(15)
|
||||
threading.Thread(target=notification_loop, name="belki-application-notifier", daemon=True).start()
|
||||
for event in self.events():
|
||||
self.handle_event(event)
|
||||
|
||||
@@ -677,6 +817,7 @@ class BelkiDialog:
|
||||
"buttons": [
|
||||
[self._button("Прокачка ЛУ", "menu:lu", "primary"), self._button("Прокачка ЗУ", "menu:zu", "primary")],
|
||||
[self._button("Тренировка", "menu:training", "secondary"), self._button("Осмотр", "menu:inspection", "secondary")],
|
||||
[self._button("Подать заявку", "menu:application", "secondary")],
|
||||
[self._button("Помощь", "menu:help", "secondary")],
|
||||
],
|
||||
}
|
||||
|
||||
+44
-2
@@ -11,6 +11,7 @@ from urllib.parse import parse_qs, unquote, urlparse
|
||||
|
||||
from .belki.api import ApiError, calculate_and_store, inspect_bulk_payload, resolve_identity_payload
|
||||
from .belki.history import CalculationStore
|
||||
from .belki.applications import ApplicationError, ApplicationStore, validate_application
|
||||
from .belki.identity import IdentityDirectory
|
||||
from .belki.image_host import ImageHostClient
|
||||
|
||||
@@ -19,6 +20,7 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
WEB_ROOT = ROOT / "web"
|
||||
_HISTORY_STORE: CalculationStore | None = None
|
||||
_IDENTITY_DIR: IdentityDirectory | None = None
|
||||
_APPLICATION_STORE: ApplicationStore | None = None
|
||||
_WEB_SESSIONS: set[str] = set()
|
||||
|
||||
|
||||
@@ -36,6 +38,13 @@ def identity_dir() -> IdentityDirectory:
|
||||
return _IDENTITY_DIR
|
||||
|
||||
|
||||
def application_store() -> ApplicationStore:
|
||||
global _APPLICATION_STORE
|
||||
if _APPLICATION_STORE is None:
|
||||
_APPLICATION_STORE = ApplicationStore.from_environment()
|
||||
return _APPLICATION_STORE
|
||||
|
||||
|
||||
_WEB_PROFILE_KEY = "web_user"
|
||||
|
||||
|
||||
@@ -115,6 +124,9 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if path == "/admin":
|
||||
self._file(WEB_ROOT / "admin.html")
|
||||
return
|
||||
if path in ("/applications", "/applications/"):
|
||||
self._file(WEB_ROOT / "applications.html")
|
||||
return
|
||||
if path == "/api/admin/calculations":
|
||||
if not self._admin_authorized():
|
||||
return
|
||||
@@ -127,6 +139,13 @@ class Handler(BaseHTTPRequestHandler):
|
||||
limit = 100
|
||||
self._json(200, {"items": history_store().list_calculations(sort_by=sort_by, descending=descending, limit=limit)})
|
||||
return
|
||||
if path == "/api/admin/applications":
|
||||
if not self._admin_authorized():
|
||||
return
|
||||
query = parse_qs(urlparse(self.path).query)
|
||||
status = query.get("status", [None])[0] or None
|
||||
self._json(200, {"items": application_store().list(status=status)})
|
||||
return
|
||||
if path == "/api/web/session":
|
||||
expected = os.getenv("BELKI_WEB_PASSWORD", "")
|
||||
cookies = self.headers.get("Cookie", "")
|
||||
@@ -150,7 +169,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
|
||||
def do_POST(self) -> None: # noqa: N802
|
||||
if self.path not in ("/api/web/auth", "/api/web/logout", "/api/web/upload", "/api/calculate", "/api/inspect-bulk", "/api/resolve-identity",
|
||||
"/api/save-profile", "/api/get-profile"):
|
||||
"/api/save-profile", "/api/get-profile", "/api/applications"):
|
||||
self._json(404, {"error": "Не найдено"})
|
||||
return
|
||||
try:
|
||||
@@ -195,9 +214,13 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self._json(200, save_profile(payload))
|
||||
elif self.path == "/api/get-profile":
|
||||
self._json(200, get_profile())
|
||||
elif self.path == "/api/applications":
|
||||
application = validate_application(payload)
|
||||
application_id = application_store().create(application=application, actor_id=None, reply_peer_id=None, source="web")
|
||||
self._json(201, {"id": application_id, "status": "pending", "message": "Заявка отправлена на рассмотрение."})
|
||||
else:
|
||||
self._json(200, calculate_and_store(payload, actor_id=None, source="web"))
|
||||
except ApiError as exc:
|
||||
except (ApiError, ApplicationError) as exc:
|
||||
self._json(400, {"error": str(exc)})
|
||||
except (ValueError, json.JSONDecodeError) as exc:
|
||||
self._json(400, {"error": str(exc)})
|
||||
@@ -224,6 +247,25 @@ class Handler(BaseHTTPRequestHandler):
|
||||
return
|
||||
self._json(200, {"deleted": calculation_id})
|
||||
|
||||
def do_PATCH(self) -> None: # noqa: N802
|
||||
parsed = urlparse(self.path)
|
||||
prefix = "/api/admin/applications/"
|
||||
if not parsed.path.startswith(prefix) or not parsed.path.endswith("/accept"):
|
||||
self._json(404, {"error": "Не найдено"})
|
||||
return
|
||||
if not self._admin_authorized():
|
||||
return
|
||||
raw_id = parsed.path[len(prefix):-len("/accept")].strip("/")
|
||||
try:
|
||||
application = application_store().accept(int(raw_id))
|
||||
except (ValueError, ApplicationError) as exc:
|
||||
self._json(400, {"error": str(exc)})
|
||||
return
|
||||
if application is None:
|
||||
self._json(404, {"error": "Заявка не найдена или уже принята"})
|
||||
return
|
||||
self._json(200, {"item": application})
|
||||
|
||||
def log_message(self, format: str, *args: object) -> None:
|
||||
if os.getenv("BELKI_ACCESS_LOG", "0") == "1":
|
||||
super().log_message(format, *args)
|
||||
|
||||
Reference in new issue
Block a user