Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

9.0 KB
Raw Blame
import { useActions, useValues } from 'kea'
import { router } from 'kea-router'

import { IconArrowLeft, IconCheckCircle, IconWarning } from '@posthog/icons'
import { LemonBanner, LemonButton, Link, Spinner } from '@posthog/lemon-ui'

import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
import { TeamMembershipLevel } from 'lib/constants'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { describeOAuthCallbackError, INTEGRATION_ERROR_PARAM } from 'lib/integrations/oauthCallbackErrors'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { urls } from 'scenes/urls'

import { IntegrationType } from '~/types'

import { IntegrationAccessRequest } from './components/IntegrationAccessRequest'
import { IntegrationDefinition, IntegrationStatus, SettingsSectionComponent } from './integrationTypes'

export function IntegrationFullPage({
    definition,
    SettingsSection,
}: {
    definition: IntegrationDefinition
    SettingsSection: SettingsSectionComponent
}): JSX.Element {
    const { getIntegrationsByKind, integrationsLoading } = useValues(integrationsLogic)

    const integrations = getIntegrationsByKind([definition.kind])
    const connected = integrations.length > 0

    return (
        <div className="flex flex-col items-center justify-center min-h-full w-full p-4">
            <div className="flex flex-col items-center gap-4 max-w-160 w-full bg-surface-primary border rounded-lg overflow-hidden shadow-sm">
                {definition.banner ? (
                    <img src={definition.banner} alt={`${definition.name} banner`} className="w-full object-cover" />
                ) : null}

                <div className="flex flex-col items-center gap-4 w-full px-8 pb-8 pt-2">
                    <div className="flex items-center justify-center w-16 h-16 rounded-lg bg-white border p-2.5">
                        <img
                            src={definition.logo}
                            alt={`${definition.name} logo`}
                            className="max-w-full max-h-full object-contain"
                        />
                    </div>

                    <ConnectErrorBanner definition={definition} />

                    {integrationsLoading ? (
                        <Spinner className="text-2xl" />
                    ) : connected ? (
                        <ConnectedView definition={definition} integrations={integrations} />
                    ) : (
                        <ConnectView definition={definition} SettingsSection={SettingsSection} />
                    )}
                </div>
            </div>

            <Link to={urls.projectHomepage()} className="flex items-center gap-1 mt-6 text-secondary">
                <IconArrowLeft />
                Back to PostHog
            </Link>
        </div>
    )
}

/**
 * Explains a connect attempt the provider sent back without a code. The callback handler parks the
 * raw provider error code in the URL rather than firing a toast, because the user's next step is
 * the connect button on this page and a toast is gone by the time they read the reason.
 */
function ConnectErrorBanner({ definition }: { definition: IntegrationDefinition }): JSX.Element | null {
    const { searchParams } = useValues(router)

    const error = searchParams[INTEGRATION_ERROR_PARAM]
    if (!error) {
        return null
    }

    return (
        <LemonBanner type="warning" className="w-full">
            {describeOAuthCallbackError(String(error), definition.kind)}
        </LemonBanner>
    )
}

function ConnectView({
    definition,
    SettingsSection,
}: {
    definition: IntegrationDefinition
    SettingsSection: SettingsSectionComponent
}): JSX.Element {
    const { reportIntegrationConnectClicked } = useActions(eventUsageLogic)
    // Connecting an integration requires project membership (enforced again in the backend);
    // editing or removing one still requires admin. Users with no project access fall back to
    // the request-access flow below.
    const restrictionReason = useRestrictedArea({
        scope: RestrictionScope.Project,
        minimumAccessLevel: TeamMembershipLevel.Member,
    })

    const onConnectClick = (): void => {
        reportIntegrationConnectClicked(definition.slug, definition.kind, 'integration_landing_page')
    }

    return (
        <>
            <div className="flex flex-col items-center gap-1 text-center">
                <h1 className="text-2xl font-bold m-0">Connect {definition.name}</h1>
                <p className="text-secondary m-0">{definition.subtitle}</p>
            </div>

            <div className="text-center text-sm">{definition.description}</div>

            {restrictionReason ? (
                <IntegrationAccessRequest kind={definition.kind} name={definition.name} />
            ) : (
                // onClickCapture fires before the connect button triggers its OAuth redirect
                <div onClickCapture={onConnectClick}>
                    <SettingsSection next={urls.integration(definition.slug)} centered />
                </div>
            )}

            {definition.docsUrl ? (
                <Link to={definition.docsUrl} target="_blank" className="text-sm">
                    Learn more
                </Link>
            ) : null}
        </>
    )
}

function ConnectedView({
    definition,
    integrations,
}: {
    definition: IntegrationDefinition
    integrations: IntegrationType[]
}): JSX.Element {
    const PostConnect = definition.PostConnect
    // Default to ``ok`` when no status hook is provided so today's integrations keep their
    // current "Everything is set up" copy without each having to opt in.
    const status: IntegrationStatus = definition.useStatus?.(integrations) ?? 'ok'
    const ok = status === 'ok'

    return (
        <>
            {ok ? (
                <IconCheckCircle className="text-success text-4xl" />
            ) : (
                <IconWarning className="text-warning text-4xl" />
            )}

            <div className="flex flex-col items-center gap-1 text-center">
                <h1 className="text-2xl font-bold m-0">
                    {ok ? `You're connected to ${definition.name}` : `${definition.name} is connected, with caveats`}
                </h1>
                <p className="text-secondary m-0">
                    {ok
                        ? 'Everything is set up and ready to go.'
                        : PostConnect
                          ? 'Review the items below before using it.'
                          : 'Some settings may need your attention.'}
                </p>
            </div>

            {PostConnect ? (
                <div className="w-full flex flex-col gap-2">
                    {integrations.map((integration) => (
                        <PostConnect key={integration.id} integration={integration} />
                    ))}
                </div>
            ) : null}

            {definition.capabilities.length > 0 ? (
                <div className="w-full">
                    <p className="font-semibold mb-2">What you can do now</p>
                    <ul className="flex flex-col gap-1">
                        {definition.capabilities.map((capability) => (
                            <li key={capability} className="flex items-start gap-2">
                                <IconCheckCircle className="text-success mt-0.5 shrink-0" />
                                <span>{capability}</span>
                            </li>
                        ))}
                    </ul>
                </div>
            ) : null}

            <ConnectedNextStep definition={definition} integrations={integrations} />
        </>
    )
}

/**
 * Where the user goes after connecting. This page is reached by clicking through a provider's
 * consent screen, which is mostly something a setup agent run sent the user off to do. That run owns
 * the flow it started, so the page points back to the terminal rather than into the app: routing a
 * run's user anywhere is wrong for every path the agent can produce. The link below still gets anyone
 * who arrived some other way where they wanted to go. An integration with its own web setup, such as
 * the Slack app, sends the user on to that setup instead.
 */
function ConnectedNextStep({
    definition,
    integrations,
}: {
    definition: IntegrationDefinition
    integrations: IntegrationType[]
}): JSX.Element {
    const setupUrl = definition.useSetupUrl?.(integrations) ?? null

    if (setupUrl) {
        return (
            <LemonButton type="primary" to={setupUrl} data-attr="integration-continue-setup">
                Continue setup
            </LemonButton>
        )
    }

    return (
        <div className="flex flex-col items-center gap-2">
            <p className="text-secondary text-center m-0">
                If the setup agent sent you here, head back to your terminal. It picks up from there.
            </p>
            <LemonButton type="tertiary" size="small" to={urls.projectHomepage()}>
                Go to PostHog
            </LemonButton>
        </div>
    )
}