feat(applications): add keyboard flow and export outbox

This commit is contained in:
nyan404 committed 2026-08-21 13:25:33 +03:00
1 parent cfeee5a814
commit 27bcc291db
11 files changed
+255 -10

No files matched your search

+76 -5
View File
@@ -5,7 +5,6 @@ from __future__ import annotations
import json
import os
import sqlite3
import time
from pathlib import Path
from typing import Any
@@ -110,6 +109,12 @@ class ApplicationStore:
connection.execute("ALTER TABLE applications ADD COLUMN notified_at TEXT")
except sqlite3.OperationalError:
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:
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
)""")
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:
if self.database_url.startswith(("postgres://", "postgresql://")):
@@ -127,12 +138,20 @@ class ApplicationStore:
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])
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:
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)
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]]:
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,))
if not cursor.rowcount:
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:
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()}
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]]:
"""Возвращает принятые VK-заявки, для которых ещё не отправлено уведомление."""