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.6 KB
Raw Blame
import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { urlToAction } from 'kea-router'

import api from 'lib/api'
import { getReferralFollowUp } from 'lib/components/SignupReferralSource'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { getRelativeNextPath } from 'lib/utils/url'
import { readPendingOAuthConnection } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'

export interface ConfirmOrganizationFormValues {
    organization_name?: string
    first_name?: string
    role_at_organization?: string
    referral_source?: string
    referral_source_ai_prompt?: string
    referral_source_influencer?: string
}

const LOGIC_PATH = ['scenes', 'organization', 'confirmOrganizationLogic']
const FORM_KEY = 'confirmOrganization'

// In the order the form renders them, so a failed submit lands on the first field to fix
const FIELDS_IN_RENDER_ORDER: (keyof ConfirmOrganizationFormValues)[] = [
    'first_name',
    'organization_name',
    'role_at_organization',
    'referral_source',
    'referral_source_ai_prompt',
    'referral_source_influencer',
]

// kea-forms ids each field input `<logic path>.<form key>.<field>`
const fieldInputId = (field: keyof ConfirmOrganizationFormValues): string => [...LOGIC_PATH, FORM_KEY, field].join('.')

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface confirmOrganizationLogicValues {
    confirmOrganization: ConfirmOrganizationFormValues
    confirmOrganizationAllErrors: Record<string, any>
    confirmOrganizationChanged: boolean
    confirmOrganizationErrors: DeepPartialMap<ConfirmOrganizationFormValues, ValidationErrorType>
    confirmOrganizationHasErrors: boolean
    confirmOrganizationManualErrors: Record<string, any>
    confirmOrganizationTouched: boolean
    confirmOrganizationTouches: Record<string, boolean>
    confirmOrganizationValidationErrors: DeepPartialMap<ConfirmOrganizationFormValues, ValidationErrorType>
    email: string
    hasPrefilled: boolean
    isConfirmOrganizationSubmitting: boolean
    isConfirmOrganizationValid: boolean
    showConfirmOrganizationErrors: boolean
    showNewOrgWarning: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface confirmOrganizationLogicActions {
    resetConfirmOrganization: (values?: ConfirmOrganizationFormValues) => {
        values?: ConfirmOrganizationFormValues
    }
    setConfirmOrganizationManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setConfirmOrganizationValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setConfirmOrganizationValues: (values: DeepPartial<ConfirmOrganizationFormValues>) => {
        values: DeepPartial<ConfirmOrganizationFormValues>
    }
    setEmail: (email: string) => {
        email: string
    }
    setHasPrefilled: () => {
        value: true
    }
    setShowNewOrgWarning: (show: boolean) => {
        show: boolean
    }
    submitConfirmOrganization: () => {
        value: boolean
    }
    submitConfirmOrganizationFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitConfirmOrganizationRequest: (confirmOrganization: ConfirmOrganizationFormValues) => {
        confirmOrganization: ConfirmOrganizationFormValues
    }
    submitConfirmOrganizationSuccess: (confirmOrganization: ConfirmOrganizationFormValues) => {
        confirmOrganization: ConfirmOrganizationFormValues
    }
    touchConfirmOrganizationField: (key: string) => {
        key: string
    }
}

export type confirmOrganizationLogicType = MakeLogicType<
    confirmOrganizationLogicValues,
    confirmOrganizationLogicActions
>

export const confirmOrganizationLogic = kea<confirmOrganizationLogicType>([
    path(LOGIC_PATH),
    actions({
        setEmail: (email: string) => ({
            email,
        }),
        setHasPrefilled: true,
        setShowNewOrgWarning: (show: boolean) => ({ show }),
    }),

    reducers({
        showNewOrgWarning: [
            false,
            {
                setShowNewOrgWarning: (_, { show }) => show,
            },
        ],
        email: [
            '',
            {
                setEmail: (_, { email }) => email,
            },
        ],
        hasPrefilled: [
            false,
            {
                setHasPrefilled: () => true,
            },
        ],
    }),

    forms(({ actions }) => ({
        confirmOrganization: {
            options: {
                showErrorsOnTouch: true,
            },
            defaults: {
                organization_name: '',
                first_name: '',
                role_at_organization: '',
                // The partner that started the OAuth connection is where this person heard about PostHog
                referral_source: readPendingOAuthConnection()?.clientName ?? '',
                referral_source_ai_prompt: '',
                referral_source_influencer: '',
            } as ConfirmOrganizationFormValues,
            errors: ({ organization_name, first_name, role_at_organization }) => ({
                first_name: !first_name?.trim() ? 'Please enter your name' : undefined,
                organization_name: !organization_name?.trim()
                    ? "Please enter an organization name. You can use your own name if you don't belong to one."
                    : undefined,
                role_at_organization: !role_at_organization ? 'Please select your role to continue' : undefined,
            }),

            // A manual error from a rejected attempt counts as a validation error, and only its own
            // field being touched clears it. Without this, fixing a different field never submits.
            preSubmit: () => {
                actions.setConfirmOrganizationManualErrors({})
            },

            submit: async (formValues) => {
                // An answer typed into a follow-up that a later referral source edit hid again must not be sent
                const followUp = getReferralFollowUp(formValues.referral_source ?? '')
                try {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                    await api.create('api/social_signup/', {
                        ...formValues,
                        // Trim rather than reject: surrounding whitespace is still a good signup
                        first_name: formValues.first_name?.trim(),
                        organization_name: formValues.organization_name?.trim(),
                        referral_source_ai_prompt: followUp === 'ai' ? formValues.referral_source_ai_prompt : '',
                        referral_source_influencer:
                            followUp === 'influencer' ? formValues.referral_source_influencer : '',
                    })
                } catch (error: any) {
                    const attr = error.attr as keyof ConfirmOrganizationFormValues | undefined
                    if (attr && FIELDS_IN_RENDER_ORDER.includes(attr) && error.detail) {
                        // Put the message on the field the API names, rather than in a toast that
                        // leaves the person guessing which input to fix
                        actions.setConfirmOrganizationManualErrors({ [attr]: String(error.detail) })
                    } else {
                        console.error('error', error)
                        lemonToast.error(error.detail || 'Failed to create organization')
                    }
                    // Rethrow so kea-forms keeps the errors on screen. A swallowed rejection counts
                    // as a successful submit, which hides them again.
                    throw error
                }

                const nextUrl = getRelativeNextPath(new URLSearchParams(location.search).get('next'), location)

                // this url is validated in getRelativeNextPath as either being relative or on the same origin
                // nosemgrep: javascript.browser.security.open-redirect.js-open-redirect
                location.href = nextUrl || '/'
            },
        },
    })),

    listeners(({ values }) => ({
        // kea-forms passes its own `errors` payload here, but reads it off a selector that does not
        // exist, so it always arrives undefined. Take the errors from the logic instead.
        submitConfirmOrganizationFailure: () => {
            const errors = values.confirmOrganizationAllErrors
            const firstInvalidField = FIELDS_IN_RENDER_ORDER.find((field) => errors[field])
            if (!firstInvalidField) {
                return
            }
            const input = document.getElementById(fieldInputId(firstInvalidField))
            // preventScroll so the smooth scroll below is the only movement the person sees
            input?.focus({ preventScroll: true })
            input?.scrollIntoView({ behavior: 'smooth', block: 'center' })
        },
    })),

    urlToAction(({ actions, values }) => ({
        '/organization/confirm-creation': (_, __, ___, { search }) => {
            // Prefill from the URL once. Later location changes on this same page (for example
            // opening the docs side panel) re-fire this handler with empty params, which would
            // otherwise wipe what the user has typed.
            if (values.hasPrefilled) {
                return
            }
            actions.setHasPrefilled()

            // Read the raw query string, because kea-router parses a value that looks like a number
            // into one. A name of only digits must stay text for the validators to trim it.
            const params = new URLSearchParams(search)
            const email = params.get('email')
            const organizationName = params.get('organization_name')
            const firstName = params.get('first_name')

            if (email) {
                actions.setEmail(email)
            }
            const prefill: DeepPartial<ConfirmOrganizationFormValues> = {}
            if (organizationName) {
                prefill.organization_name = organizationName
            }
            if (firstName) {
                prefill.first_name = firstName
            }
            if (Object.keys(prefill).length > 0) {
                actions.setConfirmOrganizationValues(prefill)
            }
        },
    })),
])