: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
fix(subscriptions): restore scheduling editor controls (#78996)
Matt Pua227d9ff4e960
diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.tsindex b6d662ea4cae..f94b2d84748c 100644--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts@@ -51,6 +51,11 @@ describe('subscriptionLogic', () => {get: {'/api/environments/:team/subscriptions': { count: 1, results: [fixtureSubscriptionResponse(1)] },'/api/environments/:team/subscriptions/1': fixtureSubscriptionResponse(1),+ '/api/projects/:team/subscriptions/1/deliveries/': {+ next: null,+ previous: null,+ results: [],+ },'/api/projects/:team/integrations': { count: 0, results: [] },'/api/environments/:team/subscriptions/summary_quota': {active_count: 0,@@ -102,6 +107,29 @@ describe('subscriptionLogic', () => {})})+ it('loads the latest delivery for the current subscription', async () => {+ useMocks({+ get: {+ '/api/projects/:team/subscriptions/1/deliveries/': {+ next: null,+ previous: null,+ results: [+ {+ id: 'delivery-1',+ created_at: '2026-08-06T13:00:00Z',+ finished_at: '2026-08-06T13:01:00Z',+ },+ ],+ },+ },+ })++ router.actions.push('/insights/123/subscriptions/1')+ await expectLogic(existingLogic).toFinishListeners().toDispatchActions(['loadLastDeliverySuccess'])++ expect(existingLogic.values.lastDelivery).toMatchObject({ id: 'delivery-1' })+ })+it('uses the UTC weekday for legacy weekly subscriptions', async () => {useMocks({get: {@@ -120,7 +148,7 @@ describe('subscriptionLogic', () => {expect(existingLogic.values.subscription.byweekday).toEqual(['monday'])})- it('preserves selected days for daily subscriptions with intervals greater than one', async () => {+ it('removes hidden weekday constraints from daily subscriptions with intervals greater than one', async () => {useMocks({get: {'/api/environments/:team/subscriptions/1': fixtureSubscriptionResponse(1, {@@ -134,7 +162,15 @@ describe('subscriptionLogic', () => {router.actions.push('/insights/123/subscriptions/1')await expectLogic(existingLogic).toFinishListeners().toDispatchActions(['loadSubscriptionSuccess'])- expect(existingLogic.values.subscription.byweekday).toEqual(['monday', 'wednesday'])+ expect(existingLogic.values.subscription.byweekday).toEqual([+ 'monday',+ 'tuesday',+ 'wednesday',+ 'thursday',+ 'friday',+ 'saturday',+ 'sunday',+ ])})it('updates values depending on frequency', async () => {@@ -157,6 +193,18 @@ describe('subscriptionLogic', () => {byweekday: ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'],})+ newLogic.actions.setSubscriptionValue('interval', 2)+ await expectLogic(newLogic).toFinishListeners()+ expect(newLogic.values.subscription.byweekday).toEqual([+ 'monday',+ 'tuesday',+ 'wednesday',+ 'thursday',+ 'friday',+ 'saturday',+ 'sunday',+ ])+newLogic.actions.setSubscriptionValues({interval: 7,start_date: '2024-01-01T09:00:00Z',diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.tsindex 411b18ce48b6..99822e386a35 100644--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts@@ -9,6 +9,7 @@ import api, { ApiError } from 'lib/api'import { dayjs } from 'lib/dayjs'import { recordRecentSlackChannel, slackChannelId } from 'lib/integrations/slackChannel'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { getCurrentTeamId } from 'lib/utils/getAppContext'import { objectsEqual } from 'lib/utils/objects'import { isEmail } from 'lib/utils/url'import { getInsightId } from 'scenes/insights/utils'@@ -17,11 +18,16 @@ import { userLogic } from 'scenes/userLogic'import { ExportedAssetType, ExporterFormat, SubscriptionResourceTypes, SubscriptionType } from '~/types'-import type { AIWindowConfigApi } from 'products/subscriptions/frontend/generated/api.schemas'+import {+ subscriptionsDeliveriesList,+ subscriptionsTestDeliveryCreate,+} from 'products/subscriptions/frontend/generated/api'+import type { AIWindowConfigApi, SubscriptionDeliveryApi } from 'products/subscriptions/frontend/generated/api.schemas'import type { SubscriptionResourceType, UserBasicType, WeekdayType } from '../../../../../frontend/src/types'import type { OrganizationType, UserType } from '../../../../../frontend/src/types'import type { AIPromptConfigApi } from '../../generated/api.schemas'+import { runSubscriptionTestDelivery } from './runSubscriptionTestDelivery'import { subscriptionsLogic } from './subscriptionsLogic'import {ALL_DAYS,@@ -179,6 +185,9 @@ export interface subscriptionLogicValues {user: UserType | null // userLogicisSubscriptionSubmitting: booleanisSubscriptionValid: boolean+ lastDelivery: SubscriptionDeliveryApi | null+ lastDeliveryLoadFailed: boolean+ lastDeliveryLoading: booleanpreviewAsset: ExportedAssetType | nullpreviewError: string | nullpreviewImageUrl: string | null@@ -200,6 +209,7 @@ export interface subscriptionLogicValues {limit: number | null} | nullsummaryQuotaLoading: boolean+ testDeliveryLoading: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -210,6 +220,21 @@ export interface subscriptionLogicActions {generatePreview: () => {value: true}+ loadLastDelivery: () => any+ loadLastDeliveryFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadLastDeliverySuccess: (+ lastDelivery: SubscriptionDeliveryApi | null,+ payload?: any+ ) => {+ lastDelivery: SubscriptionDeliveryApi | null+ payload?: any+ }loadSubscription: () => anyloadSubscriptionFailure: (error: string,@@ -318,6 +343,15 @@ export interface subscriptionLogicActions {prompt: stringwindow: AIWindowConfigApi | undefined}+ sendTestDelivery: () => {+ value: true+ }+ sendTestDeliveryFailure: () => {+ value: true+ }+ sendTestDeliverySuccess: () => {+ value: true+ }setPreviewAsset: (asset: ExportedAssetType | null) => {asset: ExportedAssetType | null}@@ -384,6 +418,9 @@ export const subscriptionLogic = kea<subscriptionLogicType>([actions({generatePreview: true,+ sendTestDelivery: true,+ sendTestDeliveryFailure: true,+ sendTestDeliverySuccess: true,setPreviewAsset: (asset: ExportedAssetType | null) => ({ asset }),setPreviewLoading: (loading: boolean) => ({ loading }),setPreviewError: (error: string | null) => ({ error }),@@ -397,6 +434,22 @@ export const subscriptionLogic = kea<subscriptionLogicType>([}),reducers({+ lastDeliveryLoadFailed: [+ false,+ {+ loadLastDelivery: () => false,+ loadLastDeliveryFailure: () => true,+ loadLastDeliverySuccess: () => false,+ },+ ],+ testDeliveryLoading: [+ false,+ {+ sendTestDelivery: () => true,+ sendTestDeliveryFailure: () => false,+ sendTestDeliverySuccess: () => false,+ },+ ],previewAsset: [null as ExportedAssetType | null,{@@ -424,6 +477,16 @@ export const subscriptionLogic = kea<subscriptionLogicType>([}),loaders(({ props }) => ({+ lastDelivery: {+ __default: null as SubscriptionDeliveryApi | null,+ loadLastDelivery: async () => {+ if (props.id === 'new') {+ return null+ }+ const deliveries = await subscriptionsDeliveriesList(String(getCurrentTeamId()), props.id)+ return deliveries.results[0] ?? null+ },+ },subscription: {__default: undefined as unknown as SubscriptionType,loadSubscription: async () => {@@ -432,7 +495,10 @@ export const subscriptionLogic = kea<subscriptionLogicType>([// Rows created before a window was chosen carry ai_prompt_config: {} — normalise// so the analysis window select renders the effective default instead of empty.let byweekday = subscription.byweekday- if (!byweekday?.length && subscription.frequency === 'daily') {+ if (+ subscription.frequency === 'daily' &&+ ((subscription.interval ?? 1) > 1 || !subscription.byweekday?.length)+ ) {byweekday = [...ALL_DAYS]} else if (!byweekday?.length && subscription.frequency === 'weekly') {byweekday = [dayjs.utc(subscription.start_date).format('dddd').toLowerCase() as WeekdayType]@@ -532,6 +598,30 @@ export const subscriptionLogic = kea<subscriptionLogicType>([})),listeners(({ actions, values, props, selectors, cache }) => ({+ loadSubscriptionSuccess: () => {+ if (props.id !== 'new') {+ actions.loadLastDelivery()+ }+ },+ sendTestDelivery: async () => {+ if (props.id === 'new') {+ actions.sendTestDeliveryFailure()+ return+ }+ const subscriptionId = props.id+ const result = await runSubscriptionTestDelivery(() =>+ subscriptionsTestDeliveryCreate(String(getCurrentTeamId()), subscriptionId)+ )+ if (result === 'success') {+ actions.sendTestDeliverySuccess()+ return+ }+ actions.sendTestDeliveryFailure()+ },+ sendTestDeliverySuccess: async (_, breakpoint) => {+ await breakpoint(2000)+ actions.loadLastDelivery()+ },submitSubscriptionSuccess: ({ subscription }) => {if (subscription?.target_type === 'slack' && subscription.target_value && subscription.integration_id) {recordRecentSlackChannel(subscription.integration_id, slackChannelId(subscription.target_value))@@ -623,6 +713,10 @@ export const subscriptionLogic = kea<subscriptionLogicType>([}}+ if (key === 'interval' && values.subscription.frequency === 'daily' && value > 1) {+ actions.setSubscriptionValue('byweekday', [...ALL_DAYS])+ }+if (key === 'target_type') {actions.setSubscriptionValues({target_value: '',diff --git a/products/subscriptions/frontend/components/Subscriptions/utils.test.ts b/products/subscriptions/frontend/components/Subscriptions/utils.test.tsindex 4fa28b9d0054..f25a276431b3 100644--- a/products/subscriptions/frontend/components/Subscriptions/utils.test.ts+++ b/products/subscriptions/frontend/components/Subscriptions/utils.test.ts@@ -1,4 +1,41 @@-import { getAiSubscriptionGate, getNextDeliveryDate } from './utils'+import {+ getAiSubscriptionGate,+ getNextDeliveryDate,+ selectedDaysToDayPickerLabel,+ shouldShowDayPicker,+ toggleSelectedDay,+} from './utils'++describe('day picker values', () => {+ it.each([+ ['daily', 1, true],+ ['daily', 2, false],+ ['weekly', 1, true],+ ['weekly', 2, true],+ ['monthly', 1, false],+ ['yearly', 1, false],+ ] as const)('%s interval %s shows day picker: %s', (frequency, interval, expected) => {+ expect(shouldShowDayPicker(frequency, interval)).toBe(expected)+ })++ it.each([+ [[], 'Select at least one day'],+ [['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'], 'on Monday to Sunday'],+ [['monday', 'tuesday', 'wednesday', 'thursday', 'friday'], 'on weekdays'],+ [['saturday', 'sunday'], 'on weekends'],+ [['wednesday'], 'on Wednesday'],+ [['monday', 'wednesday'], 'on 2 days'],+ ] as const)('summarizes %s as %s', (selectedDays, expected) => {+ expect(selectedDaysToDayPickerLabel([...selectedDays])).toBe(expected)+ })++ it.each([+ ['adds another day', ['wednesday'], 'tuesday', ['tuesday', 'wednesday']],+ ['removes a selected day', ['tuesday', 'wednesday'], 'tuesday', ['wednesday']],+ ] as const)('%s without replacing the other selections', (_label, selectedDays, day, expected) => {+ expect(toggleSelectedDay([...selectedDays], day)).toEqual(expected)+ })+})describe('getNextDeliveryDate', () => {beforeEach(() => {diff --git a/products/subscriptions/frontend/components/Subscriptions/utils.tsx b/products/subscriptions/frontend/components/Subscriptions/utils.tsxindex 792ad8332654..65201e9b4ba3 100644--- a/products/subscriptions/frontend/components/Subscriptions/utils.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/utils.tsx@@ -65,6 +65,10 @@ export const intervalOptions: LemonSelectOptions<number> = range(1, 13).map((x)export type FrequencyOptionValue = 'daily' | 'weekly' | 'monthly'+export function shouldShowDayPicker(frequency: SubscriptionType['frequency'], interval: number): boolean {+ return frequency === 'weekly' || (frequency === 'daily' && interval === 1)+}+export const frequencyOptionsSingular: LemonSelectOption<FrequencyOptionValue>[] = [{ value: 'daily', label: 'day' },{ value: 'weekly', label: 'week' },@@ -87,13 +91,45 @@ export const weekdayOptions = [] satisfies LemonSelectOptionLeaf<WeekdayType>[]export const ALL_DAYS = weekdayOptions.map(({ value }) => value)-export const weekdayInputOptions = weekdayOptions.map(({ value, label }) => ({- key: value,- value,- label,-}))+export const WEEKDAY_DAYS = ALL_DAYS.slice(0, 5)+export const WEEKEND_DAYS = ALL_DAYS.slice(5)++export const WEEKDAYS: Set<string> = new Set(WEEKDAY_DAYS)-export const WEEKDAYS: Set<string> = new Set(['monday', 'tuesday', 'wednesday', 'thursday', 'friday'])+function hasSameDays(selectedDays: WeekdayType[], presetDays: WeekdayType[]): boolean {+ const selectedSet = new Set(selectedDays)+ return selectedSet.size === presetDays.length && presetDays.every((day) => selectedSet.has(day))+}++export function selectedDaysToDayPickerLabel(selectedDays: WeekdayType[]): string {+ if (selectedDays.length === 0) {+ return 'Select at least one day'+ }+ if (hasSameDays(selectedDays, ALL_DAYS)) {+ return 'on Monday to Sunday'+ }+ if (hasSameDays(selectedDays, WEEKDAY_DAYS)) {+ return 'on weekdays'+ }+ if (hasSameDays(selectedDays, WEEKEND_DAYS)) {+ return 'on weekends'+ }+ if (selectedDays.length === 1) {+ const dayLabel = weekdayOptions.find(({ value }) => value === selectedDays[0])?.label ?? selectedDays[0]+ return `on ${dayLabel}`+ }+ return `on ${selectedDays.length} days`+}++export function toggleSelectedDay(selectedDays: WeekdayType[], day: WeekdayType): WeekdayType[] {+ const nextDays = new Set(selectedDays)+ if (nextDays.has(day)) {+ nextDays.delete(day)+ } else {+ nextDays.add(day)+ }+ return ALL_DAYS.filter((weekday) => nextDays.has(weekday))+}export const monthlyWeekdayOptions: LemonSelectOptions<'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday' | 'sunday' | 'day' | 'weekday'diff --git a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsxindex 37bbb7259c29..c61492588e53 100644--- a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx@@ -1,8 +1,8 @@import { useActions, useValues } from 'kea'import { Form } from 'kea-forms'-import { IconChevronLeft } from '@posthog/icons'-import { LemonInput, LemonTextArea, Link } from '@posthog/lemon-ui'+import { IconChevronLeft, IconSend } from '@posthog/icons'+import { LemonCheckbox, LemonDropdown, LemonInput, LemonTextArea, Link } from '@posthog/lemon-ui'import { IntegrationChoice } from 'lib/components/CyclotronJob/integrations/IntegrationChoice'import { FlaggedFeature } from 'lib/components/FlaggedFeature'@@ -35,9 +35,9 @@ import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'import { SubscriptionFreeTierLimit } from '~/queries/schema/schema-general'-import { AvailableFeature, DashboardType, InsightShortId, SubscriptionResourceTypes } from '~/types'+import { AvailableFeature, DashboardType, InsightShortId, SubscriptionResourceTypes, WeekdayType } from '~/types'-import type { AIWindowConfigApi } from 'products/subscriptions/frontend/generated/api.schemas'+import type { AIWindowConfigApi, SubscriptionDeliveryApi } from 'products/subscriptions/frontend/generated/api.schemas'import { InsightSelector } from '../InsightSelector'import { subscriptionCountLogic } from '../subscriptionCountLogic'@@ -45,15 +45,18 @@ import { subscriptionLogic } from '../subscriptionLogic'import { subscriptionsLogic } from '../subscriptionsLogic'import {bysetposOptions,+ ALL_DAYS,frequencyOptionsPlural,frequencyOptionsSingular,getAiSubscriptionGate,getNextDeliveryDate,intervalOptions,monthlyWeekdayOptions,+ selectedDaysToDayPickerLabel,+ shouldShowDayPicker,targetTypeOptions,timeOptions,- weekdayInputOptions,+ toggleSelectedDay,weekdayOptions,WEEKDAYS,AI_PROMPT_MAX_LENGTH,@@ -73,6 +76,96 @@ function AiConsentGateMessage(): JSX.Element {)}+function SubscriptionDayPicker({+ value,+ onChange,+}: {+ value: WeekdayType[]+ onChange: (value: WeekdayType[]) => void+}): JSX.Element {+ let selectAllChecked: boolean | 'indeterminate' = false+ if (value.length === ALL_DAYS.length) {+ selectAllChecked = true+ } else if (value.length > 0) {+ selectAllChecked = 'indeterminate'+ }++ return (+ <LemonDropdown+ closeOnClickInside={false}+ placement="bottom-start"+ overlay={+ <div className="w-48 flex flex-col gap-0.5">+ <div className="flex items-center mb-0.5">+ <LemonButton+ size="small"+ className="flex-1"+ icon={<LemonCheckbox checked={selectAllChecked} className="pointer-events-none" />}+ disabledReason={value.length === ALL_DAYS.length ? 'All days are selected' : undefined}+ onClick={() => onChange([...ALL_DAYS])}+ >+ Select all+ </LemonButton>+ <LemonButton+ size="small"+ disabledReason={value.length === 0 ? 'No days are selected' : undefined}+ onClick={() => onChange([])}+ >+ Clear all+ </LemonButton>+ </div>+ {weekdayOptions.map((day) => (+ <LemonCheckbox+ key={day.value}+ checked={value.includes(day.value)}+ label={day.label}+ fullWidth+ className="px-2 py-1 rounded hover:bg-bg-3000"+ onChange={() => onChange(toggleSelectedDay(value, day.value))}+ />+ ))}+ </div>+ }+ >+ <LemonButton type="secondary">{selectedDaysToDayPickerLabel(value)}</LemonButton>+ </LemonDropdown>+ )+}++function LastDeliveryStatus({+ lastDelivery,+ loading,+ failed,+ currentTimezone,+}: {+ lastDelivery: SubscriptionDeliveryApi | null+ loading: boolean+ failed: boolean+ currentTimezone: string | undefined+}): JSX.Element {+ if (loading) {+ return <LemonSkeleton className="w-32 h-4 inline-block" />+ }+ if (failed) {+ return <>Last run unavailable</>+ }+ if (!lastDelivery) {+ return <>No deliveries yet</>+ }+ return (+ <>+ Last run:{' '}+ <TZLabel+ time={lastDelivery.finished_at ?? lastDelivery.created_at}+ formatDate="ddd, MMM D"+ formatTime="h:mm A"+ timestampStyle="absolute"+ />{' '}+ {currentTimezone}+ </>+ )+}+const AI_PROMPT_EXAMPLES: { label: string; prompt: string; window?: AIWindowConfigApi }[] = [{label: 'Top events',@@ -351,10 +444,19 @@ function EditSubscriptionForm({})const { meFirstMembers, membersLoading } = useValues(membersLogic)- const { subscription, subscriptionLoading, isSubscriptionSubmitting, subscriptionChanged, summaryQuota } =- useValues(logic)+ const {+ subscription,+ subscriptionLoading,+ isSubscriptionSubmitting,+ subscriptionChanged,+ lastDelivery,+ lastDeliveryLoadFailed,+ lastDeliveryLoading,+ summaryQuota,+ testDeliveryLoading,+ } = useValues(logic)const { previewLoading, previewError, previewImageUrl } = useValues(logic)- const { applyDefaultSelectedInsights, generatePreview } = useActions(logic)+ const { applyDefaultSelectedInsights, generatePreview, sendTestDelivery } = useActions(logic)const { preflight, siteUrlMisconfigured } = useValues(preflightLogic)const { currentOrganization } = useValues(organizationLogic)const { deleteSubscription } = useActions(subscriptionslogic)@@ -655,21 +757,12 @@ function EditSubscriptionForm({<LemonSelect options={availableFrequencyOptions} /></LemonField>- {(subscription.frequency === 'daily' || subscription.frequency === 'weekly') && (+ {shouldShowDayPicker(subscription.frequency, subscription.interval) && (<><LemonField name="byweekday">- {({ value, onChange }) => {- const selectedDays = value ?? []- return (- <LemonInputSelect- mode="multiple"- bulkActions="select-and-clear-all"- options={weekdayInputOptions}- value={selectedDays}- onChange={onChange}- />- )- }}+ {({ value, onChange }) => (+ <SubscriptionDayPicker value={value ?? []} onChange={onChange} />+ )}</LemonField></>)}@@ -755,6 +848,34 @@ function EditSubscriptionForm({{currentTimezone}</div>)}+ {id !== 'new' && (+ <div className="flex items-center justify-between gap-2 mt-1">+ <div className="text-sm text-secondary">+ <LastDeliveryStatus+ lastDelivery={lastDelivery}+ loading={lastDeliveryLoading}+ failed={lastDeliveryLoadFailed}+ currentTimezone={currentTimezone}+ />+ {' · '}+ <Link to={urls.subscription(id)}>View history</Link>+ </div>+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconSend />}+ onClick={sendTestDelivery}+ loading={testDeliveryLoading}+ disabledReason={+ subscription.enabled === false+ ? 'Re-enable this subscription before sending a test delivery'+ : undefined+ }+ >+ Send test delivery+ </LemonButton>+ </div>+ )}</div>{/*