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.

10.5 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { teamLogic } from 'scenes/teamLogic'

import { Breadcrumb } from '~/types'

import type { GitHubRepoApi } from 'products/integrations/frontend/generated/api.schemas'

import type { IntegrationType } from '../../../../frontend/src/types'
import { visualReviewReposCreate, visualReviewReposList, visualReviewReposPartialUpdate } from '../generated/api'
import type { PatchedUpdateRepoRequestInputApi, RepoApi } from '../generated/api.schemas'

export interface RepoFormValues {
    baseline_file_paths: Record<string, string>
    enable_pr_comments: boolean
}

const EMPTY_FORM: RepoFormValues = {
    baseline_file_paths: {},
    enable_pr_comments: false,
}

function formValuesFromRepo(repo: RepoApi): RepoFormValues {
    return {
        baseline_file_paths: repo.baseline_file_paths || {},
        enable_pr_comments: repo.enable_pr_comments,
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface visualReviewSettingsSceneLogicValues {
    getGitHubRepositoriesFull: (integrationId: number) => GitHubRepoApi[] // integrationsLogic
    githubIntegrations: IntegrationType[] // integrationsLogic
    currentProjectId: number | string // teamLogic
    availableRepos: GitHubRepoApi[]
    breadcrumbs: Breadcrumb[]
    editingRepo: RepoApi | null
    editingRepoId: string | null
    existingRepoNames: Set<string>
    formValues: RepoFormValues
    githubManageAccessUrl: string | null
    hasChanges: boolean
    repos: RepoApi[]
    reposLoading: boolean
    saving: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface visualReviewSettingsSceneLogicActions {
    loadIntegrationsSuccess: (
        integrations: IntegrationType[],
        payload?: any
    ) => {
        integrations: IntegrationType[]
        payload?: any
    } // integrationsLogic
    addRepo: (githubRepo: GitHubRepoApi) => {
        githubRepo: GitHubRepoApi
    }
    cancelEdit: () => {
        value: true
    }
    editRepo: (repoId: string) => {
        repoId: string
    }
    loadRepos: () => any
    loadReposFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadReposSuccess: (
        repos: RepoApi[],
        payload?: any
    ) => {
        repos: RepoApi[]
        payload?: any
    }
    saveRepo: () => {
        value: true
    }
    setFormField: (
        field: keyof RepoFormValues,
        value: RepoFormValues[keyof RepoFormValues]
    ) => {
        field: keyof RepoFormValues
        value: boolean | Record<string, string>
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface visualReviewSettingsSceneLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        editingRepo: (repos: RepoApi[], editingRepoId: string | null) => RepoApi | null
        hasChanges: (formValues: RepoFormValues, editingRepo: RepoApi | null) => boolean
        availableRepos: (
            githubIntegrations: IntegrationType[],
            getGitHubRepositoriesFull: (integrationId: number) => GitHubRepoApi[] // integrationsLogic
        ) => GitHubRepoApi[]
        existingRepoNames: (repos: RepoApi[]) => Set<string>
        githubManageAccessUrl: (githubIntegrations: IntegrationType[]) => string | null
    }
}

export type visualReviewSettingsSceneLogicType = MakeLogicType<
    visualReviewSettingsSceneLogicValues,
    visualReviewSettingsSceneLogicActions,
    Record<string, any>,
    visualReviewSettingsSceneLogicMeta
>

export const visualReviewSettingsSceneLogic = kea<visualReviewSettingsSceneLogicType>([
    path(['products', 'visual_review', 'frontend', 'scenes', 'visualReviewSettingsSceneLogic']),

    connect(() => ({
        values: [
            integrationsLogic,
            ['githubIntegrations', 'getGitHubRepositoriesFull'],
            teamLogic,
            ['currentProjectId'],
        ],
        actions: [integrationsLogic, ['loadIntegrationsSuccess']],
    })),

    actions({
        editRepo: (repoId: string) => ({ repoId }),
        cancelEdit: true,
        setFormField: (field: keyof RepoFormValues, value: RepoFormValues[keyof RepoFormValues]) => ({ field, value }),
        addRepo: (githubRepo: GitHubRepoApi) => ({ githubRepo }),
        saveRepo: true,
    }),

    loaders(({ values }) => ({
        repos: [
            [] as RepoApi[],
            {
                loadRepos: async () => {
                    const response = await visualReviewReposList(String(values.currentProjectId))
                    return response.results
                },
            },
        ],
    })),

    reducers({
        editingRepoId: [
            null as string | null,
            {
                editRepo: (_, { repoId }) => repoId,
                cancelEdit: () => null,
                loadReposSuccess: () => null,
            },
        ],
        formValues: [
            EMPTY_FORM as RepoFormValues,
            {
                cancelEdit: () => EMPTY_FORM,
                setFormField: (state, { field, value }) => ({ ...state, [field]: value }),
                loadReposSuccess: () => EMPTY_FORM,
            },
        ],
        saving: [
            false,
            {
                saveRepo: () => true,
                addRepo: () => true,
                loadReposSuccess: () => false,
                loadReposFailure: () => false,
            },
        ],
    }),

    selectors({
        editingRepo: [
            (s) => [s.repos, s.editingRepoId],
            (repos: RepoApi[], editingRepoId: string | null): RepoApi | null => {
                if (!editingRepoId) {
                    return null
                }
                return repos.find((r) => r.id === editingRepoId) || null
            },
        ],
        hasChanges: [
            (s) => [s.formValues, s.editingRepo],
            (formValues: RepoFormValues, editingRepo: RepoApi | null): boolean => {
                if (!editingRepo) {
                    return false
                }
                return (
                    JSON.stringify(formValues.baseline_file_paths) !==
                        JSON.stringify(editingRepo.baseline_file_paths || {}) ||
                    formValues.enable_pr_comments !== editingRepo.enable_pr_comments
                )
            },
        ],
        availableRepos: [
            (s) => [s.githubIntegrations, s.getGitHubRepositoriesFull],
            (
                githubIntegrations: IntegrationType[],
                getGitHubRepositoriesFull: (id: number) => GitHubRepoApi[]
            ): GitHubRepoApi[] => {
                const repos: GitHubRepoApi[] = []
                for (const integration of githubIntegrations) {
                    const integrationRepos = getGitHubRepositoriesFull(integration.id) || []
                    repos.push(...integrationRepos)
                }
                return repos
            },
        ],
        existingRepoNames: [
            (s) => [s.repos],
            (repos: RepoApi[]): Set<string> => new Set(repos.map((r) => r.repo_full_name)),
        ],
        githubManageAccessUrl: [
            (s) => [s.githubIntegrations],
            (githubIntegrations: IntegrationType[]): string | null => {
                const github = githubIntegrations[0]
                const installationId = github?.config?.installation_id
                if (installationId) {
                    const accountType = github?.config?.account?.type
                    const accountName = github?.config?.account?.name
                    if (accountType === 'Organization' && accountName) {
                        return `https://github.com/organizations/${accountName}/settings/installations/${installationId}`
                    }
                    return `https://github.com/settings/installations/${installationId}`
                }
                return null
            },
        ],
        breadcrumbs: [
            () => [],
            (): Breadcrumb[] => [
                {
                    key: 'visual_review',
                    name: 'Visual review',
                    path: '/visual-review',
                },
                {
                    key: 'visual_review_settings',
                    name: 'Settings',
                    path: '/visual-review/settings',
                },
            ],
        ],
    }),

    listeners(({ values, actions }) => ({
        loadIntegrationsSuccess: () => {
            for (const integration of values.githubIntegrations) {
                integrationsLogic.actions.loadGitHubRepositories(integration.id)
            }
        },
        editRepo: ({ repoId }) => {
            const repo = values.repos.find((r) => r.id === repoId)
            if (repo) {
                const form = formValuesFromRepo(repo)
                actions.setFormField('baseline_file_paths', form.baseline_file_paths)
                actions.setFormField('enable_pr_comments', form.enable_pr_comments)
            }
        },
        addRepo: async ({ githubRepo }) => {
            try {
                await visualReviewReposCreate(String(values.currentProjectId), {
                    repo_external_id: githubRepo.id,
                    repo_full_name: githubRepo.full_name,
                })
                lemonToast.success(`Added ${githubRepo.full_name}`)
                actions.loadRepos()
            } catch {
                lemonToast.error('Failed to add repo')
                actions.loadReposFailure('Add failed')
            }
        },
        saveRepo: async () => {
            try {
                const { editingRepoId, formValues } = values

                if (editingRepoId) {
                    const updates: PatchedUpdateRepoRequestInputApi = {
                        baseline_file_paths: formValues.baseline_file_paths,
                        enable_pr_comments: formValues.enable_pr_comments,
                    }
                    await visualReviewReposPartialUpdate(String(values.currentProjectId), editingRepoId, updates)
                    lemonToast.success('Settings saved')
                }

                actions.loadRepos()
            } catch {
                lemonToast.error('Failed to save')
                actions.loadReposFailure('Save failed')
            }
        },
    })),

    afterMount(({ actions }) => {
        actions.loadRepos()
    }),
])