feat(applications): add keyboard flow and export outbox
This commit is contained in:
1 parent
cfeee5a814
commit
27bcc291db
11 files changed
+254
-9
No files matched your search
@@ -11,3 +11,8 @@ BELKI_IDENTITIES_DB=data/belki.sqlite3
|
|||||||
BELKI_ADMIN_PASSWORD=change-me
|
BELKI_ADMIN_PASSWORD=change-me
|
||||||
# Optional image-hosting-web API origin, e.g. https://nyan.nyan404.ru.
|
# Optional image-hosting-web API origin, e.g. https://nyan.nyan404.ru.
|
||||||
BELKI_IMAGE_HOST_API_URL=
|
BELKI_IMAGE_HOST_API_URL=
|
||||||
|
# Google Sheets export stays disabled until a Google Apps Script Web App endpoint is approved.
|
||||||
|
# When enabled, both created and accepted application events are delivered from the durable outbox.
|
||||||
|
BELKI_GOOGLE_EXPORT_ENABLED=0
|
||||||
|
BELKI_GOOGLE_EXPORT_URL=
|
||||||
|
BELKI_GOOGLE_EXPORT_TOKEN=
|
||||||
@@ -22,6 +22,7 @@
|
|||||||
- 2026-08-16 production deployment: namespace `belki` is live in k3s. Web and bot use `reg.nyan404.ru/cwshed-clone/belki:6b74dfa`; the migrated cwshed Nginx gateway keeps MetalLB `10.12.0.204` and routes `/belki`, `/admin`, and `/api/*` to web `10.12.0.212`; PostgreSQL uses the amd64 mirror `reg.nyan404.ru/library/postgres:16-alpine-amd64` on Longhorn. Runtime credentials remain only in the cluster Secret `belki-runtime`.
|
- 2026-08-16 production deployment: namespace `belki` is live in k3s. Web and bot use `reg.nyan404.ru/cwshed-clone/belki:6b74dfa`; the migrated cwshed Nginx gateway keeps MetalLB `10.12.0.204` and routes `/belki`, `/admin`, and `/api/*` to web `10.12.0.212`; PostgreSQL uses the amd64 mirror `reg.nyan404.ru/library/postgres:16-alpine-amd64` on Longhorn. Runtime credentials remain only in the cluster Secret `belki-runtime`.
|
||||||
- GitLab CI/CD now builds SHA/latest tags and deploys `deploy/k8s/production.yaml` from `main`. The ignored `.gitlab.variables.env` is a local handoff for GitLab Variables; CI uses namespace-scoped ServiceAccount `belki/gitlab-deploy`, not cluster-admin credentials.
|
- GitLab CI/CD now builds SHA/latest tags and deploys `deploy/k8s/production.yaml` from `main`. The ignored `.gitlab.variables.env` is a local handoff for GitLab Variables; CI uses namespace-scoped ServiceAccount `belki/gitlab-deploy`, not cluster-admin credentials.
|
||||||
- 2026-08-21: applications use a separate store/table from calculator history. `/applications` and VK `/заявка` collect typed data; `/admin` accepts it. The bot can automatically notify only VK submissions, because a web form has no known reply peer.
|
- 2026-08-21: applications use a separate store/table from calculator history. `/applications` and VK `/заявка` collect typed data; `/admin` accepts it. The bot can automatically notify only VK submissions, because a web form has no known reply peer.
|
||||||
|
- 2026-08-21: Google Sheets export is intentionally disabled by default. Application create/accept events go to a durable outbox and will be delivered through an explicitly configured Apps Script Web App endpoint once the feature flag is enabled.
|
||||||
# 2026-08-16 — несколько котят в прокачке
|
# 2026-08-16 — несколько котят в прокачке
|
||||||
|
|
||||||
`CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде.
|
`CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде.
|
||||||
@@ -41,10 +41,14 @@ python3 -m app.belki.vk_bot
|
|||||||
|
|
||||||
## Заявки
|
## Заявки
|
||||||
|
|
||||||
`/applications` — защищённая той же веб-сессией форма для пожертвования перьев, бельчонка, белки-летяги и куратора. Она сохраняет структурированные данные в очередь модерации, а не генерирует форумную отпись. В VK используйте `/заявка` и выберите сценарий.
|
`/applications` — защищённая той же веб-сессией форма для пожертвования перьев, бельчонка, белки-летяги и куратора. Она сохраняет структурированные данные в очередь модерации, а не генерирует форумную отпись. В VK используйте `/заявка`: виртуальная клавиатура проводит через выбор типа, пропуск VK-ссылки, ответы «да/нет», «готово» и отмену; вручную вводятся только свободные данные, например ссылки и источники перьев.
|
||||||
|
|
||||||
В `/admin` есть верхняя вкладка «Заявки» рядом с «Отчётами»; внутри неё — вкладки новых и принятых заявок, полное содержимое и действие «Принять». После принятия VK-заявки бот пишет заявителю в личные сообщения. У веб-заявки нет автоматически известного VK-получателя: она получает номер, а VK-ссылку можно оставить для ручной связи.
|
В `/admin` есть верхняя вкладка «Заявки» рядом с «Отчётами»; внутри неё — вкладки новых и принятых заявок, полное содержимое и действие «Принять». После принятия VK-заявки бот пишет заявителю в личные сообщения. У веб-заявки нет автоматически известного VK-получателя: она получает номер, а VK-ссылку можно оставить для ручной связи.
|
||||||
|
|
||||||
|
### Будущий экспорт в Google Sheets
|
||||||
|
|
||||||
|
Экспорт заложен, но выключен: создание и принятие заявок записываются в устойчивую outbox-очередь в той же БД. После подготовки Google Apps Script Web App задайте `BELKI_GOOGLE_EXPORT_ENABLED=1` и `BELKI_GOOGLE_EXPORT_URL`; при необходимости передайте `BELKI_GOOGLE_EXPORT_TOKEN`. Бот доставляет очередь каждые 15 секунд и сохраняет неудачные попытки для повторной отправки. Пока флаг равен `0`, приложение не делает запросов во внешние сервисы.
|
||||||
|
|
||||||
Осмотр теперь считает баллы: 2 за каждый осмотр, паутина — 7, обычный мох — 3, водяной мох — 2, остальные ресурсы — 1, надпись и ядовитая дичь — 0. Луговая змея и гадюка относятся к обычным ресурсам и дают 1 балл, а обычная змея, щитомордник и полосатый аспид — 0. Названия нормализуются по регистру, пробелам и распространённым опечаткам. Количество ресурса умножается на его стоимость с учётом знака.
|
Осмотр теперь считает баллы: 2 за каждый осмотр, паутина — 7, обычный мох — 3, водяной мох — 2, остальные ресурсы — 1, надпись и ядовитая дичь — 0. Луговая змея и гадюка относятся к обычным ресурсам и дают 1 балл, а обычная змея, щитомордник и полосатый аспид — 0. Названия нормализуются по регистру, пробелам и распространённым опечаткам. Количество ресурса умножается на его стоимость с учётом знака.
|
||||||
|
|
||||||
Админская история доступна по адресу `/admin`. Она защищена заголовком пароля, показывает отдельные столбцы кота-сопровождающего и котёнка, по умолчанию сортирует по коту и позволяет удалять записи после подтверждения. Пароль задаётся через `BELKI_ADMIN_PASSWORD` в `.env` (для Kubernetes — в Secret); без него API админки отключено.
|
Админская история доступна по адресу `/admin`. Она защищена заголовком пароля, показывает отдельные столбцы кота-сопровождающего и котёнка, по умолчанию сортирует по коту и позволяет удалять записи после подтверждения. Пароль задаётся через `BELKI_ADMIN_PASSWORD` в `.env` (для Kubernetes — в Secret); без него API админки отключено.
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ from __future__ import annotations
|
|||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import sqlite3
|
import sqlite3
|
||||||
import time
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@@ -110,6 +109,12 @@ class ApplicationStore:
|
|||||||
connection.execute("ALTER TABLE applications ADD COLUMN notified_at TEXT")
|
connection.execute("ALTER TABLE applications ADD COLUMN notified_at TEXT")
|
||||||
except sqlite3.OperationalError:
|
except sqlite3.OperationalError:
|
||||||
pass
|
pass
|
||||||
|
connection.execute("""CREATE TABLE IF NOT EXISTS application_export_events (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT, application_id INTEGER NOT NULL,
|
||||||
|
event_type TEXT NOT NULL, payload_json TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, delivered_at TEXT, last_error TEXT
|
||||||
|
)""")
|
||||||
|
|
||||||
def _ensure_postgres_schema(self) -> None:
|
def _ensure_postgres_schema(self) -> None:
|
||||||
with self._psycopg.connect(self.database_url) as connection:
|
with self._psycopg.connect(self.database_url) as connection:
|
||||||
@@ -119,6 +124,12 @@ class ApplicationStore:
|
|||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), reviewed_at TIMESTAMPTZ
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), reviewed_at TIMESTAMPTZ
|
||||||
)""")
|
)""")
|
||||||
connection.execute("ALTER TABLE belki_applications ADD COLUMN IF NOT EXISTS notified_at TIMESTAMPTZ")
|
connection.execute("ALTER TABLE belki_applications ADD COLUMN IF NOT EXISTS notified_at TIMESTAMPTZ")
|
||||||
|
connection.execute("""CREATE TABLE IF NOT EXISTS belki_application_export_events (
|
||||||
|
id BIGSERIAL PRIMARY KEY, application_id BIGINT NOT NULL,
|
||||||
|
event_type TEXT NOT NULL, payload_json JSONB NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), delivered_at TIMESTAMPTZ, last_error TEXT
|
||||||
|
)""")
|
||||||
|
|
||||||
def create(self, *, application: dict[str, Any], actor_id: int | None, reply_peer_id: int | None, source: str) -> int:
|
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://")):
|
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||||
@@ -127,12 +138,20 @@ class ApplicationStore:
|
|||||||
row = connection.execute("""INSERT INTO belki_applications
|
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, application_json) VALUES (%s, %s, %s, %s) RETURNING id""",
|
||||||
(actor_id, reply_peer_id, source, Jsonb(application))).fetchone()
|
(actor_id, reply_peer_id, source, Jsonb(application))).fetchone()
|
||||||
return int(row[0])
|
application_id = int(row[0])
|
||||||
|
self.enqueue_export(application_id, "application_created", {
|
||||||
|
"id": application_id, "source": source, "status": "pending", "application": application,
|
||||||
|
})
|
||||||
|
return application_id
|
||||||
with sqlite3.connect(self.sqlite_path) as connection:
|
with sqlite3.connect(self.sqlite_path) as connection:
|
||||||
cursor = connection.execute("""INSERT INTO applications
|
cursor = connection.execute("""INSERT INTO applications
|
||||||
(actor_id, reply_peer_id, source, application_json) VALUES (?, ?, ?, ?)""",
|
(actor_id, reply_peer_id, source, application_json) VALUES (?, ?, ?, ?)""",
|
||||||
(actor_id, reply_peer_id, source, json.dumps(application, ensure_ascii=False)))
|
(actor_id, reply_peer_id, source, json.dumps(application, ensure_ascii=False)))
|
||||||
return int(cursor.lastrowid)
|
application_id = int(cursor.lastrowid)
|
||||||
|
self.enqueue_export(application_id, "application_created", {
|
||||||
|
"id": application_id, "source": source, "status": "pending", "application": application,
|
||||||
|
})
|
||||||
|
return application_id
|
||||||
|
|
||||||
def list(self, *, status: str | None = None, limit: int = 500) -> list[dict[str, Any]]:
|
def list(self, *, status: str | None = None, limit: int = 500) -> list[dict[str, Any]]:
|
||||||
if status not in (None, "pending", "accepted"):
|
if status not in (None, "pending", "accepted"):
|
||||||
@@ -172,11 +191,63 @@ class ApplicationStore:
|
|||||||
cursor = connection.execute("UPDATE applications SET status = 'accepted', reviewed_at = CURRENT_TIMESTAMP WHERE id = ? AND status = 'pending'", (application_id,))
|
cursor = connection.execute("UPDATE applications SET status = 'accepted', reviewed_at = CURRENT_TIMESTAMP WHERE id = ? AND status = 'pending'", (application_id,))
|
||||||
if not cursor.rowcount:
|
if not cursor.rowcount:
|
||||||
return None
|
return None
|
||||||
return next((item for item in self.list(limit=500) if item["id"] == application_id), None)
|
application = next((item for item in self.list(limit=500) if item["id"] == application_id), None)
|
||||||
|
if application:
|
||||||
|
self.enqueue_export(application_id, "application_accepted", application)
|
||||||
|
return application
|
||||||
if row is None:
|
if row is None:
|
||||||
return None
|
return None
|
||||||
return {"id": row[0], "actor_id": row[1], "reply_peer_id": row[2], "source": row[3],
|
application = {"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()}
|
"application": row[4], "status": row[5], "created_at": row[6].isoformat(), "reviewed_at": row[7].isoformat()}
|
||||||
|
self.enqueue_export(application_id, "application_accepted", application)
|
||||||
|
return application
|
||||||
|
|
||||||
|
def enqueue_export(self, application_id: int, event_type: str, snapshot: dict[str, Any]) -> int:
|
||||||
|
"""Сохраняет событие для будущего экспорта до любого сетевого вызова."""
|
||||||
|
payload = {"schema_version": 1, "event_type": event_type, "application": snapshot}
|
||||||
|
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_application_export_events
|
||||||
|
(application_id, event_type, payload_json) VALUES (%s, %s, %s) RETURNING id""",
|
||||||
|
(application_id, event_type, Jsonb(payload))).fetchone()
|
||||||
|
return int(row[0])
|
||||||
|
with sqlite3.connect(self.sqlite_path) as connection:
|
||||||
|
cursor = connection.execute("""INSERT INTO application_export_events
|
||||||
|
(application_id, event_type, payload_json) VALUES (?, ?, ?)""",
|
||||||
|
(application_id, event_type, json.dumps(payload, ensure_ascii=False)))
|
||||||
|
return int(cursor.lastrowid)
|
||||||
|
|
||||||
|
def pending_exports(self, *, limit: int = 100) -> list[dict[str, Any]]:
|
||||||
|
"""Возвращает недоставленные события в порядке их создания."""
|
||||||
|
limit = max(1, min(int(limit), 500))
|
||||||
|
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||||
|
with self._psycopg.connect(self.database_url) as connection:
|
||||||
|
rows = connection.execute("""SELECT id, application_id, event_type, payload_json, attempts
|
||||||
|
FROM belki_application_export_events WHERE status = 'pending' ORDER BY id LIMIT %s""", (limit,)).fetchall()
|
||||||
|
else:
|
||||||
|
with sqlite3.connect(self.sqlite_path) as connection:
|
||||||
|
rows = connection.execute("""SELECT id, application_id, event_type, payload_json, attempts
|
||||||
|
FROM application_export_events WHERE status = 'pending' ORDER BY id LIMIT ?""", (limit,)).fetchall()
|
||||||
|
return [{"id": row[0], "application_id": row[1], "event_type": row[2],
|
||||||
|
"payload": row[3] if isinstance(row[3], dict) else json.loads(row[3]), "attempts": row[4]} for row in rows]
|
||||||
|
|
||||||
|
def mark_exported(self, event_id: int) -> None:
|
||||||
|
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||||
|
with self._psycopg.connect(self.database_url) as connection:
|
||||||
|
connection.execute("UPDATE belki_application_export_events SET status = 'delivered', delivered_at = NOW(), attempts = attempts + 1, last_error = NULL WHERE id = %s", (event_id,))
|
||||||
|
else:
|
||||||
|
with sqlite3.connect(self.sqlite_path) as connection:
|
||||||
|
connection.execute("UPDATE application_export_events SET status = 'delivered', delivered_at = CURRENT_TIMESTAMP, attempts = attempts + 1, last_error = NULL WHERE id = ?", (event_id,))
|
||||||
|
|
||||||
|
def record_export_failure(self, event_id: int, message: str) -> None:
|
||||||
|
message = message[:1000]
|
||||||
|
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||||
|
with self._psycopg.connect(self.database_url) as connection:
|
||||||
|
connection.execute("UPDATE belki_application_export_events SET attempts = attempts + 1, last_error = %s WHERE id = %s", (message, event_id))
|
||||||
|
else:
|
||||||
|
with sqlite3.connect(self.sqlite_path) as connection:
|
||||||
|
connection.execute("UPDATE application_export_events SET attempts = attempts + 1, last_error = ? WHERE id = ?", (message, event_id))
|
||||||
|
|
||||||
def pending_notifications(self) -> list[dict[str, Any]]:
|
def pending_notifications(self) -> list[dict[str, Any]]:
|
||||||
"""Возвращает принятые VK-заявки, для которых ещё не отправлено уведомление."""
|
"""Возвращает принятые VK-заявки, для которых ещё не отправлено уведомление."""
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
"""Выключенный по умолчанию экспорт заявок в Google Sheets через Apps Script."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from urllib.error import URLError
|
||||||
|
from urllib.request import Request, urlopen
|
||||||
|
|
||||||
|
from .applications import ApplicationStore
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class GoogleSheetsExportConfig:
|
||||||
|
"""Настройки webhook-а Apps Script; отсутствие любой обязательной выключает экспорт."""
|
||||||
|
|
||||||
|
enabled: bool
|
||||||
|
url: str
|
||||||
|
token: str
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_environment(cls) -> "GoogleSheetsExportConfig":
|
||||||
|
return cls(
|
||||||
|
enabled=os.getenv("BELKI_GOOGLE_EXPORT_ENABLED", "0") == "1",
|
||||||
|
url=os.getenv("BELKI_GOOGLE_EXPORT_URL", "").strip(),
|
||||||
|
token=os.getenv("BELKI_GOOGLE_EXPORT_TOKEN", "").strip(),
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def ready(self) -> bool:
|
||||||
|
return self.enabled and bool(self.url)
|
||||||
|
|
||||||
|
|
||||||
|
class GoogleSheetsExportService:
|
||||||
|
"""Доставляет outbox-события; при выключенной интеграции ничего не делает."""
|
||||||
|
|
||||||
|
def __init__(self, store: ApplicationStore, config: GoogleSheetsExportConfig | None = None) -> None:
|
||||||
|
self.store = store
|
||||||
|
self.config = config or GoogleSheetsExportConfig.from_environment()
|
||||||
|
|
||||||
|
def sync_pending(self, *, limit: int = 100) -> int:
|
||||||
|
"""Пытается доставить события по порядку и возвращает число успешных отправок."""
|
||||||
|
if not self.config.ready:
|
||||||
|
return 0
|
||||||
|
delivered = 0
|
||||||
|
for event in self.store.pending_exports(limit=limit):
|
||||||
|
body = json.dumps(event["payload"], ensure_ascii=False).encode("utf-8")
|
||||||
|
headers = {"Content-Type": "application/json; charset=utf-8"}
|
||||||
|
if self.config.token:
|
||||||
|
headers["Authorization"] = f"Bearer {self.config.token}"
|
||||||
|
request = Request(self.config.url, data=body, headers=headers, method="POST")
|
||||||
|
try:
|
||||||
|
with urlopen(request, timeout=15) as response:
|
||||||
|
if not 200 <= response.status < 300:
|
||||||
|
raise RuntimeError(f"Google export returned HTTP {response.status}")
|
||||||
|
except (OSError, URLError, RuntimeError, ValueError) as exc:
|
||||||
|
self.store.record_export_failure(event["id"], str(exc))
|
||||||
|
break
|
||||||
|
self.store.mark_exported(event["id"])
|
||||||
|
delivered += 1
|
||||||
|
return delivered
|
||||||
+55
-2
@@ -16,6 +16,7 @@ from .history import CalculationStore
|
|||||||
from .image_host import ImageHostClient
|
from .image_host import ImageHostClient
|
||||||
from .identity import Identity, IdentityDirectory
|
from .identity import Identity, IdentityDirectory
|
||||||
from .applications import APPLICATION_TYPES, ApplicationError, ApplicationStore, validate_application
|
from .applications import APPLICATION_TYPES, ApplicationError, ApplicationStore, validate_application
|
||||||
|
from .google_sheets_export import GoogleSheetsExportService
|
||||||
|
|
||||||
"""
|
"""
|
||||||
Обработка VK-бота:
|
Обработка VK-бота:
|
||||||
@@ -445,6 +446,47 @@ class ApplicationDialog:
|
|||||||
def active(self, actor_id: int) -> bool:
|
def active(self, actor_id: int) -> bool:
|
||||||
return actor_id in self.states
|
return actor_id in self.states
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def is_application_command(cls, text: str) -> bool:
|
||||||
|
return text.strip().lower() in {"/заявка", "/заявки", *cls._commands}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _button(label: str, payload: str, color: str = "secondary") -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"action": {"type": "text", "label": label, "payload": json.dumps({"command": payload}, ensure_ascii=False)},
|
||||||
|
"color": color,
|
||||||
|
}
|
||||||
|
|
||||||
|
def keyboard_for(self, actor_id: int) -> dict[str, Any] | None:
|
||||||
|
"""Контекстная VK-клавиатура для всех выбираемых шагов заявки."""
|
||||||
|
state = self.states.get(actor_id)
|
||||||
|
if not state:
|
||||||
|
return None
|
||||||
|
cancel = self._button("Отмена", "menu:cancel", "negative")
|
||||||
|
if state.get("application_menu"):
|
||||||
|
return {"one_time": False, "buttons": [
|
||||||
|
[self._button("Пожертвовать перо", "application:feathers", "secondary")],
|
||||||
|
[self._button("Стать бельчонком", "application:kitten", "primary")],
|
||||||
|
[self._button("Стать летягой", "application:flying", "primary")],
|
||||||
|
[self._button("Стать куратором", "application:curator", "primary")],
|
||||||
|
[cancel],
|
||||||
|
]}
|
||||||
|
if "name" not in state:
|
||||||
|
return {"one_time": False, "buttons": [[cancel]]}
|
||||||
|
if state["type"] in ("kitten", "curator"):
|
||||||
|
return {"one_time": False, "buttons": [
|
||||||
|
[self._button("Готово", "application:done", "positive")], [cancel],
|
||||||
|
]}
|
||||||
|
if state["type"] == "flying_squirrel":
|
||||||
|
if "vk_link" not in state:
|
||||||
|
return {"one_time": False, "buttons": [[self._button("Нет ссылки VK", "application:skip-vk")], [cancel]]}
|
||||||
|
if "practiced_before" not in state:
|
||||||
|
return {"one_time": False, "buttons": [[
|
||||||
|
self._button("Да", "application:practice-yes", "positive"),
|
||||||
|
self._button("Нет", "application:practice-no", "negative"),
|
||||||
|
], [cancel]]}
|
||||||
|
return {"one_time": False, "buttons": [[cancel]]}
|
||||||
|
|
||||||
def queue_attachments(self, actor_id: int, attachments: list[dict[str, Any]]) -> None:
|
def queue_attachments(self, actor_id: int, attachments: list[dict[str, Any]]) -> None:
|
||||||
if actor_id in self.states:
|
if actor_id in self.states:
|
||||||
target = self.states[actor_id].setdefault("attachments", [])
|
target = self.states[actor_id].setdefault("attachments", [])
|
||||||
@@ -505,6 +547,7 @@ class ApplicationDialog:
|
|||||||
def handle(self, actor_id: int, peer_id: int, text: str) -> str | None:
|
def handle(self, actor_id: int, peer_id: int, text: str) -> str | None:
|
||||||
command = text.strip().lower()
|
command = text.strip().lower()
|
||||||
if command in ("/заявка", "/заявки"):
|
if command in ("/заявка", "/заявки"):
|
||||||
|
self.states[actor_id] = {"application_menu": True}
|
||||||
return self._menu()
|
return self._menu()
|
||||||
if command in self._commands:
|
if command in self._commands:
|
||||||
return self._start(actor_id, self._commands[command])
|
return self._start(actor_id, self._commands[command])
|
||||||
@@ -555,6 +598,7 @@ class BelkiBot:
|
|||||||
)
|
)
|
||||||
self.application_store = ApplicationStore.from_environment()
|
self.application_store = ApplicationStore.from_environment()
|
||||||
self.application_dialog = ApplicationDialog(identities, self.application_store)
|
self.application_dialog = ApplicationDialog(identities, self.application_store)
|
||||||
|
self.application_exporter = GoogleSheetsExportService(self.application_store)
|
||||||
|
|
||||||
def response_for_text(self, text: str) -> str:
|
def response_for_text(self, text: str) -> str:
|
||||||
"""Обработка текстового сообщения и возврат ответа."""
|
"""Обработка текстового сообщения и возврат ответа."""
|
||||||
@@ -581,16 +625,20 @@ class BelkiBot:
|
|||||||
if peer_id is not None:
|
if peer_id is not None:
|
||||||
sender = int(sender_id or peer_id)
|
sender = int(sender_id or peer_id)
|
||||||
photos = extract_photo_attachments(message)
|
photos = extract_photo_attachments(message)
|
||||||
|
if self.application_dialog.is_application_command(text):
|
||||||
|
self.dialog._reset(sender)
|
||||||
if photos:
|
if photos:
|
||||||
self.dialog.queue_attachments(sender, photos)
|
if self.application_dialog.active(sender) or self.application_dialog.is_application_command(text):
|
||||||
self.application_dialog.queue_attachments(sender, photos)
|
self.application_dialog.queue_attachments(sender, photos)
|
||||||
|
else:
|
||||||
|
self.dialog.queue_attachments(sender, photos)
|
||||||
if text:
|
if text:
|
||||||
response = self.application_dialog.handle(sender, int(peer_id), text)
|
response = self.application_dialog.handle(sender, int(peer_id), text)
|
||||||
if response is None:
|
if response is None:
|
||||||
response = self.dialog.handle(int(peer_id), text, user_id=sender)
|
response = self.dialog.handle(int(peer_id), text, user_id=sender)
|
||||||
keyboard = self.dialog.keyboard_for(sender)
|
keyboard = self.dialog.keyboard_for(sender)
|
||||||
else:
|
else:
|
||||||
keyboard = None
|
keyboard = self.application_dialog.keyboard_for(sender) or self.dialog.keyboard_for(sender)
|
||||||
self.client.send(int(peer_id), response, keyboard=keyboard)
|
self.client.send(int(peer_id), response, keyboard=keyboard)
|
||||||
|
|
||||||
def notify_accepted_applications(self) -> None:
|
def notify_accepted_applications(self) -> None:
|
||||||
@@ -619,6 +667,10 @@ class BelkiBot:
|
|||||||
return {
|
return {
|
||||||
"menu:lu": "/лу", "menu:zu": "/зу", "menu:training": "/урок",
|
"menu:lu": "/лу", "menu:zu": "/зу", "menu:training": "/урок",
|
||||||
"menu:inspection": "/осмотр", "menu:help": "/help", "menu:cancel": "/отмена", "menu:application": "/заявка",
|
"menu:inspection": "/осмотр", "menu:help": "/help", "menu:cancel": "/отмена", "menu:application": "/заявка",
|
||||||
|
"application:feathers": "/перо", "application:kitten": "/бельчонок",
|
||||||
|
"application:flying": "/летяга", "application:curator": "/куратор",
|
||||||
|
"application:skip-vk": "нет", "application:practice-yes": "да", "application:practice-no": "нет",
|
||||||
|
"application:done": "готово",
|
||||||
"quick:today": "__today__", "quick:no_resources": "без ресурсов",
|
"quick:today": "__today__", "quick:no_resources": "без ресурсов",
|
||||||
"place:hollow": "дупло", "place:crevice": "расщелина",
|
"place:hollow": "дупло", "place:crevice": "расщелина",
|
||||||
"skill:lu": "ЛУ", "skill:zu": "ЗУ",
|
"skill:lu": "ЛУ", "skill:zu": "ЗУ",
|
||||||
@@ -653,6 +705,7 @@ class BelkiBot:
|
|||||||
def notification_loop() -> None:
|
def notification_loop() -> None:
|
||||||
while True:
|
while True:
|
||||||
self.notify_accepted_applications()
|
self.notify_accepted_applications()
|
||||||
|
self.application_exporter.sync_pending()
|
||||||
time.sleep(15)
|
time.sleep(15)
|
||||||
threading.Thread(target=notification_loop, name="belki-application-notifier", daemon=True).start()
|
threading.Thread(target=notification_loop, name="belki-application-notifier", daemon=True).start()
|
||||||
for event in self.events():
|
for event in self.events():
|
||||||
|
|||||||
@@ -12,6 +12,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.api import ApiError, calculate_and_store, inspect_bulk_payload, resolve_identity_payload
|
||||||
from .belki.history import CalculationStore
|
from .belki.history import CalculationStore
|
||||||
from .belki.applications import ApplicationError, ApplicationStore, validate_application
|
from .belki.applications import ApplicationError, ApplicationStore, validate_application
|
||||||
|
from .belki.google_sheets_export import GoogleSheetsExportService
|
||||||
from .belki.identity import IdentityDirectory
|
from .belki.identity import IdentityDirectory
|
||||||
from .belki.image_host import ImageHostClient
|
from .belki.image_host import ImageHostClient
|
||||||
|
|
||||||
@@ -45,6 +46,11 @@ def application_store() -> ApplicationStore:
|
|||||||
return _APPLICATION_STORE
|
return _APPLICATION_STORE
|
||||||
|
|
||||||
|
|
||||||
|
def sync_application_exports() -> int:
|
||||||
|
"""No-op until the explicitly disabled Google export is configured."""
|
||||||
|
return GoogleSheetsExportService(application_store()).sync_pending()
|
||||||
|
|
||||||
|
|
||||||
_WEB_PROFILE_KEY = "web_user"
|
_WEB_PROFILE_KEY = "web_user"
|
||||||
|
|
||||||
|
|
||||||
@@ -217,6 +223,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
elif self.path == "/api/applications":
|
elif self.path == "/api/applications":
|
||||||
application = validate_application(payload)
|
application = validate_application(payload)
|
||||||
application_id = application_store().create(application=application, actor_id=None, reply_peer_id=None, source="web")
|
application_id = application_store().create(application=application, actor_id=None, reply_peer_id=None, source="web")
|
||||||
|
sync_application_exports()
|
||||||
self._json(201, {"id": application_id, "status": "pending", "message": "Заявка отправлена на рассмотрение."})
|
self._json(201, {"id": application_id, "status": "pending", "message": "Заявка отправлена на рассмотрение."})
|
||||||
else:
|
else:
|
||||||
self._json(200, calculate_and_store(payload, actor_id=None, source="web"))
|
self._json(200, calculate_and_store(payload, actor_id=None, source="web"))
|
||||||
@@ -264,6 +271,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
if application is None:
|
if application is None:
|
||||||
self._json(404, {"error": "Заявка не найдена или уже принята"})
|
self._json(404, {"error": "Заявка не найдена или уже принята"})
|
||||||
return
|
return
|
||||||
|
sync_application_exports()
|
||||||
self._json(200, {"item": application})
|
self._json(200, {"item": application})
|
||||||
|
|
||||||
def log_message(self, format: str, *args: object) -> None:
|
def log_message(self, format: str, *args: object) -> None:
|
||||||
|
|||||||
@@ -29,6 +29,7 @@
|
|||||||
│ │ ├── vk_bot.py — VK Bots Long Poll API
|
│ │ ├── vk_bot.py — VK Bots Long Poll API
|
||||||
│ │ ├── history.py — CalculationStore (PG/SQLite)
|
│ │ ├── history.py — CalculationStore (PG/SQLite)
|
||||||
│ │ ├── applications.py — ApplicationStore и валидация заявок
|
│ │ ├── applications.py — ApplicationStore и валидация заявок
|
||||||
|
│ │ ├── google_sheets_export.py — выключенный outbox-экспорт в Google Sheets
|
||||||
│ │ ├── identity.py — IdentityDirectory (имя↔ID котёнка)
|
│ │ ├── identity.py — IdentityDirectory (имя↔ID котёнка)
|
||||||
│ │ └── image_host.py — ImageHostClient (зеркалирование фото)
|
│ │ └── image_host.py — ImageHostClient (зеркалирование фото)
|
||||||
│ │
|
│ │
|
||||||
@@ -158,11 +159,13 @@
|
|||||||
│ │ ├── BELKI_DATABASE_URL
|
│ │ ├── BELKI_DATABASE_URL
|
||||||
│ │ ├── Таблица: calculations
|
│ │ ├── Таблица: calculations
|
||||||
│ │ ├── Таблица: belki_applications
|
│ │ ├── Таблица: belki_applications
|
||||||
|
│ │ ├── Таблица: belki_application_export_events
|
||||||
│ │ └── Таблица: identities
|
│ │ └── Таблица: identities
|
||||||
│ ├── SQLite (development)
|
│ ├── SQLite (development)
|
||||||
│ │ ├── data/belki.sqlite3
|
│ │ ├── data/belki.sqlite3
|
||||||
│ │ ├── Калькуляции
|
│ │ ├── Калькуляции
|
||||||
│ │ ├── Заявки
|
│ │ ├── Заявки
|
||||||
|
│ │ ├── Очередь экспорта заявок
|
||||||
│ │ ├── Связки персонажей
|
│ │ ├── Связки персонажей
|
||||||
│ │ └── Профили пользователей
|
│ │ └── Профили пользователей
|
||||||
│ └── ImageHost API
|
│ └── ImageHost API
|
||||||
@@ -208,6 +211,7 @@
|
|||||||
│
|
│
|
||||||
└── 🔗 Внешние интеграции
|
└── 🔗 Внешние интеграции
|
||||||
├── VK Bots Long Poll API
|
├── VK Bots Long Poll API
|
||||||
|
├── Google Apps Script Web App (готово к включению; выключено)
|
||||||
├── Image Host API (зеркалирование фото)
|
├── Image Host API (зеркалирование фото)
|
||||||
├── PostgreSQL / SQLite
|
├── PostgreSQL / SQLite
|
||||||
├── Tampermonkey / GreasyFork (userscripts)
|
├── Tampermonkey / GreasyFork (userscripts)
|
||||||
|
|||||||
@@ -28,7 +28,8 @@
|
|||||||
- VK photo attachments received during an active dialog are normalized into `input.attachments` and persisted with the calculation; active reports attach photos immediately and deduplicate repeated VK events. `/admin` renders all thumbnails in a wrapped gallery. With `BELKI_IMAGE_HOST_API_URL`, the bot mirrors each photo through image-hosting-web and stores `mirror_url`; Google Sheets export remains deferred.
|
- VK photo attachments received during an active dialog are normalized into `input.attachments` and persisted with the calculation; active reports attach photos immediately and deduplicate repeated VK events. `/admin` renders all thumbnails in a wrapped gallery. With `BELKI_IMAGE_HOST_API_URL`, the bot mirrors each photo through image-hosting-web and stores `mirror_url`; Google Sheets export remains deferred.
|
||||||
- `/admin` and `/api/admin/calculations` expose the calculation history for review. The table shows both the reporting cat (escort) and kitten; default sorting is by the reporting cat, with optional kitten sorting. The API requires `X-Admin-Password` matching `BELKI_ADMIN_PASSWORD`; the web page supports deleting individual records through authenticated `DELETE /api/admin/calculations/{id}`, with confirmation in the UI.
|
- `/admin` and `/api/admin/calculations` expose the calculation history for review. The table shows both the reporting cat (escort) and kitten; default sorting is by the reporting cat, with optional kitten sorting. The API requires `X-Admin-Password` matching `BELKI_ADMIN_PASSWORD`; the web page supports deleting individual records through authenticated `DELETE /api/admin/calculations/{id}`, with confirmation in the UI.
|
||||||
- Applications are stored independently of calculation history by `app/belki/applications.py`: `belki_applications` in PostgreSQL and `applications` in SQLite. `/applications` reuses the existing password-gated web session and upload endpoint; `/api/applications` creates web applications, while `/api/admin/applications` lists them and `PATCH /api/admin/applications/{id}/accept` accepts one.
|
- Applications are stored independently of calculation history by `app/belki/applications.py`: `belki_applications` in PostgreSQL and `applications` in SQLite. `/applications` reuses the existing password-gated web session and upload endpoint; `/api/applications` creates web applications, while `/api/admin/applications` lists them and `PATCH /api/admin/applications/{id}/accept` accepts one.
|
||||||
- Typed flows are: feather donation (amount/color/source rows), kitten (activity screenshot), flying squirrel (past practice and a review link when applicable), and curator (LU screenshot with fraction). VK uses `/заявка`, `/перо`, `/бельчонок`, `/летяга`, and `/куратор`. The bot polls accepted VK applications every 15 seconds and notifies the original peer; web applications have no inferred VK recipient.
|
- Typed flows are: feather donation (amount/color/source rows), kitten (activity screenshot), flying squirrel (past practice and a review link when applicable), and curator (LU screenshot with fraction). VK uses `/заявка`, `/перо`, `/бельчонок`, `/летяга`, and `/куратор`; its context keyboard drives every selectable application branch, while users type only free-form values. The bot polls accepted VK applications every 15 seconds and notifies the original peer; web applications have no inferred VK recipient.
|
||||||
|
- Google Sheets export is pre-wired but disabled by `BELKI_GOOGLE_EXPORT_ENABLED=0`. `ApplicationStore` records `application_created` and `application_accepted` snapshots in the PostgreSQL `belki_application_export_events` or SQLite `application_export_events` outbox. `GoogleSheetsExportService` sends FIFO JSON events only to an explicitly configured Google Apps Script Web App URL, retains failed events for retry, and is polled by the bot every 15 seconds when enabled.
|
||||||
- The admin page uses a restrained light editorial table layout with a separate password gate, category tabs (all, осмотры, ЛУ, ЗУ, ПУ/уроки), responsive filters, client-side sorting across every visible column, cat/kitten selectors, sticky headings, and a keyboard-navigable photo gallery; behavior remains backed by the existing history API.
|
- The admin page uses a restrained light editorial table layout with a separate password gate, category tabs (all, осмотры, ЛУ, ЗУ, ПУ/уроки), responsive filters, client-side sorting across every visible column, cat/kitten selectors, sticky headings, and a keyboard-navigable photo gallery; behavior remains backed by the existing history API.
|
||||||
- VK `messages.send` responses include a serialized context-aware keyboard; button payloads are translated back into the same dialog commands, while text commands remain supported.
|
- VK `messages.send` responses include a serialized context-aware keyboard; button payloads are translated back into the same dialog commands, while text commands remain supported.
|
||||||
- Production k3s deployment (2026-08-16): namespace `belki` runs the Belki web calculator, VK bot, PostgreSQL 16, and the migrated cwshed Nginx gateway. The gateway keeps MetalLB IP `10.12.0.204`, serves the legacy CatWar site, and routes `/belki`, `/admin`, and `/api/*` to Belki web on `10.12.0.212`. Belki images are `reg.nyan404.ru/cwshed-clone/belki` and `reg.nyan404.ru/cwshed`; PostgreSQL is mirrored as `reg.nyan404.ru/library/postgres:16-alpine-amd64` because cluster nodes cannot pull Docker Hub directly. Registry pull credentials and runtime secrets are created out-of-band in the `belki` namespace.
|
- Production k3s deployment (2026-08-16): namespace `belki` runs the Belki web calculator, VK bot, PostgreSQL 16, and the migrated cwshed Nginx gateway. The gateway keeps MetalLB IP `10.12.0.204`, serves the legacy CatWar site, and routes `/belki`, `/admin`, and `/api/*` to Belki web on `10.12.0.212`. Belki images are `reg.nyan404.ru/cwshed-clone/belki` and `reg.nyan404.ru/cwshed`; PostgreSQL is mirrored as `reg.nyan404.ru/library/postgres:16-alpine-amd64` because cluster nodes cannot pull Docker Hub directly. Registry pull credentials and runtime secrets are created out-of-band in the `belki` namespace.
|
||||||
@@ -50,6 +51,7 @@
|
|||||||
- 2026-08-17: aligned `web/calculator.html` status controls with the VK bot and shared domain: LU allows at most one non-self-sufficient kitten, while ZU forces all kittens to self-sufficient; extra-kitten status controls are synchronized and validated before submission.
|
- 2026-08-17: aligned `web/calculator.html` status controls with the VK bot and shared domain: LU allows at most one non-self-sufficient kitten, while ZU forces all kittens to self-sufficient; extra-kitten status controls are synchronized and validated before submission.
|
||||||
- 2026-08-17: added password-gated web sessions via `BELKI_WEB_PASSWORD` and `/api/web/auth`; web-selected screenshots are sent through `/api/web/upload` to `BELKI_IMAGE_HOST_API_URL` (production `https://img.nyan404.ru`) and persisted as report attachments.
|
- 2026-08-17: added password-gated web sessions via `BELKI_WEB_PASSWORD` and `/api/web/auth`; web-selected screenshots are sent through `/api/web/upload` to `BELKI_IMAGE_HOST_API_URL` (production `https://img.nyan404.ru`) and persisted as report attachments.
|
||||||
- 2026-08-21: added structured community applications for feathers, kitten, flying-squirrel, and curator roles across VK, `/applications`, and the top-level `/admin` "Заявки" tab; acceptance is a status transition, not a generated forum post.
|
- 2026-08-21: added structured community applications for feathers, kitten, flying-squirrel, and curator roles across VK, `/applications`, and the top-level `/admin` "Заявки" tab; acceptance is a status transition, not a generated forum post.
|
||||||
|
- 2026-08-21: added a disabled durable Google Sheets export outbox for application-created and application-accepted events; no external request is attempted until an approved Apps Script URL and `BELKI_GOOGLE_EXPORT_ENABLED=1` are configured.
|
||||||
# Обновление 2026-08-16: несколько котят
|
# Обновление 2026-08-16: несколько котят
|
||||||
|
|
||||||
Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`.
|
Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`.
|
||||||
@@ -3,6 +3,7 @@ import unittest
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from app.belki.applications import ApplicationError, ApplicationStore, validate_application
|
from app.belki.applications import ApplicationError, ApplicationStore, validate_application
|
||||||
|
from app.belki.google_sheets_export import GoogleSheetsExportConfig, GoogleSheetsExportService
|
||||||
from app.belki.identity import IdentityDirectory
|
from app.belki.identity import IdentityDirectory
|
||||||
from app.belki.vk_bot import ApplicationDialog
|
from app.belki.vk_bot import ApplicationDialog
|
||||||
|
|
||||||
@@ -31,6 +32,22 @@ class ApplicationTests(unittest.TestCase):
|
|||||||
store.mark_notified(application_id)
|
store.mark_notified(application_id)
|
||||||
self.assertEqual(store.pending_notifications(), [])
|
self.assertEqual(store.pending_notifications(), [])
|
||||||
|
|
||||||
|
def test_export_outbox_collects_create_and_accept_events_while_disabled(self) -> None:
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
store = ApplicationStore(sqlite_path=Path(directory) / "applications.sqlite3")
|
||||||
|
application = validate_application({
|
||||||
|
"type": "feather_donation", "name": "Белка", "character_id": 58775,
|
||||||
|
"feathers": [{"amount": 1, "color": "красное", "source": "личные запасы"}],
|
||||||
|
})
|
||||||
|
application_id = store.create(application=application, actor_id=None, reply_peer_id=None, source="web")
|
||||||
|
store.accept(application_id)
|
||||||
|
events = store.pending_exports()
|
||||||
|
self.assertEqual([event["event_type"] for event in events], ["application_created", "application_accepted"])
|
||||||
|
self.assertEqual(events[0]["payload"]["schema_version"], 1)
|
||||||
|
exporter = GoogleSheetsExportService(store, GoogleSheetsExportConfig(enabled=False, url="https://example.test", token=""))
|
||||||
|
self.assertEqual(exporter.sync_pending(), 0)
|
||||||
|
self.assertEqual(len(store.pending_exports()), 2)
|
||||||
|
|
||||||
def test_vk_kitten_application_uses_profile_and_saves(self) -> None:
|
def test_vk_kitten_application_uses_profile_and_saves(self) -> None:
|
||||||
with tempfile.TemporaryDirectory() as directory:
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
store = ApplicationStore(sqlite_path=Path(directory) / "applications.sqlite3")
|
store = ApplicationStore(sqlite_path=Path(directory) / "applications.sqlite3")
|
||||||
@@ -42,6 +59,22 @@ class ApplicationTests(unittest.TestCase):
|
|||||||
self.assertIn("отправлена", dialog.handle(55, 55, "готово").lower())
|
self.assertIn("отправлена", dialog.handle(55, 55, "готово").lower())
|
||||||
self.assertEqual(store.list()[0]["application"]["type"], "kitten")
|
self.assertEqual(store.list()[0]["application"]["type"], "kitten")
|
||||||
|
|
||||||
|
def test_vk_application_uses_keyboard_for_menu_and_branches(self) -> None:
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
store = ApplicationStore(sqlite_path=Path(directory) / "applications.sqlite3")
|
||||||
|
identities = IdentityDirectory(db_path=Path(directory) / "identities.sqlite3")
|
||||||
|
identities.remember_profile(actor_id=77, name="Муся", character_id=1337)
|
||||||
|
dialog = ApplicationDialog(identities, store)
|
||||||
|
dialog.handle(77, 77, "/заявка")
|
||||||
|
labels = [button["action"]["label"] for row in dialog.keyboard_for(77)["buttons"] for button in row]
|
||||||
|
self.assertEqual(labels[:4], ["Пожертвовать перо", "Стать бельчонком", "Стать летягой", "Стать куратором"])
|
||||||
|
dialog.handle(77, 77, "/летяга")
|
||||||
|
labels = [button["action"]["label"] for row in dialog.keyboard_for(77)["buttons"] for button in row]
|
||||||
|
self.assertIn("Нет ссылки VK", labels)
|
||||||
|
dialog.handle(77, 77, "нет")
|
||||||
|
labels = [button["action"]["label"] for row in dialog.keyboard_for(77)["buttons"] for button in row]
|
||||||
|
self.assertEqual(labels[:2], ["Да", "Нет"])
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
@@ -53,6 +53,8 @@ class VkBotTests(unittest.TestCase):
|
|||||||
def test_button_payload_maps_to_command(self):
|
def test_button_payload_maps_to_command(self):
|
||||||
self.assertEqual(BelkiBot._button_text({"payload": "menu:lu"}), "/лу")
|
self.assertEqual(BelkiBot._button_text({"payload": "menu:lu"}), "/лу")
|
||||||
self.assertEqual(BelkiBot._button_text({"payload": '{"command":"confirm:yes"}'}), "да")
|
self.assertEqual(BelkiBot._button_text({"payload": '{"command":"confirm:yes"}'}), "да")
|
||||||
|
self.assertEqual(BelkiBot._button_text({"payload": '{"command":"application:flying"}'}), "/летяга")
|
||||||
|
self.assertEqual(BelkiBot._button_text({"payload": '{"command":"application:practice-no"}'}), "нет")
|
||||||
|
|
||||||
def test_keyboard_button_payloads_are_valid_json(self):
|
def test_keyboard_button_payloads_are_valid_json(self):
|
||||||
keyboard = BelkiDialog().keyboard_for(503)
|
keyboard = BelkiDialog().keyboard_for(503)
|
||||||
|
|||||||
Reference in new issue
Block a user