: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, props, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'
import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { billingLogic } from 'lib/logic/billing/billingLogic'
import { organizationLogic } from 'scenes/organizationLogic'
import { userLogic } from 'scenes/userLogic'
import { ClaimedCouponInfo, CouponsOverview } from '~/types'
import type { BillingType, OrganizationType, UserType } from '../../types'
export interface CouponLogicProps {
campaign?: string
}
export interface CouponFormValues {
code: string
organization_name: string
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface couponLogicValues {
billing: BillingType | null // billingLogic
billingLoading: boolean // billingLogic
currentOrganization: OrganizationType | null // organizationLogic
isAdminOrOwner: boolean | null // organizationLogic
user: UserType | null // userLogic
activeCoupons: ClaimedCouponInfo[]
claimed: boolean
claimedDetails: any
coupon: CouponFormValues
couponAllErrors: Record<string, any>
couponChanged: boolean
couponErrors: DeepPartialMap<CouponFormValues, ValidationErrorType>
couponHasErrors: boolean
couponManualErrors: Record<string, any>
couponTouched: boolean
couponTouches: Record<string, boolean>
couponValidationErrors: DeepPartialMap<CouponFormValues, ValidationErrorType>
couponsOverview: CouponsOverview | null
couponsOverviewLoading: boolean
getClaimedCouponForCampaign: (campaignSlug: string) => ClaimedCouponInfo | null
isCouponSubmitting: boolean
isCouponValid: boolean
showCouponErrors: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface couponLogicActions {
loadBillingSuccess: (
billing: BillingType | null,
payload?: any
) => {
billing: BillingType | null
payload?: any
} // billingLogic
loadCurrentOrganizationSuccess: (
currentOrganization: OrganizationType | null,
payload?: any
) => {
currentOrganization: OrganizationType | null
payload?: any
} // organizationLogic
loadCouponsOverview: () => any
loadCouponsOverviewFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadCouponsOverviewSuccess: (
couponsOverview: CouponsOverview | null,
payload?: any
) => {
couponsOverview: CouponsOverview | null
payload?: any
}
resetCoupon: (values?: CouponFormValues) => {
values?: CouponFormValues
}
setClaimed: (claimed: boolean) => {
claimed: boolean
}
setClaimedDetails: (details: any) => {
details: any
}
setCouponManualErrors: (errors: Record<string, any>) => {
errors: Record<string, any>
}
setCouponValue: (
key: FieldName,
value: any
) => {
name: FieldName
value: any
}
setCouponValues: (values: DeepPartial<CouponFormValues>) => {
values: DeepPartial<CouponFormValues>
}
submitCoupon: () => {
value: boolean
}
submitCouponFailure: (
error: Error,
errors: Record<string, any>
) => {
error: Error
errors: Record<string, any>
}
submitCouponRequest: (coupon: CouponFormValues) => {
coupon: CouponFormValues
}
submitCouponSuccess: (coupon: CouponFormValues) => {
coupon: CouponFormValues
}
touchCouponField: (key: string) => {
key: string
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface couponLogicMeta {
__keaTypeGenInternalSelectorTypes: {
getClaimedCouponForCampaign: (
couponsOverview: CouponsOverview | null
) => (campaignSlug: string) => ClaimedCouponInfo | null
activeCoupons: (couponsOverview: CouponsOverview | null) => ClaimedCouponInfo[]
}
}
export type couponLogicType = MakeLogicType<couponLogicValues, couponLogicActions, CouponLogicProps, couponLogicMeta>
export const couponLogic = kea<couponLogicType>([
path(['scenes', 'coupons', 'couponLogic']),
props({} as CouponLogicProps),
connect(() => ({
values: [
userLogic,
['user'],
organizationLogic,
['currentOrganization', 'isAdminOrOwner'],
billingLogic,
['billing', 'billingLoading'],
],
actions: [billingLogic, ['loadBillingSuccess'], organizationLogic, ['loadCurrentOrganizationSuccess']],
})),
actions({
setClaimed: (claimed: boolean) => ({ claimed }),
setClaimedDetails: (details: any) => ({ details }),
}),
loaders(({ values }) => ({
couponsOverview: [
null as CouponsOverview | null,
{
loadCouponsOverview: async () => {
if (values.isAdminOrOwner === false && values.currentOrganization) {
return null
}
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. billingCouponsOverviewRetrieve() 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.
return await api.get('api/billing/coupons/overview')
},
},
],
})),
reducers({
claimed: [false, { setClaimed: (_, { claimed }) => claimed }],
claimedDetails: [null as any, { setClaimedDetails: (_, { details }) => details }],
}),
selectors({
getClaimedCouponForCampaign: [
(s) => [s.couponsOverview],
(couponsOverview: CouponsOverview | null) =>
(campaignSlug: string): ClaimedCouponInfo | null => {
return couponsOverview?.claimed_coupons?.find((c) => c.campaign_slug === campaignSlug) || null
},
],
activeCoupons: [
(s) => [s.couponsOverview],
(couponsOverview: CouponsOverview | null): ClaimedCouponInfo[] => {
return couponsOverview?.claimed_coupons?.filter((c) => c.status === 'claimed') ?? []
},
],
}),
forms(({ values, actions, props }) => ({
coupon: {
defaults: {
code: '',
organization_name: values.currentOrganization?.name || '',
} as CouponFormValues,
errors: ({ code }) => {
if (!values.billingLoading && !values.billing?.has_active_subscription) {
return {
_form: 'You need to be on a paid plan before claiming this coupon',
}
}
return {
code: !code ? 'Please enter a coupon code' : undefined,
}
},
submit: async (formValues: CouponFormValues) => {
try {
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. billingCouponsClaimCreate() 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.
const res = await api.create('api/billing/coupons/claim', {
code: formValues.code,
})
actions.setClaimed(true)
actions.setClaimedDetails(res)
actions.loadCouponsOverview()
posthog.capture('billing coupon claimed', {
campaign: props.campaign,
code: formValues.code,
})
} catch (error: any) {
lemonToast.error(error.detail || 'Failed to claim coupon')
posthog.capture('billing coupon claim failed', {
campaign: props.campaign,
code: formValues.code,
error: error.detail || 'Unknown error',
})
throw error
}
},
},
})),
listeners(({ values, actions }) => ({
loadBillingSuccess: () => {
// kea-forms errors() is a selector that only recalculates when form state changes.
// Since we depend on external billing state, we force recalculation by re-setting a form value.
actions.setCouponValue('code', values.coupon.code)
},
loadCurrentOrganizationSuccess: () => {
if (!values.couponsOverview && values.isAdminOrOwner) {
actions.loadCouponsOverview()
}
},
})),
afterMount(({ actions }) => {
actions.loadCouponsOverview()
}),
])