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.

2.1 KB
Raw Blame
import { MakeLogicType, afterMount, connect, kea, path } from 'kea'
import { loaders } from 'kea-loaders'

import { getCurrentTeamId } from 'lib/utils/getAppContext'
import { userLogic } from 'scenes/userLogic'

import { AvailableFeature } from '~/types'

import { subscriptionsList } from 'products/subscriptions/frontend/generated/api'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface subscriptionCountLogicValues {
    hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic
    subscriptionCount: number | null
    subscriptionCountLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface subscriptionCountLogicActions {
    loadSubscriptionCount: () => any
    loadSubscriptionCountFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSubscriptionCountSuccess: (
        subscriptionCount: number,
        payload?: any
    ) => {
        subscriptionCount: number
        payload?: any
    }
}

export type subscriptionCountLogicType = MakeLogicType<subscriptionCountLogicValues, subscriptionCountLogicActions>

export const subscriptionCountLogic = kea<subscriptionCountLogicType>([
    path(['lib', 'components', 'Subscriptions', 'subscriptionCountLogic']),
    connect(() => ({ values: [userLogic, ['hasAvailableFeature']] })),
    loaders({
        // null = not loaded yet; consumers treat null as "unknown" and fail open.
        subscriptionCount: [
            null as number | null,
            {
                loadSubscriptionCount: async (): Promise<number> => {
                    // limit=1 keeps the payload tiny; `count` reflects the full team total.
                    const response = await subscriptionsList(String(getCurrentTeamId()), { limit: 1 })
                    return response.count ?? 0
                },
            },
        ],
    }),
    afterMount(({ actions, values }) => {
        if (!values.hasAvailableFeature(AvailableFeature.SUBSCRIPTIONS)) {
            actions.loadSubscriptionCount()
        }
    }),
])