import type { WhatsappAccount } from '@generated/prisma/client'; import type { ProblemDetails, Result, WhatsappCallbackReason, WhatsappConnectionStart, WhatsappMessageKind, WhatsappReadiness, WhatsappReturnTo, } from '@gruperly/shared'; /** * The port every WhatsApp gateway implements. The domain (linking, the weekly * jobs, the webhook) only talks to this interface; everything that knows about * OpenWA or Kapso lives in `providers//`. Switching gateways is a matter of * `WHATSAPP_PROVIDER` plus an adapter, never of touching the jobs or the UI. */ export type MessagingProviderId = 'OPENWA' | 'KAPSO'; export type WhatsappAccountRecord = Pick< WhatsappAccount, 'id' | 'ownerId' | 'provider' | 'status' | 'externalId' | 'displayPhoneNumber' | 'providerData' >; /** * What the teacher receives, in domain terms. Each provider turns it into its * own wire format: free text (OpenWA) or a template with parameters (Kapso). */ export type WhatsappMessage = | { kind: 'PAYMENT_REMINDER'; studentName: string; groupName: string; amount: string; dueDate: string; paymentLink: string; } | { kind: 'REENGAGEMENT'; studentName: string; groupName: string; } | { /** The monthly combined link, to whoever pays (the adult for kids). */ kind: 'PAYMENT_LINK'; studentName: string; /** What it pays, e.g. "Yoga (Juan) y Natación (Ana)". */ detail: string; amount: string; dueDate: string; paymentLink: string; }; export type StartConnectionContext = { ownerId: string; ownerName: string; returnTo: WhatsappReturnTo; /** The teacher's existing row, if any, to reuse provider-side resources. */ account: WhatsappAccountRecord | null; }; export type StartConnectionResult = { start: WhatsappConnectionStart; /** OpenWA: the session id. Kapso: null until the setup finishes. */ externalId: string | null; providerData?: Record | null; }; /** The live state of a linking, as the provider reports it. */ export type ConnectionSnapshot = | { state: 'pending'; qrCode: string | null } | { state: 'active'; displayPhoneNumber: string | null } | { state: 'disconnected'; reason: string | null }; /** The provider-side result of finishing a redirect-based linking (Kapso). */ export type CompletedConnection = { externalId: string; displayPhoneNumber: string | null; providerData?: Record | null; }; export type RecipientResolution = | { ok: true; to: string } | { ok: false; code: 'no_whatsapp' | 'provider_error' }; export type SendOutcome = | { ok: true; providerMessageId: string } | { ok: false; /** Worth trying again on the next run (5xx, network). */ retryable: boolean; /** The gateway asked us to stop sending from this account for a while. */ rateLimitedForMs?: number; code: string; message: string; }; export type MessageDeliveryStatus = 'SENT' | 'DELIVERED' | 'READ' | 'FAILED'; /** Webhook payloads reduced to the two things the domain cares about. */ export type NormalizedEvent = | { type: 'connection'; /** Session id (OpenWA) or phone_number_id (Kapso). */ externalId: string; /** When the provider carries our own reference (Kapso's external customer id). */ ownerId?: string; status: 'active' | 'disconnected'; displayPhoneNumber?: string | null; providerData?: Record | null; } | { type: 'message_status'; providerMessageId: string; status: MessageDeliveryStatus; errorCode?: string | null; errorMessage?: string | null; }; export type ParsedWebhook = { /** The delivery's idempotency key; burned before the events are applied. */ dedupeKey: string; events: NormalizedEvent[]; }; export type WebhookParseError = 'invalid_signature' | 'invalid_payload'; export interface MessagingProvider { readonly id: MessagingProviderId; /** Starts (or restarts) linking the teacher's number. */ startConnection( context: StartConnectionContext, ): Promise>; /** Asks the provider how the linking is going (fresh QR, linked, failed). */ refreshConnection( account: WhatsappAccountRecord, ): Promise>; /** * Asks for a code to link by phone number instead of scanning the QR, for a * linking already started with `startConnection`. `phoneDigits` is the * teacher's number in international format, digits only. Only providers that * link a WhatsApp Web session (OpenWA) implement it. */ requestPairingCode?( account: WhatsappAccountRecord, phoneDigits: string, ): Promise>; /** * Finishes a redirect-based linking from the callback query. Only providers * whose `startConnection` answers `redirect` implement it. */ completeRedirect?( account: WhatsappAccountRecord, query: Record, ): Promise>; /** Unlinks the number on the provider side. Best effort. */ disconnect(account: WhatsappAccountRecord): Promise>; /** Runs once the account becomes ACTIVE (Kapso: templates and webhooks). */ onConnected?(account: WhatsappAccountRecord): Promise; /** Whether a message of this kind can be sent from the account right now. */ readiness(account: WhatsappAccountRecord, kind: WhatsappMessageKind): Promise; /** Turns an E.164 number into the provider's recipient id, or says it has no WhatsApp. */ resolveRecipient(account: WhatsappAccountRecord, e164: string): Promise; send( account: WhatsappAccountRecord, to: string, message: WhatsappMessage, idempotencyKey: string, ): Promise; /** Verifies the signature over the raw body and normalizes the payload. */ parseWebhook( rawBody: string, headers: Headers, ): Result; }