feat(applications): add keyboard flow and export outbox
This commit is contained in:
1 parent
cfeee5a814
commit
27bcc291db
11 files changed
+255
-10
No files matched your search
@@ -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
|
||||
Reference in new issue
Block a user