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.

12.7 KB
Raw Blame
import { MakeLogicType, actions, kea, path, props, reducers, selectors, useActions, useValues } from 'kea'
import { router, urlToAction } from 'kea-router'

import { LemonButton } from '@posthog/lemon-ui'
import { Button } from '@posthog/quill'

import { AccessControlAction } from 'lib/components/AccessControlAction'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { isUUIDLike } from 'lib/utils/guards'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { addProductIntent } from 'lib/utils/product-intents'
import { capitalizeFirstLetter } from 'lib/utils/strings'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene, SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'

import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
import { AccessControlLevel, AccessControlResourceType, Breadcrumb } from '~/types'

import { EmailSuspensionBanner } from './EmailSuspensionBanner'
import { workflowsEmptyState } from './emptyState/workflowsEmptyState'
import { MessagingSetup } from './MessagingSetup'
import { MessagingTabActions } from './MessagingTabActions'
import { isMessagingSetupTab } from './messagingTabs'
import { SendCalendar } from './SendCalendar/SendCalendar'
import { SendCalendarTabLabel } from './SendCalendar/SendCalendarTabLabel'
import { MessagingSetupTabLabel } from './setupGuide/MessagingSetupTabLabel'
import { WorkflowsOnboardingWizard } from './setupGuide/wizard/WorkflowsOnboardingWizard'
import { customerioImportLogic } from './Workflows/import/customerioImportLogic'
import { CustomerioImportModal } from './Workflows/import/CustomerioImportModal'
import { newWorkflowLogic } from './Workflows/newWorkflowLogic'
import { NewWorkflowModal } from './Workflows/NewWorkflowModal'
import { workflowTemplatesLogic } from './Workflows/templates/workflowTemplatesLogic'
import { workflowsLogic } from './Workflows/workflowsLogic'
import { WorkflowsTable } from './Workflows/WorkflowsTable'
import { templateTypeForListType } from './Workflows/workflowTypeFilters'
import { WorkflowsTemplates } from './WorkflowsTemplates'

// pinned: URL path segments under /workflows - renaming breaks bookmarks
const WORKFLOW_SCENE_TABS = [
    'workflows',
    'calendar',
    'templates',
    'library',
    'channels',
    'opt-outs',
    'suppression',
    'reputation',
    'settings',
    'onboarding',
] as const
export type WorkflowsSceneTab = (typeof WORKFLOW_SCENE_TABS)[number]

export type WorkflowsSceneProps = {
    tab?: WorkflowsSceneTab
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface workflowsSceneLogicValues {
    breadcrumbs: Breadcrumb[]
    currentTab: WorkflowsSceneTab
    logicProps: any
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface workflowsSceneLogicActions {
    setCurrentTab: (tab: WorkflowsSceneTab) => {
        tab:
            | 'calendar'
            | 'channels'
            | 'library'
            | 'onboarding'
            | 'opt-outs'
            | 'reputation'
            | 'settings'
            | 'suppression'
            | 'templates'
            | 'workflows'
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface workflowsSceneLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        logicProps: (arg: any) => any
        breadcrumbs: (
            currentTab:
                | 'calendar'
                | 'channels'
                | 'library'
                | 'onboarding'
                | 'opt-outs'
                | 'reputation'
                | 'settings'
                | 'suppression'
                | 'templates'
                | 'workflows'
        ) => Breadcrumb[]
    }
}

export type workflowsSceneLogicType = MakeLogicType<
    workflowsSceneLogicValues,
    workflowsSceneLogicActions,
    WorkflowsSceneProps,
    workflowsSceneLogicMeta
>

export const workflowsSceneLogic = kea<workflowsSceneLogicType>([
    props({} as WorkflowsSceneProps),
    path(() => ['scenes', 'workflows', 'workflowsSceneLogic']),
    actions({
        setCurrentTab: (tab: WorkflowsSceneTab) => ({ tab }),
    }),
    reducers(() => ({
        currentTab: [
            'workflows' as WorkflowsSceneTab,
            {
                setCurrentTab: (_, { tab }) => tab,
            },
        ],
    })),
    selectors({
        logicProps: [() => [(_, props) => props], (props) => props],
        breadcrumbs: [
            (s) => [s.currentTab],
            (currentTab: WorkflowsSceneTab): Breadcrumb[] => {
                return [
                    {
                        key: [Scene.Workflows, currentTab],
                        name: capitalizeFirstLetter(currentTab.replaceAll('_', ' ')),
                        iconType: 'workflows',
                    },
                ]
            },
        ],
    }),
    trackedActionToUrl(({ values }) => ({
        setCurrentTab: () => {
            const target = urls.workflows(values.currentTab)
            // A tab set from the URL keeps that URL's params, such as a template search or the onboarding wizard's path and step.
            return removeProjectIdIfPresent(router.values.location.pathname) === target
                ? [target, router.values.searchParams, router.values.hashParams]
                : [target]
        },
    })),
    urlToAction(({ actions, values }) => {
        return {
            [urls.workflows()]: () => {
                if (values.currentTab !== 'workflows') {
                    actions.setCurrentTab('workflows')
                }
            },
            [urls.workflows(':tab' as WorkflowsSceneTab)]: ({ tab }) => {
                // A shared link often drops the tab segment, so `/workflows/<id>` lands here with the id as the tab.
                if (tab && isUUIDLike(tab)) {
                    router.actions.replace(urls.workflow(tab, 'workflow'), router.values.searchParams)
                    return
                }
                let possibleTab: WorkflowsSceneTab = (tab as WorkflowsSceneTab) ?? 'workflows'
                possibleTab = WORKFLOW_SCENE_TABS.includes(possibleTab) ? possibleTab : 'workflows'

                if (possibleTab !== values.currentTab) {
                    actions.setCurrentTab(possibleTab)
                }
            },
        }
    }),
])

export const scene: SceneExport<WorkflowsSceneProps> = {
    component: WorkflowsScene,
    logic: workflowsSceneLogic,
    paramsToProps: ({ params: { tab } }) => ({ tab }),
    productKey: ProductKey.WORKFLOWS,
    emptyState: workflowsEmptyState,
}

type WorkflowsTopTab = 'workflows' | 'calendar' | 'templates' | 'messaging-setup'

function topTabFor(tab: WorkflowsSceneTab): WorkflowsTopTab {
    if (tab === 'calendar') {
        return 'calendar'
    }
    if (tab === 'templates' || tab === 'library') {
        return 'templates'
    }
    return isMessagingSetupTab(tab) ? 'messaging-setup' : 'workflows'
}

export function WorkflowsScene(props: WorkflowsSceneProps = {}): JSX.Element {
    const { currentTab } = useValues(workflowsSceneLogic(props))
    const { startNewWorkflow } = useActions(newWorkflowLogic)
    const { setTypeFilter } = useActions(workflowTemplatesLogic)
    const { filters } = useValues(workflowsLogic)
    const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')
    const customerioImportEnabled = useFeatureFlag('WORKFLOWS_CUSTOMERIO_IMPORT')
    const { openImportModal } = useActions(customerioImportLogic)

    const workflowsTab = {
        label: 'Workflows',
        key: 'workflows' as const,
        content: <WorkflowsTable />,
        link: urls.workflows(),
    }
    const showsNewWorkflowButton = currentTab === 'workflows' || currentTab === 'templates' || currentTab === 'calendar'
    const onNewWorkflow = (): void => {
        void addProductIntent({
            product_type: ProductKey.WORKFLOWS,
            intent_context: ProductIntentContext.WORKFLOW_CREATED,
        })
        // Open the template chooser on the type the list shows, so a person on the
        // Messaging tab sees messaging templates first.
        setTypeFilter(currentTab === 'workflows' ? templateTypeForListType(filters.type) : 'all')
        startNewWorkflow()
    }

    if (currentTab === 'onboarding') {
        return (
            <SceneContent className="workflows">
                <WorkflowsOnboardingWizard />
            </SceneContent>
        )
    }

    return (
        <SceneContent className="workflows">
            <SceneTitleSection
                name={sceneConfigurations[Scene.Workflows].name}
                description={sceneConfigurations[Scene.Workflows].description}
                resourceType={{
                    type: sceneConfigurations[Scene.Workflows].iconType || 'default_icon_type',
                }}
                actions={
                    <>
                        {showsNewWorkflowButton && customerioImportEnabled && (
                            <AccessControlAction
                                resourceType={AccessControlResourceType.Workflow}
                                minAccessLevel={AccessControlLevel.Editor}
                            >
                                <LemonButton
                                    data-attr="workflows-import-customerio"
                                    onClick={openImportModal}
                                    type="secondary"
                                    size="small"
                                >
                                    Import from Customer.io
                                </LemonButton>
                            </AccessControlAction>
                        )}
                        {showsNewWorkflowButton && (
                            <AccessControlAction
                                resourceType={AccessControlResourceType.Workflow}
                                minAccessLevel={AccessControlLevel.Editor}
                            >
                                {todayRailNav ? (
                                    <Button data-attr="new-workflow" onClick={onNewWorkflow} variant="primary">
                                        New workflow
                                    </Button>
                                ) : (
                                    <LemonButton
                                        data-attr="new-workflow"
                                        onClick={onNewWorkflow}
                                        type="primary"
                                        size="small"
                                    >
                                        New workflow
                                    </LemonButton>
                                )}
                            </AccessControlAction>
                        )}
                        {currentTab !== 'workflows' && currentTab !== 'templates' && currentTab !== 'calendar' && (
                            <MessagingTabActions tab={currentTab} channelsUrl={urls.workflows('channels')} />
                        )}
                    </>
                }
            />
            {customerioImportEnabled && <CustomerioImportModal />}
            <EmailSuspensionBanner />
            <LemonTabs<WorkflowsTopTab>
                activeKey={topTabFor(currentTab)}
                tabs={[
                    workflowsTab,
                    {
                        label: <SendCalendarTabLabel />,
                        key: 'calendar',
                        link: urls.workflows('calendar'),
                        content: <SendCalendar />,
                    },
                    {
                        label: 'Templates',
                        key: 'templates',
                        link: urls.workflows('library'),
                        content: <WorkflowsTemplates tab={currentTab === 'templates' ? 'templates' : 'library'} />,
                    },
                    {
                        label: <MessagingSetupTabLabel />,
                        key: 'messaging-setup',
                        link: urls.workflows('channels'),
                        content: (
                            <MessagingSetup
                                tab={isMessagingSetupTab(currentTab) ? currentTab : 'channels'}
                                linkFor={(tab) => urls.workflows(tab)}
                            />
                        ),
                    },
                ]}
                sceneInset
                data-attr="workflows-scene-tabs"
            />
            <NewWorkflowModal />
        </SceneContent>
    )
}