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.

16.8 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, path, props, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'

import { lemonToast } from '@posthog/lemon-ui'

import api from 'lib/api'
import { Dayjs, dayjs } from 'lib/dayjs'
import { billingLogic } from 'lib/logic/billing/billingLogic'
import { organizationLogic } from 'scenes/organizationLogic'
import { userLogic } from 'scenes/userLogic'

import { BillingType } from '~/types'

import type { OrganizationType, StartupProgramLabel, UserType } from '../../types'
import { YC_VERIFICATION_URL_REGEX } from './constants'
import { getEmailDomain, getYCBatchOptions, isPublicEmailDomain } from './utils'

export enum StartupProgramType {
    YC = 'YC',
    Startup = 'startup',
}

export interface StartupProgramFormValues {
    type: StartupProgramType
    startup_domain: string
    organization_name: string
    organization_id: string
    raised?: string
    incorporation_date?: Dayjs
    yc_verification_url?: string
    yc_batch?: string
    yc_proof_screenshot_url?: string
    yc_merch_count?: number
}

export interface StartupProgramLogicProps {
    referrer?: string
}

function validateIncorporationDate(date: Dayjs | undefined, isYC: boolean): string | undefined {
    if (isYC) {
        return undefined
    }
    if (!date) {
        return 'Please enter your incorporation date'
    }
    if (!dayjs.isDayjs(date)) {
        return 'Invalid date format'
    }
    if (date.isAfter(dayjs())) {
        return 'Incorporation date cannot be in the future'
    }
    if (date.isBefore(dayjs().subtract(2, 'year'))) {
        return 'Company must be less than 2 years old to be eligible'
    }
    return undefined
}

function validateFunding(raised: string | undefined, isYC: boolean): string | undefined {
    if (isYC) {
        return undefined
    }
    if (!raised) {
        return 'Please select how much funding you have raised'
    }
    const raisedAmount = parseInt(raised)
    if (raisedAmount >= 5000000) {
        return 'Companies that have raised $5M or more are not eligible for the startup program'
    }
    return undefined
}

/** Ensure the link has a scheme before it's sent to the billing service, which expects a full URL. */
function normalizeYcVerificationUrl(url: string | undefined): string | undefined {
    const trimmed = url?.trim()
    if (!trimmed) {
        return undefined
    }
    return /^https?:\/\//.test(trimmed) ? trimmed : `https://${trimmed}`
}

/**
 * Only the URL shape is checked client-side. The billing service does the real verification
 * against YC once, on submit, and its errors surface through the submit failure path.
 */
function validateYcVerificationUrl(url: string | undefined, isYC: boolean): string | undefined {
    if (!isYC) {
        return undefined
    }
    if (!url) {
        return 'Please enter your YC verification link'
    }
    if (!YC_VERIFICATION_URL_REGEX.test(url.trim())) {
        return 'This should look like https://www.ycombinator.com/verify/your-unique-code'
    }
    return undefined
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface startupProgramLogicValues {
    billing: BillingType | null // billingLogic
    isAnnualPlanCustomer: boolean // billingLogic
    currentOrganization: OrganizationType | null // organizationLogic
    currentOrganizationId: string // organizationLogic
    isAdminOrOwner: boolean | null // organizationLogic
    user: UserType | null // userLogic
    currentStartupProgramLabel: StartupProgramLabel | null
    domainFromEmail: string
    formSubmitted: boolean
    isCurrentlyOnStartupPlan: boolean
    isEmailDomainBlocked: boolean
    isReferralProgram: boolean
    isStartupProgramSubmitting: boolean
    isStartupProgramValid: boolean
    isYC: boolean
    referrer: string | undefined
    referrerDisplayName: string | undefined
    shouldShowEmailDomainBlockedGate: boolean
    showStartupProgramErrors: boolean
    startupProgram: StartupProgramFormValues
    startupProgramAllErrors: Record<string, any>
    startupProgramChanged: boolean
    startupProgramErrors: DeepPartialMap<StartupProgramFormValues, ValidationErrorType>
    startupProgramHasErrors: boolean
    startupProgramManualErrors: Record<string, any>
    startupProgramTouched: boolean
    startupProgramTouches: Record<string, boolean>
    startupProgramValidationErrors: DeepPartialMap<StartupProgramFormValues, ValidationErrorType>
    userEmailDomain: string
    wasPreviouslyOnStartupPlan: boolean
    ycBatchOptions: {
        label: string
        value: string
    }[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface startupProgramLogicActions {
    resetStartupProgram: (values?: StartupProgramFormValues) => {
        values?: StartupProgramFormValues
    }
    setFormSubmitted: (submitted: boolean) => {
        submitted: boolean
    }
    setStartupProgramManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setStartupProgramValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setStartupProgramValues: (values: DeepPartial<StartupProgramFormValues>) => {
        values: DeepPartial<StartupProgramFormValues>
    }
    submitStartupProgram: () => {
        value: boolean
    }
    submitStartupProgramFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitStartupProgramRequest: (startupProgram: StartupProgramFormValues) => {
        startupProgram: StartupProgramFormValues
    }
    submitStartupProgramSuccess: (startupProgram: StartupProgramFormValues) => {
        startupProgram: StartupProgramFormValues
    }
    touchStartupProgramField: (key: string) => {
        key: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface startupProgramLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        isYC: (arg: any) => boolean
        isReferralProgram: (arg: any) => boolean
        referrer: (arg: any) => string | undefined
        referrerDisplayName: (arg: any) => string | undefined
        isCurrentlyOnStartupPlan: (billing: BillingType | null) => boolean
        currentStartupProgramLabel: (billing: BillingType | null) => StartupProgramLabel | null
        wasPreviouslyOnStartupPlan: (billing: BillingType | null) => boolean
        userEmailDomain: (user: UserType | null) => string
        isEmailDomainBlocked: (user: UserType | null) => boolean
        domainFromEmail: (userEmailDomain: string, isEmailDomainBlocked: boolean) => string
        shouldShowEmailDomainBlockedGate: (
            billing: BillingType | null,
            formSubmitted: boolean,
            isAdminOrOwner: boolean | null,
            isAnnualPlanCustomer: boolean,
            isCurrentlyOnStartupPlan: boolean,
            isEmailDomainBlocked: boolean,
            isYC: boolean,
            wasPreviouslyOnStartupPlan: boolean
        ) => boolean
    }
}

export type startupProgramLogicType = MakeLogicType<
    startupProgramLogicValues,
    startupProgramLogicActions,
    StartupProgramLogicProps,
    startupProgramLogicMeta
>

function captureBlockedApplicationIfGateShown(values: startupProgramLogicValues, cache: Record<string, any>): void {
    if (!values.shouldShowEmailDomainBlockedGate || cache.blockedApplicationCaptured) {
        return
    }

    cache.blockedApplicationCaptured = true
    posthog.capture('startup program application blocked', {
        email_domain: values.userEmailDomain,
        program: values.isYC ? StartupProgramType.YC : StartupProgramType.Startup,
        organization_id: values.currentOrganizationId,
        blocked_at: 'form',
    })
}

export const startupProgramLogic = kea<startupProgramLogicType>([
    path(['scenes', 'startups', 'startupProgramLogic']),
    props({} as StartupProgramLogicProps),
    connect(() => ({
        values: [
            userLogic,
            ['user'],
            organizationLogic,
            ['currentOrganization', 'currentOrganizationId', 'isAdminOrOwner'],
            billingLogic,
            ['billing', 'isAnnualPlanCustomer'],
        ],
    })),
    actions({
        setFormSubmitted: (submitted: boolean) => ({ submitted }),
    }),
    reducers({
        formSubmitted: [
            false,
            {
                setFormSubmitted: (_, { submitted }) => submitted,
            },
        ],
    }),
    selectors({
        isYC: [() => [(_, props) => props.referrer], (referrer: string | undefined) => referrer === 'yc'],
        isReferralProgram: [
            () => [(_, props) => props.referrer],
            (referrer: string | undefined) => !!referrer && referrer !== 'yc',
        ],
        referrer: [() => [(_, props) => props.referrer], (referrer: string | undefined) => referrer],
        referrerDisplayName: [
            () => [(_, props) => props.referrer],
            (referrer: string | undefined) => {
                if (!referrer || referrer === 'yc') {
                    return undefined
                }
                return referrer.split('-').join(' ')
            },
        ],
        isCurrentlyOnStartupPlan: [
            (s) => [s.billing],
            (billing: BillingType | null) => {
                return !!billing?.startup_program_label
            },
        ],
        currentStartupProgramLabel: [
            (s) => [s.billing],
            (billing: BillingType | null) => {
                return billing?.startup_program_label || null
            },
        ],
        wasPreviouslyOnStartupPlan: [
            (s) => [s.billing],
            (billing: BillingType | null) => {
                return !!billing?.startup_program_label_previous
            },
        ],
        userEmailDomain: [(s) => [s.user], (user: UserType | null) => getEmailDomain(user?.email)],
        isEmailDomainBlocked: [(s) => [s.user], (user: UserType | null) => isPublicEmailDomain(user?.email)],
        domainFromEmail: [
            (s) => [s.userEmailDomain, s.isEmailDomainBlocked],
            (userEmailDomain: string, isEmailDomainBlocked: boolean) => (isEmailDomainBlocked ? '' : userEmailDomain),
        ],
        shouldShowEmailDomainBlockedGate: [
            (s) => [
                s.billing,
                s.formSubmitted,
                s.isAdminOrOwner,
                s.isAnnualPlanCustomer,
                s.isCurrentlyOnStartupPlan,
                s.isEmailDomainBlocked,
                s.isYC,
                s.wasPreviouslyOnStartupPlan,
            ],
            (
                billing: BillingType | null,
                formSubmitted: boolean,
                isAdminOrOwner: boolean | null,
                isAnnualPlanCustomer: boolean,
                isCurrentlyOnStartupPlan: boolean,
                isEmailDomainBlocked: boolean,
                isYC: boolean,
                wasPreviouslyOnStartupPlan: boolean
            ): boolean => {
                return (
                    !!billing &&
                    !formSubmitted &&
                    isAdminOrOwner === true &&
                    !isAnnualPlanCustomer &&
                    !isCurrentlyOnStartupPlan &&
                    !(wasPreviouslyOnStartupPlan && !isYC) &&
                    isEmailDomainBlocked
                )
            },
        ],
        ycBatchOptions: [
            () => [],
            () => {
                return getYCBatchOptions()
            },
        ],
    }),
    forms(({ values, actions, props }) => ({
        startupProgram: {
            defaults: {
                type: values.isYC ? StartupProgramType.YC : StartupProgramType.Startup,
                startup_domain: values.domainFromEmail || '',
                organization_name: values.currentOrganization!.name,
                organization_id: values.currentOrganizationId,
                raised: undefined,
                incorporation_date: undefined,
                yc_verification_url: values.isYC ? '' : undefined,
                yc_batch: values.isYC ? '' : undefined,
                yc_proof_screenshot_url: undefined,
                yc_merch_count: values.isYC ? 1 : undefined,
            } as StartupProgramFormValues,
            // Selector-style errors so that validation recomputes when billing
            // or isYC change, not only when form values change
            errors: [
                (s) => [s.startupProgram, s.billing, s.isYC, s.isEmailDomainBlocked],
                (
                    {
                        organization_id,
                        raised,
                        incorporation_date,
                        yc_verification_url,
                        yc_batch,
                        yc_proof_screenshot_url,
                    }: StartupProgramFormValues,
                    billing: BillingType | null,
                    isYC: boolean,
                    isEmailDomainBlocked: boolean
                ) => {
                    if (isEmailDomainBlocked) {
                        return {
                            _form: 'The startup program requires a company email address. Update your account email to your company domain, then apply again.',
                        }
                    }

                    if (!billing?.has_active_subscription) {
                        return {
                            _form: 'You need to upgrade to a paid plan before submitting your application',
                        }
                    }

                    return {
                        organization_id: !organization_id ? 'Please select an organization' : undefined,
                        raised: validateFunding(raised, isYC),
                        incorporation_date: validateIncorporationDate(incorporation_date, isYC),
                        yc_verification_url: validateYcVerificationUrl(yc_verification_url, isYC),
                        yc_batch: isYC && !yc_batch ? 'Please select your YC batch' : undefined,
                        yc_proof_screenshot_url:
                            isYC && !yc_proof_screenshot_url ? 'Please upload a screenshot' : undefined,
                    }
                },
            ],
            submit: async (formValues: StartupProgramFormValues) => {
                const valuesToSubmit: Record<string, any> = {
                    program: values.isYC ? StartupProgramType.YC : StartupProgramType.Startup,
                    organization_id: formValues.organization_id,
                    yc_merch_count: formValues.yc_merch_count,
                }

                if (values.isYC) {
                    valuesToSubmit.yc_verification_url = normalizeYcVerificationUrl(formValues.yc_verification_url)
                    valuesToSubmit.yc_batch = formValues.yc_batch
                    valuesToSubmit.yc_proof_screenshot_url = formValues.yc_proof_screenshot_url
                }

                if (!values.isYC) {
                    valuesToSubmit.raised = formValues.raised
                    valuesToSubmit.incorporation_date = dayjs.isDayjs(formValues.incorporation_date)
                        ? formValues.incorporation_date.format('YYYY-MM-DD')
                        : undefined
                    if (props.referrer) {
                        valuesToSubmit.referrer = props.referrer.toLowerCase()
                    }
                }

                try {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. billingStartupsApplyCreate() from 'products/billing/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/billing/startups/apply', valuesToSubmit)
                    actions.setFormSubmitted(true)
                    // The verification link is bearer proof of YC founder status, so it stays out of analytics
                    const { yc_verification_url: _discarded, ...capturedValues } = valuesToSubmit
                    posthog.capture('startup program application submitted', capturedValues)
                } catch (error: any) {
                    // Billing-service validation errors can arrive as an object under error.detail
                    const detail = typeof error.detail === 'string' ? error.detail : error.detail?.detail
                    lemonToast.error(detail || 'Failed to submit application')
                    throw error
                }
            },
        },
    })),
    subscriptions(({ values, cache }) => ({
        shouldShowEmailDomainBlockedGate: () => {
            captureBlockedApplicationIfGateShown(values, cache)
        },
    })),
    afterMount(({ values, cache }) => {
        captureBlockedApplicationIfGateShown(values, cache)
    }),
])