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.

28.3 KB
Raw Blame
import {
    MakeLogicType,
    actions,
    afterMount,
    connect,
    kea,
    listeners,
    path,
    reducers,
    selectors,
    sharedListeners,
} from 'kea'
import type { BreakPointFunction } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'

import { ApiError } from 'lib/api-error'
import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs, Dayjs } from 'lib/dayjs'
import { billingLogic } from 'lib/logic/billing/billingLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { getBillingLimitConfig } from 'scenes/billing/billingLimitConfig'
import {
    INBOX_PRODUCT_TYPE,
    creditsPerPr as deriveCreditsPerPr,
    freePrs as deriveFreePrs,
    pricePerPrUsd as derivePricePerPrUsd,
} from 'scenes/billing/inboxPricing'
import { teamLogic } from 'scenes/teamLogic'

import { BillingProductV2Type } from '~/types'
import type { BillingType } from '~/types'

import { signalsReportsRefundSummaryRetrieve } from 'products/signals/frontend/generated/api'
import type { SignalReportRefundSummaryResponseApi } from 'products/signals/frontend/generated/api.schemas'

import { inboxBulkActionsLogic } from './inboxBulkActionsLogic'

export type InboxUsageStatus = 'normal' | 'warning' | 'limit'

// Above this fraction of the limit we warn the user before they run out.
const WARNING_THRESHOLD = 0.8

const MAX_LIMIT_PRS = 10000

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface inboxUsageLogicValues {
    billing: BillingType | null // billingLogic
    billingLoading: boolean // billingLogic
    canAccessBilling: boolean // billingLogic
    featureFlags: FeatureFlagsSet // featureFlagLogic
    currentTeamId: number | null // teamLogic
    billingDate: string
    createdPrs: number
    creditsPerPr: number | null
    customLimitUsd: number | null
    estimatedBudgetUsd: number | null
    freePrs: number
    isLimitFormSubmitting: boolean
    isLimitFormValid: boolean
    isLoading: boolean
    isModalOpen: boolean
    isSubscribed: boolean
    limitForm: {
        prs: number | null
    }
    limitFormAllErrors: Record<string, any>
    limitFormChanged: boolean
    limitFormErrors: DeepPartialMap<
        {
            prs: number | null
        },
        ValidationErrorType
    >
    limitFormHasErrors: boolean
    limitFormManualErrors: Record<string, any>
    limitFormTouched: boolean
    limitFormTouches: Record<string, boolean>
    limitFormValidationErrors: DeepPartialMap<
        {
            prs: number | null
        },
        ValidationErrorType
    >
    limitPrs: number | null
    maxPrs: number
    percentage: number
    pricePerPrUsd: number | null
    product: BillingProductV2Type | null
    quotaEnforcementFlagEnabled: boolean
    quotaLimited: boolean
    refundSummary: SignalReportRefundSummaryResponseApi | null
    refundSummaryLoading: boolean
    refundedPrs: number
    refundsFlagEnabled: boolean
    resetDate: Dayjs | null
    showLimitFormErrors: boolean
    spendAmountUsd: number | null
    spendProduct: BillingProductV2Type | null
    spentUsd: number | null
    status: InboxUsageStatus
    summaryFlagEnabled: boolean
    usedPrs: number
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface inboxUsageLogicActions {
    loadBilling: () => any // billingLogic
    updateBillingLimits: (limits: { [key: string]: number | null }) => {
        [key: string]: number | null
    } // billingLogic
    updateBillingLimitsSuccess: (
        billing: BillingType | null,
        payload?:
            | {
                  [key: string]: number | null
              }
            | undefined
    ) => {
        billing: BillingType | null
        payload?: {
            [key: string]: number | null
        }
    } // billingLogic
    checkBillingDate: (now?: number) => {
        now: number
    }
    clearRefundSummary: () => {
        value: true
    }
    closeModal: () => {
        value: true
    }
    loadRefundSummary: (_?: any) => any
    loadRefundSummaryFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadRefundSummarySuccess: (
        refundSummary: SignalReportRefundSummaryResponseApi | null,
        payload?: any
    ) => {
        refundSummary: SignalReportRefundSummaryResponseApi | null
        payload?: any
    }
    openModal: () => {
        value: true
    }
    resetLimitForm: (values?: { prs: number | null }) => {
        values?: {
            prs: number | null
        }
    }
    setLimitFormManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setLimitFormValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setLimitFormValues: (
        values: DeepPartial<{
            prs: number | null
        }>
    ) => {
        values: DeepPartial<{
            prs: number | null
        }>
    }
    submitLimitForm: () => {
        value: boolean
    }
    submitLimitFormFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitLimitFormRequest: (limitForm: { prs: number | null }) => {
        limitForm: {
            prs: number | null
        }
    }
    submitLimitFormSuccess: (limitForm: { prs: number | null }) => {
        limitForm: {
            prs: number | null
        }
    }
    touchLimitFormField: (key: string) => {
        key: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface inboxUsageLogicMeta {
    sharedListeners: {
        refreshQuotaForMeterChange: (
            payload: any,
            breakpoint: BreakPointFunction,
            action: {
                type: string
                payload: any
            },
            previousState: any
        ) => void | Promise<void>
    }
    __keaTypeGenInternalSelectorTypes: {
        refundsFlagEnabled: (featureFlags: FeatureFlagsSet) => boolean
        quotaEnforcementFlagEnabled: (featureFlags: FeatureFlagsSet) => boolean
        summaryFlagEnabled: (refundsFlagEnabled: boolean, quotaEnforcementFlagEnabled: boolean) => boolean
        spendProduct: (billing: BillingType | null, billingDate: string) => BillingProductV2Type | null
        spendAmountUsd: (spendProduct: BillingProductV2Type | null, billing: BillingType | null) => number | null
        product: (billing: BillingType | null) => BillingProductV2Type | null
        isLoading: (
            billing: BillingType | null,
            billingLoading: boolean,
            product: BillingProductV2Type | null,
            refundSummary: SignalReportRefundSummaryResponseApi | null,
            refundSummaryLoading: boolean,
            summaryFlagEnabled: boolean
        ) => boolean
        isSubscribed: (product: BillingProductV2Type | null) => boolean
        creditsPerPr: (product: BillingProductV2Type | null) => number | null
        pricePerPrUsd: (product: BillingProductV2Type | null) => number | null
        freePrs: (product: BillingProductV2Type | null) => number
        createdPrs: (
            product: BillingProductV2Type | null,
            creditsPerPr: number | null,
            refundSummary: SignalReportRefundSummaryResponseApi | null
        ) => number
        refundedPrs: (refundSummary: SignalReportRefundSummaryResponseApi | null) => number
        usedPrs: (createdPrs: number, refundedPrs: number) => number
        customLimitUsd: (billing: BillingType | null, product: BillingProductV2Type | null) => number | null
        limitPrs: (
            product: BillingProductV2Type | null,
            creditsPerPr: number | null,
            customLimitUsd: number | null,
            pricePerPrUsd: number | null,
            freePrs: number
        ) => number | null
        status: (usedPrs: number, limitPrs: number | null) => InboxUsageStatus
        quotaLimited: (refundSummary: SignalReportRefundSummaryResponseApi | null) => boolean
        spentUsd: (usedPrs: number, freePrs: number, pricePerPrUsd: number | null) => number | null
        percentage: (usedPrs: number, limitPrs: number | null, freePrs: number) => number
        maxPrs: (
            billing: BillingType | null,
            product: BillingProductV2Type | null,
            customLimitUsd: number | null,
            pricePerPrUsd: number | null,
            freePrs: number
        ) => number
        resetDate: (billing: BillingType | null) => Dayjs | null
        estimatedBudgetUsd: (
            limitForm: {
                prs: number | null
            },
            pricePerPrUsd: number | null,
            freePrs: number
        ) => number | null
    }
}

export type inboxUsageLogicType = MakeLogicType<
    inboxUsageLogicValues,
    inboxUsageLogicActions,
    Record<string, any>,
    inboxUsageLogicMeta
>

/**
 * Drives the PR-usage widget in the inbox agents rail. Reads the inbox/signals billing product and
 * surfaces usage, limit, and reset date in PRs (the product bills in credits; `display_divisor`
 * converts credits → PRs). Usage is the quota's net count, not capped at the limit, and the widget
 * names the gross count and refunds so it still reconciles with the billing page. Editing the limit
 * writes a USD spend cap to `custom_limits_usd`, the same mechanism the billing page uses.
 */
export const inboxUsageLogic = kea<inboxUsageLogicType>([
    path(['scenes', 'inbox', 'logics', 'inboxUsageLogic']),
    connect(() => ({
        values: [
            billingLogic,
            ['billing', 'billingLoading', 'canAccessBilling'],
            featureFlagLogic,
            ['featureFlags'],
            teamLogic,
            ['currentTeamId'],
        ],
        actions: [billingLogic, ['loadBilling', 'updateBillingLimits', 'updateBillingLimitsSuccess']],
    })),
    actions({
        checkBillingDate: (now: number = Date.now()) => ({ now }),
        clearRefundSummary: true,
        openModal: true,
        closeModal: true,
    }),
    loaders(({ values }) => ({
        // Credited-path refund totals for the org's current billing period. Billing usage still
        // contains credited-refunded PRs (the money comes back as an invoice credit, not lower
        // usage), so the widget subtracts them to show the count the quota check uses, and names
        // them next to it. Excluded-path refunds never reach billing usage and need no adjustment.
        // Usage + refund summary are org-wide (billing allocates the free PR tier per org); the
        // widget labels the count accordingly. Revisit if billing ever splits usage per project.
        refundSummary: [
            null as SignalReportRefundSummaryResponseApi | null,
            {
                loadRefundSummary: async (
                    _ = undefined,
                    breakpoint
                ): Promise<SignalReportRefundSummaryResponseApi | null> => {
                    if (!values.summaryFlagEnabled || values.currentTeamId == null) {
                        return null
                    }
                    try {
                        const summary = await signalsReportsRefundSummaryRetrieve(String(values.currentTeamId))
                        breakpoint()
                        return summary
                    } catch (error) {
                        breakpoint()
                        // The refunds flag is org-keyed and resolves late on the client, so the client can
                        // believe refunds are on while the server (re-checking the same flag) disagrees and
                        // returns 404. Degrade to the same null the client-flag guard returns when refunds
                        // are off, rather than surfacing a transient mismatch as an error.
                        if (error instanceof ApiError && error.status === 404) {
                            return null
                        }
                        throw error
                    }
                },
            },
        ],
    })),
    reducers(() => ({
        refundSummary: [null as SignalReportRefundSummaryResponseApi | null, { clearRefundSummary: () => null }],
        billingDate: [
            dayjs.utc().format('YYYY-MM-DD'),
            { checkBillingDate: (_, { now }) => dayjs.utc(now).format('YYYY-MM-DD') },
        ],
        isModalOpen: [
            false,
            {
                openModal: () => true,
                closeModal: () => false,
                // The billing loader swallows a rejected save, so the form's own submit success fires either way.
                updateBillingLimitsSuccess: () => false,
            },
        ],
    })),
    // Defined before `selectors` so the `limitForm` values selector exists when
    // `estimatedBudgetUsd` lists it as an input (kea builds in array order).
    forms(({ values }) => ({
        limitForm: {
            defaults: { prs: null as number | null },
            errors: ({ prs }) => ({
                prs:
                    prs == null
                        ? 'Enter a number of PRs'
                        : !Number.isInteger(prs) || prs < 0
                          ? 'Enter a whole number'
                          : prs < values.freePrs
                            ? `Minimum is ${values.freePrs} PRs (the free tier)`
                            : prs > values.maxPrs
                              ? `Maximum is ${values.maxPrs.toLocaleString()} PRs`
                              : undefined,
            }),
            submit: async ({ prs }) => {
                const { product, pricePerPrUsd, freePrs } = values
                if (!product || pricePerPrUsd == null || prs == null) {
                    return
                }
                const usd = Math.max(0, prs - freePrs) * pricePerPrUsd
                await billingLogic.asyncActions.updateBillingLimits({ [product.type]: usd })
            },
        },
    })),
    selectors({
        // The refunds flag is keyed on the organization group, so posthog-js only resolves it
        // after the org group is registered and flags are re-fetched — typically after this logic
        // has mounted. Derived here so a subscription can react to it flipping on.
        refundsFlagEnabled: [
            (s) => [s.featureFlags],
            (featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet): boolean =>
                !!featureFlags[FEATURE_FLAGS.SIGNALS_PR_REFUNDS],
        ],
        quotaEnforcementFlagEnabled: [
            (s) => [s.featureFlags],
            (featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet): boolean =>
                !!featureFlags[FEATURE_FLAGS.SELF_DRIVING_QUOTA_ENFORCEMENT],
        ],
        // The refund summary matters under either flag: refunds needs the netting numbers, quota
        // enforcement needs quota_limited for the paused banner. The flags roll out independently,
        // so gating the load on refunds alone would hide the paused state for enforcement-only orgs.
        summaryFlagEnabled: [
            (s) => [s.refundsFlagEnabled, s.quotaEnforcementFlagEnabled],
            (refundsFlagEnabled: boolean, quotaEnforcementFlagEnabled: boolean): boolean =>
                refundsFlagEnabled || quotaEnforcementFlagEnabled,
        ],
        spendProduct: [
            (s) => [s.billing, s.billingDate],
            (billing: BillingType | null, billingDate: string): BillingProductV2Type | null => {
                const summary = billing?.usage_summary?.signals_spend_credits
                const cutoff = summary?.billing_start_date
                return cutoff && cutoff <= billingDate
                    ? (billing?.products?.find((product) => product.type === 'inbox_usage') ?? null)
                    : null
            },
        ],
        spendAmountUsd: [
            (s) => [s.spendProduct, s.billing],
            (spendProduct: BillingProductV2Type | null, billing: BillingType | null): number | null =>
                spendProduct?.current_amount_usd != null
                    ? Number(spendProduct.current_amount_usd) * (1 - (billing?.discount_percent || 0) / 100)
                    : null,
        ],
        product: [
            (s) => [s.billing],
            (billing: null | import('~/types').BillingType): BillingProductV2Type | null =>
                billing?.products?.find((p) => p.type === INBOX_PRODUCT_TYPE) ?? null,
        ],
        isLoading: [
            (s) => [
                s.billing,
                s.billingLoading,
                s.product,
                s.refundSummary,
                s.refundSummaryLoading,
                s.summaryFlagEnabled,
            ],
            (
                billing: null | import('~/types').BillingType,
                billingLoading: boolean,
                product: BillingProductV2Type | null,
                refundSummary: SignalReportRefundSummaryResponseApi | null,
                refundSummaryLoading: boolean,
                summaryFlagEnabled: boolean
            ): boolean => {
                if (billing === null && billingLoading) {
                    return true
                }
                // With refunds on, the PR count needs the refund summary too (live top-up +
                // credited netting) — but only hold the skeleton while the card has nothing to
                // show yet. Once billing has rendered a count, a summary load kicked off by the
                // late-resolving org-keyed flag updates the number in place instead of tearing
                // the card down into a skeleton and back.
                return !product && summaryFlagEnabled && refundSummary === null && refundSummaryLoading
            },
        ],
        // Free plan can't raise the limit past the free allocation — the widget points to
        // billing to upgrade instead of editing a limit.
        isSubscribed: [(s) => [s.product], (product: BillingProductV2Type | null): boolean => !!product?.subscribed],
        // Credits per PR — the API's credits → PR divisor. Null means we can't safely show PRs.
        creditsPerPr: [
            (s) => [s.product],
            (product: BillingProductV2Type | null): number | null => deriveCreditsPerPr(product),
        ],
        pricePerPrUsd: [
            (s) => [s.product],
            (product: BillingProductV2Type | null): number | null => derivePricePerPrUsd(product),
        ],
        freePrs: [(s) => [s.product], (product: BillingProductV2Type | null): number => deriveFreePrs(product)],
        // Gross PRs on billing's own basis, so this matches the usage on the billing page.
        createdPrs: [
            (s) => [s.product, s.creditsPerPr, s.refundSummary],
            (
                product: BillingProductV2Type | null,
                creditsPerPr: number | null,
                refundSummary: SignalReportRefundSummaryResponseApi | null
            ): number => {
                if (!product || !creditsPerPr) {
                    return 0
                }
                // Billing's recorded usage lags by up to a day; the refund summary carries the org's
                // live billable credits, so take the max. A just-created PR counts immediately and a
                // same-day (excluded-path) refund visibly un-counts it.
                const billedCredits = Math.max(product.current_usage ?? 0, refundSummary?.period_billable_credits ?? 0)
                return Math.round(billedCredits / creditsPerPr)
            },
        ],
        // Credited-path refunds stay in billing usage, so they are inside `createdPrs`.
        refundedPrs: [
            (s) => [s.refundSummary],
            (refundSummary: SignalReportRefundSummaryResponseApi | null): number =>
                refundSummary?.credited_refund_count ?? 0,
        ],
        // The PRs that count toward the limit. The quota check subtracts credited refunds from
        // billing usage (see `_signals_credited_refund_offset` in ee/billing/quota_limiting.py), so
        // a refund frees a slot. Keep this in step with that check, or the widget reports the org at
        // its limit while agents still run. Not capped at the limit, because usage can run past it
        // before the quota cron pauses agents.
        usedPrs: [
            (s) => [s.createdPrs, s.refundedPrs],
            (createdPrs: number, refundedPrs: number): number => Math.max(0, createdPrs - refundedPrs),
        ],
        customLimitUsd: [
            (s) => [s.billing, s.product],
            (billing: null | import('~/types').BillingType, product: BillingProductV2Type | null): number | null => {
                if (!product) {
                    return null
                }
                const limit = billing?.custom_limits_usd?.[product.type]
                return limit === 0 || limit ? Number(limit) : null
            },
        ],
        // The effective monthly PR cap: a user-set custom limit takes precedence, otherwise the
        // product's own usage_limit (credits). Null means uncapped.
        limitPrs: [
            (s) => [s.product, s.creditsPerPr, s.customLimitUsd, s.pricePerPrUsd, s.freePrs],
            (
                product: BillingProductV2Type | null,
                creditsPerPr: number | null,
                customLimitUsd: number | null,
                pricePerPrUsd: number | null,
                freePrs: number
            ): number | null => {
                if (!product || !creditsPerPr) {
                    return null
                }
                if (customLimitUsd != null && pricePerPrUsd) {
                    return freePrs + Math.round(customLimitUsd / pricePerPrUsd)
                }
                if (product.usage_limit != null) {
                    return Math.round(product.usage_limit / creditsPerPr)
                }
                return null
            },
        ],
        status: [
            (s) => [s.usedPrs, s.limitPrs],
            (usedPrs: number, limitPrs: number | null): InboxUsageStatus => {
                if (limitPrs == null) {
                    return 'normal'
                }
                if (usedPrs >= limitPrs) {
                    return 'limit'
                }
                if (usedPrs / limitPrs >= WARNING_THRESHOLD) {
                    return 'warning'
                }
                return 'normal'
            },
        ],
        // Server truth from the quota limiter: enforcement is actually pausing the pipeline,
        // as opposed to the widget's own usage math in `status`.
        quotaLimited: [
            (s) => [s.refundSummary],
            (refundSummary: SignalReportRefundSummaryResponseApi | null): boolean =>
                refundSummary?.quota_limited === true,
        ],
        // USD spent so far this period: PRs beyond the free allowance, at the per-PR price.
        // Null when we can't price a PR (so the widget hides the figure rather than show "$0").
        spentUsd: [
            (s) => [s.usedPrs, s.freePrs, s.pricePerPrUsd],
            (usedPrs: number, freePrs: number, pricePerPrUsd: number | null): number | null =>
                pricePerPrUsd == null ? null : Math.max(0, usedPrs - freePrs) * pricePerPrUsd,
        ],
        // Bar fill as a % of the denominator (the limit, or the free allowance when uncapped).
        percentage: [
            (s) => [s.usedPrs, s.limitPrs, s.freePrs],
            (usedPrs: number, limitPrs: number | null, freePrs: number): number => {
                const denominator = limitPrs ?? (freePrs || null)
                if (!denominator) {
                    return 0
                }
                return Math.min(100, Math.round((usedPrs / denominator) * 100))
            },
        ],
        // The billing service rejects a dollar limit above its ceiling.
        maxPrs: [
            (s) => [s.billing, s.product, s.customLimitUsd, s.pricePerPrUsd, s.freePrs],
            (
                billing: null | import('~/types').BillingType,
                product: BillingProductV2Type | null,
                customLimitUsd: number | null,
                pricePerPrUsd: number | null,
                freePrs: number
            ): number => {
                if (!product || !pricePerPrUsd) {
                    return MAX_LIMIT_PRS
                }
                const { max } = getBillingLimitConfig({
                    billing,
                    product,
                    customLimitUsd,
                    billingLimitNextPeriod: null,
                })
                return Math.min(MAX_LIMIT_PRS, freePrs + Math.floor(max / pricePerPrUsd))
            },
        ],
        resetDate: [
            (s) => [s.billing],
            (billing: null | import('~/types').BillingType): Dayjs | null =>
                billing?.billing_period?.current_period_end ?? null,
        ],
        // USD spend cap implied by the limit currently typed into the modal. Drives the live budget.
        estimatedBudgetUsd: [
            (s) => [s.limitForm, s.pricePerPrUsd, s.freePrs],
            (
                limitForm: {
                    prs: number | null
                },
                pricePerPrUsd: number | null,
                freePrs: number
            ): number | null => {
                const prs = limitForm?.prs
                if (pricePerPrUsd == null || prs == null || Number.isNaN(prs)) {
                    return null
                }
                return Math.max(0, prs - freePrs) * pricePerPrUsd
            },
        ],
    }),
    sharedListeners(({ actions, values, selectors }) => ({
        refreshQuotaForMeterChange: (_, __, ___, previousState) => {
            if (values.spendProduct?.type !== selectors.spendProduct(previousState)?.type) {
                actions.clearRefundSummary()
                actions.loadRefundSummary()
            }
        },
    })),
    listeners(({ actions, values, selectors, sharedListeners }) => ({
        checkBillingDate: sharedListeners.refreshQuotaForMeterChange,
        [billingLogic.actionTypes.loadBillingSuccess]: sharedListeners.refreshQuotaForMeterChange,
        openModal: () => {
            // Seed the field with the current limit (or the free allowance when uncapped).
            actions.setLimitFormValue('prs', values.limitPrs ?? values.freePrs)
        },
        // Refunds broadcast `reportStateChanged` after dismissing server-side; reload the summary so
        // the widget's PR and refund counts update in-session (mirrors the reportListLogic reconcile
        // listener — a plain dismiss or resolve just makes this a cheap no-op reload).
        [inboxBulkActionsLogic.actionTypes.reportStateChanged]: () => actions.loadRefundSummary(),
        // A raised limit can lift the quota pause, and `quotaLimited` only comes from the summary.
        updateBillingLimitsSuccess: (_, __, ___, previousState) => {
            if (values.spendProduct?.type !== selectors.spendProduct(previousState)?.type) {
                actions.clearRefundSummary()
            }
            actions.loadRefundSummary()
        },
    })),
    // Fires on mount and again when the org-group-keyed flag arrives after mount — a mount-time
    // load alone silently skips the summary on pageloads where flags resolve late, leaving the
    // widget on billing's lagging recorded usage until something else re-triggers the loader.
    subscriptions(({ actions }) => ({
        summaryFlagEnabled: (enabled: boolean) => {
            if (enabled) {
                actions.loadRefundSummary()
            }
        },
    })),
    afterMount(({ actions, values, cache }) => {
        cache.disposables.add(() => {
            let timeout: ReturnType<typeof setTimeout>
            const updateDate = (): void => {
                const now = dayjs.utc()
                actions.checkBillingDate(now.valueOf())
                timeout = setTimeout(updateDate, now.add(1, 'day').startOf('day').diff(now))
            }
            const onVisibilityChange = (): void => {
                if (document.visibilityState === 'visible') {
                    actions.checkBillingDate()
                }
            }
            updateDate()
            document.addEventListener('visibilitychange', onVisibilityChange)
            return () => {
                clearTimeout(timeout)
                document.removeEventListener('visibilitychange', onVisibilityChange)
            }
        }, 'billingDate')
        if (!values.billing) {
            actions.loadBilling()
        }
    }),
])