/** * Audience service types: contacts and everything hanging off them. * Mirrors `packages/contracts/src/audience/*`. */ import type { ContactFilter, ContactFilterEntry } from './contact-filter'; import type { IsoDate, JsonObject, ListQuery, ObjectId, PageQuery } from './common'; /** A label a contact can carry. */ export interface ContactTag { id: string; name: string; icon: string; color: string; } export interface CreateContactTagInput { /** Trimmed, 1..120 characters. */ name: string; /** Icon name or emoji, up to 120 characters. Default `''`. */ icon?: string; /** Free-form so the palette can evolve; only length is checked (32). Default `''`. */ color?: string; } export type UpdateContactTagInput = Partial; /** `search` matches the tag name. */ export type ListContactTagsQuery = ListQuery; export type ContactStatus = 'live' | 'trashed'; export type ContactPrivacyStatus = 'open' | 'locked'; export type ContactChannel = 'whatsapp' | 'facebook' | 'instagram' | 'telegram' | 'email' | 'rcs' | 'webchat'; /** One channel identity of a contact. Server-owned: never sent on a write. */ export interface ContactProfile { id: string; channel: ContactChannel; /** Phone number, handle or address, depending on the channel. */ identifier: string; name: string; profile_pic: string; extra: JsonObject; } export interface ContactName { /** Up to 20 characters. */ salutation: string; /** Up to 120 characters. */ first_name: string; /** Up to 120 characters. */ last_name: string; } /** Which directions of traffic are blocked for this contact. */ export interface ContactBlocked { incoming: boolean; outgoing: boolean; bot: boolean; api: boolean; } export interface ContactChatMetadata { new: boolean; archived: boolean; unread: number; /** Seconds to pause automation for. */ pause_duration: number; marked_as_unread: boolean; closed: boolean; marked_as_done: boolean; blocked: ContactBlocked; } export interface ContactLeadSource { type?: string; module?: string; id: string | null; } export interface Contact { id: string; name: ContactName; /** Channel identities, keyed by channel. Server-owned. */ profile: Record; /** Custom field values, keyed by field slug. */ custom_field_hash: JsonObject; chat_metadata: ContactChatMetadata; order?: string; /** Unix seconds. Server-owned. */ last_seen: number; /** Unix seconds of the last inbound customer message. Server-owned. */ last_icm_timestamp: number; /** Server-owned. */ last_interaction_props: JsonObject; agent: string | null; team: string | null; lead_source: ContactLeadSource; status: ContactStatus; privacy_status: ContactPrivacyStatus; /** Resolved tag documents, not ids. */ tags: ContactTag[]; createdAt: IsoDate; updatedAt: IsoDate; } /** * Everything a caller may set. The server-owned paths (`profile`, `last_seen`, * `last_icm_timestamp`, `last_interaction_props`) are deliberately absent. */ export interface CreateContactInput { name?: Partial; /** * Creates the contact's WhatsApp identity with it, and writes its id to * `profile.whatsapp`. Any shape is accepted -- `+91 98765 43210` -- and stored * as digits only, which is the form an inbound message carries. Create-only. */ whatsapp?: string; order?: string; /** Contact tag ids. Default `[]`. */ tags?: ObjectId[]; agent?: ObjectId | null; team?: ObjectId | null; lead_source?: { type?: string; module?: string; id?: ObjectId | null; }; status?: ContactStatus; privacy_status?: ContactPrivacyStatus; /** Values keyed by custom field slug. */ custom_field_hash?: JsonObject; chat_metadata?: Partial> & { blocked?: Partial; }; } /** * `whatsapp` is absent: changing a channel identity is a write to the profile * collection, which a contact patch cannot express. */ export type UpdateContactInput = Partial>; /** * `search` matches the first and last name, plus the name and identifier of * every channel identity. `segment` names a saved filter; `filter` carries * ad-hoc conditions. Sending both narrows the segment by the conditions. */ export interface ListContactsQuery extends ListQuery { /** A contact tag id. */ tag?: ObjectId; agent?: ObjectId; /** Default `'live'`; pass `'trashed'` to read the trash. */ status?: ContactStatus; /** A segment's id or its name; ids are tried first when the value looks like one. */ segment?: string; /** Serialised to JSON by the SDK before it goes on the query string. */ filter?: ContactFilter; } /** * `delete` is two-stage: the first call trashes the contact, a second one on an * already-trashed contact destroys it. The body says which happened, since the * status code (200 either way) does not. */ export interface ContactDeleteResult { id: string; status: 'trashed' | 'deleted'; } export interface ContactNoteAttachment { type?: string; size?: string; url: string; mime?: string; file_name?: string; } export interface ContactNote { id: string; /** The contact the note hangs off. */ contact: string; note: string; attachments: ContactNoteAttachment[]; /** Ids of team members mentioned in the note. */ mentions: string[]; createdAt: IsoDate; updatedAt: IsoDate; } export interface CreateContactNoteInput { /** 1..5000 characters. */ note: string; /** Default `[]`. */ attachments?: ContactNoteAttachment[]; /** Team member ids. Default `[]`. */ mentions?: ObjectId[]; } export type UpdateContactNoteInput = Partial; /** Cursor paginated -- notes are appended, so an offset would shift under you. */ export type ListContactNotesQuery = PageQuery; export type CustomFieldType = 'text' | 'url' | 'email' | 'date' | 'phone' | 'number' | 'decimal' | 'amount' | 'address' | 'location' | 'country' | 'language' | 'attachment' | 'periodic_time' | 'percent' | 'timezone' | 'textarea' | 'checkbox' | 'dropdown' | 'timestamp' | 'dial_code' | 'multi_select'; /** `system` fields are provisioned by the platform, `user` ones by tenants. */ export type CustomFieldSource = 'system' | 'user'; export type CustomFieldTeamAccess = 'restricted' | 'open_to_all'; export interface CustomField { id: string; /** Machine name, unique per account. Usable in place of the id on every route. */ slug: string; name?: string; caption?: string; /** Who owns the field, not its data type -- that is `dataType`. */ type: CustomFieldSource; dataType?: CustomFieldType; /** Default value, shaped by `dataType`. */ default: JsonObject; /** Type-specific configuration: dropdown options, number precision, and so on. */ props: JsonObject; required: boolean; displayInPanel: boolean; showInSidebar: boolean; showAsLabel: boolean; isBoard: boolean; teamAccess: CustomFieldTeamAccess; createdAt: IsoDate; updatedAt: IsoDate; } export interface CreateCustomFieldInput { /** * snake_case, `^[a-z][a-z0-9_]{0,63}$`, and not one of the reserved names -- * contact document paths (`name`, `tags`, `status`, ...), channel keys * (`whatsapp`, `email`, ...) or built-in filter fields (`system_last_seen`, * `system_identifier`, ...). Immutable: `update` cannot change it. */ slug: string; /** 1..120 characters. */ name: string; /** Up to 240 characters. */ caption?: string; dataType: CustomFieldType; /** Default `{}`. */ default?: JsonObject; /** Type-specific configuration. Default `{}`. */ props?: JsonObject; /** Default `false`. */ required?: boolean; /** Default `false`. */ displayInPanel?: boolean; /** Default `false`. */ showInSidebar?: boolean; /** Default `false`. */ showAsLabel?: boolean; /** Default `false`. */ isBoard?: boolean; /** Default `'open_to_all'`. */ teamAccess?: CustomFieldTeamAccess; } /** Everything but the slug, which a field keeps for life. */ export type UpdateCustomFieldInput = Partial>; /** `search` matches the slug, the label and the caption. */ export interface ListCustomFieldsQuery extends ListQuery { /** Quick filter: the field's data type. */ dataType?: CustomFieldType; /** Quick filter: platform-provisioned or tenant-created. */ type?: CustomFieldSource; teamAccess?: CustomFieldTeamAccess; } /** * A saved contact filter. Nothing is materialised: a segment holds no contact * ids, and covers whatever its conditions match the next time it is run. */ export interface Segment { id: string; name: string; description?: string; filter: ContactFilter; createdAt: IsoDate; updatedAt: IsoDate; } export interface CreateSegmentInput { /** Trimmed, 1..120 characters. */ name: string; /** Trimmed, up to 500 characters. */ description?: string; /** Rejected on write if the conditions do not parse, rather than when first run. */ filter: ContactFilter; } export type UpdateSegmentInput = Partial; /** `search` matches the segment name and description. */ export type ListSegmentsQuery = ListQuery; /** The only module triggers watch today. */ export type CrmTriggerModule = 'contact'; /** * `event` triggers run off a contact change. `time` triggers are scheduled, and * are stored and served but not yet dispatched -- nothing schedules them. */ export type CrmTriggerType = 'event' | 'time'; /** * What happened to the contact. `edited` and `modified` are both any-change; the * rest are narrower readings of the same update, decided by which paths moved. */ export type CrmTriggerEvent = 'agent_assigned' | 'agent_deassigned' | 'created' | 'edited' | 'modified' | 'deleted' | 'marked_as_done' | 'marked_as_closed' | 'marked_as_archived' | 'blocked'; /** * Narrows an event to the fields it touched. `any` fires on every change, * `any_of_selected` needs one of `fields` to have moved, `all` needs all of * them. Events with no change set -- a creation, a deletion -- pass regardless. */ export interface CrmTriggerWhen { /** Default `'any'`. */ condition?: 'any' | 'any_of_selected' | 'all'; /** Dotted contact paths: `name.first_name`, `chat_metadata.closed`. Default `[]`. */ fields?: string[]; } export type CrmTriggerHttpMethod = 'POST' | 'PUT' | 'PATCH' | 'GET'; /** Webhook is the only action the schema defines. */ export interface CrmTriggerAction { /** Default `'webhook'`. */ type?: 'webhook'; config: { url: string; /** Default `'POST'`. */ method?: CrmTriggerHttpMethod; /** Sent alongside the contact payload. Default `{}`. */ headers?: Record; }; } export interface CrmTrigger { id: string; name: string; active: boolean; module: CrmTriggerModule; type: CrmTriggerType; trigger: CrmTriggerEvent; when: Required; /** * The same conditions `contacts.list({ filter })` speaks, flat rather than * wrapped: the changed contact has to match them for the trigger to fire. */ filters: ContactFilterEntry[]; action: CrmTriggerAction; createdAt: IsoDate; updatedAt: IsoDate; } export interface CreateCrmTriggerInput { /** Trimmed, 1..120 characters. */ name: string; /** Default `true`. */ active?: boolean; /** Default `'contact'`. */ module?: CrmTriggerModule; /** Default `'event'`. */ type?: CrmTriggerType; /** Default `'edited'`. */ trigger?: CrmTriggerEvent; /** Default `{ condition: 'any', fields: [] }`. */ when?: CrmTriggerWhen; /** At most 50 conditions. Default `[]`, which fires on every matching event. */ filters?: ContactFilterEntry[]; action: CrmTriggerAction; } export type UpdateCrmTriggerInput = Partial; /** `search` matches the trigger name. */ export interface ListCrmTriggersQuery extends ListQuery { /** Quick filter: the contact event the trigger watches. */ trigger?: CrmTriggerEvent; type?: CrmTriggerType; active?: boolean; } export type CrmTriggerLogStatus = 'success' | 'fail'; /** * One dispatch attempt. Logs are written by the dispatcher, never by a caller, * and the collection expires them after 30 days. */ export interface CrmTriggerLog { id: string; /** Id of the trigger that fired. */ trigger: string; event: CrmTriggerEvent; status: CrmTriggerLogStatus; payload: { url?: string; body?: unknown; }; /** Whatever came back: status and body, or the error that stopped the call. */ response?: unknown; /** When the log row is removed. */ expiryDate: IsoDate; createdAt: IsoDate; updatedAt: IsoDate; } export interface ListCrmTriggerLogsQuery extends ListQuery { /** Quick filter: one trigger's history. */ trigger?: ObjectId; event?: CrmTriggerEvent; status?: CrmTriggerLogStatus; } /** Import and export history share one lifecycle, and a row starts out `pending`. */ export type HistoryStatus = 'pending' | 'processing' | 'completed' | 'failed'; /** What a history row moved: contacts, or datastore records. */ export type HistoryModule = 'contact' | 'datastore'; /** * `extra` is an untyped column on both schemas. The SDK carries it through * verbatim, so anything an older writer left there survives a round trip. * A failed import puts its reason in `extra.error`. */ export type HistoryExtra = JsonObject; /** * Everything the worker needs to read the file. The stored column is untyped, * so the keys the platform acts on are named and anything else is passed * through rather than dropped. */ export interface ImportConfig { /** Column header -> contact field. Default `{}`. */ mapping?: Record; /** What to do with a row matching an existing contact. Default `'skip'`. */ duplicateStrategy?: 'skip' | 'update'; /** Anything else a caller or an older writer put here. */ [key: string]: unknown; } /** Counted by the worker as it walks the file; `new` + `duplicate` = `success`. */ export interface ImportStatistics { total: number; success: number; failed: number; /** Rows that created a contact. */ new: number; /** Rows that matched one that already existed. */ duplicate: number; } export interface ImportHistory { id: string; /** The team member who started it; rows written before members existed carry none. */ member?: string; module: HistoryModule; /** Storage key of the uploaded file. */ file: string; title: string; status: HistoryStatus; config: ImportConfig; extra: HistoryExtra; statistics: ImportStatistics; createdAt: IsoDate; updatedAt: IsoDate; } export interface CreateImportHistoryInput { /** Default `'contact'`. */ module?: HistoryModule; /** Storage key of the uploaded file, 1..1024 characters. The worker resolves it. */ file: string; /** Trimmed, 1..200 characters. */ title: string; /** Default `{}`, which means an empty mapping and `duplicateStrategy: 'skip'`. */ config?: ImportConfig; /** Default `{}`. */ extra?: HistoryExtra; } /** `search` matches the title. */ export interface ListImportHistoryQuery extends ListQuery { module?: HistoryModule; status?: HistoryStatus; } /** * What to write out. Sending both a segment and a filter narrows the segment, * the same way `contacts.list` reads the pair. */ export interface ExportConfig { /** A saved segment's id or its name. */ segment?: string; filter?: ContactFilter; /** Columns to write; empty means the worker's default set. Default `[]`. */ fields?: string[]; /** Anything else a caller or an older writer put here. */ [key: string]: unknown; } export interface ExportHistory { id: string; /** The team member who started it; rows written before members existed carry none. */ member?: string; module: HistoryModule; /** Storage key of the finished file; absent until the worker has written one. */ file?: string; title: string; /** Rows written. `0` until the export completes. */ count: number; status: HistoryStatus; /** Why it failed, when it did. */ error?: string; config: ExportConfig; extra: HistoryExtra; createdAt: IsoDate; updatedAt: IsoDate; } export interface CreateExportHistoryInput { /** Default `'contact'`. */ module?: HistoryModule; /** Trimmed, 1..200 characters. */ title: string; /** Default `{}`, which exports every contact with the worker's default columns. */ config?: ExportConfig; /** Default `{}`. */ extra?: HistoryExtra; } /** `search` matches the title. */ export interface ListExportHistoryQuery extends ListQuery { module?: HistoryModule; status?: HistoryStatus; } export type WebhookEventType = 'contact.created' | 'contact.updated' | 'contact.deleted'; export interface Webhook { id: string; url: string; events: WebhookEventType[]; enabled: boolean; /** Consecutive delivery failures. */ failureCount: number; lastDeliveredAt?: IsoDate; createdAt: IsoDate; updatedAt: IsoDate; } export interface CreateWebhookInput { /** Must be a valid absolute URL. */ url: string; /** At least one event. */ events: WebhookEventType[]; /** Default `true`. */ enabled?: boolean; } export type UpdateWebhookInput = Partial; /** Cursor paginated. */ export interface ListWebhooksQuery extends PageQuery { enabled?: boolean; } /** The body the platform POSTs to a registered webhook URL. */ export interface WebhookEnvelope { /** Delivery id, stable across retries of the same event. */ id: string; type: string; tenantId: string; createdAt: IsoDate; data: unknown; } /** * Where a push notification can be delivered. * * It decides which half of the FCM payload the send path fills in -- `webpush` * for a browser, `android`/`apns` for an app -- and it is the one thing about a * device that cannot be inferred from its token. A registration token is an * opaque string identifying a browser or app *instance*; nothing in it says what * kind of thing that instance is. */ export type DevicePlatform = 'web' | 'android' | 'ios'; /** * A subscribed device, as it reads back. * * The registration token is **never** returned. It is a send credential -- * anything holding one can push to that browser through the agency's Firebase * project -- and the list exists so a user can recognise and revoke their own * devices, which needs the label and the last-seen time and nothing more. */ export interface Device { id: ObjectId; platform: DevicePlatform; /** Whatever `device_label` was sent on registration; `''` when none was. */ label: string; /** The reseller frontend it registered from; `null` for the white-label one. */ clientId: string | null; /** * Last time a notification to this device succeeded, or it re-subscribed. * * The only signal that a device is still real: FCM does not revoke a token * when an app is uninstalled or a browser's site data is cleared, it simply * stops delivering to it. A device unseen for 60 days is pruned on that basis, * which is another reason to call {@link Notifications.subscribe} on every app * load rather than once. */ lastSeenAt: IsoDate; createdAt: IsoDate; } /** * What `notifications.subscribe()` takes. Mirrors the wire body field for field. * * There is deliberately no user field. The acting user comes from the verified * token the client was constructed with; a body that could name its own user * would let any caller point someone else's notifications at their browser. */ export interface SubscribeNotificationsInput { /** * The FCM registration token for this browser or app instance, from * `getToken()`. 20..4096 characters -- a sanity check rather than a format, * since Google publishes no shape for these. */ token: string; /** * Defaults to `'web'` when the SDK can see a DOM, and is otherwise required: * a React Native runtime has a `navigator` but no `document`, and guessing * `'web'` there would send the wrong half of every payload. */ platform?: DevicePlatform; /** * What the user would recognise this device as, for the device list -- up to * 200 characters. Left out, the SDK derives something like `Chrome on Windows` * from the user agent when it is running in a browser. Cosmetic, never matched * on. */ device_label?: string; /** * The reseller client this frontend belongs to (`tpc_…`), when there is one. * * Rarely needed: the client id the `CrmClient` already sends is verified and * wins. Supplying a *different* one is refused with 403 rather than ignored. * Omitted by the white-label frontend, which has no client. */ tpc_id?: string; } /** * `page` and `rows` only. * * The endpoint's schema accepts `search` because it shares the common list * query, but the service does not apply it -- a device list is one person's few * rows, so there is nothing to search. It is left out here rather than accepted * and silently dropped. */ export type ListDevicesQuery = Pick;