Spaces:
Running

File size: 2,196 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""Per-tenant channel accounts (RLS forced; migration 0005).



One row per (tenant, channel). ``config`` holds only NON-secret identifiers, for example:



* WhatsApp (``provider='meta_cloud'``): ``phone_number_id``, ``waba_id``, ``api_version``,

  ``display_number``, ``templates: {name: {language, category, params, buttons}}``

  (the allowlist of Meta-approved templates the agent may use);

* email (``provider='gmail'|'outlook'``, via Nango): ``connection_id``,

  ``provider_config_key``, ``from_address``, optional ``nango_base_url``.



``secret_ref`` names the secret (WhatsApp access token, Nango secret key) in the secret

store; see ``core.channels.secrets``. ``cursor`` is the inbox poller's position.

"""

from __future__ import annotations

import uuid
from datetime import datetime
from typing import Any

from sqlalchemy import Boolean, DateTime, String, UniqueConstraint, func
from sqlalchemy.dialects.postgresql import JSONB, UUID
from sqlalchemy.orm import Mapped, mapped_column

from core.db.base import Base, TenantMixin, TimestampMixin, new_id

PROVIDERS: dict[str, tuple[str, ...]] = {
    "whatsapp": ("meta_cloud",),
    "email": ("gmail", "outlook"),
    "webchat": ("builtin",),
    "sms": ("stub",),
}


class ChannelAccount(TenantMixin, TimestampMixin, Base):
    __tablename__ = "channel_accounts"
    __table_args__ = (
        UniqueConstraint("tenant_id", "channel", name="uq_channel_accounts_tenant_channel"),
    )

    id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=new_id)
    channel: Mapped[str] = mapped_column(String(20), nullable=False)
    provider: Mapped[str] = mapped_column(String(30), nullable=False)
    config: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False, default=dict)
    secret_ref: Mapped[str | None] = mapped_column(String(120), nullable=True)
    enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
    cursor: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False, default=dict)
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), nullable=False
    )