diff --git a/apps/web/app/(with-contexts)/dashboard/(sidebar)/support/__tests__/page.test.tsx b/apps/web/app/(with-contexts)/dashboard/(sidebar)/support/__tests__/page.test.tsx new file mode 100644 index 000000000..1e9605d18 --- /dev/null +++ b/apps/web/app/(with-contexts)/dashboard/(sidebar)/support/__tests__/page.test.tsx @@ -0,0 +1,91 @@ +import React from "react"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { ServerConfigContext } from "@components/contexts"; +import Page from "../page"; + +jest.mock("@components/admin/dashboard-content", () => ({ + __esModule: true, + default: ({ children }: { children: React.ReactNode }) => <>{children}, +})); + +jest.mock("@courselit/components-library", () => { + const Box = ({ children }: { children: React.ReactNode }) => ( +
{children}
+ ); + return { + Card: Box, + CardContent: Box, + CardFooter: Box, + CardHeader: Box, + CardTitle: Box, + Button2: ({ + children, + onClick, + }: { + children: React.ReactNode; + onClick?: () => void; + }) => , + ToastAction: () => null, + useToast: () => ({ toast: jest.fn() }), + }; +}); + +jest.mock("next/navigation", () => ({ + usePathname: () => "/dashboard/support", +})); + +const supportChat = { + teamId: "team_support", + loaderUrl: "https://embed.support.test/chat.js", +}; + +function renderPage(config: Record) { + return render( + + + , + ); +} + +type ChatWindow = { FrontLit?: { q?: unknown[][] } }; + +describe("dashboard support page", () => { + beforeEach(() => { + delete (window as unknown as ChatWindow).FrontLit; + global.fetch = jest.fn().mockResolvedValue({ + ok: true, + json: async () => ({ token: "session-token" }), + }) as unknown as typeof fetch; + }); + + it("offers the support chat instead of community channels on hosted schools", async () => { + renderPage({ supportChat }); + + expect(screen.getByText("Documentation")).toBeInTheDocument(); + expect(screen.getByText("Chat with us")).toBeInTheDocument(); + expect(screen.queryByText("Ask in Discord")).not.toBeInTheDocument(); + expect(screen.queryByText("Found a bug?")).not.toBeInTheDocument(); + expect(screen.queryByText("Priority Support")).not.toBeInTheDocument(); + + fireEvent.click(screen.getByText("Start a chat")); + + await waitFor(() => + expect( + (window as unknown as ChatWindow).FrontLit?.q, + ).toContainEqual(["open", { token: "session-token" }]), + ); + const body = JSON.parse( + (global.fetch as jest.Mock).mock.calls[0][1].body, + ); + expect(body.error).toBeUndefined(); + }); + + it("keeps community channels and paid support on self-hosted setups", () => { + renderPage({}); + + expect(screen.getByText("Ask in Discord")).toBeInTheDocument(); + expect(screen.getByText("Found a bug?")).toBeInTheDocument(); + expect(screen.getByText("Priority Support")).toBeInTheDocument(); + expect(screen.queryByText("Chat with us")).not.toBeInTheDocument(); + }); +}); diff --git a/apps/web/app/(with-contexts)/dashboard/(sidebar)/support/page.tsx b/apps/web/app/(with-contexts)/dashboard/(sidebar)/support/page.tsx index 237f58b0a..baefe1b38 100644 --- a/apps/web/app/(with-contexts)/dashboard/(sidebar)/support/page.tsx +++ b/apps/web/app/(with-contexts)/dashboard/(sidebar)/support/page.tsx @@ -10,12 +10,25 @@ import { CardHeader, CardTitle, } from "@courselit/components-library"; -import { HEADER_HELP } from "@ui-config/strings"; +import { ServerConfigContext } from "@components/contexts"; +import { useContactSupport } from "@components/support-chat"; +import { + HEADER_HELP, + SUPPORT_CHAT_CARD_BUTTON, + SUPPORT_CHAT_CARD_DESCRIPTION, + SUPPORT_CHAT_CARD_TITLE, +} from "@ui-config/strings"; +import { useContext } from "react"; const { permissions } = UIConstants; const breadcrumbs = [{ label: HEADER_HELP, href: "#" }]; export default function Page() { + // Hosted schools get the support chat; self-hosted ones keep the + // community channels and paid support. + const { supportChat } = useContext(ServerConfigContext); + const contactSupport = useContactSupport(); + return (
- + Documentation @@ -53,62 +66,91 @@ export default function Page() { - - - Ask in Discord - - -

- Come ask your questions directly from the team. We - are quite active there. -

-
- - - Open Discord - - -
- - - Found a bug? - - -

- We encourage you to raise an issue so that we can - make the product better for everyone. -

-
- + {supportChat ? ( + + + {SUPPORT_CHAT_CARD_TITLE} + + +

+ {SUPPORT_CHAT_CARD_DESCRIPTION} +

+
+ + void contactSupport()} + > + {SUPPORT_CHAT_CARD_BUTTON} + + +
+ ) : ( + <> + + + Ask in Discord + + +

+ Come ask your questions directly from the + team. We are quite active there. +

+
+ + + + Open Discord + + + +
+ + + Found a bug? + + +

+ We encourage you to raise an issue so that + we can make the product better for everyone. +

+
+ + + + Post an issue + + + +
+ + )} +
+ {!supportChat && ( +
+

+ Priority Support +

+

+ In case you need to get in touch with the team to get + help faster, we offer paid support. + Please reach out to us on{" "} - Post an issue - - - -

-
-

- Priority Support -

-

- In case you need to get in touch with the team to get help - faster, we offer paid support. Please reach - out to us on{" "} - - CourseLit Support - {" "} - with your requirements . -

-
+ CourseLit Support + {" "} + with your requirements . +

+ + )}
); } diff --git a/apps/web/app/(with-contexts)/layout-with-context.tsx b/apps/web/app/(with-contexts)/layout-with-context.tsx index 7905f7489..9424295c2 100644 --- a/apps/web/app/(with-contexts)/layout-with-context.tsx +++ b/apps/web/app/(with-contexts)/layout-with-context.tsx @@ -23,6 +23,7 @@ import { Theme } from "@courselit/page-models"; import { ThemeProvider as NextThemesProvider } from "@components/next-theme-provider"; import { defaultState } from "@components/default-state"; import { getUserProfile } from "./helpers"; +import { SupportChat, useSupportErrorToasts } from "@components/support-chat"; import { auth } from "@/auth"; type BetterAuthSession = Awaited> | null; @@ -47,6 +48,7 @@ function LayoutContent({ const [profile, setProfile] = useState(defaultState.profile); const [theme, setTheme] = useState(initialTheme); const { toast } = useToast(); + const mapToast = useSupportErrorToasts(config.supportChat); const updateUserProfile = useCallback(async () => { try { @@ -109,7 +111,8 @@ function LayoutContent({ - + + ); diff --git a/apps/web/app/(with-contexts)/layout.tsx b/apps/web/app/(with-contexts)/layout.tsx index 373ead0a5..989c19446 100644 --- a/apps/web/app/(with-contexts)/layout.tsx +++ b/apps/web/app/(with-contexts)/layout.tsx @@ -8,6 +8,7 @@ import { defaultState } from "@components/default-state"; import { decode } from "base-64"; import { ServerConfig, SiteInfo } from "@courselit/common-models"; import constants from "@config/constants"; +import { getSupportChatConfig } from "@/lib/support-chat"; export default async function Layout({ children, @@ -25,6 +26,7 @@ export default async function Layout({ queueServer: process.env.QUEUE_SERVER || "", cacheEnabled: constants.cacheEnabled, recaptchaSiteKey: process.env.RECAPTCHA_SITE_KEY || "", + supportChat: getSupportChatConfig(), }; return ( diff --git a/apps/web/app/api/support/session/__tests__/route.test.ts b/apps/web/app/api/support/session/__tests__/route.test.ts new file mode 100644 index 000000000..6aebaf82f --- /dev/null +++ b/apps/web/app/api/support/session/__tests__/route.test.ts @@ -0,0 +1,159 @@ +/** + * @jest-environment node + */ + +import { NextRequest } from "next/server"; +import Domain from "@models/Domain"; +import User from "@models/User"; +import { auth } from "@/auth"; +import constants from "@config/constants"; + +jest.mock("@models/Domain"); +jest.mock("@models/User"); +jest.mock("@/services/logger", () => ({ error: jest.fn() })); +jest.mock("@config/constants", () => ({ + __esModule: true, + default: { multitenant: true }, +})); +jest.mock("@/auth", () => ({ + auth: { + api: { + getSession: jest.fn(), + }, + }, +})); + +const domain = { + _id: "domain-id", + name: "school", + settings: { title: "Acme School" }, +}; + +function request(body: unknown, headers: Record = {}) { + const all: Record = { + domain: "school", + host: "school.courselit.app", + "x-forwarded-proto": "https", + "user-agent": "jest", + ...headers, + }; + return { + headers: { + get: jest.fn((name: string) => all[name] ?? null), + }, + json: jest.fn().mockResolvedValue(body), + } as unknown as NextRequest; +} + +const fetchMock = jest.fn(); + +describe("POST /api/support/session", () => { + beforeEach(() => { + jest.clearAllMocks(); + global.fetch = fetchMock as unknown as typeof fetch; + (constants as { multitenant: boolean }).multitenant = true; + process.env.FRONTLIT_TEAM_ID = "team_support"; + process.env.FRONTLIT_SUPPORT_API_KEY = "support-key"; + process.env.FRONTLIT_API_URL = "https://api.support.test/"; + (Domain.findOne as jest.Mock).mockResolvedValue(domain); + (auth.api.getSession as unknown as jest.Mock).mockResolvedValue({ + user: { email: "admin@acme.test" }, + }); + (User.findOne as jest.Mock).mockResolvedValue({ + userId: "user-1", + email: "admin@acme.test", + name: "Ada Admin", + }); + fetchMock.mockResolvedValue({ + ok: true, + json: async () => ({ token: "session-token" }), + }); + }); + + afterAll(() => { + delete process.env.FRONTLIT_TEAM_ID; + delete process.env.FRONTLIT_SUPPORT_API_KEY; + delete process.env.FRONTLIT_API_URL; + }); + + it("starts a session with the user, school and error", async () => { + const { POST } = await import("../route"); + const response = await POST( + request({ + page: "/dashboard/product/abc/content", + error: { title: "Upload Failed", message: "TUS 413" }, + }), + ); + + expect(response.status).toBe(200); + await expect(response.json()).resolves.toEqual({ + token: "session-token", + }); + expect(fetchMock).toHaveBeenCalledWith( + "https://api.support.test/support-sessions", + expect.objectContaining({ method: "POST" }), + ); + const [, init] = fetchMock.mock.calls[0]; + expect(init.headers["x-frontlit-apikey"]).toBe("support-key"); + expect(JSON.parse(init.body)).toEqual({ + contact: { + email: "admin@acme.test", + name: "Ada Admin", + externalId: "user-1", + }, + account: { + id: "school", + name: "Acme School", + url: "https://school.courselit.app", + }, + context: { + page: "/dashboard/product/abc/content", + errorTitle: "Upload Failed", + error: "TUS 413", + userAgent: "jest", + }, + }); + }); + + it("is unavailable on self-hosted (single tenant) setups", async () => { + (constants as { multitenant: boolean }).multitenant = false; + const { POST } = await import("../route"); + const response = await POST(request({ page: "/dashboard" })); + + expect(response.status).toBe(404); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("is unavailable without a support team", async () => { + delete process.env.FRONTLIT_TEAM_ID; + const { POST } = await import("../route"); + const response = await POST(request({ page: "/dashboard" })); + + expect(response.status).toBe(404); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("rejects signed-out requests", async () => { + (auth.api.getSession as unknown as jest.Mock).mockResolvedValue(null); + const { POST } = await import("../route"); + const response = await POST(request({ page: "/dashboard" })); + + expect(response.status).toBe(401); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("rejects a malformed body", async () => { + const { POST } = await import("../route"); + const response = await POST(request({ page: 42 })); + + expect(response.status).toBe(400); + }); + + it("reports a failed session as a bad gateway", async () => { + fetchMock.mockResolvedValue({ ok: false, status: 500 }); + const { POST } = await import("../route"); + const response = await POST(request({ page: "/dashboard" })); + + expect(response.status).toBe(502); + }); +}); diff --git a/apps/web/app/api/support/session/route.ts b/apps/web/app/api/support/session/route.ts new file mode 100644 index 000000000..6d1e3a762 --- /dev/null +++ b/apps/web/app/api/support/session/route.ts @@ -0,0 +1,96 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { auth } from "@/auth"; +import User from "@models/User"; +import DomainModel, { Domain } from "@models/Domain"; +import { error as logError } from "@/services/logger"; +import { getBackendAddress } from "@/app/actions"; +import { getSupportApiUrl, isSupportChatEnabled } from "@/lib/support-chat"; + +const MAX_TEXT = 2000; + +const requestSchema = z.object({ + page: z.string().max(MAX_TEXT), + error: z + .object({ + title: z.string().max(MAX_TEXT).optional(), + message: z.string().max(MAX_TEXT).optional(), + }) + .optional(), +}); + +/** + * Starts an in-app support session for the signed-in user and returns the + * token the support chat opens with. Identity and school come from the + * server; the browser only sends the page and the error it saw. + */ +export async function POST(req: NextRequest) { + if (!isSupportChatEnabled()) { + return Response.json({}, { status: 404 }); + } + + const parsed = requestSchema.safeParse(await req.json().catch(() => null)); + if (!parsed.success) { + return Response.json({ message: "Invalid request" }, { status: 400 }); + } + + const domain = await DomainModel.findOne({ + name: req.headers.get("domain"), + }); + if (!domain) { + return Response.json({ message: "Domain not found" }, { status: 404 }); + } + + const session = await auth.api.getSession({ headers: req.headers }); + const user = session + ? await User.findOne({ + email: session.user!.email, + domain: domain._id, + active: true, + }) + : null; + if (!user) { + return Response.json({}, { status: 401 }); + } + + const { page, error } = parsed.data; + const schoolUrl = await getBackendAddress(req.headers); + + try { + const response = await fetch(`${getSupportApiUrl()}/support-sessions`, { + method: "POST", + headers: { + "content-type": "application/json", + "x-frontlit-apikey": process.env.FRONTLIT_SUPPORT_API_KEY!, + }, + body: JSON.stringify({ + contact: { + email: user.email, + name: user.name || undefined, + externalId: user.userId, + }, + account: { + id: domain.name, + name: domain.settings?.title || domain.name, + url: schoolUrl, + }, + context: { + page, + ...(error?.title ? { errorTitle: error.title } : {}), + ...(error?.message ? { error: error.message } : {}), + userAgent: req.headers.get("user-agent") || undefined, + }, + }), + }); + if (!response.ok) { + throw new Error( + `Support session request failed with ${response.status}`, + ); + } + const { token } = await response.json(); + return Response.json({ token }); + } catch (err: any) { + logError(err.message, { stack: err.stack }); + return Response.json({}, { status: 502 }); + } +} diff --git a/apps/web/components/__tests__/support-chat.test.tsx b/apps/web/components/__tests__/support-chat.test.tsx new file mode 100644 index 000000000..5b2f7f5d1 --- /dev/null +++ b/apps/web/components/__tests__/support-chat.test.tsx @@ -0,0 +1,181 @@ +import React from "react"; +import { + act, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/react"; +import { SupportChat, useSupportErrorToasts } from "../support-chat"; + +type TestToast = { + title?: React.ReactNode; + description?: React.ReactNode; + variant?: string; + action?: React.ReactNode; +}; + +// A stand-in for the library's toast store and Toaster: the real Toaster +// applies `mapToast` to each toast before rendering it, as this one does. +let mockToasts: TestToast[] = []; +let mockRerender: () => void = () => {}; +jest.mock("@courselit/components-library", () => ({ + useToast: () => ({ + toast: (item: TestToast) => { + mockToasts = [item]; + mockRerender(); + }, + }), + ToastAction: ({ + children, + onClick, + }: { + children: React.ReactNode; + onClick: () => void; + }) => , +})); + +function Toaster({ mapToast }: { mapToast?: (t: TestToast) => TestToast }) { + const [, setTick] = React.useState(0); + React.useEffect(() => { + mockRerender = () => setTick((n) => n + 1); + }, []); + return ( + <> + {mockToasts.map((item, index) => { + const shown = mapToast ? mapToast(item) : item; + return ( +
+

{shown.title}

+

{shown.description}

+ {shown.action} +
+ ); + })} + + ); +} + +let mockPathname = "/dashboard/products"; +jest.mock("next/navigation", () => ({ + usePathname: () => mockPathname, +})); + +const config = { + teamId: "team_support", + loaderUrl: "https://embed.support.test/chat.js", +}; + +function showToast(item: TestToast) { + mockToasts = [item]; + mockRerender(); +} + +function Harness({ enabled = true }: { enabled?: boolean }) { + const mapToast = useSupportErrorToasts(enabled ? config : undefined); + return ( + <> + + + + ); +} + +type ChatWindow = { FrontLit?: { q?: unknown[][] } }; + +describe("support chat on the dashboard", () => { + beforeEach(() => { + mockPathname = "/dashboard/products"; + mockToasts = []; + delete (window as unknown as ChatWindow).FrontLit; + document + .querySelectorAll("script[data-support-chat]") + .forEach((script) => script.remove()); + global.fetch = jest.fn().mockResolvedValue({ + ok: true, + json: async () => ({ token: "session-token" }), + }) as unknown as typeof fetch; + }); + + it("replaces the raw error with a contact support prompt", async () => { + render(); + act(() => { + showToast({ + title: "Upload Failed", + description: "TUS: unexpected response 413", + variant: "destructive", + }); + }); + + expect(screen.getByText("Something went wrong")).toBeInTheDocument(); + expect( + screen.getByText("We've encountered an error while doing that."), + ).toBeInTheDocument(); + expect( + screen.queryByText("TUS: unexpected response 413"), + ).not.toBeInTheDocument(); + + fireEvent.click(screen.getByText("Contact support")); + + await waitFor(() => + expect(global.fetch).toHaveBeenCalledWith( + "/api/support/session", + expect.objectContaining({ method: "POST" }), + ), + ); + const body = JSON.parse( + (global.fetch as jest.Mock).mock.calls[0][1].body, + ); + expect(body.error).toEqual({ + title: "Upload Failed", + message: "TUS: unexpected response 413", + }); + await waitFor(() => + expect( + (window as unknown as ChatWindow).FrontLit?.q, + ).toContainEqual(["open", { token: "session-token" }]), + ); + }); + + it("loads the chat without a launcher on dashboard pages", () => { + render(); + + const script = document.querySelector("script[data-support-chat]"); + expect(script?.getAttribute("src")).toBe(config.loaderUrl); + expect((window as unknown as ChatWindow).FrontLit?.q).toContainEqual([ + "init", + { teamId: "team_support", launcher: false }, + ]); + }); + + it("leaves error toasts alone outside the dashboard", () => { + mockPathname = "/courses"; + render(); + act(() => { + showToast({ + title: "Error", + description: "Raw error", + variant: "destructive", + }); + }); + + expect(screen.getByText("Raw error")).toBeInTheDocument(); + expect(screen.queryByText("Contact support")).not.toBeInTheDocument(); + expect(document.querySelector("script[data-support-chat]")).toBeNull(); + }); + + it("leaves error toasts alone when support isn't configured", () => { + render(); + act(() => { + showToast({ + title: "Error", + description: "Raw error", + variant: "destructive", + }); + }); + + expect(screen.getByText("Raw error")).toBeInTheDocument(); + expect(screen.queryByText("Contact support")).not.toBeInTheDocument(); + expect(document.querySelector("script[data-support-chat]")).toBeNull(); + }); +}); diff --git a/apps/web/components/support-chat.tsx b/apps/web/components/support-chat.tsx new file mode 100644 index 000000000..0e58156ff --- /dev/null +++ b/apps/web/components/support-chat.tsx @@ -0,0 +1,170 @@ +"use client"; + +import { ReactNode, useCallback, useEffect } from "react"; +import { usePathname } from "next/navigation"; +import { + ToastAction, + useToast, + type ToasterToast, +} from "@courselit/components-library"; +import type { + SupportChatConfig, + SupportSessionRequest, +} from "@courselit/common-models"; +import { + SUPPORT_CONTACT_BUTTON, + SUPPORT_ERROR_TOAST_DESCRIPTION, + SUPPORT_ERROR_TOAST_TITLE, + SUPPORT_UNAVAILABLE_DESCRIPTION, + SUPPORT_UNAVAILABLE_TITLE, + TOAST_TITLE_ERROR, +} from "@ui-config/strings"; + +const SUPPORT_PATH_PREFIX = "/dashboard"; +const LOADER_MARKER = "data-support-chat"; + +type ChatCommand = [string, unknown?]; +interface ChatGlobal { + q?: ChatCommand[]; + push: (...command: ChatCommand) => void; +} + +function chatGlobal(): ChatGlobal { + const w = window as unknown as { FrontLit?: ChatGlobal }; + if (!w.FrontLit) { + // The standard queue stub: calls made before the loader arrives are + // replayed once it has loaded. + const stub: ChatGlobal = { + q: [], + push(...command) { + stub.q!.push(command); + }, + }; + w.FrontLit = stub; + } + return w.FrontLit; +} + +function loadChat(config: SupportChatConfig) { + if (document.querySelector(`script[${LOADER_MARKER}]`)) { + return; + } + chatGlobal().push("init", { teamId: config.teamId, launcher: false }); + const script = document.createElement("script"); + script.async = true; + script.src = config.loaderUrl; + script.setAttribute(LOADER_MARKER, ""); + document.head.appendChild(script); +} + +export function isSupportPath(pathname: string | null) { + return ( + !!pathname && + (pathname === SUPPORT_PATH_PREFIX || + pathname.startsWith(`${SUPPORT_PATH_PREFIX}/`)) + ); +} + +function asText(node: ReactNode) { + return typeof node === "string" || typeof node === "number" + ? String(node) + : undefined; +} + +/** Loads the support chat on dashboard pages and closes it outside them. */ +export function SupportChat({ config }: { config?: SupportChatConfig }) { + const pathname = usePathname(); + const onSupportPath = isSupportPath(pathname); + + useEffect(() => { + if (!config) { + return; + } + if (onSupportPath) { + loadChat(config); + } else if (document.querySelector(`script[${LOADER_MARKER}]`)) { + chatGlobal().push("close"); + } + }, [config, onSupportPath]); + + return null; +} + +/** + * Returns a function that starts a support session for the signed-in user and + * opens the chat with it, optionally with an error attached. + */ +export function useContactSupport() { + const { toast } = useToast(); + + return useCallback( + async (error?: SupportSessionRequest["error"]) => { + const body: SupportSessionRequest = { + page: `${window.location.pathname}${window.location.search}`, + error, + }; + try { + const response = await fetch("/api/support/session", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), + }); + if (!response.ok) { + throw new Error( + `Support session failed: ${response.status}`, + ); + } + const { token } = await response.json(); + chatGlobal().push("open", { token }); + } catch { + toast({ + title: SUPPORT_UNAVAILABLE_TITLE, + description: SUPPORT_UNAVAILABLE_DESCRIPTION, + }); + } + }, + [toast], + ); +} + +/** + * On dashboard pages, replaces an error toast's raw message with a friendly + * one and a button that opens the support chat with the error attached. + * Returns undefined when support isn't available, leaving toasts unchanged. + */ +export function useSupportErrorToasts(config?: SupportChatConfig) { + const pathname = usePathname(); + const contactSupport = useContactSupport(); + const enabled = !!config && isSupportPath(pathname); + + const mapToast = useCallback( + (item: ToasterToast): ToasterToast => { + const isError = + item.variant === "destructive" || + item.title === TOAST_TITLE_ERROR; + if (!isError) { + return item; + } + const error = { + title: asText(item.title), + message: asText(item.description), + }; + return { + ...item, + title: SUPPORT_ERROR_TOAST_TITLE, + description: SUPPORT_ERROR_TOAST_DESCRIPTION, + action: ( + void contactSupport(error)} + > + {SUPPORT_CONTACT_BUTTON} + + ), + }; + }, + [contactSupport], + ); + + return enabled ? mapToast : undefined; +} diff --git a/apps/web/lib/support-chat.ts b/apps/web/lib/support-chat.ts new file mode 100644 index 000000000..d01c31c1b --- /dev/null +++ b/apps/web/lib/support-chat.ts @@ -0,0 +1,34 @@ +import constants from "@config/constants"; +import type { SupportChatConfig } from "@courselit/common-models"; + +const DEFAULT_API_URL = "https://api.frontlit.app"; +const DEFAULT_EMBED_URL = "https://embed.frontlit.app"; + +/** + * In-app support runs only on the hosted (multitenant) app, and only when a + * support team is configured. Self-hosted setups never get it. + */ +export function isSupportChatEnabled() { + return ( + constants.multitenant && + !!process.env.FRONTLIT_TEAM_ID && + !!process.env.FRONTLIT_SUPPORT_API_KEY + ); +} + +export function getSupportChatConfig(): SupportChatConfig | undefined { + if (!isSupportChatEnabled()) { + return undefined; + } + const embedUrl = ( + process.env.FRONTLIT_EMBED_URL || DEFAULT_EMBED_URL + ).replace(/\/$/, ""); + return { + teamId: process.env.FRONTLIT_TEAM_ID!, + loaderUrl: `${embedUrl}/chat.js`, + }; +} + +export function getSupportApiUrl() { + return (process.env.FRONTLIT_API_URL || DEFAULT_API_URL).replace(/\/$/, ""); +} diff --git a/apps/web/ui-config/strings.ts b/apps/web/ui-config/strings.ts index 8f660fda6..da1400c9f 100644 --- a/apps/web/ui-config/strings.ts +++ b/apps/web/ui-config/strings.ts @@ -901,3 +901,13 @@ export const LESSON_CONTENT_LABEL = "Content"; export const EMAIL_EDITOR_EMAIL_EDIT_HEADER = "Editing email"; export const EMAIL_EDITOR_TEMPLATE_EDIT_HEADER = "Editing template"; export const LOGIN_FORM_PERSONAL_INFORMATION_LABEL = "Personal Information"; +export const SUPPORT_ERROR_TOAST_TITLE = "Something went wrong"; +export const SUPPORT_ERROR_TOAST_DESCRIPTION = + "We've encountered an error while doing that."; +export const SUPPORT_CONTACT_BUTTON = "Contact support"; +export const SUPPORT_UNAVAILABLE_TITLE = "Couldn't reach support"; +export const SUPPORT_UNAVAILABLE_DESCRIPTION = "Please try again in a moment."; +export const SUPPORT_CHAT_CARD_TITLE = "Chat with us"; +export const SUPPORT_CHAT_CARD_DESCRIPTION = + "Questions, problems or bugs: talk to the CourseLit team right here."; +export const SUPPORT_CHAT_CARD_BUTTON = "Start a chat"; diff --git a/packages/common-models/src/index.ts b/packages/common-models/src/index.ts index 4f00e285e..b00020f1f 100644 --- a/packages/common-models/src/index.ts +++ b/packages/common-models/src/index.ts @@ -53,7 +53,11 @@ export type { Domain } from "./domain"; export type { Progress } from "./progress"; export type { Drip, DripType } from "./drip"; export type { PaymentMethod } from "./payment-method"; -export type { ServerConfig } from "./server-config"; +export type { + ServerConfig, + SupportChatConfig, + SupportSessionRequest, +} from "./server-config"; export type { Community } from "./community"; export type { CommunityPost } from "./community-post"; export type { CommunityMemberStatus } from "./community-member-status"; diff --git a/packages/common-models/src/server-config.ts b/packages/common-models/src/server-config.ts index 19dc8882f..07fa06929 100644 --- a/packages/common-models/src/server-config.ts +++ b/packages/common-models/src/server-config.ts @@ -1,6 +1,21 @@ +export interface SupportChatConfig { + teamId: string; + loaderUrl: string; +} + export interface ServerConfig { turnstileSiteKey: string; queueServer: string; cacheEnabled: boolean; recaptchaSiteKey?: string; + /** Set only on the hosted (multitenant) app with a support team configured. */ + supportChat?: SupportChatConfig; +} + +export interface SupportSessionRequest { + page: string; + error?: { + title?: string; + message?: string; + }; } diff --git a/packages/components-library/src/components/ui/toaster.tsx b/packages/components-library/src/components/ui/toaster.tsx index 45bf9f685..480e58357 100644 --- a/packages/components-library/src/components/ui/toaster.tsx +++ b/packages/components-library/src/components/ui/toaster.tsx @@ -1,4 +1,4 @@ -import { useToast } from "@/hooks/use-toast"; +import { useToast, type ToasterToast } from "@/hooks/use-toast"; import { Toast, ToastClose, @@ -8,18 +8,20 @@ import { ToastViewport, } from "@/components/ui/toast"; -export function Toaster() { +export interface ToasterProps { + /** Rewrites a toast just before it is shown, e.g. to replace raw errors. */ + mapToast?: (toast: ToasterToast) => ToasterToast; +} + +export function Toaster({ mapToast }: ToasterProps = {}) { const { toasts } = useToast(); return ( - {toasts.map(function ({ - id, - title, - description, - action, - ...props - }) { + {toasts.map(function (toast) { + const { id, title, description, action, ...props } = mapToast + ? mapToast(toast) + : toast; return (
diff --git a/packages/components-library/src/hooks/use-toast.ts b/packages/components-library/src/hooks/use-toast.ts index b51c7571e..104cf4199 100644 --- a/packages/components-library/src/hooks/use-toast.ts +++ b/packages/components-library/src/hooks/use-toast.ts @@ -5,7 +5,7 @@ import type { ToastActionElement, ToastProps } from "@/components/ui/toast"; const TOAST_LIMIT = 1; const TOAST_REMOVE_DELAY = 1000000; -type ToasterToast = ToastProps & { +export type ToasterToast = ToastProps & { id: string; title?: React.ReactNode; description?: React.ReactNode; diff --git a/packages/components-library/src/toast2.tsx b/packages/components-library/src/toast2.tsx index 63aacafdf..b95aaefa3 100644 --- a/packages/components-library/src/toast2.tsx +++ b/packages/components-library/src/toast2.tsx @@ -1,3 +1,5 @@ export { Toaster } from "@/components/ui/toaster"; +export type { ToasterProps } from "@/components/ui/toaster"; export { useToast } from "@/hooks/use-toast"; +export type { ToasterToast } from "@/hooks/use-toast"; export { ToastAction } from "@/components/ui/toast";