65 lines
2.6 KiB
Python
65 lines
2.6 KiB
Python
"""Выключенный по умолчанию экспорт заявок в Google Sheets через Apps Script."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
from dataclasses import dataclass
|
||
from urllib.error import URLError
|
||
from urllib.parse import urlparse
|
||
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:
|
||
parsed = urlparse(self.url)
|
||
return self.enabled and parsed.scheme == "https" and bool(parsed.hostname)
|
||
|
||
|
||
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
|