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.

11.7 KB
Raw Blame
import clsx from 'clsx'
import { useActions, useValues } from 'kea'
import { useEffect } from 'react'

import { IconTrash } from '@posthog/icons'
import { LemonBanner, LemonButton, Tooltip } from '@posthog/lemon-ui'

import api from 'lib/api'
import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
import { TZLabel } from 'lib/components/TZLabel'
import { UserActivityIndicator } from 'lib/components/UserActivityIndicator/UserActivityIndicator'
import { TeamMembershipLevel } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { GitHubRepoSummary } from 'lib/integrations/GitHubRepoSummary'
import { IntegrationScopesWarning } from 'lib/integrations/IntegrationScopesWarning'
import { LemonBannerAction } from 'lib/lemon-ui/LemonBanner/LemonBanner'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import { IntegrationType } from '~/types'

import { integrationAuthorizeUrl, integrationsLogic, reconnectReturnUrl } from './integrationsLogic'
import { DARK_MODE_INVERT_ICON_KINDS, IntegrationConnectSurface, getIntegrationNameFromKind } from './utils'

export function IntegrationView({
    integration,
    suffix,
    actions,
    schema,
    hideWebhookReconnect,
}: {
    integration: IntegrationType
    suffix?: JSX.Element
    /** Shown before the default Disconnect button. Ignored when `suffix` is set. */
    actions?: JSX.Element | null
    schema?: { requiredScopes?: string }
    hideWebhookReconnect?: boolean
}): JSX.Element {
    const { deleteIntegration } = useActions(integrationsLogic)
    const { reportIntegrationConnectClicked } = useActions(eventUsageLogic)
    const { currentTeam } = useValues(teamLogic)
    const restrictedReason = useRestrictedArea({
        scope: RestrictionScope.Project,
        minimumAccessLevel: TeamMembershipLevel.Admin,
    })

    const reconnectAction = (surface: IntegrationConnectSurface): LemonBannerAction => ({
        children: 'Reconnect',
        disableClientSideRouting: true,
        to: integrationAuthorizeUrl({
            kind: integration.kind,
            next: reconnectReturnUrl(window.location.pathname, window.location.search),
        }),
        onClick: () => reportIntegrationConnectClicked(integration.kind, integration.kind, surface),
        disabledReason: restrictedReason,
    })

    const errors = (integration.errors && integration.errors?.split(',')) || []
    const { githubRepositoriesLoading, getGitHubRepositories, getGitHubRepositoriesTotal } =
        useValues(integrationsLogic)
    const { loadGitHubRepositories } = useActions(integrationsLogic)

    const isGitHub = integration.kind === 'github'
    const repositories = isGitHub ? getGitHubRepositories(integration.id) : []
    const repositoriesTotal = isGitHub ? getGitHubRepositoriesTotal(integration.id) : null
    const refreshedAtTimestamp = integration.config?.refreshed_at || null
    const installationUnavailable = isGitHub && integration.installation_status === 'unavailable'

    // Reload when the installation's repository scope changes, not just its id: polling and the
    // focus refetch can flip repository_selection in place (e.g. after editing access on GitHub),
    // and the cached list/total would otherwise stay stale until a full page reload.
    useEffect(() => {
        if (isGitHub) {
            loadGitHubRepositories(integration.id)
        }
    }, [isGitHub, integration.id, integration.config?.repository_selection, loadGitHubRepositories])

    suffix = suffix || (
        <div className="flex flex-row gap-2">
            {actions}
            <LemonButton
                type="secondary"
                status="danger"
                onClick={() => deleteIntegration(integration.id)}
                icon={<IconTrash />}
                disabledReason={restrictedReason}
            >
                Disconnect
            </LemonButton>
        </div>
    )

    const integrationName = getIntegrationNameFromKind(integration.kind)

    return (
        <div className="rounded border bg-surface-primary">
            <div className="flex flex-wrap justify-between items-center p-2 gap-2">
                <div className="flex gap-4 items-center ml-2">
                    <img
                        src={integration.icon_url}
                        alt={`Integration for ${integrationName}`}
                        title={integrationName}
                        className={clsx(
                            'w-10 h-10 rounded',
                            DARK_MODE_INVERT_ICON_KINDS.has(integration.kind) && 'dark:invert'
                        )}
                    />
                    <div>
                        <div className="flex gap-2">
                            <span>
                                {installationUnavailable ? (
                                    <>No longer connected</>
                                ) : refreshedAtTimestamp ? (
                                    <Tooltip
                                        title={
                                            <div className="flex gap-1 items-baseline">
                                                Last refreshed <TZLabel time={dayjs.unix(refreshedAtTimestamp)} />
                                            </div>
                                        }
                                    >
                                        <strong className="cursor-help underline">Connected</strong>
                                    </Tooltip>
                                ) : (
                                    <>Connected</>
                                )}{' '}
                                to <strong>{integration.display_name}</strong>
                            </span>
                        </div>
                        {integration.created_by ? (
                            <div className="flex items-center">
                                <UserActivityIndicator
                                    at={integration.created_at}
                                    by={integration.created_by}
                                    prefix="Created"
                                    className="text-secondary"
                                />
                            </div>
                        ) : null}
                        {isGitHub && (
                            <GitHubRepoSummary
                                repoNames={repositories}
                                loading={githubRepositoriesLoading}
                                installationId={integration.config?.installation_id}
                                accountType={integration.config?.account?.type}
                                accountName={integration.config?.account?.name}
                                repositorySelection={integration.config?.repository_selection}
                                total={repositoriesTotal}
                                onBeforeManage={
                                    currentTeam?.id
                                        ? async () => {
                                              // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. integrationsGithubPrepareCallbackCreate() from 'products/integrations/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
                                              await api.create(
                                                  `api/projects/${currentTeam.id}/integrations/github/prepare_callback/`,
                                                  {
                                                      next: urls.project(
                                                          currentTeam.id,
                                                          urls.settings('project-integrations')
                                                      ),
                                                      installation_id: integration.config?.installation_id,
                                                  }
                                              )
                                          }
                                        : undefined
                                }
                            />
                        )}
                    </div>
                </div>

                {suffix}
            </div>

            {installationUnavailable ? (
                <div className="p-2">
                    <LemonBanner type="error">
                        <div className="flex flex-wrap items-center justify-between gap-2">
                            <span>
                                The PostHog app was removed from GitHub. Remove this connection or reinstall the app.
                            </span>
                            <div className="flex gap-2 shrink-0">
                                <LemonButton
                                    type="secondary"
                                    status="danger"
                                    size="small"
                                    onClick={() => deleteIntegration(integration.id)}
                                    disabledReason={restrictedReason}
                                >
                                    Remove
                                </LemonButton>
                                <LemonButton
                                    type="secondary"
                                    size="small"
                                    disableClientSideRouting
                                    to={integrationAuthorizeUrl({
                                        kind: integration.kind,
                                        next: reconnectReturnUrl(window.location.pathname, window.location.search),
                                    })}
                                    onClick={() =>
                                        reportIntegrationConnectClicked(
                                            integration.kind,
                                            integration.kind,
                                            'unavailable_banner_reconnect'
                                        )
                                    }
                                    disabledReason={restrictedReason}
                                >
                                    Reconnect
                                </LemonButton>
                            </div>
                        </div>
                    </LemonBanner>
                </div>
            ) : errors.length > 0 ? (
                <div className="p-2">
                    <LemonBanner type="error" action={reconnectAction('error_banner_reconnect')}>
                        {errors[0] === 'TOKEN_REFRESH_FAILED'
                            ? 'Authentication token could not be refreshed. You can reconnect this account or disconnect it and connect a different one.'
                            : `There was an error with this integration: ${errors[0]}`}
                    </LemonBanner>
                </div>
            ) : integration.needs_webhook_reconnect && !hideWebhookReconnect ? (
                <div className="p-2">
                    <LemonBanner type="info" action={reconnectAction('webhook_banner_reconnect')}>
                        <span>
                            Error tracking issues can now sync their status with linked Linear tickets. To turn this on,
                            switch to <strong>{integration.display_name}</strong> in Linear and reconnect.
                        </span>
                    </LemonBanner>
                </div>
            ) : (
                <IntegrationScopesWarning integration={integration} schema={schema} />
            )}
        </div>
    )
}