From db80085212b8cecba68cb9bee0cb545ffce18bde Mon Sep 17 00:00:00 2001 From: Patrick Ng Date: Thu, 3 Dec 2026 22:02:43 +0000 Subject: [PATCH] Instagram step 1: turn on Instagram for a website's Page (ADR-0028) Same content as #211, which was merged into its stacked base branch by mistake instead of main. Signed-off-by: yatping Co-Authored-By: Claude Opus 5.5 --- apps/dashboard/src/i18n/de.ts | 9 +- apps/dashboard/src/i18n/en.ts | 9 +- apps/dashboard/src/i18n/es.ts | 9 +- apps/dashboard/src/i18n/fr.ts | 9 +- apps/dashboard/src/i18n/it.ts | 9 +- apps/dashboard/src/i18n/ja.ts | 9 +- apps/dashboard/src/i18n/ko.ts | 9 +- apps/dashboard/src/i18n/nl.ts | 9 +- apps/dashboard/src/i18n/pt.ts | 9 +- apps/dashboard/src/i18n/zh-hans.ts | 9 +- apps/dashboard/src/i18n/zh-hant.ts | 9 +- apps/dashboard/src/pages/websites.tsx | 37 + docs/architecture/data-model.md | 2 +- .../decisions/0028-instagram-channel.md | 28 +- docs/guide/admin.md | 15 + docs/known-issues.md | 10 + packages/api-contracts/generated/openapi.json | 35 +- packages/api-contracts/src/routes.ts | 23 +- packages/core/src/messenger.ts | 82 + .../database/migrations/0042_instagram.sql | 6 + .../migrations/meta/0042_snapshot.json | 6119 +++++++++++++++++ .../database/migrations/meta/_journal.json | 7 + packages/database/src/messenger-repository.ts | 31 +- packages/database/src/schema/index.ts | 4 + .../test/messenger-repository.test.ts | 13 + services/api/src/messenger.ts | 13 +- services/api/test/api.test.ts | 2 +- services/api/test/messenger.test.ts | 101 +- 28 files changed, 6575 insertions(+), 52 deletions(-) create mode 100644 packages/database/migrations/0042_instagram.sql create mode 100644 packages/database/migrations/meta/0042_snapshot.json diff --git a/apps/dashboard/src/i18n/de.ts b/apps/dashboard/src/i18n/de.ts index e67f003..bce0d3b 100644 --- a/apps/dashboard/src/i18n/de.ts +++ b/apps/dashboard/src/i18n/de.ts @@ -674,7 +674,7 @@ export const de: Messages = { whatsappCopy: 'Kopieren', whatsappDisconnect: 'Trennen', whatsappDisconnectConfirm: 'Diese Nummer trennen? Ihre Schlüssel werden gelöscht, und ihre Nachrichten erreichen den Posteingang nicht mehr.', - messengerTab: 'Messenger', + messengerTab: 'Messenger & Instagram', messengerIntro: 'Verbinden Sie die Facebook-Seite dieser Website. Wer der Seite über Messenger schreibt, landet in Ihrem Posteingang, mit dem Assistenten, der Übersetzung und den Öffnungszeiten dieser Website.', onMessenger: 'Auf Messenger', messengerMediaPending: 'Datei wird von Messenger geladen…', @@ -698,4 +698,11 @@ export const de: Messages = { messengerEnabled: 'Nachrichten von dieser Seite empfangen', messengerWebhookHelp: 'Fügen Sie in Ihrer Meta-App unter Messenger, Einstellungen diese Callback-URL und dieses Verifizierungstoken hinzu. OpenChat hat die Seite bereits für messages, deliveries, reads und echoes abonniert.', messengerDisconnectConfirm: 'Diese Seite trennen? Ihre Schlüssel werden gelöscht, und ihre Nachrichten erreichen den Posteingang nicht mehr.', + instagramTitle: 'Instagram', + instagramHelp: 'Direktnachrichten an das mit dieser Seite verknüpfte Instagram-Professional-Konto können ebenfalls Ihren Posteingang erreichen. Das Seiten-Zugriffstoken braucht zusätzlich instagram_basic und instagram_manage_messages, und in der Instagram-App muss „Zugriff auf Nachrichten erlauben“ aktiviert sein.', + instagramOn: 'Direktnachrichten an {account} werden empfangen.', + instagramOff: 'Instagram ist aus. Direktnachrichten an {account} erreichen den Posteingang nicht.', + instagramTurnOn: 'Instagram einschalten', + instagramTurnOff: 'Instagram ausschalten', + instagramWebhookHelp: 'Fügen Sie danach in Ihrer Meta-App unter Instagram, Webhooks dieselbe Callback-URL und dasselbe Verifizierungstoken hinzu und abonnieren Sie messages, messaging_seen, message_reactions, messaging_postbacks und messaging_referral.', }; diff --git a/apps/dashboard/src/i18n/en.ts b/apps/dashboard/src/i18n/en.ts index 0d48dc8..91d600e 100644 --- a/apps/dashboard/src/i18n/en.ts +++ b/apps/dashboard/src/i18n/en.ts @@ -687,7 +687,7 @@ export const en = { whatsappDisconnect: 'Disconnect', whatsappDisconnectConfirm: 'Disconnect this number? Its keys are deleted, and its messages stop reaching the inbox.', // Messenger (ADR-0027) - messengerTab: 'Messenger', + messengerTab: 'Messenger & Instagram', messengerIntro: 'Connect this website’s Facebook Page. People who message the Page on Messenger will reach your inbox, with this website’s assistant, translation and opening hours.', onMessenger: 'On Messenger', messengerMediaPending: 'Fetching the file from Messenger…', @@ -711,6 +711,13 @@ export const en = { messengerEnabled: 'Receive messages from this Page', messengerWebhookHelp: 'In your Meta app, under Messenger, Settings, add this callback URL and verify token. OpenChat has already subscribed the Page to messages, deliveries, reads and echoes.', messengerDisconnectConfirm: 'Disconnect this Page? Its keys are deleted, and its messages stop reaching the inbox.', + instagramTitle: 'Instagram', + instagramHelp: 'Direct messages to the Instagram professional account linked to this Page can reach your inbox too. The Page access token also needs instagram_basic and instagram_manage_messages, and “Allow access to messages” must be on in the Instagram app. The admin guide shows where.', + instagramOn: 'Receiving direct messages to {account}.', + instagramOff: 'Instagram is off. Direct messages to {account} do not reach the inbox.', + instagramTurnOn: 'Turn on Instagram', + instagramTurnOff: 'Turn off Instagram', + instagramWebhookHelp: 'Then in your Meta app, under Instagram, Webhooks, add the same callback URL and verify token, and subscribe to messages, messaging_seen, message_reactions, messaging_postbacks and messaging_referral.', }; export type Messages = Record; diff --git a/apps/dashboard/src/i18n/es.ts b/apps/dashboard/src/i18n/es.ts index 6f6b3cc..ef9f4d9 100644 --- a/apps/dashboard/src/i18n/es.ts +++ b/apps/dashboard/src/i18n/es.ts @@ -674,7 +674,7 @@ export const es: Messages = { whatsappCopy: 'Copiar', whatsappDisconnect: 'Desconectar', whatsappDisconnectConfirm: '¿Desconectar este número? Sus claves se eliminan y sus mensajes dejan de llegar a la bandeja de entrada.', - messengerTab: 'Messenger', + messengerTab: 'Messenger e Instagram', messengerIntro: 'Conecta la página de Facebook de este sitio web. Quienes escriban a la página por Messenger llegarán a tu bandeja de entrada, con el asistente, la traducción y el horario de este sitio web.', onMessenger: 'En Messenger', messengerMediaPending: 'Descargando el archivo de Messenger…', @@ -698,4 +698,11 @@ export const es: Messages = { messengerEnabled: 'Recibir mensajes de esta página', messengerWebhookHelp: 'En tu app de Meta, en Messenger, Configuración, añade esta URL de devolución de llamada y este token de verificación. OpenChat ya ha suscrito la página a messages, deliveries, reads y echoes.', messengerDisconnectConfirm: '¿Desconectar esta página? Sus claves se eliminan y sus mensajes dejan de llegar a la bandeja de entrada.', + instagramTitle: 'Instagram', + instagramHelp: 'Los mensajes directos a la cuenta profesional de Instagram vinculada a esta página también pueden llegar a tu bandeja de entrada. El token de acceso de la página necesita además instagram_basic e instagram_manage_messages, y en la app de Instagram debe estar activado «Permitir acceso a los mensajes». La guía de administración indica dónde.', + instagramOn: 'Se reciben los mensajes directos a {account}.', + instagramOff: 'Instagram está desactivado. Los mensajes directos a {account} no llegan a la bandeja de entrada.', + instagramTurnOn: 'Activar Instagram', + instagramTurnOff: 'Desactivar Instagram', + instagramWebhookHelp: 'Después, en tu app de Meta, en Instagram, Webhooks, añade la misma URL de devolución de llamada y el mismo token de verificación, y suscríbete a messages, messaging_seen, message_reactions, messaging_postbacks y messaging_referral.', }; diff --git a/apps/dashboard/src/i18n/fr.ts b/apps/dashboard/src/i18n/fr.ts index 9ab0ef7..129528b 100644 --- a/apps/dashboard/src/i18n/fr.ts +++ b/apps/dashboard/src/i18n/fr.ts @@ -674,7 +674,7 @@ export const fr: Messages = { whatsappCopy: 'Copier', whatsappDisconnect: 'Déconnecter', whatsappDisconnectConfirm: 'Déconnecter ce numéro ? Ses clés sont supprimées et ses messages n’arrivent plus dans la boîte de réception.', - messengerTab: 'Messenger', + messengerTab: 'Messenger et Instagram', messengerIntro: 'Connectez la Page Facebook de ce site. Les personnes qui écrivent à la Page sur Messenger arriveront dans votre boîte de réception, avec l’assistant, la traduction et les horaires de ce site.', onMessenger: 'Sur Messenger', messengerMediaPending: 'Récupération du fichier depuis Messenger…', @@ -698,4 +698,11 @@ export const fr: Messages = { messengerEnabled: 'Recevoir les messages de cette Page', messengerWebhookHelp: 'Dans votre app Meta, sous Messenger, Paramètres, ajoutez cette URL de rappel et ce jeton de vérification. OpenChat a déjà abonné la Page à messages, deliveries, reads et echoes.', messengerDisconnectConfirm: 'Déconnecter cette Page ? Ses clés sont supprimées et ses messages n’arrivent plus dans la boîte de réception.', + instagramTitle: 'Instagram', + instagramHelp: 'Les messages privés adressés au compte professionnel Instagram lié à cette Page peuvent aussi arriver dans votre boîte de réception. Le jeton d’accès de la Page doit aussi avoir instagram_basic et instagram_manage_messages, et « Autoriser l’accès aux messages » doit être activé dans l’app Instagram. Le guide d’administration indique où.', + instagramOn: 'Les messages privés adressés à {account} sont reçus.', + instagramOff: 'Instagram est désactivé. Les messages privés adressés à {account} n’arrivent pas dans la boîte de réception.', + instagramTurnOn: 'Activer Instagram', + instagramTurnOff: 'Désactiver Instagram', + instagramWebhookHelp: 'Ensuite, dans votre app Meta, sous Instagram, Webhooks, ajoutez la même URL de rappel et le même jeton de vérification, et abonnez-vous à messages, messaging_seen, message_reactions, messaging_postbacks et messaging_referral.', }; diff --git a/apps/dashboard/src/i18n/it.ts b/apps/dashboard/src/i18n/it.ts index fcb4192..c4afd8a 100644 --- a/apps/dashboard/src/i18n/it.ts +++ b/apps/dashboard/src/i18n/it.ts @@ -674,7 +674,7 @@ export const it: Messages = { whatsappCopy: 'Copia', whatsappDisconnect: 'Scollega', whatsappDisconnectConfirm: 'Scollegare questo numero? Le sue chiavi vengono eliminate e i suoi messaggi non arrivano più nella casella.', - messengerTab: 'Messenger', + messengerTab: 'Messenger e Instagram', messengerIntro: 'Collega la Pagina Facebook di questo sito web. Chi scrive alla Pagina su Messenger arriverà nella tua posta in arrivo, con l’assistente, la traduzione e gli orari di questo sito.', onMessenger: 'Su Messenger', messengerMediaPending: 'Recupero del file da Messenger…', @@ -698,4 +698,11 @@ export const it: Messages = { messengerEnabled: 'Ricevi i messaggi da questa Pagina', messengerWebhookHelp: 'Nella tua app Meta, in Messenger, Impostazioni, aggiungi questo URL di callback e questo token di verifica. OpenChat ha già iscritto la Pagina a messages, deliveries, reads ed echoes.', messengerDisconnectConfirm: 'Scollegare questa Pagina? Le sue chiavi vengono eliminate e i suoi messaggi non arrivano più nella posta in arrivo.', + instagramTitle: 'Instagram', + instagramHelp: 'Anche i messaggi diretti all’account professionale Instagram collegato a questa Pagina possono arrivare nella tua posta in arrivo. Il token di accesso della Pagina deve avere anche instagram_basic e instagram_manage_messages, e nell’app Instagram deve essere attivo «Consenti l’accesso ai messaggi». La guida per l’amministratore indica dove.', + instagramOn: 'I messaggi diretti a {account} vengono ricevuti.', + instagramOff: 'Instagram è disattivato. I messaggi diretti a {account} non arrivano nella posta in arrivo.', + instagramTurnOn: 'Attiva Instagram', + instagramTurnOff: 'Disattiva Instagram', + instagramWebhookHelp: 'Poi, nella tua app Meta, in Instagram, Webhooks, aggiungi lo stesso URL di callback e lo stesso token di verifica, e iscriviti a messages, messaging_seen, message_reactions, messaging_postbacks e messaging_referral.', }; diff --git a/apps/dashboard/src/i18n/ja.ts b/apps/dashboard/src/i18n/ja.ts index 917b8b0..b5429f6 100644 --- a/apps/dashboard/src/i18n/ja.ts +++ b/apps/dashboard/src/i18n/ja.ts @@ -674,7 +674,7 @@ export const ja: Messages = { whatsappCopy: 'コピー', whatsappDisconnect: '接続を解除', whatsappDisconnectConfirm: 'この番号の接続を解除しますか?キーは削除され、メッセージは受信トレイに届かなくなります。', - messengerTab: 'Messenger', + messengerTab: 'Messenger と Instagram', messengerIntro: 'このウェブサイトの Facebook ページを接続します。Messenger でページにメッセージを送った人は、このウェブサイトのアシスタント、翻訳、営業時間とともに受信トレイに届きます。', onMessenger: 'Messenger から', messengerMediaPending: 'Messenger からファイルを取得しています…', @@ -698,4 +698,11 @@ export const ja: Messages = { messengerEnabled: 'このページからのメッセージを受け取る', messengerWebhookHelp: 'Meta アプリの Messenger の「設定」で、このコールバック URL と認証トークンを追加してください。OpenChat はすでにページを messages、deliveries、reads、echoes にサブスクライブしています。', messengerDisconnectConfirm: 'このページの接続を解除しますか?キーは削除され、メッセージは受信トレイに届かなくなります。', + instagramTitle: 'Instagram', + instagramHelp: 'このページにリンクされた Instagram プロアカウントへのダイレクトメッセージも受信トレイに届くようにできます。ページアクセストークンには instagram_basic と instagram_manage_messages も必要です。また Instagram アプリで「メッセージへのアクセスを許可」をオンにしてください(場所は管理者ガイドを参照)。', + instagramOn: '{account} へのダイレクトメッセージを受信しています。', + instagramOff: 'Instagram はオフです。{account} へのダイレクトメッセージは受信トレイに届きません。', + instagramTurnOn: 'Instagram をオンにする', + instagramTurnOff: 'Instagram をオフにする', + instagramWebhookHelp: '次に Meta アプリの Instagram > Webhooks で同じコールバック URL と認証トークンを追加し、messages、messaging_seen、message_reactions、messaging_postbacks、messaging_referral を購読してください。', }; diff --git a/apps/dashboard/src/i18n/ko.ts b/apps/dashboard/src/i18n/ko.ts index c5f53d2..1d18487 100644 --- a/apps/dashboard/src/i18n/ko.ts +++ b/apps/dashboard/src/i18n/ko.ts @@ -674,7 +674,7 @@ export const ko: Messages = { whatsappCopy: '복사', whatsappDisconnect: '연결 해제', whatsappDisconnectConfirm: '이 번호의 연결을 해제할까요? 키가 삭제되고 메시지가 더 이상 받은편지함에 도착하지 않습니다.', - messengerTab: 'Messenger', + messengerTab: 'Messenger 및 Instagram', messengerIntro: '이 웹사이트의 Facebook 페이지를 연결하세요. Messenger로 페이지에 메시지를 보낸 사람은 이 웹사이트의 어시스턴트, 번역, 운영 시간과 함께 받은편지함에 도착합니다.', onMessenger: 'Messenger에서', messengerMediaPending: 'Messenger에서 파일을 가져오는 중…', @@ -698,4 +698,11 @@ export const ko: Messages = { messengerEnabled: '이 페이지의 메시지 받기', messengerWebhookHelp: 'Meta 앱의 Messenger > 설정에서 이 콜백 URL과 인증 토큰을 추가하세요. OpenChat이 이미 페이지를 messages, deliveries, reads, echoes에 구독했습니다.', messengerDisconnectConfirm: '이 페이지의 연결을 해제할까요? 키가 삭제되고 메시지가 더 이상 받은편지함에 도착하지 않습니다.', + instagramTitle: 'Instagram', + instagramHelp: '이 페이지에 연결된 Instagram 프로페셔널 계정으로 오는 다이렉트 메시지도 받은편지함으로 받을 수 있습니다. 페이지 액세스 토큰에는 instagram_basic과 instagram_manage_messages도 필요하며, Instagram 앱에서 “메시지 액세스 허용”을 켜야 합니다(위치는 관리자 가이드 참고).', + instagramOn: '{account}(으)로 오는 다이렉트 메시지를 받고 있습니다.', + instagramOff: 'Instagram이 꺼져 있습니다. {account}(으)로 오는 다이렉트 메시지는 받은편지함에 도착하지 않습니다.', + instagramTurnOn: 'Instagram 켜기', + instagramTurnOff: 'Instagram 끄기', + instagramWebhookHelp: '그런 다음 Meta 앱의 Instagram > Webhooks에서 같은 콜백 URL과 인증 토큰을 추가하고 messages, messaging_seen, message_reactions, messaging_postbacks, messaging_referral을 구독하세요.', }; diff --git a/apps/dashboard/src/i18n/nl.ts b/apps/dashboard/src/i18n/nl.ts index 0c8322b..83e7c4a 100644 --- a/apps/dashboard/src/i18n/nl.ts +++ b/apps/dashboard/src/i18n/nl.ts @@ -674,7 +674,7 @@ export const nl: Messages = { whatsappCopy: 'Kopiëren', whatsappDisconnect: 'Ontkoppelen', whatsappDisconnectConfirm: 'Dit nummer ontkoppelen? De sleutels worden verwijderd en de berichten komen niet meer in de inbox.', - messengerTab: 'Messenger', + messengerTab: 'Messenger en Instagram', messengerIntro: 'Koppel de Facebook-pagina van deze website. Wie de pagina via Messenger een bericht stuurt, komt in je inbox terecht, met de assistent, vertaling en openingstijden van deze website.', onMessenger: 'Op Messenger', messengerMediaPending: 'Bestand ophalen van Messenger…', @@ -698,4 +698,11 @@ export const nl: Messages = { messengerEnabled: 'Berichten van deze pagina ontvangen', messengerWebhookHelp: 'Voeg in je Meta-app onder Messenger, Instellingen deze callback-URL en verificatietoken toe. OpenChat heeft de pagina al geabonneerd op messages, deliveries, reads en echoes.', messengerDisconnectConfirm: 'Deze pagina ontkoppelen? De sleutels worden verwijderd en berichten komen niet meer in de inbox.', + instagramTitle: 'Instagram', + instagramHelp: 'Directe berichten aan het zakelijke Instagram-account dat aan deze pagina is gekoppeld, kunnen ook in je inbox komen. Het paginatoegangstoken heeft daarnaast instagram_basic en instagram_manage_messages nodig, en in de Instagram-app moet ‘Toegang tot berichten toestaan’ aan staan. De beheerdershandleiding laat zien waar.', + instagramOn: 'Directe berichten aan {account} worden ontvangen.', + instagramOff: 'Instagram staat uit. Directe berichten aan {account} komen niet in de inbox.', + instagramTurnOn: 'Instagram aanzetten', + instagramTurnOff: 'Instagram uitzetten', + instagramWebhookHelp: 'Voeg daarna in je Meta-app onder Instagram, Webhooks dezelfde callback-URL en verificatietoken toe, en abonneer je op messages, messaging_seen, message_reactions, messaging_postbacks en messaging_referral.', }; diff --git a/apps/dashboard/src/i18n/pt.ts b/apps/dashboard/src/i18n/pt.ts index ab00379..300fe33 100644 --- a/apps/dashboard/src/i18n/pt.ts +++ b/apps/dashboard/src/i18n/pt.ts @@ -674,7 +674,7 @@ export const pt: Messages = { whatsappCopy: 'Copiar', whatsappDisconnect: 'Desconectar', whatsappDisconnectConfirm: 'Desconectar este número? As chaves dele são excluídas e as mensagens deixam de chegar à caixa de entrada.', - messengerTab: 'Messenger', + messengerTab: 'Messenger e Instagram', messengerIntro: 'Ligue a Página do Facebook deste site. Quem escrever à Página no Messenger chegará à sua caixa de entrada, com o assistente, a tradução e o horário deste site.', onMessenger: 'No Messenger', messengerMediaPending: 'Buscando o arquivo no Messenger…', @@ -698,4 +698,11 @@ export const pt: Messages = { messengerEnabled: 'Receber mensagens desta Página', messengerWebhookHelp: 'Na sua app Meta, em Messenger, Definições, adicione este URL de callback e este token de verificação. O OpenChat já subscreveu a Página a messages, deliveries, reads e echoes.', messengerDisconnectConfirm: 'Desligar esta Página? As suas chaves são eliminadas e as mensagens deixam de chegar à caixa de entrada.', + instagramTitle: 'Instagram', + instagramHelp: 'As mensagens diretas para a conta profissional do Instagram ligada a esta Página também podem chegar à sua caixa de entrada. O token de acesso da Página também precisa de instagram_basic e instagram_manage_messages, e na app do Instagram tem de estar ativado «Permitir acesso às mensagens». O guia de administração indica onde.', + instagramOn: 'As mensagens diretas para {account} são recebidas.', + instagramOff: 'O Instagram está desativado. As mensagens diretas para {account} não chegam à caixa de entrada.', + instagramTurnOn: 'Ativar o Instagram', + instagramTurnOff: 'Desativar o Instagram', + instagramWebhookHelp: 'Depois, na sua app Meta, em Instagram, Webhooks, adicione o mesmo URL de callback e o mesmo token de verificação, e subscreva messages, messaging_seen, message_reactions, messaging_postbacks e messaging_referral.', }; diff --git a/apps/dashboard/src/i18n/zh-hans.ts b/apps/dashboard/src/i18n/zh-hans.ts index 678f293..2af56fc 100644 --- a/apps/dashboard/src/i18n/zh-hans.ts +++ b/apps/dashboard/src/i18n/zh-hans.ts @@ -674,7 +674,7 @@ export const zhHans: Messages = { whatsappCopy: '复制', whatsappDisconnect: '断开连接', whatsappDisconnectConfirm: '要断开此号码吗?其密钥将被删除,消息也不会再进入收件箱。', - messengerTab: 'Messenger', + messengerTab: 'Messenger 和 Instagram', messengerIntro: '连接此网站的 Facebook 主页。通过 Messenger 给主页发消息的人将进入你的收件箱,并使用此网站的助手、翻译和营业时间。', onMessenger: '来自 Messenger', messengerMediaPending: '正在从 Messenger 获取文件…', @@ -698,4 +698,11 @@ export const zhHans: Messages = { messengerEnabled: '接收此主页的消息', messengerWebhookHelp: '在你的 Meta 应用中,于 Messenger > 设置添加此回调网址和验证口令。OpenChat 已为主页订阅 messages、deliveries、reads 和 echoes。', messengerDisconnectConfirm: '断开此主页?其密钥将被删除,消息也不会再进入收件箱。', + instagramTitle: 'Instagram', + instagramHelp: '发给与此主页关联的 Instagram 专业账号的私信也可以进入你的收件箱。主页访问口令还需要 instagram_basic 和 instagram_manage_messages,并且必须在 Instagram 应用中打开“允许访问消息”(位置见管理员指南)。', + instagramOn: '正在接收发给 {account} 的私信。', + instagramOff: 'Instagram 已关闭。发给 {account} 的私信不会进入收件箱。', + instagramTurnOn: '开启 Instagram', + instagramTurnOff: '关闭 Instagram', + instagramWebhookHelp: '然后在你的 Meta 应用中,于 Instagram > Webhooks 下添加相同的回调网址和验证口令,并订阅 messages、messaging_seen、message_reactions、messaging_postbacks 和 messaging_referral。', }; diff --git a/apps/dashboard/src/i18n/zh-hant.ts b/apps/dashboard/src/i18n/zh-hant.ts index 9e1e0fd..2ae46f3 100644 --- a/apps/dashboard/src/i18n/zh-hant.ts +++ b/apps/dashboard/src/i18n/zh-hant.ts @@ -674,7 +674,7 @@ export const zhHant: Messages = { whatsappCopy: '複製', whatsappDisconnect: '中斷連接', whatsappDisconnectConfirm: '要中斷此號碼的連接嗎?其密鑰將被刪除,訊息也不會再進入收件匣。', - messengerTab: 'Messenger', + messengerTab: 'Messenger 與 Instagram', messengerIntro: '連接此網站的 Facebook 專頁。透過 Messenger 傳訊息給專頁的人會進入你的收件匣,並使用此網站的助理、翻譯和營業時間。', onMessenger: '來自 Messenger', messengerMediaPending: '正在從 Messenger 取得檔案…', @@ -698,4 +698,11 @@ export const zhHant: Messages = { messengerEnabled: '接收此專頁的訊息', messengerWebhookHelp: '在你的 Meta 應用程式中,於 Messenger > 設定加入此回呼網址和驗證權杖。OpenChat 已為專頁訂閱 messages、deliveries、reads 和 echoes。', messengerDisconnectConfirm: '中斷此專頁?其密鑰將被刪除,訊息也不會再進入收件匣。', + instagramTitle: 'Instagram', + instagramHelp: '傳給與此專頁連結的 Instagram 專業帳號的私訊也可以進入你的收件匣。專頁存取權杖還需要 instagram_basic 和 instagram_manage_messages,並且必須在 Instagram 應用程式中開啟「允許存取訊息」(位置見管理員指南)。', + instagramOn: '正在接收傳給 {account} 的私訊。', + instagramOff: 'Instagram 已關閉。傳給 {account} 的私訊不會進入收件匣。', + instagramTurnOn: '開啟 Instagram', + instagramTurnOff: '關閉 Instagram', + instagramWebhookHelp: '然後在你的 Meta 應用程式中,於 Instagram > Webhooks 下新增相同的回呼網址和驗證權杖,並訂閱 messages、messaging_seen、message_reactions、messaging_postbacks 和 messaging_referral。', }; diff --git a/apps/dashboard/src/pages/websites.tsx b/apps/dashboard/src/pages/websites.tsx index 060d1c3..28ef6d4 100644 --- a/apps/dashboard/src/pages/websites.tsx +++ b/apps/dashboard/src/pages/websites.tsx @@ -332,6 +332,7 @@ function MessengerForm({ website, workspaceId, connection, onChange }: { website

{t('messengerWebhookHelp')}

+
+ {toggle.isPending && ( +

+ {t('whatsappChecking')} +

+ )} + +
+ + ); +} + type Tab = 'install' | 'appearance' | 'chat' | 'hours' | 'whatsapp' | 'messenger' | 'details'; const TABS: { tab: Tab; label: MessageKey }[] = [ { tab: 'install', label: 'websiteTabInstall' }, diff --git a/docs/architecture/data-model.md b/docs/architecture/data-model.md index 07f65b9..bbfb999 100644 --- a/docs/architecture/data-model.md +++ b/docs/architecture/data-model.md @@ -41,7 +41,7 @@ Beyond the spec's entities, the schema adds what stated requirements need: | `outbox`, `job_receipts`, `failed_jobs` | Reliable dispatch, consumer idempotency, durable failure records | | `audit_log` | §18 | | `whatsapp_connections` | A WhatsApp Business number connected to a website, one per website, and a number on one website only ([ADR-0026](decisions/0026-whatsapp-channel.md)). The access token, the app secret and the webhook's verify token are sealed with `DATA_ENCRYPTION_KEY` and share `key_version`. Changed only by an installation admin, each change audited as `whatsapp.connected`, `whatsapp.updated` or `whatsapp.disconnected` in [Pattern 2a](#pattern-2a-the-audit-row-as-the-guard). Goes with its website. Migration 0036 | -| `messenger_connections` | A Facebook Page connected to a website for Messenger, one per website, and a Page on one website only ([ADR-0027](decisions/0027-messenger-channel.md)). As `whatsapp_connections`: the Page access token, the app secret and the verify token sealed with one `key_version`, changes by an installation admin audited as `messenger.connected`, `messenger.updated` or `messenger.disconnected`, and gone with its website. Migration 0039 | +| `messenger_connections` | A Facebook Page connected to a website for Messenger, one per website, and a Page on one website only ([ADR-0027](decisions/0027-messenger-channel.md)). As `whatsapp_connections`: the Page access token, the app secret and the verify token sealed with one `key_version`, changes by an installation admin audited as `messenger.connected`, `messenger.updated` or `messenger.disconnected`, and gone with its website. Migration 0039. Migration 0042 adds the Instagram account linked to the Page ([ADR-0028](decisions/0028-instagram-channel.md)): `instagram_account_id` (unique across the installation, kept when Instagram is turned off), `instagram_username` and `instagram_enabled` | | `messenger_identities` | A Messenger customer of one connected Page: Meta's page-scoped ID (`psid`), unique per Page in a workspace ([ADR-0027](decisions/0027-messenger-channel.md)). Keyed by the Page's ID, not the connection, and made with its contact on the first message, with IDs derived from who the customer is, as for WhatsApp. The contact's name comes afterwards from Meta, by a job, and only fills an empty name. Goes with its contact. Migration 0040 | | `whatsapp_identities` | A WhatsApp customer on one connected number: Meta's business-scoped user ID, their phone number (`wa_id`), or both, each unique per number in a workspace ([ADR-0026](decisions/0026-whatsapp-channel.md)). Keyed by Meta's ID for the number, not the connection, so connecting a number again finds the same contacts. A first message makes the identity and its contact together, with IDs derived from who the customer is, so two first messages at once agree on one. Goes with its contact. Migration 0037 | | `conversations.channel` | `web` or `whatsapp`, defaulting to `web`, with its CHECK written by hand in migration 0037. A WhatsApp message goes to the customer's newest open or pending WhatsApp conversation on that website, or a new one whose ID comes from the conversation before it, so two messages at once agree. Its WhatsApp message ID is its `client_message_id`. Email follow-ups never schedule `next_automation_at` for WhatsApp. A file still to fetch, or something OpenChat cannot show, is under `whatsapp` in `messages.metadata_json`, and so is a reply's `delivery` and its `error`. Meta's 24-hour window runs from the latest `last_visitor_message_at` of the customer's WhatsApp conversations on the website | diff --git a/docs/architecture/decisions/0028-instagram-channel.md b/docs/architecture/decisions/0028-instagram-channel.md index 78449f1..7eb5ba6 100644 --- a/docs/architecture/decisions/0028-instagram-channel.md +++ b/docs/architecture/decisions/0028-instagram-channel.md @@ -21,8 +21,8 @@ Meta offers two ways for an app to read and answer Instagram direct messages: The owner chose the first way. What it requires, as read from Meta's documentation in December 2026: - **The account.** It must be an Instagram professional account (business or creator) linked to the Page. In the - Instagram app, *Allow access to messages* must be on (in December 2026 under *Settings and activity → Account - type and tools → Messaging tools → Message controls*). A creator account must make one Conversations API request before webhooks arrive. + Instagram app, *Settings → Messages and story replies → Message controls → Connected tools → Allow access to + messages* must be on. A creator account must make one Conversations API request before webhooks arrive. - **The token.** The Page access token also needs `instagram_basic` and `instagram_manage_messages`, on top of what Messenger asks for. `business_management` is a dependency of both. In a business portfolio, the system user must be given the Instagram account as well as the Page. @@ -47,30 +47,6 @@ The owner chose the first way. What it requires, as read from Meta's documentati Messenger customers with no role. Whether that holds for Instagram decides how hard setup is, so step 1 tests it first, as ADR-0027 did. -**Step 1 finding, 2 December 2026.** Tested on real Cloudflare with OpenChat's own Page, its linked Instagram business -account (@openchat.run) and the same published Meta app as Messenger's test, with no App Review and an unverified -business portfolio. Turning Instagram on worked: Meta named the account, and the Conversations API call succeeded, so -"Allow access to messages" was on. A direct message from an Instagram account linked to the app's admin reached the -webhook. Three from an account with no role on the app did not, neither while in the account's message requests nor -after the request was accepted. So, unlike Messenger, Instagram customers reach a business's own app only after Meta -grants Advanced Access to `instagram_manage_messages` through App Review, which needs business verification. Until -then only people with a role on the app get through, which is enough to build and test the next steps. - -**Step 2 note, 2 December 2026.** Two details differ from the Decision. `messenger_identities` gains a `channel` -column (migration 0043, expand only), so that export and the profile job tell an Instagram customer from a Messenger -one without depending on the connection, which can be removed. A message the customer unsends keeps its own Meta ID, so -the line saying so is keyed `unsent:`, or it would be taken for a repeat. Tested the same day on real Cloudflare -with an account that has a role on the app: a text, a photo, a reaction and an unsent message arrived, and the contact -was named from Meta's profile. The test found that Instagram's CDN redirects a request with no User-Agent, which is -what a Worker sends, to an "unsupported browser" page, so file downloads now send one. - -**Step 3 note, 2 December 2026.** Replies go with the Page's token to `POST /{page-id}/messages`, as on Messenger. -Instagram's read names one message and has no watermark, so everything sent before the read's time counts as read, and -a window refused by Meta comes as code 10, subcode 2534022. Past the window, a reply is refused with its own code, -`instagram_window_closed`. Tested the same day on real Cloudflare: a short reply and a 1,053-byte reply in Chinese, -which went as two parts, reached the customer and were marked Read when they opened the chat. A reply typed in the -Instagram app showed as sent from Instagram, and the echoes of OpenChat's own replies were not shown again. - ## Decision Instagram is an addition to a website's **Messenger connection**, not a separate connection. A business connects diff --git a/docs/guide/admin.md b/docs/guide/admin.md index 8acd9d5..4ee41e6 100644 --- a/docs/guide/admin.md +++ b/docs/guide/admin.md @@ -95,6 +95,21 @@ Each new customer becomes a contact, named from their Messenger profile when Met A Page can be connected to one website at a time. **Receive messages from this Page** turns it off without forgetting the keys. **Disconnect** unsubscribes the Page from the app, if Meta allows it, and deletes the keys. Each change is in the audit log. +### Connecting Instagram + +Direct messages to an Instagram account can reach the same website's inbox, through the Facebook Page the account is linked to ([ADR-0028](../architecture/decisions/0028-instagram-channel.md)). Connect Messenger first, as above: Instagram uses the Page's token and app. + +**Instagram messages do not reach the inbox yet.** This is step 1 of four: OpenChat checks the account and Meta's webhook reaches it, but the messages themselves arrive in a later step. + +1. The Instagram account must be a **professional** account (business or creator) linked to the Page. In the Instagram app, under **Settings and activity**, **Account type and tools**, **Messaging tools**, **Message controls**, turn on **Allow access to messages** (as of December 2026; Meta moves it from time to time). It is only in the phone app. +2. In [Business settings](https://business.facebook.com/settings), give the system user the Instagram account as well as the Page, and **Generate new token** again with `instagram_basic` and `instagram_manage_messages` added to the Messenger permissions (Meta adds `business_management` with them). Get the Page access token from it as before, and paste it on the website's **Messenger & Instagram** tab, replacing the old one. +3. Choose **Turn on Instagram**. OpenChat asks Meta for the account linked to the Page and checks that the token can read its messages. If Meta names no account, or refuses, it says which, and nothing changes. +4. In the Meta app, under **Instagram**, **Webhooks** (in some dashboards, **Messenger**, **Instagram settings**), add the same callback URL and verify token as for Messenger, and subscribe to `messages`, `messaging_seen`, `message_reactions`, `messaging_postbacks` and `messaging_referral`. + +**App Review is needed before customers get through.** Unlike Messenger, Meta sends Instagram messages from people with no role on the app only once the app has Advanced Access to `instagram_manage_messages`, granted through App Review, which needs your business to be verified ([test of 2 December 2026](../architecture/decisions/0028-instagram-channel.md)). Until then, only messages from people with a role on the app, such as its admins and testers, arrive. In the Meta app, open **App Review**, **Permissions and features**, and request Advanced Access to `instagram_manage_messages` (Meta also asks for `business_management`). + +An Instagram account can be connected to one website at a time. **Turn off Instagram** stops its messages without forgetting the account. Messenger cannot be turned off while Instagram is on. + ### Retention **Keep closed conversations** decides how long resolved and archived conversations stay: **Forever**, the default, or 30 days to two years after their last message. Once one is older, it is deleted with its messages and files, within the hour, and cannot be recovered from OpenChat. Contacts left with no conversations go too. Open and pending conversations are never deleted this way. Each run is in the audit log. diff --git a/docs/known-issues.md b/docs/known-issues.md index e176d8d..23cf3b6 100644 --- a/docs/known-issues.md +++ b/docs/known-issues.md @@ -47,6 +47,16 @@ To report a new problem, [open an issue](https://github.com/OpenChatRun/OpenChat - **The Page token needs `pages_read_engagement`** as well as `pages_messaging`, `pages_manage_metadata` and `pages_show_list`: without it Meta refuses to let a Page token read its own Page (error 100), found in that test. - **Its dashboard text was machine-translated**, like the rest. +## Instagram + +- **Only step 1 of [ADR-0028](architecture/decisions/0028-instagram-channel.md) is built:** an installation admin can turn on Instagram for the account linked to a website's Facebook Page, and Meta's webhook reaches OpenChat, which only counts what arrives. Instagram messages do not reach the inbox yet. +- **Customers get through only after Meta's App Review.** On 2 December 2026, with a published app and no review, a direct message from an account linked to the app's admin reached OpenChat, and three from an account with no role did not, even after its message request was accepted. Each business's Meta app needs Advanced Access to `instagram_manage_messages`, which needs App Review and business verification. A single Orango Labs app on Cloud, reviewed once, would spare businesses this; it is a separate decision. +- **A business needs a Facebook Page** linked to its Instagram professional account. Connecting with Instagram Login, which needs no Page, is a later decision. +- **Comments on posts are not in the inbox**, only direct messages. +- **GIFs and stickers a customer sends will never reach OpenChat:** Meta sends no webhook for them. +- **Replies will show Sent and Read, never Delivered:** Instagram has no delivery receipts. +- **Its dashboard text was machine-translated**, like the rest. + ## WhatsApp - **All four steps of [ADR-0026](architecture/decisions/0026-whatsapp-channel.md) are built:** an installation admin can connect a website's number, customers' messages reach the inbox, members and the assistant reply on WhatsApp, and the apps show it all. diff --git a/packages/api-contracts/generated/openapi.json b/packages/api-contracts/generated/openapi.json index 352f417..3b7ef3c 100644 --- a/packages/api-contracts/generated/openapi.json +++ b/packages/api-contracts/generated/openapi.json @@ -3935,6 +3935,33 @@ "type": "string", "description": "The verify token to paste with it. It only proves the webhook address to Meta." }, + "instagram": { + "type": [ + "object", + "null" + ], + "properties": { + "accountId": { + "type": "string" + }, + "username": { + "type": [ + "string", + "null" + ], + "description": "The account's username, as Meta gave it when it was last checked." + }, + "enabled": { + "type": "boolean" + } + }, + "required": [ + "accountId", + "username", + "enabled" + ], + "description": "The Instagram professional account linked to the Page, once Instagram has been turned on (ADR-0028, from API minor 11). Null until then. Its webhook uses the same `webhookUrl` and `verifyToken`, pasted into the Meta app's Instagram webhook settings." + }, "createdAt": { "type": "string" }, @@ -3949,6 +3976,7 @@ "enabled", "webhookUrl", "verifyToken", + "instagram", "createdAt", "updatedAt" ], @@ -11882,7 +11910,7 @@ ], "operationId": "saveMessenger", "summary": "Connect a website's Facebook Page for Messenger, or change it", - "description": "The token is checked with Meta, which must answer, before anything is kept: it must be a Page access token for that Page. To connect, accessToken and appSecret are required; afterwards they are given only to replace them. The Page is subscribed to the Meta app's webhook fields for messages, deliveries, reads and echoes.", + "description": "The token is checked with Meta, which must answer, before anything is kept: it must be a Page access token for that Page. To connect, accessToken and appSecret are required; afterwards they are given only to replace them. The Page is subscribed to the Meta app's webhook fields for messages, deliveries, reads and echoes. `instagram: true` (from API minor 11) asks Meta for the Instagram account linked to the Page and turns on its direct messages: 400 `instagram_not_linked` when the Page has none, 400 `instagram_permission_missing` when Meta will not let the token read its messages, and 409 `instagram_account_taken` when another website has it. It is refused with 400 `validation_failed` until the Page is connected. Messenger cannot be turned off while Instagram is on: 400 `instagram_needs_messenger`.", "parameters": [ { "schema": { @@ -11924,6 +11952,9 @@ }, "enabled": { "type": "boolean" + }, + "instagram": { + "type": "boolean" } }, "required": [ @@ -12073,7 +12104,7 @@ "messenger" ], "operationId": "receiveMessengerWebhook", - "summary": "Messages and receipts from Meta for a Messenger connection", + "summary": "Messages and receipts from Meta for a Messenger connection, and for its Instagram account", "description": "The body is Meta's JSON, at most 1 MB, signed with the Meta app's secret in `X-Hub-Signature-256`. It is not described here, because it is read only after the signature over the raw bytes is checked.", "security": [], "parameters": [ diff --git a/packages/api-contracts/src/routes.ts b/packages/api-contracts/src/routes.ts index 2b7fc58..892d798 100644 --- a/packages/api-contracts/src/routes.ts +++ b/packages/api-contracts/src/routes.ts @@ -98,8 +98,9 @@ export const getSecurityTxtRoute = createRoute({ * - 9: `messenger` as a conversation's `channel`, and `messenger` on a message (ADR-0027 step 2). * - 10: replies on Messenger: `messengerWindowEndsAt` on a conversation, `messenger.delivery`, `messenger.error` and * `messenger.echo` on a message, and retryMessengerMessage (ADR-0027 step 3). + * - 11: `instagram` on a Messenger connection, to turn on Instagram direct messages (ADR-0028). */ -export const API_MINOR_VERSION = 10; +export const API_MINOR_VERSION = 11; // ---------- Authentication ---------- @@ -1907,6 +1908,17 @@ export const MessengerConnectionSchema = z enabled: z.boolean(), webhookUrl: z.string().openapi({ description: "The callback URL to paste into the Meta app's Messenger webhook settings." }), verifyToken: z.string().openapi({ description: 'The verify token to paste with it. It only proves the webhook address to Meta.' }), + instagram: z + .object({ + accountId: z.string(), + username: z.string().nullable().openapi({ description: "The account's username, as Meta gave it when it was last checked." }), + enabled: z.boolean(), + }) + .nullable() + .openapi({ + description: + "The Instagram professional account linked to the Page, once Instagram has been turned on (ADR-0028, from API minor 11). Null until then. Its webhook uses the same `webhookUrl` and `verifyToken`, pasted into the Meta app's Instagram webhook settings.", + }), createdAt: z.string(), updatedAt: z.string(), }) @@ -1929,10 +1941,13 @@ export const saveMessengerRoute = createRoute({ operationId: 'saveMessenger', summary: "Connect a website's Facebook Page for Messenger, or change it", description: - "The token is checked with Meta, which must answer, before anything is kept: it must be a Page access token for that Page. To connect, accessToken and appSecret are required; afterwards they are given only to replace them. The Page is subscribed to the Meta app's webhook fields for messages, deliveries, reads and echoes.", + "The token is checked with Meta, which must answer, before anything is kept: it must be a Page access token for that Page. To connect, accessToken and appSecret are required; afterwards they are given only to replace them. The Page is subscribed to the Meta app's webhook fields for messages, deliveries, reads and echoes. `instagram: true` (from API minor 11) asks Meta for the Instagram account linked to the Page and turns on its direct messages: 400 `instagram_not_linked` when the Page has none, 400 `instagram_permission_missing` when Meta will not let the token read its messages, and 409 `instagram_account_taken` when another website has it. It is refused with 400 `validation_failed` until the Page is connected. Messenger cannot be turned off while Instagram is on: 400 `instagram_needs_messenger`.", request: { params: websiteParams, - body: { required: true, ...json(z.strictObject({ pageId: GraphId, accessToken: MetaSecret.optional(), appSecret: MetaSecret.optional(), enabled: z.boolean().optional() })) }, + body: { + required: true, + ...json(z.strictObject({ pageId: GraphId, accessToken: MetaSecret.optional(), appSecret: MetaSecret.optional(), enabled: z.boolean().optional(), instagram: z.boolean().optional() })), + }, }, responses: { 200: { description: 'Saved', ...json(MessengerConnectionSchema) }, default: problemResponse }, }); @@ -1976,7 +1991,7 @@ export const receiveMessengerWebhookRoute = createRoute({ path: '/api/v1/messenger/webhook/{connectionId}', tags: ['messenger'], operationId: 'receiveMessengerWebhook', - summary: 'Messages and receipts from Meta for a Messenger connection', + summary: 'Messages and receipts from Meta for a Messenger connection, and for its Instagram account', description: "The body is Meta's JSON, at most 1 MB, signed with the Meta app's secret in `X-Hub-Signature-256`. It is not described here, because it is read only after the signature over the raw bytes is checked.", security: [], request: { params: z.object({ connectionId: z.string() }), headers: z.object({ 'x-hub-signature-256': z.string().optional() }) }, diff --git a/packages/core/src/messenger.ts b/packages/core/src/messenger.ts index 3a70799..f782341 100644 --- a/packages/core/src/messenger.ts +++ b/packages/core/src/messenger.ts @@ -79,6 +79,44 @@ async function checkWithMeta(fetcher: Fetcher, input: { accessToken: string; pag return { pageName: typeof me.name === 'string' && me.name.length > 0 ? me.name.slice(0, 200) : null }; } +// ---------- Instagram (ADR-0028) ---------- + +const instagramPermissionMissing = () => + new AppError( + 400, + 'instagram_permission_missing', + 'Meta did not let this token read Instagram messages. Give it instagram_basic and instagram_manage_messages, give the system user the Instagram account, and turn on "Allow access to messages" in the Instagram app', + ); + +/** Meta's refusals of the Instagram calls. A bad token is still the token's fault; anything else the admin fixes in Meta. */ +async function instagramGraphFailure(response: Response): Promise { + if (response.status >= 500) return messengerGraphFailure(response); + const code = await graphErrorCode(response.clone()); + if (response.status === 401 || code === 190 || code === 102) return messengerGraphFailure(response); + createLogger().warn('instagram_graph_refused', { status: response.status, ...(code !== undefined ? { errorCode: String(code) } : {}) }); + return instagramPermissionMissing(); +} + +const instagramGraph = (fetcher: Fetcher, accessToken: string, path: string): Promise => + callGraph(fetcher, accessToken, path, {}, instagramGraphFailure, () => new AppError(503, 'messenger_unavailable', 'Meta could not be reached just now. Try again'), 'messenger'); + +/** + * The Instagram professional account linked to the Page, proved able to read direct messages: the Conversations API is + * asked for one conversation, which needs instagram_manage_messages and "Allow access to messages". Meta also asks a + * creator account to make that request once before it sends webhooks. + */ +async function linkedInstagram(fetcher: Fetcher, accessToken: string, pageId: string): Promise<{ accountId: string; username: string | null }> { + const page = (await instagramGraph(fetcher, accessToken, `${pageId}?fields=instagram_business_account%7Bid,username%7D`)) as { instagram_business_account?: { id?: unknown; username?: unknown } }; + const account = page.instagram_business_account; + const accountId = typeof account?.id === 'string' && GRAPH_ID.test(account.id) ? account.id : null; + if (!accountId) { + throw new AppError(400, 'instagram_not_linked', 'Meta named no Instagram professional account linked to this Page. Link one in the Page settings, and check that the token has instagram_basic'); + } + await instagramGraph(fetcher, accessToken, `${pageId}/conversations?platform=instagram&limit=1`); + const username = typeof account?.username === 'string' && account.username.length > 0 ? account.username.slice(0, 100) : null; + return { accountId, username }; +} + // ---------- What the admin sees ---------- export const messengerWebhookUrl = (publicBaseUrl: string, connectionId: string) => `${publicBaseUrl.replace(/\/+$/, '')}/api/v1/messenger/webhook/${connectionId}`; @@ -92,6 +130,7 @@ async function toView(keys: DataKeys, row: MessengerConnectionWithSecrets, publi webhookUrl: messengerWebhookUrl(publicBaseUrl, row.id), // Shown again so the admin can paste it into Meta at any time. It only proves the webhook address to Meta. verifyToken: await openMessengerSecret(keys, row, 'verifyToken'), + instagram: row.instagram, createdAt: toIso(row.createdAt), updatedAt: toIso(row.updatedAt), }; @@ -116,9 +155,13 @@ export interface MessengerInput { accessToken?: string | undefined; appSecret?: string | undefined; enabled?: boolean | undefined; + /** Instagram direct messages through the account linked to the Page (ADR-0028). */ + instagram?: boolean | undefined; } const pageTaken = () => new AppError(409, 'messenger_page_taken', 'This Page is already connected to a website'); +const instagramTaken = () => new AppError(409, 'instagram_account_taken', 'This Instagram account is already connected to a website'); +const instagramNeedsMessenger = () => new AppError(400, 'instagram_needs_messenger', 'Instagram uses the Page connection, so turn Instagram off before turning Messenger off'); /** Connects the website's Page, or changes it. Meta is asked again whenever the Page or its token change. */ export async function saveMessenger(deps: MessengerDeps, ctx: AdminContext, workspaceId: string, websiteId: string, input: MessengerInput) { @@ -128,6 +171,8 @@ export async function saveMessenger(deps: MessengerDeps, ctx: AdminContext, work const existing = await repo.get(workspaceId, websiteId); if (!existing) { + // Instagram is turned on once the Page is connected, so that a refusal from Meta does not lose the Page. + if (input.instagram) throw new AppError(400, 'validation_failed', 'Connect the Page first, then turn on Instagram'); if (!input.accessToken || !input.appSecret) throw new AppError(400, 'messenger_keys_required', 'A Page access token and the app secret are needed to connect'); const id = newId('messengerConnection'); const display = await checkWithMeta(deps.fetcher, { accessToken: input.accessToken, pageId: input.pageId }); @@ -149,14 +194,27 @@ export async function saveMessenger(deps: MessengerDeps, ctx: AdminContext, work const display = recheck ? await checkWithMeta(deps.fetcher, { accessToken: next.accessToken, pageId: input.pageId }) : {}; // Sealed again with the active key when anything secret changed, or the row predates the active key. const reseal = next.accessToken !== current.accessToken || next.appSecret !== current.appSecret || existing.sealed.keyVersion !== keys.active.version; + + // Instagram stays on unless turned off, and is asked about again whenever it is turned on or the Page or token change. + const instagramOn = input.instagram ?? existing.instagram?.enabled ?? false; + if (instagramOn && (input.enabled ?? existing.enabled) === false) throw instagramNeedsMessenger(); + const askInstagram = instagramOn && (recheck || existing.instagram?.enabled !== true); + const instagram = askInstagram + ? ({ ...(await linkedInstagram(deps.fetcher, next.accessToken, input.pageId)), enabled: true } as const) + : input.instagram === false && existing.instagram?.enabled + ? ({ enabled: false } as const) + : undefined; + const row = await repo.update(workspaceId, websiteId, { pageId: input.pageId, enabled: input.enabled, ...display, + instagram, sealed: reseal ? await sealAll(keys, workspaceId, existing.id, next) : undefined, }); if (row === 'not_found') throw notFound(); if (row === 'page_taken') throw pageTaken(); + if (row === 'instagram_taken') throw instagramTaken(); return toView(keys, row, deps.publicBaseUrl); } @@ -181,6 +239,30 @@ export async function deleteMessenger(deps: MessengerDeps, ctx: AdminContext, wo // ---------- Meta's webhook ---------- +/** + * What an Instagram webhook body for this connection carries, counted by kind for the log (ADR-0028 step 1: nothing is + * stored yet). Null when it is not for this connection's Instagram account, or Instagram is off. + */ +export function countInstagramWebhook(connection: Pick, body: unknown): Record | null { + const root = typeof body === 'object' && body !== null ? (body as { object?: unknown; entry?: unknown }) : null; + const account = connection.instagram; + if (root?.object !== 'instagram' || !account?.enabled) return null; + const counts: Record = {}; + let matched = false; + for (const entry of Array.isArray(root.entry) ? root.entry : []) { + const e = typeof entry === 'object' && entry !== null ? (entry as { id?: unknown; messaging?: unknown }) : null; + if (e?.id !== account.accountId) continue; + matched = true; + for (const raw of Array.isArray(e.messaging) ? e.messaging.slice(0, 1000) : []) { + const event = typeof raw === 'object' && raw !== null ? (raw as Record) : {}; + const message = typeof event.message === 'object' && event.message !== null ? (event.message as Record) : null; + const kind = message ? (message.is_echo === true ? 'echo' : 'message') : (['read', 'reaction', 'postback', 'referral'].find((k) => k in event) ?? 'other'); + counts[kind] = (counts[kind] ?? 0) + 1; + } + } + return matched ? counts : null; +} + /** Meta's subscription check: `hub.mode=subscribe` with the verify token the admin pasted. */ export async function acceptsMessengerChallenge(keys: DataKeys, connection: MessengerConnectionWithSecrets, mode: string | undefined, token: string | undefined): Promise { if (mode !== 'subscribe' || !token) return false; diff --git a/packages/database/migrations/0042_instagram.sql b/packages/database/migrations/0042_instagram.sql new file mode 100644 index 0000000..05bbb17 --- /dev/null +++ b/packages/database/migrations/0042_instagram.sql @@ -0,0 +1,6 @@ +-- Instagram direct messages on a Messenger connection (ADR-0028). Columns added nullable or with a default, so the +-- previous Worker reads and writes connections as before. +ALTER TABLE `messenger_connections` ADD `instagram_account_id` text;--> statement-breakpoint +ALTER TABLE `messenger_connections` ADD `instagram_username` text;--> statement-breakpoint +ALTER TABLE `messenger_connections` ADD `instagram_enabled` integer DEFAULT false NOT NULL;--> statement-breakpoint +CREATE UNIQUE INDEX `messenger_connections_instagram_account_id_unique` ON `messenger_connections` (`instagram_account_id`); \ No newline at end of file diff --git a/packages/database/migrations/meta/0042_snapshot.json b/packages/database/migrations/meta/0042_snapshot.json new file mode 100644 index 0000000..7876c0d --- /dev/null +++ b/packages/database/migrations/meta/0042_snapshot.json @@ -0,0 +1,6119 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "b8de87a9-d187-4a3a-9ddb-0335cb20e0c1", + "prevId": "381677e7-bbee-4c38-ab30-125bc2a374a2", + "tables": { + "assistant_chunks": { + "name": "assistant_chunks", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "assistant_chunks_source_idx": { + "name": "assistant_chunks_source_idx", + "columns": [ + "workspace_id", + "source_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "assistant_chunks_source_fk": { + "name": "assistant_chunks_source_fk", + "tableFrom": "assistant_chunks", + "tableTo": "assistant_sources", + "columnsFrom": [ + "workspace_id", + "source_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "assistant_learned": { + "name": "assistant_learned", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conversation_id": { + "name": "conversation_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "question": { + "name": "question", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "discard_reason": { + "name": "discard_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "learned_seq": { + "name": "learned_seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "indexed_generation": { + "name": "indexed_generation", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_by_member_id": { + "name": "decided_by_member_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_at": { + "name": "decided_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "assistant_learned_website_idx": { + "name": "assistant_learned_website_idx", + "columns": [ + "workspace_id", + "website_id", + "status" + ], + "isUnique": false + }, + "assistant_learned_conversation_uq": { + "name": "assistant_learned_conversation_uq", + "columns": [ + "workspace_id", + "conversation_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "assistant_learned_conversation_fk": { + "name": "assistant_learned_conversation_fk", + "tableFrom": "assistant_learned", + "tableTo": "conversations", + "columnsFrom": [ + "workspace_id", + "conversation_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "assistant_learned_website_fk": { + "name": "assistant_learned_website_fk", + "tableFrom": "assistant_learned", + "tableTo": "websites", + "columnsFrom": [ + "workspace_id", + "website_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "assistant_learned_status_ck": { + "name": "assistant_learned_status_ck", + "value": "\"assistant_learned\".\"status\" IN ('pending','approved','rejected','discarded')" + } + } + }, + "assistant_question_reviews": { + "name": "assistant_question_reviews", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "member_id": { + "name": "member_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "assistant_question_reviews_message_fk": { + "name": "assistant_question_reviews_message_fk", + "tableFrom": "assistant_question_reviews", + "tableTo": "messages", + "columnsFrom": [ + "workspace_id", + "message_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "assistant_question_reviews_pk": { + "columns": [ + "workspace_id", + "message_id" + ], + "name": "assistant_question_reviews_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": { + "assistant_question_reviews_outcome_ck": { + "name": "assistant_question_reviews_outcome_ck", + "value": "\"assistant_question_reviews\".\"outcome\" IN ('answered','dismissed')" + } + } + }, + "assistant_settings": { + "name": "assistant_settings", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "learn": { + "name": "learn", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "instructions": { + "name": "instructions", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "handover_message": { + "name": "handover_message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "assistant_settings_tenant_uq": { + "name": "assistant_settings_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + }, + "assistant_settings_website_uq": { + "name": "assistant_settings_website_uq", + "columns": [ + "workspace_id", + "website_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "assistant_settings_website_fk": { + "name": "assistant_settings_website_fk", + "tableFrom": "assistant_settings", + "tableTo": "websites", + "columnsFrom": [ + "workspace_id", + "website_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "assistant_sources": { + "name": "assistant_sources", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "indexed_generation": { + "name": "indexed_generation", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "chunk_count": { + "name": "chunk_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "page_count": { + "name": "page_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "indexed_at": { + "name": "indexed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "assistant_sources_website_idx": { + "name": "assistant_sources_website_idx", + "columns": [ + "workspace_id", + "website_id" + ], + "isUnique": false + }, + "assistant_sources_refresh_idx": { + "name": "assistant_sources_refresh_idx", + "columns": [ + "indexed_at" + ], + "isUnique": false, + "where": "\"assistant_sources\".\"kind\" = 'page'" + }, + "assistant_sources_tenant_uq": { + "name": "assistant_sources_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "assistant_sources_website_fk": { + "name": "assistant_sources_website_fk", + "tableFrom": "assistant_sources", + "tableTo": "websites", + "columnsFrom": [ + "workspace_id", + "website_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "assistant_sources_kind_ck": { + "name": "assistant_sources_kind_ck", + "value": "\"assistant_sources\".\"kind\" IN ('page','text')" + }, + "assistant_sources_status_ck": { + "name": "assistant_sources_status_ck", + "value": "\"assistant_sources\".\"status\" IN ('pending','indexing','ready','failed')" + }, + "assistant_sources_shape_ck": { + "name": "assistant_sources_shape_ck", + "value": "(\"assistant_sources\".\"kind\" = 'page') = (\"assistant_sources\".\"url\" IS NOT NULL) AND (\"assistant_sources\".\"kind\" = 'text') = (\"assistant_sources\".\"content\" IS NOT NULL)" + } + } + }, + "assistant_usage": { + "name": "assistant_usage", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "day": { + "name": "day", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "answers": { + "name": "answers", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "pages": { + "name": "pages", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "chunks": { + "name": "chunks", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "translated_chars": { + "name": "translated_chars", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": {}, + "foreignKeys": { + "assistant_usage_workspace_id_workspaces_id_fk": { + "name": "assistant_usage_workspace_id_workspaces_id_fk", + "tableFrom": "assistant_usage", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "assistant_usage_pk": { + "columns": [ + "workspace_id", + "day" + ], + "name": "assistant_usage_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "attachments": { + "name": "attachments", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conversation_id": { + "name": "conversation_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "storage_key": { + "name": "storage_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "filename": { + "name": "filename", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content_type": { + "name": "content_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "uploaded_by_type": { + "name": "uploaded_by_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "uploaded_by_id": { + "name": "uploaded_by_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "attachments_storage_key_unique": { + "name": "attachments_storage_key_unique", + "columns": [ + "storage_key" + ], + "isUnique": true + }, + "attachments_message_idx": { + "name": "attachments_message_idx", + "columns": [ + "workspace_id", + "message_id" + ], + "isUnique": false + }, + "attachments_conversation_idx": { + "name": "attachments_conversation_idx", + "columns": [ + "workspace_id", + "conversation_id" + ], + "isUnique": false + }, + "attachments_orphan_idx": { + "name": "attachments_orphan_idx", + "columns": [ + "created_at" + ], + "isUnique": false, + "where": "\"attachments\".\"message_id\" IS NULL" + }, + "attachments_tenant_uq": { + "name": "attachments_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "attachments_conversation_fk": { + "name": "attachments_conversation_fk", + "tableFrom": "attachments", + "tableTo": "conversations", + "columnsFrom": [ + "workspace_id", + "conversation_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "attachments_message_fk": { + "name": "attachments_message_fk", + "tableFrom": "attachments", + "tableTo": "messages", + "columnsFrom": [ + "workspace_id", + "message_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "attachments_size_ck": { + "name": "attachments_size_ck", + "value": "\"attachments\".\"size\" > 0" + }, + "attachments_status_ck": { + "name": "attachments_status_ck", + "value": "\"attachments\".\"status\" IN ('pending','ready','rejected')" + }, + "attachments_uploader_ck": { + "name": "attachments_uploader_ck", + "value": "\"attachments\".\"uploaded_by_type\" IN ('visitor','member')" + } + } + }, + "audit_log": { + "name": "audit_log", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_type": { + "name": "actor_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata_json": { + "name": "metadata_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "audit_log_idx": { + "name": "audit_log_idx", + "columns": [ + "workspace_id", + "\"created_at\" DESC", + "\"id\" DESC" + ], + "isUnique": false + }, + "audit_log_recent_idx": { + "name": "audit_log_recent_idx", + "columns": [ + "\"created_at\" DESC", + "\"id\" DESC" + ], + "isUnique": false + } + }, + "foreignKeys": { + "audit_log_workspace_id_workspaces_id_fk": { + "name": "audit_log_workspace_id_workspaces_id_fk", + "tableFrom": "audit_log", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "auth_sessions": { + "name": "auth_sessions", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "refresh_token_hash": { + "name": "refresh_token_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "previous_token_hash": { + "name": "previous_token_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "client_type": { + "name": "client_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_label": { + "name": "client_label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "auth_sessions_refresh_token_hash_unique": { + "name": "auth_sessions_refresh_token_hash_unique", + "columns": [ + "refresh_token_hash" + ], + "isUnique": true + }, + "auth_sessions_user_idx": { + "name": "auth_sessions_user_idx", + "columns": [ + "user_id", + "revoked_at" + ], + "isUnique": false + }, + "auth_sessions_expiry_idx": { + "name": "auth_sessions_expiry_idx", + "columns": [ + "expires_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "auth_sessions_user_id_users_id_fk": { + "name": "auth_sessions_user_id_users_id_fk", + "tableFrom": "auth_sessions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "auth_sessions_client_ck": { + "name": "auth_sessions_client_ck", + "value": "\"auth_sessions\".\"client_type\" IN ('dashboard','mobile')" + } + } + }, + "auth_tokens": { + "name": "auth_tokens", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "purpose": { + "name": "purpose", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "consumed_at": { + "name": "consumed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "consumed_by": { + "name": "consumed_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "auth_tokens_expiry_idx": { + "name": "auth_tokens_expiry_idx", + "columns": [ + "expires_at" + ], + "isUnique": false + }, + "auth_tokens_user_idx": { + "name": "auth_tokens_user_idx", + "columns": [ + "user_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "auth_tokens_user_id_users_id_fk": { + "name": "auth_tokens_user_id_users_id_fk", + "tableFrom": "auth_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "auth_tokens_purpose_ck": { + "name": "auth_tokens_purpose_ck", + "value": "\"auth_tokens\".\"purpose\" IN ('password_reset','email_verification')" + } + } + }, + "automation_rules": { + "name": "automation_rules", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "trigger_type": { + "name": "trigger_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conditions_json": { + "name": "conditions_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "actions_json": { + "name": "actions_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "automation_rules_trigger_idx": { + "name": "automation_rules_trigger_idx", + "columns": [ + "workspace_id", + "trigger_type", + "enabled" + ], + "isUnique": false + }, + "automation_rules_tenant_uq": { + "name": "automation_rules_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "automation_rules_workspace_id_workspaces_id_fk": { + "name": "automation_rules_workspace_id_workspaces_id_fk", + "tableFrom": "automation_rules", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "automation_runs": { + "name": "automation_runs", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "rule_id": { + "name": "rule_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conversation_id": { + "name": "conversation_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "trigger_key": { + "name": "trigger_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "automation_runs_conversation_idx": { + "name": "automation_runs_conversation_idx", + "columns": [ + "workspace_id", + "conversation_id" + ], + "isUnique": false + }, + "automation_runs_dedupe_uq": { + "name": "automation_runs_dedupe_uq", + "columns": [ + "workspace_id", + "rule_id", + "conversation_id", + "trigger_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "automation_runs_rule_fk": { + "name": "automation_runs_rule_fk", + "tableFrom": "automation_runs", + "tableTo": "automation_rules", + "columnsFrom": [ + "workspace_id", + "rule_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "automation_runs_conversation_fk": { + "name": "automation_runs_conversation_fk", + "tableFrom": "automation_runs", + "tableTo": "conversations", + "columnsFrom": [ + "workspace_id", + "conversation_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "contact_tags": { + "name": "contact_tags", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "contact_id": { + "name": "contact_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tag_id": { + "name": "tag_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "contact_tags_tag_idx": { + "name": "contact_tags_tag_idx", + "columns": [ + "workspace_id", + "tag_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "contact_tags_contact_fk": { + "name": "contact_tags_contact_fk", + "tableFrom": "contact_tags", + "tableTo": "contacts", + "columnsFrom": [ + "workspace_id", + "contact_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "contact_tags_tag_fk": { + "name": "contact_tags_tag_fk", + "tableFrom": "contact_tags", + "tableTo": "tags", + "columnsFrom": [ + "workspace_id", + "tag_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "contact_tags_workspace_id_contact_id_tag_id_pk": { + "columns": [ + "workspace_id", + "contact_id", + "tag_id" + ], + "name": "contact_tags_workspace_id_contact_id_tag_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "contacts": { + "name": "contacts", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text COLLATE NOCASE", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "phone": { + "name": "phone", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "attributes_json": { + "name": "attributes_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'{}'" + }, + "follow_up_consent_at": { + "name": "follow_up_consent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "follow_up_consent_source": { + "name": "follow_up_consent_source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "merged_into_contact_id": { + "name": "merged_into_contact_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "first_seen_at": { + "name": "first_seen_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "contacts_email_idx": { + "name": "contacts_email_idx", + "columns": [ + "workspace_id", + "email" + ], + "isUnique": false, + "where": "\"contacts\".\"email\" IS NOT NULL" + }, + "contacts_list_idx": { + "name": "contacts_list_idx", + "columns": [ + "workspace_id", + "\"last_seen_at\" DESC", + "\"id\" DESC" + ], + "isUnique": false + }, + "contacts_stale_idx": { + "name": "contacts_stale_idx", + "columns": [ + "last_seen_at" + ], + "isUnique": false + }, + "contacts_merged_idx": { + "name": "contacts_merged_idx", + "columns": [ + "workspace_id", + "merged_into_contact_id" + ], + "isUnique": false, + "where": "\"contacts\".\"merged_into_contact_id\" IS NOT NULL" + }, + "contacts_tenant_uq": { + "name": "contacts_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "contacts_workspace_id_workspaces_id_fk": { + "name": "contacts_workspace_id_workspaces_id_fk", + "tableFrom": "contacts", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "contacts_merged_fk": { + "name": "contacts_merged_fk", + "tableFrom": "contacts", + "tableTo": "contacts", + "columnsFrom": [ + "workspace_id", + "merged_into_contact_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "conversation_events": { + "name": "conversation_events", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conversation_id": { + "name": "conversation_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "actor_type": { + "name": "actor_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata_json": { + "name": "metadata_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "conversation_events_idx": { + "name": "conversation_events_idx", + "columns": [ + "workspace_id", + "conversation_id", + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "conversation_events_conversation_fk": { + "name": "conversation_events_conversation_fk", + "tableFrom": "conversation_events", + "tableTo": "conversations", + "columnsFrom": [ + "workspace_id", + "conversation_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "conversation_events_actor_ck": { + "name": "conversation_events_actor_ck", + "value": "\"conversation_events\".\"actor_type\" IN ('visitor','member','system')" + } + } + }, + "conversation_read_cursors": { + "name": "conversation_read_cursors", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conversation_id": { + "name": "conversation_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reader_type": { + "name": "reader_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reader_id": { + "name": "reader_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "delivered_seq": { + "name": "delivered_seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "read_seq": { + "name": "read_seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "read_cursors_conversation_fk": { + "name": "read_cursors_conversation_fk", + "tableFrom": "conversation_read_cursors", + "tableTo": "conversations", + "columnsFrom": [ + "workspace_id", + "conversation_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "conversation_read_cursors_workspace_id_conversation_id_reader_type_reader_id_pk": { + "columns": [ + "workspace_id", + "conversation_id", + "reader_type", + "reader_id" + ], + "name": "conversation_read_cursors_workspace_id_conversation_id_reader_type_reader_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": { + "read_cursors_reader_ck": { + "name": "read_cursors_reader_ck", + "value": "\"conversation_read_cursors\".\"reader_type\" IN ('visitor','member')" + } + } + }, + "conversation_tags": { + "name": "conversation_tags", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conversation_id": { + "name": "conversation_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tag_id": { + "name": "tag_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "conversation_tags_tag_idx": { + "name": "conversation_tags_tag_idx", + "columns": [ + "workspace_id", + "tag_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "conversation_tags_conversation_fk": { + "name": "conversation_tags_conversation_fk", + "tableFrom": "conversation_tags", + "tableTo": "conversations", + "columnsFrom": [ + "workspace_id", + "conversation_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "conversation_tags_tag_fk": { + "name": "conversation_tags_tag_fk", + "tableFrom": "conversation_tags", + "tableTo": "tags", + "columnsFrom": [ + "workspace_id", + "tag_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "conversation_tags_workspace_id_conversation_id_tag_id_pk": { + "columns": [ + "workspace_id", + "conversation_id", + "tag_id" + ], + "name": "conversation_tags_workspace_id_conversation_id_tag_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "conversations": { + "name": "conversations", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "contact_id": { + "name": "contact_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "assigned_member_id": { + "name": "assigned_member_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'open'" + }, + "priority": { + "name": "priority", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'normal'" + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_message_seq": { + "name": "last_message_seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "last_public_seq": { + "name": "last_public_seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "last_message_at": { + "name": "last_message_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_visitor_message_at": { + "name": "last_visitor_message_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_agent_message_at": { + "name": "last_agent_message_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_automation_at": { + "name": "next_automation_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_unanswered_alert_at": { + "name": "next_unanswered_alert_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "last_mutation_id": { + "name": "last_mutation_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "assistant_state": { + "name": "assistant_state", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "help_article_id": { + "name": "help_article_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "visitor_language": { + "name": "visitor_language", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "visitor_page_url": { + "name": "visitor_page_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "visitor_page_at": { + "name": "visitor_page_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "visitor_rating": { + "name": "visitor_rating", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "visitor_rating_comment": { + "name": "visitor_rating_comment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "visitor_rated_at": { + "name": "visitor_rated_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "channel": { + "name": "channel", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'web'" + }, + "channel_kind": { + "name": "channel_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "conversations_inbox_idx": { + "name": "conversations_inbox_idx", + "columns": [ + "workspace_id", + "status", + "\"last_message_at\" DESC", + "\"id\" DESC" + ], + "isUnique": false + }, + "conversations_assignee_idx": { + "name": "conversations_assignee_idx", + "columns": [ + "workspace_id", + "assigned_member_id", + "status", + "\"last_message_at\" DESC", + "\"id\" DESC" + ], + "isUnique": false + }, + "conversations_contact_idx": { + "name": "conversations_contact_idx", + "columns": [ + "workspace_id", + "contact_id", + "\"last_message_at\" DESC" + ], + "isUnique": false + }, + "conversations_automation_idx": { + "name": "conversations_automation_idx", + "columns": [ + "next_automation_at" + ], + "isUnique": false, + "where": "\"conversations\".\"next_automation_at\" IS NOT NULL" + }, + "conversations_unanswered_idx": { + "name": "conversations_unanswered_idx", + "columns": [ + "next_unanswered_alert_at" + ], + "isUnique": false, + "where": "\"conversations\".\"next_unanswered_alert_at\" IS NOT NULL" + }, + "conversations_updated_idx": { + "name": "conversations_updated_idx", + "columns": [ + "workspace_id", + "updated_at", + "id" + ], + "isUnique": false + }, + "conversations_website_idx": { + "name": "conversations_website_idx", + "columns": [ + "workspace_id", + "website_id" + ], + "isUnique": false + }, + "conversations_created_idx": { + "name": "conversations_created_idx", + "columns": [ + "workspace_id", + "created_at" + ], + "isUnique": false + }, + "conversations_tenant_uq": { + "name": "conversations_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "conversations_workspace_id_workspaces_id_fk": { + "name": "conversations_workspace_id_workspaces_id_fk", + "tableFrom": "conversations", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "conversations_website_fk": { + "name": "conversations_website_fk", + "tableFrom": "conversations", + "tableTo": "websites", + "columnsFrom": [ + "workspace_id", + "website_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "conversations_contact_fk": { + "name": "conversations_contact_fk", + "tableFrom": "conversations", + "tableTo": "contacts", + "columnsFrom": [ + "workspace_id", + "contact_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "conversations_assignee_fk": { + "name": "conversations_assignee_fk", + "tableFrom": "conversations", + "tableTo": "workspace_members", + "columnsFrom": [ + "workspace_id", + "assigned_member_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "conversations_status_ck": { + "name": "conversations_status_ck", + "value": "\"conversations\".\"status\" IN ('open','pending','resolved','archived')" + }, + "conversations_priority_ck": { + "name": "conversations_priority_ck", + "value": "\"conversations\".\"priority\" IN ('low','normal','high','urgent')" + } + } + }, + "email_deliveries": { + "name": "email_deliveries", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "template": { + "name": "template", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "recipient_hash": { + "name": "recipient_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider_message_id": { + "name": "provider_message_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "email_deliveries_dedupe_uq": { + "name": "email_deliveries_dedupe_uq", + "columns": [ + "workspace_id", + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "email_deliveries_workspace_id_workspaces_id_fk": { + "name": "email_deliveries_workspace_id_workspaces_id_fk", + "tableFrom": "email_deliveries", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "email_deliveries_status_ck": { + "name": "email_deliveries_status_ck", + "value": "\"email_deliveries\".\"status\" IN ('claimed','sent','failed','suppressed')" + } + } + }, + "email_settings": { + "name": "email_settings", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sender_name": { + "name": "sender_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sender_email": { + "name": "sender_email", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "configuration_enc": { + "name": "configuration_enc", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key_version": { + "name": "key_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "email_settings_workspace_id_workspaces_id_fk": { + "name": "email_settings_workspace_id_workspaces_id_fk", + "tableFrom": "email_settings", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "email_suppressions": { + "name": "email_suppressions", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text COLLATE NOCASE", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "email_suppressions_workspace_id_workspaces_id_fk": { + "name": "email_suppressions_workspace_id_workspaces_id_fk", + "tableFrom": "email_suppressions", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "email_suppressions_workspace_id_email_pk": { + "columns": [ + "workspace_id", + "email" + ], + "name": "email_suppressions_workspace_id_email_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": { + "email_suppressions_reason_ck": { + "name": "email_suppressions_reason_ck", + "value": "\"email_suppressions\".\"reason\" IN ('unsubscribe','bounce','complaint','manual')" + } + } + }, + "email_unsubscribe_links": { + "name": "email_unsubscribe_links", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text COLLATE NOCASE", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "email_unsubscribe_links_email_idx": { + "name": "email_unsubscribe_links_email_idx", + "columns": [ + "workspace_id", + "email" + ], + "isUnique": false + } + }, + "foreignKeys": { + "email_unsubscribe_links_workspace_id_workspaces_id_fk": { + "name": "email_unsubscribe_links_workspace_id_workspaces_id_fk", + "tableFrom": "email_unsubscribe_links", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "failed_jobs": { + "name": "failed_jobs", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "queue": { + "name": "queue", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "job_type": { + "name": "job_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "envelope_json": { + "name": "envelope_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "failed_at": { + "name": "failed_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "replayed_at": { + "name": "replayed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "failed_jobs_recent_idx": { + "name": "failed_jobs_recent_idx", + "columns": [ + "\"failed_at\" DESC" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "google_app_codes": { + "name": "google_app_codes", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "challenge": { + "name": "challenge", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "google_app_codes_user_idx": { + "name": "google_app_codes_user_idx", + "columns": [ + "user_id" + ], + "isUnique": false + }, + "google_app_codes_expiry_idx": { + "name": "google_app_codes_expiry_idx", + "columns": [ + "expires_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "google_app_codes_user_id_users_id_fk": { + "name": "google_app_codes_user_id_users_id_fk", + "tableFrom": "google_app_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "help_article_chunks": { + "name": "help_article_chunks", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "article_id": { + "name": "article_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "help_article_chunks_article_idx": { + "name": "help_article_chunks_article_idx", + "columns": [ + "workspace_id", + "article_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "help_article_chunks_article_fk": { + "name": "help_article_chunks_article_fk", + "tableFrom": "help_article_chunks", + "tableTo": "help_articles", + "columnsFrom": [ + "workspace_id", + "article_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "help_article_stats": { + "name": "help_article_stats", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "article_id": { + "name": "article_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "views": { + "name": "views", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "helpful": { + "name": "helpful", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "not_helpful": { + "name": "not_helpful", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": {}, + "foreignKeys": { + "help_article_stats_article_fk": { + "name": "help_article_stats_article_fk", + "tableFrom": "help_article_stats", + "tableTo": "help_articles", + "columnsFrom": [ + "workspace_id", + "article_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "help_article_stats_pk": { + "columns": [ + "workspace_id", + "article_id" + ], + "name": "help_article_stats_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "help_articles": { + "name": "help_articles", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "collection_id": { + "name": "collection_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "translation_group_id": { + "name": "translation_group_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "language": { + "name": "language", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "body_markdown": { + "name": "body_markdown", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "body_html": { + "name": "body_html", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "search_title": { + "name": "search_title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "search_text": { + "name": "search_text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'draft'" + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "published_at": { + "name": "published_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_by_member_id": { + "name": "updated_by_member_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "draft_run_id": { + "name": "draft_run_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "draft_index": { + "name": "draft_index", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ai_drafted": { + "name": "ai_drafted", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "ai_sources_json": { + "name": "ai_sources_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "indexed_version": { + "name": "indexed_version", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "indexed_chunks": { + "name": "indexed_chunks", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": { + "help_articles_draft_uq": { + "name": "help_articles_draft_uq", + "columns": [ + "draft_run_id", + "draft_index" + ], + "isUnique": true, + "where": "\"help_articles\".\"draft_run_id\" IS NOT NULL" + }, + "help_articles_website_idx": { + "name": "help_articles_website_idx", + "columns": [ + "workspace_id", + "website_id" + ], + "isUnique": false + }, + "help_articles_public_idx": { + "name": "help_articles_public_idx", + "columns": [ + "website_id", + "language", + "status" + ], + "isUnique": false + }, + "help_articles_collection_idx": { + "name": "help_articles_collection_idx", + "columns": [ + "workspace_id", + "collection_id" + ], + "isUnique": false + }, + "help_articles_group_idx": { + "name": "help_articles_group_idx", + "columns": [ + "workspace_id", + "translation_group_id" + ], + "isUnique": false + }, + "help_articles_tenant_uq": { + "name": "help_articles_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + }, + "help_articles_slug_uq": { + "name": "help_articles_slug_uq", + "columns": [ + "website_id", + "language", + "slug" + ], + "isUnique": true + } + }, + "foreignKeys": { + "help_articles_website_fk": { + "name": "help_articles_website_fk", + "tableFrom": "help_articles", + "tableTo": "websites", + "columnsFrom": [ + "workspace_id", + "website_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "help_articles_collection_fk": { + "name": "help_articles_collection_fk", + "tableFrom": "help_articles", + "tableTo": "help_collections", + "columnsFrom": [ + "workspace_id", + "collection_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "help_articles_status_ck": { + "name": "help_articles_status_ck", + "value": "\"help_articles\".\"status\" IN ('draft','published')" + }, + "help_articles_published_ck": { + "name": "help_articles_published_ck", + "value": "(\"help_articles\".\"status\" = 'published') = (\"help_articles\".\"published_at\" IS NOT NULL)" + } + } + }, + "help_assets": { + "name": "help_assets", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content_type": { + "name": "content_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "size_bytes": { + "name": "size_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "filename": { + "name": "filename", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by_member_id": { + "name": "created_by_member_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "help_assets_website_idx": { + "name": "help_assets_website_idx", + "columns": [ + "workspace_id", + "website_id" + ], + "isUnique": false + }, + "help_assets_tenant_uq": { + "name": "help_assets_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "help_assets_website_fk": { + "name": "help_assets_website_fk", + "tableFrom": "help_assets", + "tableTo": "websites", + "columnsFrom": [ + "workspace_id", + "website_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "help_assets_type_ck": { + "name": "help_assets_type_ck", + "value": "\"help_assets\".\"content_type\" IN ('image/png','image/jpeg','image/gif','image/webp')" + } + } + }, + "help_collections": { + "name": "help_collections", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "language": { + "name": "language", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "help_collections_website_idx": { + "name": "help_collections_website_idx", + "columns": [ + "workspace_id", + "website_id" + ], + "isUnique": false + }, + "help_collections_tenant_uq": { + "name": "help_collections_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + }, + "help_collections_slug_uq": { + "name": "help_collections_slug_uq", + "columns": [ + "website_id", + "language", + "slug" + ], + "isUnique": true + } + }, + "foreignKeys": { + "help_collections_website_fk": { + "name": "help_collections_website_fk", + "tableFrom": "help_collections", + "tableTo": "websites", + "columnsFrom": [ + "workspace_id", + "website_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "help_draft_runs": { + "name": "help_draft_runs", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "language": { + "name": "language", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "collection_id": { + "name": "collection_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "read_website": { + "name": "read_website", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "links_json": { + "name": "links_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "files_json": { + "name": "files_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'uploading'" + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "outline_json": { + "name": "outline_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "planned": { + "name": "planned", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "failed_json": { + "name": "failed_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "material_chars": { + "name": "material_chars", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_by_member_id": { + "name": "created_by_member_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "help_draft_runs_website_idx": { + "name": "help_draft_runs_website_idx", + "columns": [ + "workspace_id", + "website_id", + "created_at" + ], + "isUnique": false + }, + "help_draft_runs_open_idx": { + "name": "help_draft_runs_open_idx", + "columns": [ + "updated_at" + ], + "isUnique": false, + "where": "\"help_draft_runs\".\"status\" NOT IN ('done','failed')" + }, + "help_draft_runs_tenant_uq": { + "name": "help_draft_runs_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "help_draft_runs_website_fk": { + "name": "help_draft_runs_website_fk", + "tableFrom": "help_draft_runs", + "tableTo": "websites", + "columnsFrom": [ + "workspace_id", + "website_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "help_draft_runs_status_ck": { + "name": "help_draft_runs_status_ck", + "value": "\"help_draft_runs\".\"status\" IN ('uploading','queued','reading','writing','done','failed')" + } + } + }, + "installation": { + "name": "installation", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "singleton": { + "name": "singleton", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "public_base_url": { + "name": "public_base_url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "relay_registered_id": { + "name": "relay_registered_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "relay_disconnected_id": { + "name": "relay_disconnected_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "signup_policy": { + "name": "signup_policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'invite_only'" + }, + "system_email_enc": { + "name": "system_email_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "installation_singleton_unique": { + "name": "installation_singleton_unique", + "columns": [ + "singleton" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "installation_singleton_ck": { + "name": "installation_singleton_ck", + "value": "\"installation\".\"singleton\" = 1" + }, + "installation_signup_ck": { + "name": "installation_signup_ck", + "value": "\"installation\".\"signup_policy\" IN ('invite_only','open')" + } + } + }, + "invitations": { + "name": "invitations", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text COLLATE NOCASE", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invited_by_member_id": { + "name": "invited_by_member_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "accepted_at": { + "name": "accepted_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "invitations_token_hash_unique": { + "name": "invitations_token_hash_unique", + "columns": [ + "token_hash" + ], + "isUnique": true + }, + "invitations_inviter_idx": { + "name": "invitations_inviter_idx", + "columns": [ + "workspace_id", + "invited_by_member_id" + ], + "isUnique": false + }, + "invitations_tenant_uq": { + "name": "invitations_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "invitations_workspace_id_workspaces_id_fk": { + "name": "invitations_workspace_id_workspaces_id_fk", + "tableFrom": "invitations", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "invitations_inviter_fk": { + "name": "invitations_inviter_fk", + "tableFrom": "invitations", + "tableTo": "workspace_members", + "columnsFrom": [ + "workspace_id", + "invited_by_member_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "invitations_role_ck": { + "name": "invitations_role_ck", + "value": "\"invitations\".\"role\" IN ('admin','supervisor','agent')" + } + } + }, + "job_receipts": { + "name": "job_receipts", + "columns": { + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "job_type": { + "name": "job_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "claimed_at": { + "name": "claimed_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "completed_at": { + "name": "completed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "job_receipts_claimed_idx": { + "name": "job_receipts_claimed_idx", + "columns": [ + "claimed_at" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "job_receipts_status_ck": { + "name": "job_receipts_status_ck", + "value": "\"job_receipts\".\"status\" IN ('claimed','done')" + } + } + }, + "login_codes": { + "name": "login_codes", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "login_codes_expiry_idx": { + "name": "login_codes_expiry_idx", + "columns": [ + "expires_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "login_codes_user_id_users_id_fk": { + "name": "login_codes_user_id_users_id_fk", + "tableFrom": "login_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "message_translations": { + "name": "message_translations", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "language": { + "name": "language", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "message_translations_message_fk": { + "name": "message_translations_message_fk", + "tableFrom": "message_translations", + "tableTo": "messages", + "columnsFrom": [ + "workspace_id", + "message_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "message_translations_pk": { + "columns": [ + "workspace_id", + "message_id", + "language" + ], + "name": "message_translations_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "messages": { + "name": "messages", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conversation_id": { + "name": "conversation_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "seq": { + "name": "seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "public_seq": { + "name": "public_seq", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "client_message_id": { + "name": "client_message_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sender_type": { + "name": "sender_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sender_id": { + "name": "sender_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "message_type": { + "name": "message_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "visibility": { + "name": "visibility", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "metadata_json": { + "name": "metadata_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "assistant_id": { + "name": "assistant_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "original_language": { + "name": "original_language", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "messages_assistant_idx": { + "name": "messages_assistant_idx", + "columns": [ + "workspace_id", + "created_at" + ], + "isUnique": false, + "where": "\"messages\".\"assistant_id\" IS NOT NULL" + }, + "messages_tenant_uq": { + "name": "messages_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + }, + "messages_seq_uq": { + "name": "messages_seq_uq", + "columns": [ + "workspace_id", + "conversation_id", + "seq" + ], + "isUnique": true + }, + "messages_public_seq_uq": { + "name": "messages_public_seq_uq", + "columns": [ + "workspace_id", + "conversation_id", + "public_seq" + ], + "isUnique": true + }, + "messages_client_uq": { + "name": "messages_client_uq", + "columns": [ + "workspace_id", + "conversation_id", + "client_message_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "messages_conversation_fk": { + "name": "messages_conversation_fk", + "tableFrom": "messages", + "tableTo": "conversations", + "columnsFrom": [ + "workspace_id", + "conversation_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "messages_sender_ck": { + "name": "messages_sender_ck", + "value": "\"messages\".\"sender_type\" IN ('visitor','member','system')" + }, + "messages_type_ck": { + "name": "messages_type_ck", + "value": "\"messages\".\"message_type\" IN ('text','image','file','system','internal_note')" + }, + "messages_visibility_ck": { + "name": "messages_visibility_ck", + "value": "\"messages\".\"visibility\" IN ('public','internal')" + }, + "messages_note_visibility_ck": { + "name": "messages_note_visibility_ck", + "value": "(\"messages\".\"message_type\" = 'internal_note') = (\"messages\".\"visibility\" = 'internal')" + }, + "messages_public_seq_ck": { + "name": "messages_public_seq_ck", + "value": "(\"messages\".\"visibility\" = 'public') = (\"messages\".\"public_seq\" IS NOT NULL)" + }, + "messages_note_sender_ck": { + "name": "messages_note_sender_ck", + "value": "\"messages\".\"message_type\" <> 'internal_note' OR \"messages\".\"sender_type\" = 'member'" + } + } + }, + "messenger_connections": { + "name": "messenger_connections", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "page_id": { + "name": "page_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "page_name": { + "name": "page_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "access_token_sealed": { + "name": "access_token_sealed", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "app_secret_sealed": { + "name": "app_secret_sealed", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "verify_token_sealed": { + "name": "verify_token_sealed", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key_version": { + "name": "key_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "instagram_account_id": { + "name": "instagram_account_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "instagram_username": { + "name": "instagram_username", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "instagram_enabled": { + "name": "instagram_enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "messenger_connections_page_id_unique": { + "name": "messenger_connections_page_id_unique", + "columns": [ + "page_id" + ], + "isUnique": true + }, + "messenger_connections_instagram_account_id_unique": { + "name": "messenger_connections_instagram_account_id_unique", + "columns": [ + "instagram_account_id" + ], + "isUnique": true + }, + "messenger_connections_tenant_uq": { + "name": "messenger_connections_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + }, + "messenger_connections_website_uq": { + "name": "messenger_connections_website_uq", + "columns": [ + "workspace_id", + "website_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "messenger_connections_website_fk": { + "name": "messenger_connections_website_fk", + "tableFrom": "messenger_connections", + "tableTo": "websites", + "columnsFrom": [ + "workspace_id", + "website_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "messenger_identities": { + "name": "messenger_identities", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "contact_id": { + "name": "contact_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "page_id": { + "name": "page_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "psid": { + "name": "psid", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "messenger_identities_contact_idx": { + "name": "messenger_identities_contact_idx", + "columns": [ + "workspace_id", + "contact_id" + ], + "isUnique": false + }, + "messenger_identities_tenant_uq": { + "name": "messenger_identities_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + }, + "messenger_identities_psid_uq": { + "name": "messenger_identities_psid_uq", + "columns": [ + "workspace_id", + "page_id", + "psid" + ], + "isUnique": true + } + }, + "foreignKeys": { + "messenger_identities_contact_fk": { + "name": "messenger_identities_contact_fk", + "tableFrom": "messenger_identities", + "tableTo": "contacts", + "columnsFrom": [ + "workspace_id", + "contact_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "messenger_sent": { + "name": "messenger_sent", + "columns": { + "mid": { + "name": "mid", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "part": { + "name": "part", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'sent'" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "messenger_sent_part_uq": { + "name": "messenger_sent_part_uq", + "columns": [ + "workspace_id", + "message_id", + "part" + ], + "isUnique": true + } + }, + "foreignKeys": { + "messenger_sent_message_fk": { + "name": "messenger_sent_message_fk", + "tableFrom": "messenger_sent", + "tableTo": "messages", + "columnsFrom": [ + "workspace_id", + "message_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "notification_preferences": { + "name": "notification_preferences", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "member_id": { + "name": "member_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "channel": { + "name": "channel", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "notification_preferences_member_fk": { + "name": "notification_preferences_member_fk", + "tableFrom": "notification_preferences", + "tableTo": "workspace_members", + "columnsFrom": [ + "workspace_id", + "member_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "notification_preferences_workspace_id_member_id_event_type_channel_pk": { + "columns": [ + "workspace_id", + "member_id", + "event_type", + "channel" + ], + "name": "notification_preferences_workspace_id_member_id_event_type_channel_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": { + "notification_preferences_channel_ck": { + "name": "notification_preferences_channel_ck", + "value": "\"notification_preferences\".\"channel\" IN ('push','email')" + } + } + }, + "outbox": { + "name": "outbox", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "topic": { + "name": "topic", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "aggregate_id": { + "name": "aggregate_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload_json": { + "name": "payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "dispatched_at": { + "name": "dispatched_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": { + "outbox_pending_idx": { + "name": "outbox_pending_idx", + "columns": [ + "created_at" + ], + "isUnique": false, + "where": "\"outbox\".\"dispatched_at\" IS NULL" + }, + "outbox_pending_aggregate_idx": { + "name": "outbox_pending_aggregate_idx", + "columns": [ + "workspace_id", + "aggregate_id" + ], + "isUnique": false, + "where": "\"outbox\".\"dispatched_at\" IS NULL" + }, + "outbox_purge_idx": { + "name": "outbox_purge_idx", + "columns": [ + "dispatched_at" + ], + "isUnique": false, + "where": "\"outbox\".\"dispatched_at\" IS NOT NULL" + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_subscriptions": { + "name": "push_subscriptions", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "member_id": { + "name": "member_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "relay_id": { + "name": "relay_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "relay_subscription_id": { + "name": "relay_subscription_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "preview_key": { + "name": "preview_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "device_label": { + "name": "device_label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "push_subscriptions_relay_uq": { + "name": "push_subscriptions_relay_uq", + "columns": [ + "relay_id", + "relay_subscription_id" + ], + "isUnique": true + }, + "push_subscriptions_member_idx": { + "name": "push_subscriptions_member_idx", + "columns": [ + "workspace_id", + "member_id" + ], + "isUnique": false + }, + "push_subscriptions_tenant_uq": { + "name": "push_subscriptions_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_subscriptions_member_fk": { + "name": "push_subscriptions_member_fk", + "tableFrom": "push_subscriptions", + "tableTo": "workspace_members", + "columnsFrom": [ + "workspace_id", + "member_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "push_subscriptions_platform_ck": { + "name": "push_subscriptions_platform_ck", + "value": "\"push_subscriptions\".\"platform\" IN ('ios', 'android')" + } + } + }, + "saved_replies": { + "name": "saved_replies", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text COLLATE NOCASE", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "saved_replies_title_uq": { + "name": "saved_replies_title_uq", + "columns": [ + "workspace_id", + "title" + ], + "isUnique": true + } + }, + "foreignKeys": { + "saved_replies_workspace_id_workspaces_id_fk": { + "name": "saved_replies_workspace_id_workspaces_id_fk", + "tableFrom": "saved_replies", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tags": { + "name": "tags", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text COLLATE NOCASE", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "tags_tenant_uq": { + "name": "tags_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + }, + "tags_name_uq": { + "name": "tags_name_uq", + "columns": [ + "workspace_id", + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "tags_workspace_id_workspaces_id_fk": { + "name": "tags_workspace_id_workspaces_id_fk", + "tableFrom": "tags", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text COLLATE NOCASE", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email_verified_at": { + "name": "email_verified_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "is_installation_admin": { + "name": "is_installation_admin", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "language": { + "name": "language", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "users_email_unique": { + "name": "users_email_unique", + "columns": [ + "email" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "visitors": { + "name": "visitors", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "contact_id": { + "name": "contact_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "refresh_token_hash": { + "name": "refresh_token_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "visitors_refresh_token_hash_unique": { + "name": "visitors_refresh_token_hash_unique", + "columns": [ + "refresh_token_hash" + ], + "isUnique": true + }, + "visitors_contact_idx": { + "name": "visitors_contact_idx", + "columns": [ + "workspace_id", + "contact_id" + ], + "isUnique": false + }, + "visitors_stale_idx": { + "name": "visitors_stale_idx", + "columns": [ + "last_seen_at" + ], + "isUnique": false + }, + "visitors_website_idx": { + "name": "visitors_website_idx", + "columns": [ + "workspace_id", + "website_id" + ], + "isUnique": false + }, + "visitors_tenant_uq": { + "name": "visitors_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "visitors_website_fk": { + "name": "visitors_website_fk", + "tableFrom": "visitors", + "tableTo": "websites", + "columnsFrom": [ + "workspace_id", + "website_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "visitors_contact_fk": { + "name": "visitors_contact_fk", + "tableFrom": "visitors", + "tableTo": "contacts", + "columnsFrom": [ + "workspace_id", + "contact_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "websites": { + "name": "websites", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_key": { + "name": "website_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "allowed_origins_json": { + "name": "allowed_origins_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "settings_json": { + "name": "settings_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'{}'" + }, + "help_slug": { + "name": "help_slug", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "help_version": { + "name": "help_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "help_noindex": { + "name": "help_noindex", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "websites_website_key_unique": { + "name": "websites_website_key_unique", + "columns": [ + "website_key" + ], + "isUnique": true + }, + "websites_help_slug_uq": { + "name": "websites_help_slug_uq", + "columns": [ + "help_slug" + ], + "isUnique": true, + "where": "\"websites\".\"help_slug\" IS NOT NULL" + }, + "websites_tenant_uq": { + "name": "websites_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "websites_workspace_id_workspaces_id_fk": { + "name": "websites_workspace_id_workspaces_id_fk", + "tableFrom": "websites", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "whatsapp_connections": { + "name": "whatsapp_connections", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "phone_number_id": { + "name": "phone_number_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "business_account_id": { + "name": "business_account_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "display_phone_number": { + "name": "display_phone_number", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "verified_name": { + "name": "verified_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "access_token_sealed": { + "name": "access_token_sealed", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "app_secret_sealed": { + "name": "app_secret_sealed", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "verify_token_sealed": { + "name": "verify_token_sealed", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key_version": { + "name": "key_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "whatsapp_connections_phone_number_id_unique": { + "name": "whatsapp_connections_phone_number_id_unique", + "columns": [ + "phone_number_id" + ], + "isUnique": true + }, + "whatsapp_connections_tenant_uq": { + "name": "whatsapp_connections_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + }, + "whatsapp_connections_website_uq": { + "name": "whatsapp_connections_website_uq", + "columns": [ + "workspace_id", + "website_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "whatsapp_connections_website_fk": { + "name": "whatsapp_connections_website_fk", + "tableFrom": "whatsapp_connections", + "tableTo": "websites", + "columnsFrom": [ + "workspace_id", + "website_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "whatsapp_identities": { + "name": "whatsapp_identities", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "contact_id": { + "name": "contact_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "phone_number_id": { + "name": "phone_number_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "wa_id": { + "name": "wa_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "whatsapp_identities_contact_idx": { + "name": "whatsapp_identities_contact_idx", + "columns": [ + "workspace_id", + "contact_id" + ], + "isUnique": false + }, + "whatsapp_identities_tenant_uq": { + "name": "whatsapp_identities_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + }, + "whatsapp_identities_user_uq": { + "name": "whatsapp_identities_user_uq", + "columns": [ + "workspace_id", + "phone_number_id", + "user_id" + ], + "isUnique": true + }, + "whatsapp_identities_wa_uq": { + "name": "whatsapp_identities_wa_uq", + "columns": [ + "workspace_id", + "phone_number_id", + "wa_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "whatsapp_identities_contact_fk": { + "name": "whatsapp_identities_contact_fk", + "tableFrom": "whatsapp_identities", + "tableTo": "contacts", + "columnsFrom": [ + "workspace_id", + "contact_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "whatsapp_identities_key_ck": { + "name": "whatsapp_identities_key_ck", + "value": "\"whatsapp_identities\".\"user_id\" IS NOT NULL OR \"whatsapp_identities\".\"wa_id\" IS NOT NULL" + } + } + }, + "whatsapp_sent": { + "name": "whatsapp_sent", + "columns": { + "wamid": { + "name": "wamid", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "part": { + "name": "part", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'sent'" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "whatsapp_sent_part_uq": { + "name": "whatsapp_sent_part_uq", + "columns": [ + "workspace_id", + "message_id", + "part" + ], + "isUnique": true + } + }, + "foreignKeys": { + "whatsapp_sent_message_fk": { + "name": "whatsapp_sent_message_fk", + "tableFrom": "whatsapp_sent", + "tableTo": "messages", + "columnsFrom": [ + "workspace_id", + "message_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "workspace_members": { + "name": "workspace_members", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'active'" + }, + "removed_at": { + "name": "removed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "away": { + "name": "away", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "workspace_members_user_idx": { + "name": "workspace_members_user_idx", + "columns": [ + "user_id", + "status" + ], + "isUnique": false + }, + "workspace_members_tenant_uq": { + "name": "workspace_members_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + }, + "workspace_members_user_uq": { + "name": "workspace_members_user_uq", + "columns": [ + "workspace_id", + "user_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "workspace_members_workspace_id_workspaces_id_fk": { + "name": "workspace_members_workspace_id_workspaces_id_fk", + "tableFrom": "workspace_members", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_members_user_id_users_id_fk": { + "name": "workspace_members_user_id_users_id_fk", + "tableFrom": "workspace_members", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "workspace_members_role_ck": { + "name": "workspace_members_role_ck", + "value": "\"workspace_members\".\"role\" IN ('owner','admin','supervisor','agent')" + }, + "workspace_members_status_ck": { + "name": "workspace_members_status_ck", + "value": "\"workspace_members\".\"status\" IN ('active','suspended')" + } + } + }, + "workspaces": { + "name": "workspaces", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "settings_json": { + "name": "settings_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'{}'" + }, + "relay_workspace_status": { + "name": "relay_workspace_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'unregistered'" + }, + "retention_days": { + "name": "retention_days", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "assistant_auto_approve": { + "name": "assistant_auto_approve", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "translation_enabled": { + "name": "translation_enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "translation_model": { + "name": "translation_model", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "workspaces_slug_unique": { + "name": "workspaces_slug_unique", + "columns": [ + "slug" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "workspaces_relay_ck": { + "name": "workspaces_relay_ck", + "value": "\"workspaces\".\"relay_workspace_status\" IN ('unregistered','registered','revoked')" + } + } + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": { + "audit_log_idx": { + "columns": { + "\"created_at\" DESC": { + "isExpression": true + }, + "\"id\" DESC": { + "isExpression": true + } + } + }, + "audit_log_recent_idx": { + "columns": { + "\"created_at\" DESC": { + "isExpression": true + }, + "\"id\" DESC": { + "isExpression": true + } + } + }, + "contacts_list_idx": { + "columns": { + "\"last_seen_at\" DESC": { + "isExpression": true + }, + "\"id\" DESC": { + "isExpression": true + } + } + }, + "conversations_inbox_idx": { + "columns": { + "\"last_message_at\" DESC": { + "isExpression": true + }, + "\"id\" DESC": { + "isExpression": true + } + } + }, + "conversations_assignee_idx": { + "columns": { + "\"last_message_at\" DESC": { + "isExpression": true + }, + "\"id\" DESC": { + "isExpression": true + } + } + }, + "conversations_contact_idx": { + "columns": { + "\"last_message_at\" DESC": { + "isExpression": true + } + } + }, + "failed_jobs_recent_idx": { + "columns": { + "\"failed_at\" DESC": { + "isExpression": true + } + } + } + } + } +} \ No newline at end of file diff --git a/packages/database/migrations/meta/_journal.json b/packages/database/migrations/meta/_journal.json index 8670004..db7dfe1 100644 --- a/packages/database/migrations/meta/_journal.json +++ b/packages/database/migrations/meta/_journal.json @@ -295,6 +295,13 @@ "when": 1796141710597, "tag": "0041_messenger_sent", "breakpoints": true + }, + { + "idx": 42, + "version": "6", + "when": 1796156543000, + "tag": "0042_instagram", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/database/src/messenger-repository.ts b/packages/database/src/messenger-repository.ts index a376249..278ea89 100644 --- a/packages/database/src/messenger-repository.ts +++ b/packages/database/src/messenger-repository.ts @@ -16,6 +16,8 @@ export interface MessengerConnectionRow { pageId: string; pageName: string | null; enabled: boolean; + /** The Instagram account linked to the Page (ADR-0028): null until Instagram is first turned on. */ + instagram: { accountId: string; username: string | null; enabled: boolean } | null; createdAt: number; updatedAt: number; } @@ -23,10 +25,16 @@ export interface MessengerConnectionRow { export type MessengerConnectionWithSecrets = MessengerConnectionRow & { sealed: SealedMetaSecrets }; const COLUMNS = `id, workspace_id AS workspaceId, website_id AS websiteId, page_id AS pageId, page_name AS pageName, - enabled, created_at AS createdAt, updated_at AS updatedAt, + enabled, instagram_account_id AS instagramAccountId, instagram_username AS instagramUsername, instagram_enabled AS instagramEnabled, + created_at AS createdAt, updated_at AS updatedAt, access_token_sealed AS accessToken, app_secret_sealed AS appSecret, verify_token_sealed AS verifyToken, key_version AS keyVersion`; -type Raw = Omit & { enabled: number } & SealedMetaSecrets; +type Raw = Omit & { + enabled: number; + instagramAccountId: string | null; + instagramUsername: string | null; + instagramEnabled: number; +} & SealedMetaSecrets; const toRow = (raw: Raw): MessengerConnectionWithSecrets => ({ id: raw.id, @@ -35,14 +43,16 @@ const toRow = (raw: Raw): MessengerConnectionWithSecrets => ({ pageId: raw.pageId, pageName: raw.pageName, enabled: raw.enabled === 1, + instagram: raw.instagramAccountId ? { accountId: raw.instagramAccountId, username: raw.instagramUsername, enabled: raw.instagramEnabled === 1 } : null, createdAt: raw.createdAt, updatedAt: raw.updatedAt, sealed: { accessToken: raw.accessToken, appSecret: raw.appSecret, verifyToken: raw.verifyToken, keyVersion: raw.keyVersion }, }); -/** The Page is connected elsewhere, or this website already has one. */ +/** The Page or its Instagram account is connected elsewhere, or this website already has one. */ const isDuplicate = (error: unknown) => error instanceof Error && /UNIQUE constraint failed/i.test(error.message); const takenBy = (error: unknown): 'page_taken' | 'exists' => (error instanceof Error && /page_id/.test(error.message) ? 'page_taken' : 'exists'); +const updateTakenBy = (error: unknown): 'page_taken' | 'instagram_taken' => (error instanceof Error && /instagram_account_id/.test(error.message) ? 'instagram_taken' : 'page_taken'); export interface NewMessengerConnection { id: string; @@ -55,6 +65,8 @@ export interface MessengerConnectionChange { pageId?: string | undefined; pageName?: string | null | undefined; enabled?: boolean | undefined; + /** Instagram turned on, with the account Meta named just now, or off. The account is kept when it is turned off. */ + instagram?: { accountId: string; username: string | null; enabled: true } | { enabled: false } | undefined; /** All three, sealed again together, or none. */ sealed?: SealedMetaSecrets | undefined; } @@ -111,11 +123,13 @@ export function messengerAdminRepository(database: Database, ctx: AdminContext) return (await this.get(workspaceId, websiteId)) ?? 'not_found'; }, - async update(workspaceId: string, websiteId: string, change: MessengerConnectionChange): Promise { + async update(workspaceId: string, websiteId: string, change: MessengerConnectionChange): Promise { const auditId = newId('audit'); const sealed = change.sealed; // The Page's name is replaced whenever given, NULL included, since it is what Meta said at the last check. const display = change.pageName !== undefined; + const instagram = change.instagram; + const linked = instagram?.enabled ? instagram : null; try { const [allowed] = await d1.batch([ audit('messenger.updated', workspaceId, websiteId, auditId), @@ -127,6 +141,9 @@ export function messengerAdminRepository(database: Database, ctx: AdminContext) enabled = COALESCE(?6, enabled), access_token_sealed = COALESCE(?7, access_token_sealed), app_secret_sealed = COALESCE(?8, app_secret_sealed), verify_token_sealed = COALESCE(?9, verify_token_sealed), key_version = COALESCE(?10, key_version), + instagram_account_id = CASE WHEN ?12 THEN ?13 ELSE instagram_account_id END, + instagram_username = CASE WHEN ?12 THEN ?14 ELSE instagram_username END, + instagram_enabled = COALESCE(?15, instagram_enabled), updated_at = ${DB_NOW_MS} WHERE workspace_id = ?1 AND website_id = ?2 AND EXISTS (SELECT 1 FROM audit_log WHERE id = ?11)`, ) @@ -142,11 +159,15 @@ export function messengerAdminRepository(database: Database, ctx: AdminContext) sealed?.verifyToken ?? null, sealed?.keyVersion ?? null, auditId, + linked ? 1 : 0, + linked?.accountId ?? null, + linked?.username ?? null, + instagram === undefined ? null : instagram.enabled ? 1 : 0, ), ]); if (allowed?.meta.changes !== 1) return 'not_found'; } catch (error) { - if (isDuplicate(error)) return 'page_taken'; + if (isDuplicate(error)) return updateTakenBy(error); throw error; } return (await this.get(workspaceId, websiteId)) ?? 'not_found'; diff --git a/packages/database/src/schema/index.ts b/packages/database/src/schema/index.ts index 8349611..c08f9ca 100644 --- a/packages/database/src/schema/index.ts +++ b/packages/database/src/schema/index.ts @@ -307,6 +307,10 @@ export const messengerConnections = sqliteTable( /** The DATA_ENCRYPTION_KEY version all three were sealed with. They are always sealed together. */ keyVersion: integer('key_version').notNull(), enabled: integer('enabled', { mode: 'boolean' }).notNull().default(true), + /** The Instagram professional account linked to the Page, once Instagram is turned on (ADR-0028). Kept when it is turned off. */ + instagramAccountId: text('instagram_account_id').unique(), + instagramUsername: text('instagram_username'), + instagramEnabled: integer('instagram_enabled', { mode: 'boolean' }).notNull().default(false), createdAt: ts('created_at'), updatedAt: ts('updated_at'), }, diff --git a/packages/database/test/messenger-repository.test.ts b/packages/database/test/messenger-repository.test.ts index 870556c..aa8ec6a 100644 --- a/packages/database/test/messenger-repository.test.ts +++ b/packages/database/test/messenger-repository.test.ts @@ -49,6 +49,19 @@ describe('Messenger connections (ADR-0027)', () => { expect(await auditCount('messenger.updated')).toBe(0); }); + it('turns Instagram on and off, keeps the account, and allows it on one connection only (ADR-0028)', async () => { + const repo = messengerAdminRepository(db(), await admin()); + expect(await repo.create('w1', 's1', input('fbc_1', 'pg1'))).toMatchObject({ instagram: null }); + expect(await repo.update('w1', 's1', { instagram: { accountId: 'ig1', username: 'shop', enabled: true } })).toMatchObject({ instagram: { accountId: 'ig1', username: 'shop', enabled: true }, enabled: true }); + expect(await repo.update('w1', 's1', { instagram: { enabled: false } })).toMatchObject({ instagram: { accountId: 'ig1', username: 'shop', enabled: false } }); + // A change that does not name Instagram leaves it as it is. + expect(await repo.update('w1', 's1', { pageName: 'Shop 2' })).toMatchObject({ instagram: { accountId: 'ig1', enabled: false } }); + + await repo.create('w1', 's2', input('fbc_2', 'pg2')); + expect(await repo.update('w1', 's2', { instagram: { accountId: 'ig1', username: 'shop', enabled: true } })).toBe('instagram_taken'); + expect(await repo.get('w1', 's2')).toMatchObject({ instagram: null }); + }); + it('finds nothing for a website named under another workspace', async () => { const repo = messengerAdminRepository(db(), await admin()); expect(await repo.create('w2', 's1', input('fbc_1', 'pg1'))).toBe('not_found'); diff --git a/services/api/src/messenger.ts b/services/api/src/messenger.ts index 1853efe..dc3f238 100644 --- a/services/api/src/messenger.ts +++ b/services/api/src/messenger.ts @@ -1,6 +1,6 @@ /** What the Messenger routes and jobs need from the environment (ADR-0027). Kept out of routes/, which may not reach the database. */ import type { DataKeys } from '@openchat/auth'; -import { fetchMessengerMedia, fetchMessengerProfile, giveUpMessengerSend, receiveMessengerWebhook, sendMessengerReply, type MessengerDeps } from '@openchat/core'; +import { countInstagramWebhook, fetchMessengerMedia, fetchMessengerProfile, giveUpMessengerSend, receiveMessengerWebhook, sendMessengerReply, type MessengerDeps } from '@openchat/core'; import { failMessengerMedia, findMessengerConnection, getInstallation, openDatabase, pendingMessengerMedia, type MessengerConnectionWithSecrets } from '@openchat/database'; import { AppError, createLogger, newId, type JobEnvelope } from '@openchat/shared'; import type { Context } from 'hono'; @@ -47,6 +47,17 @@ const job =

(type: string, key: string, workspaceId: string, payload: P): Job * again; what was stored is then found, not repeated. */ export async function storeMessengerWebhook(c: Context, connection: MessengerConnectionWithSecrets, body: unknown): Promise { + // Instagram's direct messages (ADR-0028) come to the same address. Step 1 only counts them; anything not for this + // connection's account, or while Instagram is off, is acknowledged and dropped. + if ((body as { object?: unknown } | null)?.object === 'instagram') { + const counts = countInstagramWebhook(connection, body); + if (!counts) { + c.get('log').info('instagram_webhook_ignored', { workspaceId: connection.workspaceId }); + return; + } + for (const [kind, count] of Object.entries(counts)) c.get('log').info(`instagram_webhook_${kind}`, { workspaceId: connection.workspaceId, count }); + return; + } const received = await receiveMessengerWebhook(openDatabase(c.env.DB), connection, body); for (const [workspaceId, ids] of received.written) dispatchSoon(c, workspaceId, ids); await announceUpdated(c.env, received.updated); diff --git a/services/api/test/api.test.ts b/services/api/test/api.test.ts index 9a96e76..42f1322 100644 --- a/services/api/test/api.test.ts +++ b/services/api/test/api.test.ts @@ -43,7 +43,7 @@ describe('HTTP', () => { expect(await client.getDiscovery()).toEqual({ installationId: 'inst_test', name: 'Test installation', - api: { versions: ['v1'], minor: 10 }, + api: { versions: ['v1'], minor: 11 }, realtime: { protocolVersions: [1] }, relay: null, // emailCode follows the local email setting; sign-in codes (auth.test.ts) test both. diff --git a/services/api/test/messenger.test.ts b/services/api/test/messenger.test.ts index 20f3c4c..aad8554 100644 --- a/services/api/test/messenger.test.ts +++ b/services/api/test/messenger.test.ts @@ -14,6 +14,7 @@ const DATA_ENCRYPTION_KEY = JSON.stringify({ active: generateDataKey(1) }); const withKey = { ...env, DATA_ENCRYPTION_KEY } as unknown as Env; const PATH = '/api/v1/admin/workspaces/work_1/websites/site_1/messenger'; const KEYS = { pageId: '1035550001', accessToken: 'EAAG-page-token', appSecret: 'first-app-secret' }; +const IG_ACCOUNT = '17841400000000001'; let counter = 0; async function call(method: string, path: string, options: { token?: string | undefined; body?: unknown; raw?: string; headers?: Record; testEnv?: Env } = {}) { @@ -29,7 +30,7 @@ async function call(method: string, path: string, options: { token?: string | un const code = async (response: Response) => ((await response.json()) as { code: string }).code; /** Meta's Graph API, as far as connecting a Page needs it. Records each call, without its token. */ -function fakeMeta(options: { tokenOk?: (token: string) => boolean; me?: string; unsubscribe?: 'ok' | 'refuse' } = {}) { +function fakeMeta(options: { tokenOk?: (token: string) => boolean; me?: string; unsubscribe?: 'ok' | 'refuse'; instagram?: string | null; conversations?: 'ok' | 'refuse' } = {}) { const calls: { method: string; path: string; query: string; token: string }[] = []; const realFetch = globalThis.fetch; vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { @@ -43,6 +44,14 @@ function fakeMeta(options: { tokenOk?: (token: string) => boolean; me?: string; expect(version).toBe('v26.0'); if (id === 'me' && !edge) return Response.json({ id: options.me ?? KEYS.pageId, name: 'Shop Page' }); if (edge === 'subscribed_apps' && method === 'POST') return Response.json({ success: true }); + if (id !== 'me' && !edge && url.searchParams.get('fields') === 'instagram_business_account{id,username}') { + const account = options.instagram === undefined ? IG_ACCOUNT : options.instagram; + return Response.json(account ? { id, instagram_business_account: { id: account, username: 'shop.ig' } } : { id }); + } + if (edge === 'conversations') { + expect(url.searchParams.get('platform')).toBe('instagram'); + return options.conversations === 'refuse' ? Response.json({ error: { code: 230 } }, { status: 403 }) : Response.json({ data: [] }); + } if (edge === 'subscribed_apps' && method === 'DELETE') return options.unsubscribe === 'refuse' ? Response.json({ error: { code: 190 } }, { status: 401 }) : Response.json({ success: true }); return Response.json({ error: { code: 100 } }, { status: 400 }); }); @@ -192,6 +201,96 @@ describe('connecting a Facebook Page (ADR-0027)', () => { }); }); +describe('turning on Instagram (ADR-0028)', () => { + it('finds the linked account, proves it can read messages, and keeps it when turned off', async () => { + await connect(); + const calls = fakeMeta(); + const on = await call('PUT', PATH, { token: tokens.boss, body: { pageId: KEYS.pageId, instagram: true } }); + expect(on.status).toBe(200); + expect(await on.json()).toMatchObject({ enabled: true, instagram: { accountId: IG_ACCOUNT, username: 'shop.ig', enabled: true } }); + expect(calls.map((c) => c.path)).toEqual([`/v26.0/${KEYS.pageId}`, `/v26.0/${KEYS.pageId}/conversations`]); + + // Saving again without a change does not ask Meta. + calls.length = 0; + expect((await call('PUT', PATH, { token: tokens.boss, body: { pageId: KEYS.pageId } })).status).toBe(200); + expect(calls).toHaveLength(0); + + expect(await code(await call('PUT', PATH, { token: tokens.boss, body: { pageId: KEYS.pageId, enabled: false } }))).toBe('instagram_needs_messenger'); + const off = await call('PUT', PATH, { token: tokens.boss, body: { pageId: KEYS.pageId, instagram: false } }); + expect(await off.json()).toMatchObject({ instagram: { accountId: IG_ACCOUNT, enabled: false } }); + const got = await call('GET', PATH, { token: tokens.boss }); + expect(await got.json()).toMatchObject({ instagram: { accountId: IG_ACCOUNT, enabled: false } }); + }); + + it("says why when Meta names no account, or won't let the token read messages, and keeps nothing", async () => { + await connect(); + fakeMeta({ instagram: null }); + expect(await code(await call('PUT', PATH, { token: tokens.boss, body: { pageId: KEYS.pageId, instagram: true } }))).toBe('instagram_not_linked'); + vi.restoreAllMocks(); + fakeMeta({ conversations: 'refuse' }); + expect(await code(await call('PUT', PATH, { token: tokens.boss, body: { pageId: KEYS.pageId, instagram: true } }))).toBe('instagram_permission_missing'); + vi.restoreAllMocks(); + fakeMeta({ tokenOk: (t) => t !== 'EAAG-expired' }); + expect(await code(await call('PUT', PATH, { token: tokens.boss, body: { pageId: KEYS.pageId, accessToken: 'EAAG-expired', instagram: true } }))).toBe('messenger_token_invalid'); + expect(await env.DB.prepare(`SELECT instagram_account_id FROM messenger_connections`).first('instagram_account_id')).toBeNull(); + }); + + it('refuses Instagram before the Page is connected, and an account another website has', async () => { + fakeMeta(); + expect(await code(await call('PUT', PATH, { token: tokens.boss, body: { ...KEYS, instagram: true } }))).toBe('validation_failed'); + vi.restoreAllMocks(); + await connect(); + fakeMeta(); + expect((await call('PUT', PATH, { token: tokens.boss, body: { pageId: KEYS.pageId, instagram: true } })).status).toBe(200); + await env.DB.prepare(`INSERT INTO websites (id, workspace_id, name, website_key, created_at, updated_at) VALUES ('site_3', 'work_1', 'Blog', 'key_3', 1, 1)`).run(); + vi.restoreAllMocks(); + const other = '/api/v1/admin/workspaces/work_1/websites/site_3/messenger'; + fakeMeta({ me: '1035550002' }); + expect((await call('PUT', other, { token: tokens.boss, body: { ...KEYS, pageId: '1035550002' } })).status).toBe(200); + vi.restoreAllMocks(); + // Meta names the same Instagram account for the second Page. + fakeMeta(); + expect(await code(await call('PUT', other, { token: tokens.boss, body: { pageId: '1035550002', instagram: true } }))).toBe('instagram_account_taken'); + }); + + it("counts Instagram events for the connection's account in the log, with no IDs or text, and stores nothing", async () => { + const { id } = await connect(); + fakeMeta(); + await call('PUT', PATH, { token: tokens.boss, body: { pageId: KEYS.pageId, instagram: true } }); + vi.restoreAllMocks(); + const lines: string[] = []; + vi.spyOn(console, 'log').mockImplementation((line: unknown) => void lines.push(String(line))); + const body = JSON.stringify({ + object: 'instagram', + entry: [ + { + id: IG_ACCOUNT, + time: 1764500000000, + messaging: [ + { sender: { id: '9000001' }, recipient: { id: IG_ACCOUNT }, message: { mid: 'ig_secret', text: 'my private words' } }, + { sender: { id: IG_ACCOUNT }, recipient: { id: '9000001' }, message: { mid: 'ig_2', text: 'hello', is_echo: true } }, + { sender: { id: '9000001' }, recipient: { id: IG_ACCOUNT }, read: { mid: 'ig_2' } }, + ], + }, + ], + }); + const signed = async (raw: string) => call('POST', `/api/v1/messenger/webhook/${id}`, { raw, headers: { 'x-hub-signature-256': await signature(KEYS.appSecret, raw) } }); + expect((await signed(body)).status).toBe(200); + const all = lines.join('\n'); + expect(all).toContain('instagram_webhook_message'); + expect(all).toContain('instagram_webhook_echo'); + expect(all).toContain('instagram_webhook_read'); + expect(all).not.toContain('my private words'); + expect(all).not.toContain('9000001'); + expect(await env.DB.prepare(`SELECT COUNT(*) AS n FROM messages`).first('n')).toBe(0); + + // Another account's entries, or anything while Instagram is off, are acknowledged and dropped. + lines.length = 0; + expect((await signed(body.replaceAll(IG_ACCOUNT, '17841400000000099'))).status).toBe(200); + expect(lines.join('\n')).toContain('instagram_webhook_ignored'); + }); +}); + describe("Meta's Messenger webhook", () => { it("answers Meta's challenge only with the right verify token", async () => { const { id, verifyToken } = await connect();