Files
gogo-telefon/gogo/db.py
Senad Uka 646917c322 M3: chat widget, owner dashboard, super-admin panel
- Embeddable vanilla-JS chat widget (one script tag + tenant public key):
  WebSocket, resumable sessions (24h localStorage token), honeypot + per-IP
  and per-message rate limits, Bosnian UI (§7)
- Session auth (bcrypt + signed cookies), owner accounts + super-admins,
  admin impersonation ('otvori kao salon', §11)
- Owner dashboard (§10, Bosnian): requests with same actions as email,
  call/chat history with transcripts, usage bar; settings for profile,
  working hours (manual + LLM paste-to-parse), services CRUD + 'Zalijepi
  cjenovnik' LLM import with review step, scheduling (Google OAuth free/busy
  read-only + calendar mappings + buffers, partner status), telephony
  (forwarding MMI codes per operator, ring group, worker SIP creds + QR),
  agent voice/price-mode/notes + widget snippet, notifications/SMS templates
- Super-admin panel (§11): tenant CRUD incl. plan/minutes/paid-until,
  partner API config (encrypted secrets), number/SIM registry + assignment,
  connectivity test (live availability + dry-run push), versioned prompt
  template editor with publish/rollback, playground, usage overview, health
- Fixes: WAL + busy_timeout for sqlite tests, no awaits in WS disconnect
  path (deadlock), template publish autoflush bug
- 76 tests green (incl. widget WS e2e booking flow); dashboard, widget and
  admin verified live in a browser against Postgres

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 10:51:57 +02:00

64 lines
2.0 KiB
Python

"""Async SQLAlchemy engine/session setup."""
from collections.abc import AsyncIterator
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase
from gogo.config import get_settings
class Base(DeclarativeBase):
pass
_engine = None
_sessionmaker: async_sessionmaker[AsyncSession] | None = None
def get_engine():
global _engine, _sessionmaker
if _engine is None:
url = get_settings().database_url
kwargs = {}
if url.startswith("sqlite"):
# tests: fresh connection per checkout so sessions work across event loops
from sqlalchemy.pool import NullPool
kwargs["poolclass"] = NullPool
kwargs["connect_args"] = {"timeout": 30}
_engine = create_async_engine(url, pool_pre_ping=True, **kwargs)
if url.startswith("sqlite"):
from sqlalchemy import event
@event.listens_for(_engine.sync_engine, "connect")
def _sqlite_pragmas(dbapi_conn, _record):
# WAL lets readers proceed alongside a writer — the test suite runs
# the app and fixtures on different event loops/connections
cursor = dbapi_conn.cursor()
cursor.execute("PRAGMA journal_mode=WAL")
cursor.execute("PRAGMA busy_timeout=30000")
cursor.close()
_sessionmaker = async_sessionmaker(_engine, expire_on_commit=False)
return _engine
def get_sessionmaker() -> async_sessionmaker[AsyncSession]:
get_engine()
assert _sessionmaker is not None
return _sessionmaker
async def get_session() -> AsyncIterator[AsyncSession]:
"""FastAPI dependency."""
async with get_sessionmaker()() as session:
yield session
def reset_engine() -> None:
"""Test helper: force re-creation of the engine (e.g. after settings change)."""
global _engine, _sessionmaker
_engine = None
_sessionmaker = None