Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions apps/builder/__tests__/messenger-select-account.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { act } from "react"
import { createRoot, type Root } from "react-dom/client"
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"

/** Echoes the key back so assertions never depend on the English copy. */
vi.mock("next-intl", () => ({
useTranslations: () => (key: string) => key,
}))

const { mockMessengerPages } = vi.hoisted(() => ({
mockMessengerPages: vi.fn((_props: { items: unknown[] }) => null),
}))

// The picker list is unit-tested in `messenger-pages.test.tsx`; here it is a
// capture stub so this file can assert what `SelectPage` hands it.
vi.mock("@/features/integration-messenger/components/messenger-pages", () => ({
MessengerPages: mockMessengerPages,
}))

const { SelectPage } = await import(
"@/features/integration-messenger/components/select-account"
)

describe("SelectPage", () => {
let container: HTMLDivElement
let root: Root

beforeEach(() => {
vi.clearAllMocks()
container = document.createElement("div")
document.body.appendChild(container)
root = createRoot(container)
})

afterEach(async () => {
await act(async () => root.unmount())
container.remove()
})

const readErrorBox = () => container.querySelector('[role="alert"]')

test("shows Meta's own sentence in a box when the page list failed with a Graph error", async () => {
await act(() => {
root.render(
<SelectPage
bmLookupFailed={false}
items={[]}
loadError={{
providerMessage:
"(#1) Please reduce the amount of data you're asking for",
}}
workspaceId="ws-1"
/>,
)
})

expect(readErrorBox()?.textContent).toContain(
"(#1) Please reduce the amount of data you're asking for",
)
// The picker still renders, empty, so its own "No Facebook Pages found"
// state is what the operator sees under the box.
expect(mockMessengerPages).toHaveBeenCalledWith(
expect.objectContaining({ items: [] }),
undefined,
)
})

test("shows the generic copy when the failure carried no Graph message", async () => {
await act(() => {
root.render(
<SelectPage
bmLookupFailed={false}
items={[]}
loadError={{}}
workspaceId="ws-1"
/>,
)
})

expect(readErrorBox()?.textContent).toContain(
"messenger.selectPage.loadFailed",
)
})

test("renders no error box when the page list loaded", async () => {
await act(() => {
root.render(
<SelectPage bmLookupFailed={false} items={[]} workspaceId="ws-1" />,
)
})

expect(readErrorBox()).toBeNull()
})
})
73 changes: 73 additions & 0 deletions apps/builder/__tests__/messenger-select-page.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,16 @@ import { beforeEach, describe, expect, test, vi } from "vitest"
const {
mockFindConnectedMessengerPageIds,
mockGetUserPages,
mockLoggerError,
mockMapToChannelError,
mockReadPendingAuth,
mockRedirect,
mockSelectPage,
} = vi.hoisted(() => ({
mockFindConnectedMessengerPageIds: vi.fn(),
mockGetUserPages: vi.fn(),
mockLoggerError: vi.fn(),
mockMapToChannelError: vi.fn(),
mockReadPendingAuth: vi.fn(),
mockRedirect: vi.fn((path: string) => {
throw new Error(`redirect:${path}`)
Expand All @@ -37,6 +41,11 @@ vi.mock("@chatbotx.io/business", () => ({

vi.mock("@chatbotx.io/integration-messenger", () => ({
getUserPages: mockGetUserPages,
mapToChannelError: mockMapToChannelError,
}))

vi.mock("@/lib/log", () => ({
logger: { error: mockLoggerError },
}))

vi.mock("@/lib/facebook-pending-auth", () => ({
Expand All @@ -57,6 +66,7 @@ const { default: MessengerSelectPage } = await import(
)

type SelectPageElementProps = {
loadError?: { providerMessage?: string }
items: Array<{
id: string
isAlreadyConnected: boolean
Expand Down Expand Up @@ -186,6 +196,69 @@ describe("MessengerSelectPage", () => {
expect(connectable?.secondary).toBe("page-connectable")
})

// Meta answers `/me/accounts` with `{"error":{"code":1,"message":"Please
// reduce the amount of data you're asking for…"}}` for some users. That
// must render the picker's empty state with the provider's reason, not
// the route-level "Something went wrong" boundary.
test("renders an empty picker with the channel error message when Graph fails to list pages", async () => {
const graphError = new Error("graph exploded")
mockGetUserPages.mockRejectedValue(graphError)
mockMapToChannelError.mockReturnValue({
message: "(#1) Please reduce the amount of data you're asking for",
code: 1,
category: "unknown",
})

const element = await MessengerSelectPage()

if (!isValidElement<SelectPageElementProps>(element)) {
throw new Error("MessengerSelectPage did not return a valid element")
}

expect(mockMapToChannelError).toHaveBeenCalledWith(graphError)
expect(element.props.items).toEqual([])
expect(element.props.loadError).toEqual({
providerMessage:
"(#1) Please reduce the amount of data you're asking for",
})
expect(mockFindConnectedMessengerPageIds).not.toHaveBeenCalled()
expect(mockLoggerError).toHaveBeenCalledWith(
expect.objectContaining({ err: graphError }),
expect.any(String),
)
})

// No Graph body to quote (timeout, DNS, malformed JSON): the mapper reports
// UNKNOWN_ERROR's -1 code, so the UI must fall back to its own copy rather
// than surface "Unknown error." or a raw network message as Meta's words.
test("omits providerMessage when the failure carries no Graph error code", async () => {
mockGetUserPages.mockRejectedValue(new Error("fetch failed"))
mockMapToChannelError.mockReturnValue({
message: "fetch failed",
code: -1,
category: "unknown",
})

const element = await MessengerSelectPage()

if (!isValidElement<SelectPageElementProps>(element)) {
throw new Error("MessengerSelectPage did not return a valid element")
}

expect(element.props.items).toEqual([])
expect(element.props.loadError).toEqual({ providerMessage: undefined })
})

test("passes no loadError when Graph lists pages successfully", async () => {
const element = await MessengerSelectPage()

if (!isValidElement<SelectPageElementProps>(element)) {
throw new Error("MessengerSelectPage did not return a valid element")
}

expect(element.props.loadError).toBeUndefined()
})

test("redirects to channel creation when the pending-auth cookie is missing or invalid", async () => {
mockReadPendingAuth.mockResolvedValue(null)

Expand Down
1 change: 1 addition & 0 deletions apps/builder/messages/ar.json
Original file line number Diff line number Diff line change
Expand Up @@ -3386,6 +3386,7 @@
"noConnectablePagesDescription": "أنت لست مسؤولاً عن هذه الصفحة",
"bmLookupFailedTitle": "قد تكون بعض صفحات مدير الأعمال غير ظاهرة",
"bmLookupFailedDescription": "أعد ربط Messenger وامنح صلاحية الوصول إلى مدير الأعمال حتى يمكن عرض الصفحات المُدارة من خلاله.",
"loadFailed": "تعذّر تحميل صفحات فيسبوك الخاصة بك",
"alreadyConnectedNote": "هذه الصفحة مرتبطة بالفعل",
"notAdminNote": "أنت لست مسؤولاً عن هذه الصفحة",
"tryAgain": "محاولة إعادة الاتصال"
Expand Down
1 change: 1 addition & 0 deletions apps/builder/messages/da.json
Original file line number Diff line number Diff line change
Expand Up @@ -3386,6 +3386,7 @@
"noConnectablePagesDescription": "Du er ikke administrator for denne side",
"bmLookupFailedTitle": "Business Manager pages may være missing",
"bmLookupFailedDescription": "Forbind igen Messenger og grant Business Manager access so pages managed through a Business Manager kan være listed.",
"loadFailed": "Kunne ikke indlæse dine Facebook-sider",
"alreadyConnectedNote": "Denne page er allerede forbundet",
"notAdminNote": "Du er ikke administrator for denne side",
"tryAgain": "Try reconnecting"
Expand Down
1 change: 1 addition & 0 deletions apps/builder/messages/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -3386,6 +3386,7 @@
"noConnectablePagesDescription": "Sie sind kein Administrator dieser Seite",
"bmLookupFailedTitle": "Business-Manager-Seiten fehlen möglicherweise",
"bmLookupFailedDescription": "Verbinden Sie Messenger erneut und gewähren Sie Zugriff auf den Business Manager, damit über ihn verwaltete Seiten aufgelistet werden können.",
"loadFailed": "Deine Facebook-Seiten konnten nicht geladen werden",
"alreadyConnectedNote": "Diese Seite ist bereits verbunden",
"notAdminNote": "Sie sind kein Administrator dieser Seite",
"tryAgain": "Erneute Verbindung versuchen"
Expand Down
1 change: 1 addition & 0 deletions apps/builder/messages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -3574,6 +3574,7 @@
"noConnectablePagesDescription": "You are not an admin of this Page",
"bmLookupFailedTitle": "Business Manager pages may be missing",
"bmLookupFailedDescription": "Reconnect Messenger and grant Business Manager access so pages managed through a Business Manager can be listed.",
"loadFailed": "Couldn't load your Facebook Pages",
"alreadyConnectedNote": "This page is already connected",
"notAdminNote": "You are not an admin of this Page",
"tryAgain": "Try reconnecting"
Expand Down
1 change: 1 addition & 0 deletions apps/builder/messages/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -3386,6 +3386,7 @@
"noConnectablePagesDescription": "No eres administrador de esta página",
"bmLookupFailedTitle": "Empresa Manager páginas may be missing",
"bmLookupFailedDescription": "ReConectar Messenger y grant Empresa Manager access so páginas managed through un Empresa Manager puede be listed.",
"loadFailed": "No se pudieron cargar tus páginas de Facebook",
"alreadyConnectedNote": "This página es already connected",
"notAdminNote": "No eres administrador de esta página",
"tryAgain": "Intenta volver a conectar"
Expand Down
1 change: 1 addition & 0 deletions apps/builder/messages/fi.json
Original file line number Diff line number Diff line change
Expand Up @@ -3386,6 +3386,7 @@
"noConnectablePagesDescription": "Et ole tämän sivun ylläpitäjä",
"bmLookupFailedTitle": "Business Manager -sivuja saattaa puuttua",
"bmLookupFailedDescription": "Yhdistä Messenger uudelleen ja myönnä Business Manager -käyttöoikeus, jotta Business Managerin kautta hallinnoidut sivut voidaan näyttää.",
"loadFailed": "Facebook-sivujesi lataaminen epäonnistui",
"alreadyConnectedNote": "Tämä sivu on jo yhdistetty",
"notAdminNote": "Et ole tämän sivun ylläpitäjä",
"tryAgain": "Yritä yhdistää uudelleen"
Expand Down
1 change: 1 addition & 0 deletions apps/builder/messages/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -3386,6 +3386,7 @@
"noConnectablePagesDescription": "Vous n’êtes pas administrateur de cette Page",
"bmLookupFailedTitle": "Certaines Pages du Business Manager peuvent manquer",
"bmLookupFailedDescription": "Reconnectez Messenger et accordez l’accès au Business Manager afin de répertorier les Pages qu’il gère.",
"loadFailed": "Impossible de charger vos Pages Facebook",
"alreadyConnectedNote": "Cette Page est déjà connectée",
"notAdminNote": "Vous n’êtes pas administrateur de cette Page",
"tryAgain": "Réessayer la connexion"
Expand Down
1 change: 1 addition & 0 deletions apps/builder/messages/he.json
Original file line number Diff line number Diff line change
Expand Up @@ -1443,6 +1443,7 @@
"noConnectablePagesDescription": "אינך מנהל של דף זה",
"bmLookupFailedTitle": "ייתכן שחסרים דפי Business Manager",
"bmLookupFailedDescription": "חברו מחדש את Messenger והעניקו גישה ל-Business Manager כדי שניתן יהיה להציג דפים המנוהלים דרכו.",
"loadFailed": "לא ניתן לטעון את דפי הפייסבוק שלך",
"alreadyConnectedNote": "דף זה כבר מחובר",
"notAdminNote": "אינך מנהל של דף זה",
"tryAgain": "ניסיון חיבור מחדש"
Expand Down
1 change: 1 addition & 0 deletions apps/builder/messages/id.json
Original file line number Diff line number Diff line change
Expand Up @@ -3386,6 +3386,7 @@
"noConnectablePagesDescription": "Anda bukan admin Halaman ini",
"bmLookupFailedTitle": "Halaman Business Manager mungkin tidak ditampilkan",
"bmLookupFailedDescription": "Hubungkan kembali Messenger dan berikan akses Business Manager agar halaman yang dikelola melalui Business Manager dapat ditampilkan.",
"loadFailed": "Tidak dapat memuat Halaman Facebook Anda",
"alreadyConnectedNote": "Halaman ini sudah terhubung",
"notAdminNote": "Anda bukan admin Halaman ini",
"tryAgain": "Coba hubungkan kembali"
Expand Down
1 change: 1 addition & 0 deletions apps/builder/messages/it.json
Original file line number Diff line number Diff line change
Expand Up @@ -3386,6 +3386,7 @@
"noConnectablePagesDescription": "Non sei amministratore di questa Pagina",
"bmLookupFailedTitle": "Alcune Pagine di Business Manager potrebbero non essere disponibili",
"bmLookupFailedDescription": "Ricollega Messenger e concedi l'accesso a Business Manager affinché possano essere elencate le Pagine gestite tramite Business Manager.",
"loadFailed": "Impossibile caricare le tue Pagine Facebook",
"alreadyConnectedNote": "Questa Pagina è già collegata",
"notAdminNote": "Non sei amministratore di questa Pagina",
"tryAgain": "Prova a ricollegarti"
Expand Down
1 change: 1 addition & 0 deletions apps/builder/messages/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -3365,6 +3365,7 @@
"noConnectablePagesDescription": "あなたはこのページの管理者ではありません",
"bmLookupFailedTitle": "ビジネスマネージャのページが一部表示されていない可能性があります",
"bmLookupFailedDescription": "Messengerを再接続し、ビジネスマネージャへのアクセスを許可すると、ビジネスマネージャで管理されているページを一覧表示できます。",
"loadFailed": "Facebookページを読み込めませんでした",
"alreadyConnectedNote": "このページはすでに接続されています",
"notAdminNote": "あなたはこのページの管理者ではありません",
"tryAgain": "再接続を試す"
Expand Down
1 change: 1 addition & 0 deletions apps/builder/messages/nl.json
Original file line number Diff line number Diff line change
Expand Up @@ -3386,6 +3386,7 @@
"noConnectablePagesDescription": "U bent geen beheerder van deze pagina",
"bmLookupFailedTitle": "Pagina's uit Bedrijfsmanager ontbreken mogelijk",
"bmLookupFailedDescription": "Koppel Messenger opnieuw en verleen toegang tot Bedrijfsmanager zodat pagina's die via Bedrijfsmanager worden beheerd kunnen worden vermeld.",
"loadFailed": "Je Facebook-pagina's konden niet worden geladen",
"alreadyConnectedNote": "Deze pagina is al gekoppeld",
"notAdminNote": "U bent geen beheerder van deze pagina",
"tryAgain": "Probeer opnieuw te koppelen"
Expand Down
1 change: 1 addition & 0 deletions apps/builder/messages/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -3365,6 +3365,7 @@
"noConnectablePagesDescription": "Você não é administrador desta Página",
"bmLookupFailedTitle": "Algumas páginas do Gerenciador de Negócios podem não aparecer",
"bmLookupFailedDescription": "Reconecte o Messenger e conceda acesso ao Gerenciador de Negócios para que as páginas gerenciadas por ele possam ser listadas.",
"loadFailed": "Não foi possível carregar suas Páginas do Facebook",
"alreadyConnectedNote": "Esta página já está conectada",
"notAdminNote": "Você não é administrador desta Página",
"tryAgain": "Tentar reconectar"
Expand Down
1 change: 1 addition & 0 deletions apps/builder/messages/pt-PT.json
Original file line number Diff line number Diff line change
Expand Up @@ -3386,6 +3386,7 @@
"noConnectablePagesDescription": "Não é administrador desta Página",
"bmLookupFailedTitle": "Poderão faltar páginas do Gestor de Negócios",
"bmLookupFailedDescription": "Volte a ligar o Messenger e conceda acesso ao Gestor de Negócios para que as páginas geridas através dele possam ser apresentadas.",
"loadFailed": "Não foi possível carregar as suas Páginas do Facebook",
"alreadyConnectedNote": "Esta página já está ligada",
"notAdminNote": "Não é administrador desta Página",
"tryAgain": "Tentar ligar novamente"
Expand Down
1 change: 1 addition & 0 deletions apps/builder/messages/ro.json
Original file line number Diff line number Diff line change
Expand Up @@ -3386,6 +3386,7 @@
"noConnectablePagesDescription": "Nu ești administrator al acestei Pagini",
"bmLookupFailedTitle": "Este posibil să lipsească paginile din Business Manager",
"bmLookupFailedDescription": "Reconectează Messenger și acordă acces la Business Manager pentru ca paginile gestionate printr-un Business Manager să poată fi listate.",
"loadFailed": "Nu s-au putut încărca Paginile tale de Facebook",
"alreadyConnectedNote": "Această pagină este deja conectată",
"notAdminNote": "Nu ești administrator al acestei Pagini",
"tryAgain": "Încearcă să te reconectezi"
Expand Down
1 change: 1 addition & 0 deletions apps/builder/messages/sv.json
Original file line number Diff line number Diff line change
Expand Up @@ -4136,6 +4136,7 @@
"selectPage": {
"alreadyConnectedNote": "Den här sidan är redan ansluten",
"bmLookupFailedDescription": "Återanslut Messenger och bevilja åtkomst till Business Manager så att sidor som hanteras där kan visas.",
"loadFailed": "Det gick inte att läsa in dina Facebook-sidor",
"bmLookupFailedTitle": "Business Manager-sidor kan saknas",
"noConnectablePagesDescription": "Du är inte administratör för den här sidan",
"noConnectablePagesTitle": "Inga sidor tillgängliga att ansluta",
Expand Down
1 change: 1 addition & 0 deletions apps/builder/messages/tr.json
Original file line number Diff line number Diff line change
Expand Up @@ -3386,6 +3386,7 @@
"noConnectablePagesDescription": "Bu Sayfanın yöneticisi değilsiniz",
"bmLookupFailedTitle": "İşletme Yöneticisi sayfaları eksik olabilir",
"bmLookupFailedDescription": "Bir İşletme Yöneticisi üzerinden yönetilen sayfaların listelenebilmesi için Messenger'ı yeniden bağlayın ve İşletme Yöneticisi erişimi verin.",
"loadFailed": "Facebook Sayfaların yüklenemedi",
"alreadyConnectedNote": "Bu sayfa zaten bağlı",
"notAdminNote": "Bu Sayfanın yöneticisi değilsiniz",
"tryAgain": "Yeniden bağlanmayı dene"
Expand Down
1 change: 1 addition & 0 deletions apps/builder/messages/vi.json
Original file line number Diff line number Diff line change
Expand Up @@ -3386,6 +3386,7 @@
"noConnectablePagesDescription": "Bạn không phải là Admin của Page này",
"bmLookupFailedTitle": "Có thể thiếu trang trong Business Manager",
"bmLookupFailedDescription": "Hãy kết nối lại Messenger và cấp quyền Business Manager để liệt kê các trang được quản lý qua Business Manager.",
"loadFailed": "Không tải được danh sách Trang Facebook",
"alreadyConnectedNote": "Trang này đã được kết nối",
"notAdminNote": "Bạn không phải là Admin của Page này",
"tryAgain": "Kết nối lại"
Expand Down
1 change: 1 addition & 0 deletions apps/builder/messages/zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -4136,6 +4136,7 @@
"selectPage": {
"alreadyConnectedNote": "该页面已连接",
"bmLookupFailedDescription": "重新连接Messenger 并授予商务管理平台访问权限,以便可以列出通过商务管理平台管理的页面。",
"loadFailed": "无法加载你的 Facebook 主页",
"bmLookupFailedTitle": "业务管理平台页面可能遗失",
"noConnectablePagesDescription": "您不是此页面的管理员",
"noConnectablePagesTitle": "没有可连接的页面",
Expand Down
1 change: 1 addition & 0 deletions apps/builder/messages/zh-TW.json
Original file line number Diff line number Diff line change
Expand Up @@ -3419,6 +3419,7 @@
"noConnectablePagesDescription": "您不是此頁面的管理員",
"bmLookupFailedTitle": "業務管理平台頁面可能遺失",
"bmLookupFailedDescription": "重新連接Messenger 並授予商務管理平台存取權限,以便可以列出透過商務管理平台管理的頁面。",
"loadFailed": "無法載入你的 Facebook 粉絲專頁",
"alreadyConnectedNote": "該頁面已連接",
"notAdminNote": "您不是此頁面的管理員",
"tryAgain": "嘗試重新連接"
Expand Down
Loading
Loading