Files
gogo-telefon/gogo/metering.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

105 lines
3.5 KiB
Python

"""Usage metering (§12): agent voice minutes per tenant per month.
Human-answered ring-group time and chat do NOT count toward voice minutes.
Soft limits: 80% → owner email + dashboard banner; 100% → super-admin alert,
agent keeps answering (hard cutoff only via tenant flag, default off).
"""
from __future__ import annotations
import logging
import uuid
from datetime import UTC, datetime
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from gogo.models import Tenant, UsageCounter
log = logging.getLogger("gogo.metering")
def current_month(at: datetime | None = None) -> str:
at = at or datetime.now(UTC)
return f"{at.year:04d}-{at.month:02d}"
async def get_counter(
session: AsyncSession, tenant_id: uuid.UUID, month: str | None = None
) -> UsageCounter:
month = month or current_month()
counter = (
await session.execute(
select(UsageCounter).where(
UsageCounter.tenant_id == tenant_id, UsageCounter.month == month
)
)
).scalar_one_or_none()
if counter is None:
counter = UsageCounter(tenant_id=tenant_id, month=month)
session.add(counter)
await session.flush()
return counter
async def record_agent_call(
session: AsyncSession, tenant: Tenant, agent_seconds: int
) -> None:
"""Meter one agent-handled call and fire soft-limit warnings (§12)."""
counter = await get_counter(session, tenant.id)
counter.agent_seconds += max(0, agent_seconds)
counter.calls += 1
included_s = tenant.included_minutes * 60
if included_s <= 0:
return
used = counter.agent_seconds
if used >= included_s and not counter.warned_100:
counter.warned_100 = True
log.warning(
"tenant %s exceeded included minutes (%d/%d min) — super-admin alert",
tenant.slug, used // 60, tenant.included_minutes,
)
await _send_warning(session, tenant, used // 60, 100)
elif used >= included_s * 0.8 and not counter.warned_80:
counter.warned_80 = True
await _send_warning(session, tenant, used // 60, 80)
async def _send_warning(session: AsyncSession, tenant: Tenant, used_minutes: int, pct: int):
from gogo.proposals.email import send_usage_warning_email
try:
await send_usage_warning_email(session, tenant, used_minutes, pct)
except Exception: # noqa: BLE001 — metering must never break call handling
log.exception("usage warning email failed (tenant %s)", tenant.slug)
async def record_sms(session: AsyncSession, tenant_id: uuid.UUID) -> None:
counter = await get_counter(session, tenant_id)
counter.sms_sent += 1
async def record_chat_session(session: AsyncSession, tenant_id: uuid.UUID) -> None:
counter = await get_counter(session, tenant_id)
counter.chat_sessions += 1
async def usage_summary(session: AsyncSession, tenant: Tenant) -> dict:
"""For the dashboard usage bar (§10) and super-admin overview (§11)."""
counter = await get_counter(session, tenant.id)
used_min = counter.agent_seconds // 60
included = tenant.included_minutes
pct = min(100, round(used_min * 100 / included)) if included else 0
return {
"month": counter.month,
"used_minutes": used_min,
"included_minutes": included,
"pct": pct,
"calls": counter.calls,
"sms_sent": counter.sms_sent,
"chat_sessions": counter.chat_sessions,
"over_80": bool(included) and used_min >= included * 0.8,
"over_100": bool(included) and used_min >= included,
}