"""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) await _alert_admin(tenant, used // 60) 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 _alert_admin(tenant: Tenant, used_minutes: int) -> None: """100% soft-limit hit → alert the super-admin for an upsell conversation (§12).""" from gogo.config import get_settings from gogo.email import EmailMessage, send_email to = get_settings().admin_alert_email if not to: return try: await send_email( EmailMessage( [to], f"[Gogo] {tenant.name} prešao 100% minuta ({used_minutes} min)", f"Salon {tenant.name} ({tenant.slug}) je prešao uključene minute " f"({used_minutes}/{tenant.included_minutes}). Asistent i dalje odgovara " "(hard cutoff je isključen) — vrijeme za razgovor o većem paketu.", ) ) except Exception: # noqa: BLE001 log.exception("admin alert email failed") 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, }