/** * Channels service types: channels, their provider properties, templates, * webhooks, and the three log feeds that hang off a channel. * Mirrors `packages/contracts/src/channels/*`. */ import type { IsoDate, JsonObject, ListQuery } from './common'; /** Channel category, as stored in `meta.category`. */ export type ChannelType = 'whatsapp' | 'sms' | 'email' | 'rcs' | 'webchat'; /** Connection health reported by the provider. */ export type ChannelStatus = 'connected' | 'disconnected' | 'error'; /** Currencies a channel can be billed in. */ export type ChannelCurrency = 'USD' | 'EUR' | 'INR' | 'IDR'; export interface ChannelMeta { /** The channel category: whatsapp, sms, email, rcs, webchat. */ category: string; /** BSP or integration behind the channel, e.g. `EMBEDDED_PNCL_BILLING`. */ provider: string; support_template: boolean; show_template: boolean; bypass_webhook_verification: boolean; } /** Provider identifiers, flattened out of the channel's private auth block. */ export interface ChannelCloud { instagram_id: string; is_instagram_business_login: boolean; waba_id: string; /** Meta business id. */ business: string; phone_number_id: string; is_on_biz_app: boolean; /** Graph API version the channel talks. */ version: string; auto_read_receipt: number; upgrade_eligibility: boolean; /** `completed` once the number is registered with the BSP. */ wa_biz_registration: 'pending' | 'completed'; } /** * Balances are stored as ten-thousandths and divided down here, to four decimal * places. `'NULL'` when the agency has hidden the wallet from this caller. */ export interface ChannelWallet { balance: number | 'NULL'; currency: string; } /** * A channel as the list and detail endpoints return it. Credentials and the * private auth block are stripped; what remains is safe to hand a console. */ export interface Channel { id: string; /** * The team member who connected the channel, by psuid. Absent when the * account holder connected it, and on channels created before this was * recorded. */ member?: string; /** Enabled/disabled by the owner -- not the connection state. */ active: boolean; ecom?: { store_status: boolean; store?: string; }; basic_details: { name: string; color_code: string; channel_identity: string; }; meta: ChannelMeta; wallet: ChannelWallet; /** Messages per second the campaign runner may push. Defaults to 10. */ campaign_tps: number; upgraded_webhook_listener: boolean; cloud: ChannelCloud; /** Reachable only over the API, with no console inbox. */ api_only: boolean; /** Reachable only from the CRM. */ crm_only: boolean; mm_lite_enabled: boolean; /** Short-lived encrypted handle for the channel, minted per response. */ access_token: string; [key: string]: unknown; } /** `channels.get` wraps its payload, and returns `{ data: {} }` when nothing matches. */ export interface ChannelResponse { data: Channel | Record; } /** `search` matches the channel name and its identity (number, handle, address). */ export interface ListChannelsQuery extends ListQuery { /** Quick filter: channel category. */ type?: ChannelType; /** Quick filter: enabled/disabled by the owner, not the connection state. */ active?: boolean; /** Quick filter: connection health. */ status?: ChannelStatus; } /** * What the console may change about a channel itself. At least one field is * required. Everything else about a channel is provider state and moves * through the property endpoints. */ export interface UpdateChannelDetailsInput { /** 1..120 characters. */ name?: string; /** Hex colour, `#075E54` or `#fff`. */ color?: string; /** * Only moves on a WhatsApp channel with an empty wallet: a balance carried * across a switch would be worth a different amount on the other side. * Rejected with `409 wallet_not_empty` otherwise. */ currency?: ChannelCurrency; } /** Returned by the operations that report success without a body of their own. */ export interface ChannelActionResult { success: true; } /** * Readable channel properties. Each one reads something that lives with the * provider (Meta Graph, mostly) or in local configuration, rather than on the * channel document. */ export type ChannelGetProp = 'general' | 'business_profile' | 'message_analytics' | 'business_compliance' | 'business_commerce' | 'qr_code' | 'redirect_url' | 'fetch_channel_queue' | 'recharge_url' | 'channel_config' | 'conversation_automation' | 'token'; /** Writable channel properties. */ export type ChannelSetProp = 'business_profile' | 'profile_pic' | 'business_compliance' | 'resumable_upload' | 'business_commerce' | 'qr_code' | 'upload_media' | 'wa_pin_update' | 'wa_deregister' | 'wa_biz_update' | 'webhook_listener_update' | 'wa_request_otp' | 'migrate_number' | 'wa_submit_otp' | 'test_message' | 'conversation_analytics' | 'conversation_automation' | 'whatsapp_business_encryption' | 'delete_channel_queue' | 'enable_whatsapp_direct' | 'disable_whatsapp_direct'; /** Meta Business Suite pages `redirect_url` can hand the console a link to. */ export type ChannelRedirectTarget = 'meta_catalog_manager' | 'link_whatsApp_catalog' | 'wa_manager' | 'business'; /** * Props whose request body is the raw file bytes rather than JSON. Pass a * `Blob`, `ArrayBuffer` or `Uint8Array` to `channels.setProp` for these, and a * `contentType`; anything else is sent as JSON. */ export declare const BINARY_CHANNEL_PROPS: readonly ["profile_pic", "resumable_upload", "upload_media"]; export type BinaryChannelProp = (typeof BINARY_CHANNEL_PROPS)[number]; /** * Every property call answers in this envelope. `data` is whatever the provider * returned and is deliberately untyped -- its shape follows `prop`. */ export interface ChannelPropResponse { data: T; /** Echo of the property that was read or written. */ prop: string; /** Echo of the channel id. */ channel: string; } /** * Not every channel category supports every property. WhatsApp supports all of * them; RCS reads `fetch_channel_queue`, `recharge_url` and `token`, and writes * `test_message`. Anything else answers `400 unsupported_channel_prop`. */ export type ChannelPropBody = JsonObject | Blob | ArrayBuffer | Uint8Array; /** Review state. `draft` is local only; the rest mirror Meta. */ export type TemplateStatus = 'draft' | 'pending' | 'approved' | 'rejected'; export type TemplateCategory = 'MARKETING' | 'UTILITY' | 'AUTHENTICATION'; /** `AUTO_GENERATED` templates are created by the platform, not by a caller. */ export type TemplateSource = 'MANUAL' | 'AUTO_GENERATED'; /** Whether placeholders are `{{1}}` or `{{name}}`. */ export type TemplateParameterFormat = 'POSITIONAL' | 'NAMED'; /** Click-to-WhatsApp ad attribution, when the template is tied to one. */ export interface TemplateAdDetails { ad_account: string; ad_campaign: string; ad_set: string; ad_id: string; } export interface Template { id: string; channelId: string; type: 'whatsapp'; status: TemplateStatus; source: TemplateSource; /** Meta's own id; absent while the template is still a local draft. */ templateId?: string; name: string; category: TemplateCategory; subCategory: string; parameterFormat: TemplateParameterFormat; /** BCP-47 code, e.g. `en_US`. */ language: string; /** Identity of the template within the channel: name plus language. */ hash: string; adDetails: TemplateAdDetails; /** Meta's component array: HEADER, BODY, FOOTER, BUTTONS. */ components: JsonObject[]; /** The last payload sent to Meta. */ payload?: JsonObject; extra?: JsonObject; createdAt: IsoDate; updatedAt: IsoDate; } export interface CreateTemplateInput { /** Lowercase letters, digits and underscores, 1..512 characters. */ name: string; category: TemplateCategory; /** Up to 120 characters. Default `''`. */ subCategory?: string; /** 2..15 characters, e.g. `en` or `en_US`. */ language: string; /** Default `'POSITIONAL'`. */ parameterFormat?: TemplateParameterFormat; /** Default `'MANUAL'`. */ source?: TemplateSource; /** At least one component. */ components: JsonObject[]; payload?: JsonObject; extra?: JsonObject; adDetails?: Partial; /** Submit to Meta straight away instead of keeping a local draft. Default `false`. */ applyForApproval?: boolean; } /** At least one field is required. */ export type UpdateTemplateInput = Partial & { status?: TemplateStatus; }; /** `search` matches the template name and sub-category. */ export interface ListTemplatesQuery extends ListQuery { status?: TemplateStatus; category?: TemplateCategory; parameterFormat?: TemplateParameterFormat; /** Exact language code. */ language?: string; } /** What a `sync` pulled in from Meta. */ export interface TemplateSyncResult { /** Templates Meta returned. */ fetched: number; created: number; updated: number; /** Returned by Meta but not storable, e.g. an unknown category. */ skipped: number; } /** Channel events a webhook can subscribe to. */ export type ChannelWebhookEvent = 'incoming' | 'sent' | 'delivered' | 'read' | 'failed' | 'deleted' | 'template' | 'account' | 'phone_number' | 'calls'; export declare const CHANNEL_WEBHOOK_EVENTS: readonly ChannelWebhookEvent[]; /** Where the webhook was created from. */ export type ChannelWebhookSource = 'PANEL' | 'API'; /** * Audit trail: who created or last changed the webhook, and from where. Set by * the service from the caller's identity and IP, never by the caller. */ export interface ChannelWebhookMeta { source: ChannelWebhookSource; createdBy?: string; createdIp?: string; updatedBy?: string; updatedIp?: string; } export interface ChannelWebhook { id: string; channelId: string; title: string; active: boolean; events: ChannelWebhookEvent[]; url: string; meta?: ChannelWebhookMeta; createdAt: IsoDate; updatedAt: IsoDate; } export interface CreateChannelWebhookInput { /** 1..120 characters. Default `'CRM Channel Webhook'`. */ title?: string; /** Valid absolute URL, up to 2048 characters. */ url: string; /** At least one event. */ events: ChannelWebhookEvent[]; /** Default `true`. */ active?: boolean; } /** At least one field is required. */ export type UpdateChannelWebhookInput = Partial; /** `search` matches the webhook title and URL. */ export interface ListChannelWebhooksQuery extends ListQuery { /** Quick filter: enabled/disabled. */ active?: boolean; /** Quick filter: webhooks subscribed to this event. */ event?: ChannelWebhookEvent; } /** * A window in unix seconds. `0` on either end means "no bound", the way the * console sends it. Serialised to JSON by the SDK before it goes on the query * string: `range={"start":1767225600,"end":1769817600}`. */ export interface UnixRange { start: number; end: number; } /** * `summary` totals by currency (across all channels) or by message category * (one channel); `day_wise` totals per calendar day. */ export type BillingStat = 'summary' | 'day_wise'; /** One billed conversation. */ export interface BillingLog { id: string; /** The conversation the charge belongs to. */ chatId?: string; /** The recipient, as the channel addresses them. */ identifier: string; deduction: { /** `false` for free-tier conversations, which are logged but not charged. */ billable: boolean; amount: number; currency: string; }; /** Provider detail: recipient country, category, template, campaign, message id. */ meta?: JsonObject; createdAt: IsoDate; updatedAt: IsoDate; } /** * `search` matches the recipient identifier and the `meta` fields: recipient, * category, country and message id. */ export interface ListBillingLogsQuery extends ListQuery { /** Restrict to a period. */ range?: UnixRange; /** Return aggregates instead of rows; changes the response shape. */ stat?: BillingStat; /** Quick filter: templates the conversation was billed against. */ template?: string[]; /** Quick filter: recipient country codes. */ country?: string[]; /** Quick filter: campaigns that produced the conversation. */ campaign?: string[]; } export interface BillingStatRow { /** Currency, category or date, depending on the requested `stat`. */ group: string; totalRecords: number; totalDeductionAmount: number; } export interface BillingStats { data: BillingStatRow[]; stat: BillingStat; } /** Money into the channel wallet, or out of it. */ export type WalletLogType = 'credit' | 'debit'; export interface WalletLog { id: string; type: WalletLogType; currency: string; note: string; /** Stored as ten-thousandths, like the raw channel wallet balance. */ amount: number; startBalance: number; endBalance: number; status: string; category: string; createdAt: IsoDate; updatedAt: IsoDate; } /** `search` matches the note, the category and the status. */ export interface ListWalletLogsQuery extends ListQuery { /** Quick filter: credits or debits only. */ type?: WalletLogType; /** Restrict to a period. */ range?: UnixRange; } /** Who caused the entry. */ export type ActivitySource = 'user' | 'agency' | 'system'; /** Wallet movements share the feed with ordinary channel activity. */ export type ActivityLogType = 'wallet' | 'activity'; export interface ActivityLog { id: string; source: { type?: ActivitySource; id?: string; }; log: { type?: ActivityLogType; /** Machine name, e.g. `template.approved`. */ event: string; /** Human-readable line for the feed. */ message: string; }; createdAt: IsoDate; updatedAt: IsoDate; } /** `search` matches the event name and the message. */ export interface ListActivityLogsQuery extends ListQuery { /** Quick filter: wallet movements or general activity. */ type?: ActivityLogType; /** Quick filter: entries caused by the user, the agency, or the platform. */ source?: ActivitySource; /** Quick filter: a single event name, 1..120 characters. */ event?: string; /** Restrict to a period. */ range?: UnixRange; } /** Channel families the onboarding endpoints can connect today. */ export type OnboardingChannelType = 'whatsapp'; /** Every family the picker shows, implemented or not. */ export type OfferableChannelType = 'whatsapp' | 'facebook' | 'instagram'; /** One row of the "add a channel" picker. Only connectable families are listed. */ export interface ChannelOnboardingOption { type: OfferableChannelType; label: string; /** The inclusion a channel would be created against. Pass back to `url()`. */ slug?: string; limit?: number; used?: number; remaining?: number; } export interface OnboardingUrlInput { type?: OnboardingChannelType; /** Only needed when the plan carries more than one channel inclusion. */ slug?: string; /** * Which BSP to connect through, by provider code. Omit for whichever is * active for this family -- pin one only when there is a reason to. */ provider?: string; /** * Where the browser is handed back, with the outcome on it. **Required**: the * callback has no session, so nothing else says where. Meta never sees it. */ redirectUri: string; } export interface OnboardingUrlResult { /** * Open in a popup, or navigate to it; it cannot be framed. A launcher on the * app's own domain that forwards to `dialogUrl`, since Meta ties the dialog * to that domain. */ url: string; /** Meta's dialog, which `url` forwards to. Open `url`, not this. */ dialogUrl: string; /** Opaque, and already carrying `redirectUri`. Our callback is what reads it. */ state: string; /** Where the browser will come back to. */ redirectUri: string; /** What Meta was given: the service's own callback, registered on the BSP app. */ callbackUri: string; expiresAt: IsoDate; provider: string; remaining?: number; } /** `ready`: one number, bound. `select`: several, so `complete()` names one. */ export type OnboardingReturnStatus = 'ready' | 'select' | 'error'; /** The query string the service appends to `redirectUri`. All values are strings. */ export interface OnboardingReturn { status: OnboardingReturnStatus; /** Pass to `pending()`, and to `complete()` as `token`. */ token?: string; /** How many numbers the authorisation covered; `"1"` for `ready`. */ numbers?: string; wabaId?: string; phoneNumberId?: string; displayPhoneNumber?: string; verifiedName?: string; expiresAt?: string; /** `status=error` only. */ code?: string; message?: string; } /** What Meta reports about the number, for the confirmation card. */ export interface OnboardingPhoneNumber { id: string; wabaId: string; /** Formatted, e.g. `+91 93116 36081`. */ displayPhoneNumber: string; verifiedName: string; status?: string; codeVerificationStatus?: string; qualityRating?: string; } export interface OnboardingExchangeInput { state: string; code: string; wabaId: string; phoneNumberId: string; } /** Prefill for the final form. Every field is overridable in `complete()`. */ export interface OnboardingDefaults { name: string; color: string; currency: ChannelCurrency; } export interface OnboardingExchangeResult { /** The pending record's id. Pass to `complete()` as `token`. */ id: string; expiresAt: IsoDate; phoneNumber: OnboardingPhoneNumber; defaults: OnboardingDefaults; } /** A pending record, read back from the `token` on the return URL. */ export interface OnboardingPendingResult { id: string; expiresAt: IsoDate; type: OnboardingChannelType; /** Every number the authorisation covers that is still free to connect. */ numbers: OnboardingPhoneNumber[]; /** Set when there was exactly one, and so already bound to the record. */ phoneNumber?: OnboardingPhoneNumber; defaults: OnboardingDefaults; } export interface CompleteOnboardingInput { /** The `id` from `exchange()`, or `token` off the return URL. */ token: string; /** Which number, when the record covers several -- `status=select`. */ phoneNumberId?: string; name: string; color?: string; currency?: ChannelCurrency; } /** What the Meta dialog hands back, once both halves of it have arrived. */ export interface SignupCredentials { code: string; state: string; wabaId: string; phoneNumberId: string; }