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.

feat(subscriptions): add weekday scheduling (#72333)

Matt Pua71831441ff4c
diff --git a/ee/api/subscription.py b/ee/api/subscription.py
index 53021106e5ce..ce8b10cca818 100644
--- a/ee/api/subscription.py
+++ b/ee/api/subscription.py
@@ -322,7 +322,7 @@ class SubscriptionSerializer(serializers.ModelSerializer):
),
},
"byweekday": {
- "help_text": "Days of week for weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday."
+ "help_text": "Days of week for daily or weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday."
},
"bysetpos": {
"help_text": "Position within byweekday set for monthly frequency (e.g. 1 for first, -1 for last)."
diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.py
index fb671d3d8ccd..855f00d6d9a1 100644
--- a/ee/api/test/test_subscription.py
+++ b/ee/api/test/test_subscription.py
@@ -96,6 +96,18 @@ class TestSubscriptionTemporal(APILicensedTest):
response = self.client.get(f"/api/projects/{self.team.id}/subscriptions/")
assert response.status_code == status.HTTP_200_OK
+ @parameterized.expand(
+ [
+ ("daily", ["monday", "tuesday", "wednesday", "thursday", "friday"]),
+ ("weekly", ["monday", "wednesday", "friday"]),
+ ]
+ )
+ def test_accepts_multiple_delivery_weekdays(self, frequency: str, byweekday: list[str]) -> None:
+ response = self._create_subscription(frequency=frequency, byweekday=byweekday, bysetpos=None)
+
+ assert response.status_code == status.HTTP_201_CREATED
+ assert response.json()["byweekday"] == byweekday
+
def test_can_create_new_subscription(self):
response = self._create_subscription()
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
diff --git a/posthog/models/test/test_subscription_model.py b/posthog/models/test/test_subscription_model.py
index 9f2d14a89075..fcee099ceaef 100644
--- a/posthog/models/test/test_subscription_model.py
+++ b/posthog/models/test/test_subscription_model.py
@@ -29,6 +29,70 @@ from products.exports.backend.models.subscription import (
from products.product_analytics.backend.models.insight import Insight
+class TestSubscriptionScheduling:
+ def test_weekly_schedule_ignores_stale_monthly_position(self) -> None:
+ subscription = Subscription(
+ frequency=Subscription.SubscriptionFrequency.WEEKLY,
+ interval=1,
+ start_date=datetime(2026, 8, 3, 9, tzinfo=ZoneInfo("UTC")),
+ byweekday=["monday", "wednesday", "friday"],
+ bysetpos=1,
+ )
+
+ assert subscription.summary == "sent every week on Monday, Wednesday and Friday"
+ assert subscription.rrule[0] == datetime(2026, 8, 3, 9, tzinfo=ZoneInfo("UTC"))
+ assert subscription.rrule[1] == datetime(2026, 8, 5, 9, tzinfo=ZoneInfo("UTC"))
+ assert subscription.rrule[2] == datetime(2026, 8, 7, 9, tzinfo=ZoneInfo("UTC"))
+
+ @parameterized.expand(
+ [
+ (
+ "daily_weekdays",
+ "daily",
+ ["monday", "tuesday", "wednesday", "thursday", "friday"],
+ datetime(2024, 1, 5, 9, 0, tzinfo=ZoneInfo("UTC")),
+ datetime(2024, 1, 8, 9, 0, tzinfo=ZoneInfo("UTC")),
+ ),
+ (
+ "weekly_multiple_days",
+ "weekly",
+ ["wednesday", "friday"],
+ datetime(2024, 1, 1, 9, 0, tzinfo=ZoneInfo("UTC")),
+ datetime(2024, 1, 3, 9, 0, tzinfo=ZoneInfo("UTC")),
+ ),
+ ]
+ )
+ @freeze_time("2024-01-01 08:00:00")
+ def test_selected_weekdays_control_delivery_dates(
+ self,
+ _name: str,
+ frequency: str,
+ byweekday: list[str],
+ from_dt: datetime,
+ expected_next_delivery: datetime,
+ ) -> None:
+ next_delivery_date = Subscription._compute_next_delivery_date(
+ frequency=frequency,
+ interval=1,
+ start_date=datetime(2024, 1, 1, 9, 0, tzinfo=ZoneInfo("UTC")),
+ from_dt=from_dt,
+ byweekday=byweekday,
+ )
+
+ assert next_delivery_date == expected_next_delivery
+
+ @freeze_time("2024-01-01 08:00:00")
+ def test_daily_interval_without_a_possible_weekday_returns_none(self) -> None:
+ next_delivery_date = Subscription._compute_next_delivery_date(
+ frequency="daily",
+ interval=7,
+ start_date=datetime(2024, 1, 1, 9, 0, tzinfo=ZoneInfo("UTC")),
+ byweekday=["tuesday"],
+ )
+
+ assert next_delivery_date is None
+
+
@patch.object(settings, "JWT_SIGNING_KEY", "not-so-secret")
@freeze_time("2022-01-01")
class TestSubscription(BaseTest):
@@ -321,12 +385,43 @@ class TestSubscription(BaseTest):
(
"weekly_last_wednesday",
{"interval": 1, "frequency": "weekly", "byweekday": ["wednesday"], "bysetpos": -1},
- "sent every week on the last Wednesday",
+ "sent every week on Wednesday",
),
(
"weekly_wednesday_no_bysetpos",
{"interval": 1, "frequency": "weekly", "byweekday": ["wednesday"]},
- "sent every week",
+ "sent every week on Wednesday",
+ ),
+ (
+ "daily_weekdays",
+ {
+ "interval": 1,
+ "frequency": "daily",
+ "byweekday": ["monday", "tuesday", "wednesday", "thursday", "friday"],
+ },
+ "sent every day on weekdays",
+ ),
+ (
+ "weekly_multiple_days",
+ {"interval": 1, "frequency": "weekly", "byweekday": ["monday", "wednesday", "friday"]},
+ "sent every week on Monday, Wednesday and Friday",
+ ),
+ (
+ "weekly_all_days",
+ {
+ "interval": 1,
+ "frequency": "weekly",
+ "byweekday": [
+ "monday",
+ "tuesday",
+ "wednesday",
+ "thursday",
+ "friday",
+ "saturday",
+ "sunday",
+ ],
+ },
+ "sent every week on Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday",
),
(
"monthly_third_day",
@@ -356,7 +451,7 @@ class TestSubscription(BaseTest):
("third_weekday", 3, "sent every month on the third weekday"),
("fourth_weekday", 4, "sent every month on the fourth weekday"),
("last_weekday", -1, "sent every month on the last weekday"),
- ("no_bysetpos", None, "sent every month"),
+ ("no_bysetpos", None, "sent every month on weekdays"),
]
)
def test_subscription_summary_weekday(self, _name, bysetpos, expected_summary):
diff --git a/products/exports/backend/models/subscription.py b/products/exports/backend/models/subscription.py
index 10bd46439061..3cc078204f71 100644
--- a/products/exports/backend/models/subscription.py
+++ b/products/exports/backend/models/subscription.py
@@ -74,7 +74,7 @@ def _free_tier_subscription_limit() -> int:
# Max length of the prompt snippet used as an AI subscription's display name when it has no title.
AI_PROMPT_DISPLAY_MAX_LEN = 60
-RRULE_WEEKDAY_MAP = {
+DATEUTIL_WEEKDAY_SHORTHAND_BY_NAME = {
"monday": MO,
"tuesday": TU,
"wednesday": WE,
@@ -283,12 +283,23 @@ class Subscription(ModelActivityMixin, models.Model):
interval=interval,
dtstart=start_date,
until=until_date,
- bysetpos=bysetpos if byweekday else None,
+ bysetpos=bysetpos if byweekday and frequency == Subscription.SubscriptionFrequency.MONTHLY else None,
byweekday=to_rrule_weekdays(byweekday) if byweekday else None,
)
@staticmethod
def _compute_next_delivery_date(*, from_dt: Optional[datetime] = None, **rrule_fields: Any) -> Optional[datetime]:
+ interval = rrule_fields.get("interval") or 1
+ byweekday = rrule_fields.get("byweekday")
+ start_date = rrule_fields.get("start_date")
+ if (
+ rrule_fields.get("frequency") == Subscription.SubscriptionFrequency.DAILY
+ and interval % 7 == 0
+ and byweekday
+ and start_date
+ and start_date.strftime("%A").lower() not in byweekday
+ ):
+ return None
# Buffer of 15 minutes since we might run a bit early — never schedule into the past.
now = timezone.now() + timedelta(minutes=15)
return Subscription._build_rrule(**rrule_fields).after(dt=max(from_dt or now, now), inc=False)
@@ -443,7 +454,7 @@ class Subscription(ModelActivityMixin, models.Model):
summary = f"sent every {str(self.interval) + ' ' if self.interval > 1 else ''}{human_frequency}"
- if self.byweekday and self.bysetpos:
+ if self.frequency == self.SubscriptionFrequency.MONTHLY and self.byweekday and self.bysetpos:
human_bysetpos = {
1: "first",
2: "second",
@@ -458,6 +469,18 @@ class Subscription(ModelActivityMixin, models.Model):
else:
day_label = "day"
summary += f" on the {human_bysetpos} {day_label}"
+ elif self.byweekday and (
+ self.frequency != self.SubscriptionFrequency.DAILY
+ or set(self.byweekday) != set(DATEUTIL_WEEKDAY_SHORTHAND_BY_NAME)
+ ):
+ if set(self.byweekday) == WEEKDAY_SET:
+ summary += " on weekdays"
+ else:
+ day_labels = [day.capitalize() for day in self.byweekday]
+ if len(day_labels) == 1:
+ summary += f" on {day_labels[0]}"
+ else:
+ summary += f" on {', '.join(day_labels[:-1])} and {day_labels[-1]}"
return summary
except KeyError as e:
capture_exception(e)
@@ -536,7 +559,7 @@ def log_subscription_activity(
def to_rrule_weekdays(weekday: Subscription.SubscriptionByWeekDay):
- return {RRULE_WEEKDAY_MAP.get(x) for x in weekday}
+ return {DATEUTIL_WEEKDAY_SHORTHAND_BY_NAME.get(x) for x in weekday}
def get_unsubscribe_token(subscription: Subscription, email: str) -> str:
diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts
index 27be12540197..b6d662ea4cae 100644
--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts
+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts
@@ -102,12 +102,47 @@ describe('subscriptionLogic', () => {
})
})
+ it('uses the UTC weekday for legacy weekly subscriptions', async () => {
+ useMocks({
+ get: {
+ '/api/environments/:team/subscriptions/1': fixtureSubscriptionResponse(1, {
+ frequency: 'weekly',
+ start_date: '2024-01-01T00:30:00Z',
+ byweekday: null,
+ bysetpos: null,
+ }),
+ },
+ })
+
+ router.actions.push('/insights/123/subscriptions/1')
+ await expectLogic(existingLogic).toFinishListeners().toDispatchActions(['loadSubscriptionSuccess'])
+
+ expect(existingLogic.values.subscription.byweekday).toEqual(['monday'])
+ })
+
+ it('preserves selected days for daily subscriptions with intervals greater than one', async () => {
+ useMocks({
+ get: {
+ '/api/environments/:team/subscriptions/1': fixtureSubscriptionResponse(1, {
+ frequency: 'daily',
+ interval: 2,
+ byweekday: ['monday', 'wednesday'],
+ }),
+ },
+ })
+
+ router.actions.push('/insights/123/subscriptions/1')
+ await expectLogic(existingLogic).toFinishListeners().toDispatchActions(['loadSubscriptionSuccess'])
+
+ expect(existingLogic.values.subscription.byweekday).toEqual(['monday', 'wednesday'])
+ })
+
it('updates values depending on frequency', async () => {
router.actions.push('/insights/123/subscriptions/new')
await expectLogic(newLogic).toFinishListeners()
expect(newLogic.values.subscription).toMatchObject({
frequency: 'weekly',
- bysetpos: 1,
+ bysetpos: null,
byweekday: ['monday'],
})
// A plain "new subscription" open (no prefill) must not pre-mark the form as changed,
@@ -119,7 +154,31 @@ describe('subscriptionLogic', () => {
expect(newLogic.values.subscription).toMatchObject({
frequency: 'daily',
bysetpos: null,
- byweekday: null,
+ byweekday: ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'],
+ })
+
+ newLogic.actions.setSubscriptionValues({
+ interval: 7,
+ start_date: '2024-01-01T09:00:00Z',
+ byweekday: ['tuesday'],
+ })
+ newLogic.actions.submitSubscription()
+ await expectLogic(newLogic).toFinishListeners()
+ expect(newLogic.values.subscriptionErrors.frequency).toBe(
+ 'Select the delivery day matching the start date for this interval'
+ )
+
+ newLogic.actions.setSubscriptionValue('byweekday', [])
+ newLogic.actions.submitSubscription()
+ await expectLogic(newLogic).toFinishListeners()
+ expect(newLogic.values.subscriptionErrors.frequency).toBe('Select at least one delivery day')
+
+ newLogic.actions.setSubscriptionValue('frequency', 'weekly')
+ await expectLogic(newLogic).toFinishListeners()
+ expect(newLogic.values.subscription).toMatchObject({
+ frequency: 'weekly',
+ bysetpos: null,
+ byweekday: ['monday'],
})
newLogic.actions.setSubscriptionValue('frequency', 'monthly')
diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts
index bbbcc3b5e9c7..411b18ce48b6 100644
--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts
+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts
@@ -23,7 +23,13 @@ import type { SubscriptionResourceType, UserBasicType, WeekdayType } from '../..
import type { OrganizationType, UserType } from '../../../../../frontend/src/types'
import type { AIPromptConfigApi } from '../../generated/api.schemas'
import { subscriptionsLogic } from './subscriptionsLogic'
-import { AI_PROMPT_MAX_LENGTH, SUBSCRIPTION_PREFILL_PARAMS, SubscriptionBaseProps, urlForSubscription } from './utils'
+import {
+ ALL_DAYS,
+ AI_PROMPT_MAX_LENGTH,
+ SUBSCRIPTION_PREFILL_PARAMS,
+ SubscriptionBaseProps,
+ urlForSubscription,
+} from './utils'
function validatePrompt(
resource_type: SubscriptionType['resource_type'],
@@ -102,6 +108,35 @@ function validateDashboardExportInsights(
return subscription.dashboard_export_insights?.length ? undefined : 'Select at least one insight'
}
+function validateWeekdaySchedule(subscription: Partial<SubscriptionType>): string | null {
+ if (
+ (subscription.frequency === 'daily' || subscription.frequency === 'weekly') &&
+ !subscription.byweekday?.length
+ ) {
+ return 'Select at least one delivery day'
+ }
+ if (
+ subscription.frequency !== 'daily' ||
+ !subscription.interval ||
+ subscription.interval % 7 !== 0 ||
+ !subscription.start_date ||
+ !subscription.byweekday?.length
+ ) {
+ return null
+ }
+ const startWeekday = dayjs.utc(subscription.start_date).format('dddd').toLowerCase()
+ return subscription.byweekday.includes(startWeekday as WeekdayType)
+ ? null
+ : 'Select the delivery day matching the start date for this interval'
+}
+
+function validateFrequency(subscription: Partial<SubscriptionType>): string | null {
+ if (!subscription.frequency) {
+ return 'You need to set a schedule frequency'
+ }
+ return validateWeekdaySchedule(subscription)
+}
+
function subscriptionSaveErrorMessage(error: unknown): string {
if (error instanceof ApiError) {
const msg = (error.detail || error.message || '').trim()
@@ -123,7 +158,7 @@ const NEW_SUBSCRIPTION: Partial<SubscriptionType> = {
start_date: dayjs().hour(9).minute(0).second(0).toISOString(),
target_type: 'email',
byweekday: ['monday'],
- bysetpos: 1,
+ bysetpos: null,
dashboard_export_insights: [],
integration_id: null,
enabled: true,
@@ -396,8 +431,15 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
const subscription = await api.subscriptions.get(props.id)
// 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') {
+ byweekday = [...ALL_DAYS]
+ } else if (!byweekday?.length && subscription.frequency === 'weekly') {
+ byweekday = [dayjs.utc(subscription.start_date).format('dddd').toLowerCase() as WeekdayType]
+ }
return {
...subscription,
+ byweekday,
// Write-only, so never present on the API response: default the edit form's
// "Send a test run now" toggle to on, matching the create flow.
send_test_now: true,
@@ -425,7 +467,7 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
subscription: {
defaults: { enabled: NEW_SUBSCRIPTION.enabled } as unknown as SubscriptionType,
errors: (subscription) => ({
- frequency: !subscription.frequency ? 'You need to set a schedule frequency' : undefined,
+ frequency: validateFrequency(subscription),
title: !subscription.title ? 'You need to give your subscription a name' : undefined,
interval: !subscription.interval ? 'You need to set an interval' : undefined,
start_date: !subscription.start_date ? 'You need to set a delivery time' : undefined,
@@ -443,6 +485,7 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
const payload = {
...subscription,
+ bysetpos: subscription.frequency === 'monthly' ? subscription.bysetpos : null,
insight: isAi ? undefined : insightId,
dashboard: isAi ? undefined : props.dashboardId,
// AI subscriptions have no dashboard, so a carried-over insight selection would
@@ -560,12 +603,22 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
if (value === 'daily') {
actions.setSubscriptionValues({
bysetpos: null,
- byweekday: null,
+ byweekday: ALL_DAYS.slice(0, 5),
+ })
+ } else if (value === 'weekly') {
+ actions.setSubscriptionValues({
+ bysetpos: null,
+ byweekday: ['monday'],
+ })
+ } else if (value === 'monthly') {
+ actions.setSubscriptionValues({
+ bysetpos: 1,
+ byweekday: ['monday'],
})
} else {
actions.setSubscriptionValues({
- bysetpos: NEW_SUBSCRIPTION.bysetpos,
- byweekday: NEW_SUBSCRIPTION.byweekday,
+ bysetpos: null,
+ byweekday: null,
})
}
}
diff --git a/products/subscriptions/frontend/components/Subscriptions/utils.test.ts b/products/subscriptions/frontend/components/Subscriptions/utils.test.ts
index 8fc15fec9bc6..4fa28b9d0054 100644
--- a/products/subscriptions/frontend/components/Subscriptions/utils.test.ts
+++ b/products/subscriptions/frontend/components/Subscriptions/utils.test.ts
@@ -25,12 +25,22 @@ describe('getNextDeliveryDate', () => {
expect(getNextDeliveryDate(subscription)).toEqual(new Date('2024-01-16T09:00:00Z'))
})
- it('computes next weekly delivery', () => {
+ it('computes the next selected daily delivery day', () => {
+ const result = getNextDeliveryDate({
+ frequency: 'daily',
+ interval: 1,
+ start_date: '2024-01-01T09:00:00Z',
+ byweekday: ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'],
+ })
+ expect(result).toEqual(new Date('2024-01-16T09:00:00Z'))
+ })
+
+ it('computes the next selected weekly delivery day', () => {
const result = getNextDeliveryDate({
frequency: 'weekly',
interval: 1,
start_date: '2024-01-01T09:00:00Z',
- byweekday: ['wednesday'],
+ byweekday: ['wednesday', 'friday'],
})
expect(result).toEqual(new Date('2024-01-17T09:00:00Z'))
})
diff --git a/products/subscriptions/frontend/components/Subscriptions/utils.tsx b/products/subscriptions/frontend/components/Subscriptions/utils.tsx
index d6b89b7062d9..792ad8332654 100644
--- a/products/subscriptions/frontend/components/Subscriptions/utils.tsx
+++ b/products/subscriptions/frontend/components/Subscriptions/utils.tsx
@@ -8,7 +8,7 @@ import { range } from 'lib/utils/arrays'
import { urls } from 'scenes/urls'
import { SubscriptionAIPromptMaxLength } from '~/queries/schema/schema-general'
-import { InsightShortId, SubscriptionType } from '~/types'
+import { InsightShortId, SubscriptionType, WeekdayType } from '~/types'
export const AI_PROMPT_MAX_LENGTH = SubscriptionAIPromptMaxLength.CHARACTERS
@@ -76,9 +76,7 @@ export const frequencyOptionsPlural: LemonSelectOption<FrequencyOptionValue>[] =
{ value: 'monthly', label: 'months' },
]
-export const weekdayOptions: LemonSelectOptionLeaf<
- 'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday' | 'sunday'
->[] = [
+export const weekdayOptions = [
{ value: 'monday', label: 'Monday' },
{ value: 'tuesday', label: 'Tuesday' },
{ value: 'wednesday', label: 'Wednesday' },
@@ -86,7 +84,14 @@ export const weekdayOptions: LemonSelectOptionLeaf<
{ value: 'friday', label: 'Friday' },
{ value: 'saturday', label: 'Saturday' },
{ value: 'sunday', label: 'Sunday' },
-]
+] satisfies LemonSelectOptionLeaf<WeekdayType>[]
+
+export const ALL_DAYS = weekdayOptions.map(({ value }) => value)
+export const weekdayInputOptions = weekdayOptions.map(({ value, label }) => ({
+ key: value,
+ value,
+ label,
+}))
export const WEEKDAYS: Set<string> = new Set(['monday', 'tuesday', 'wednesday', 'thursday', 'friday'])
@@ -104,7 +109,7 @@ export const bysetposOptions: LemonSelectOptions<'1' | '2' | '3' | '4' | '-1'> =
export const timeOptions: LemonSelectOptions<string> = range(0, 24).map((x) => ({
value: String(x),
- label: `${String(x).padStart(2, '0')}:00`,
+ label: `${x % 12 || 12}:00 ${x < 12 ? 'AM' : 'PM'}`,
}))
const RRULE_WEEKDAY_MAP: Record<string, (typeof RRule)['MO']> = {
@@ -136,7 +141,7 @@ export function getNextDeliveryDate(subscription: Partial<SubscriptionType>): Da
interval: subscription.interval ?? 1,
dtstart: new Date(subscription.start_date),
byweekday: subscription.byweekday?.map((d) => RRULE_WEEKDAY_MAP[d]) ?? null,
- bysetpos: subscription.bysetpos ?? null,
+ bysetpos: subscription.frequency === 'monthly' ? (subscription.bysetpos ?? null) : null,
})
return rule.after(new Date())
} catch {
diff --git a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx
index ff73594770d5..37bbb7259c29 100644
--- a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx
+++ b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx
@@ -53,6 +53,7 @@ import {
monthlyWeekdayOptions,
targetTypeOptions,
timeOptions,
+ weekdayInputOptions,
weekdayOptions,
WEEKDAYS,
AI_PROMPT_MAX_LENGTH,
@@ -643,108 +644,115 @@ function EditSubscriptionForm({
) : null}
<div>
- <div className="flex items-baseline justify-between w-full">
- <LemonLabel className="mb-2">Recurrence</LemonLabel>
- <div className="text-xs text-secondary text-right">{currentTimezone}</div>
- </div>
- <div className="flex gap-2 items-center rounded border p-2 flex-wrap">
- <span>Send every</span>
- <LemonField name="interval">
- <LemonSelect options={intervalOptions} />
- </LemonField>
- <LemonField name="frequency">
- <LemonSelect options={availableFrequencyOptions} />
- </LemonField>
-
- {subscription.frequency === 'weekly' && (
- <>
- <span>on</span>
- <LemonField name="byweekday">
- {({ value, onChange }) => (
- <LemonSelect
- options={weekdayOptions}
- value={value ? value[0] : null}
- onChange={(val) => onChange([val])}
- />
- )}
- </LemonField>
- </>
- )}
+ <LemonLabel className="mb-2">Recurrence</LemonLabel>
+ <div className="rounded border p-2">
+ <div className="flex gap-2 items-center flex-wrap">
+ <span>Send every</span>
+ <LemonField name="interval">
+ <LemonSelect options={intervalOptions} />
+ </LemonField>
+ <LemonField name="frequency" renderError={() => null}>
+ <LemonSelect options={availableFrequencyOptions} />
+ </LemonField>
- {subscription.frequency === 'monthly' && (
- <>
- <span>on the</span>
- <LemonField name="bysetpos">
- {({ value, onChange }) => (
- <LemonSelect
- options={bysetposOptions}
- value={value ? String(value) : null}
- onChange={(val) => {
- onChange(typeof val === 'string' ? parseInt(val, 10) : null)
- }}
- />
- )}
- </LemonField>
- <LemonField name="byweekday">
- {({ value, onChange }) => {
- const isWeekday =
- value?.length === 5 && value.every((d: string) => WEEKDAYS.has(d))
- const displayValue = value
- ? isWeekday
- ? 'weekday'
- : value.length === 1
- ? value[0]
- : 'day'
- : null
-
- return (
+ {(subscription.frequency === 'daily' || subscription.frequency === 'weekly') && (
+ <>
+ <LemonField name="byweekday">
+ {({ value, onChange }) => {
+ const selectedDays = value ?? []
+ return (
+ <LemonInputSelect
+ mode="multiple"
+ bulkActions="select-and-clear-all"
+ options={weekdayInputOptions}
+ value={selectedDays}
+ onChange={onChange}
+ />
+ )
+ }}
+ </LemonField>
+ </>
+ )}
+ {subscription.frequency === 'monthly' && (
+ <>
+ <span>on the</span>
+ <LemonField name="bysetpos">
+ {({ value, onChange }) => (
<LemonSelect
- dropdownMatchSelectWidth={false}
- options={monthlyWeekdayOptions}
- value={displayValue}
- onChange={(val) =>
- onChange(
- val === 'day'
- ? Object.values(weekdayOptions).map((v) => v.value)
- : val === 'weekday'
- ? [...WEEKDAYS]
- : [val]
- )
- }
+ options={bysetposOptions}
+ value={value ? String(value) : null}
+ onChange={(val) => {
+ onChange(val === null ? null : Number(val))
+ }}
/>
- )
- }}
- </LemonField>
- </>
- )}
- <span>by</span>
- <LemonField name="start_date">
- {({ value, onChange }) => (
- <LemonSelect
- options={timeOptions}
- value={dayjs(value).hour().toString()}
- onChange={(val) => {
- onChange(
- dayjs()
- .hour(typeof val === 'string' ? parseInt(val, 10) : 0)
- .minute(0)
- .second(0)
- .toISOString()
- )
- }}
- />
+ )}
+ </LemonField>
+ <LemonField name="byweekday">
+ {({ value, onChange }) => {
+ const isWeekday =
+ value?.length === 5 &&
+ value.every((d: string) => WEEKDAYS.has(d))
+ let displayValue = null
+ if (isWeekday) {
+ displayValue = 'weekday'
+ } else if (value?.length === 1) {
+ displayValue = value[0]
+ } else if (value) {
+ displayValue = 'day'
+ }
+
+ return (
+ <LemonSelect
+ dropdownMatchSelectWidth={false}
+ options={monthlyWeekdayOptions}
+ value={displayValue}
+ onChange={(val) => {
+ if (val === 'day') {
+ onChange(weekdayOptions.map(({ value }) => value))
+ return
+ }
+ if (val === 'weekday') {
+ onChange([...WEEKDAYS])
+ return
+ }
+ onChange([val])
+ }}
+ />
+ )
+ }}
+ </LemonField>
+ </>
)}
- </LemonField>
+ <span>at</span>
+ <LemonField name="start_date">
+ {({ value, onChange }) => (
+ <LemonSelect
+ options={timeOptions}
+ value={dayjs(value).hour().toString()}
+ onChange={(val) => {
+ onChange(
+ dayjs()
+ .hour(Number(val ?? 0))
+ .minute(0)
+ .second(0)
+ .toISOString()
+ )
+ }}
+ />
+ )}
+ </LemonField>
+ </div>
</div>
{nextDeliveryDate && (
- <div className="text-xs text-secondary mt-1">
+ <div className="text-sm text-secondary mt-1">
Next delivery:{' '}
<TZLabel
time={dayjs(nextDeliveryDate)}
formatDate="ddd, MMM D"
- formatTime="HH:mm"
+ formatTime="h:mm A"
timestampStyle="absolute"
- />
+ />{' '}
+ {currentTimezone}
</div>
)}
</div>
@@ -834,7 +842,7 @@ function EditSubscriptionForm({
<TZLabel
time={dayjs(nextDeliveryDate)}
formatDate="ddd, MMM D"
- formatTime="HH:mm"
+ formatTime="h:mm A"
timestampStyle="absolute"
/>
)
diff --git a/products/subscriptions/frontend/components/Subscriptions/views/SubscriptionOverviewComponents.tsx b/products/subscriptions/frontend/components/Subscriptions/views/SubscriptionOverviewComponents.tsx
index 091d46afea4b..11fd7e0635cb 100644
--- a/products/subscriptions/frontend/components/Subscriptions/views/SubscriptionOverviewComponents.tsx
+++ b/products/subscriptions/frontend/components/Subscriptions/views/SubscriptionOverviewComponents.tsx
@@ -254,7 +254,7 @@ export function SubscriptionListItem({
<TZLabel
time={subscription.next_delivery_date}
formatDate="ddd, MMM D"
- formatTime="HH:mm"
+ formatTime="h:mm A"
timestampStyle="absolute"
/>
</div>
diff --git a/products/subscriptions/frontend/generated/api.schemas.ts b/products/subscriptions/frontend/generated/api.schemas.ts
index 937eb8fd3b21..6dbd7a6b3a2b 100644
--- a/products/subscriptions/frontend/generated/api.schemas.ts
+++ b/products/subscriptions/frontend/generated/api.schemas.ts
@@ -224,7 +224,7 @@ export interface SubscriptionApi {
*/
interval: number
/**
- * Days of week for weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.
+ * Days of week for daily or weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.
* @nullable
*/
byweekday?: SubscriptionApiByweekdayItem[] | null
@@ -372,7 +372,7 @@ export interface PatchedSubscriptionApi {
*/
interval?: number
/**
- * Days of week for weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.
+ * Days of week for daily or weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.
* @nullable
*/
byweekday?: PatchedSubscriptionApiByweekdayItem[] | null
diff --git a/products/subscriptions/frontend/generated/api.zod.ts b/products/subscriptions/frontend/generated/api.zod.ts
index 2162b317d589..09c7461720e5 100644
--- a/products/subscriptions/frontend/generated/api.zod.ts
+++ b/products/subscriptions/frontend/generated/api.zod.ts
@@ -118,7 +118,7 @@ export const SubscriptionsCreateBody = /* @__PURE__ */ zod
)
.nullish()
.describe(
- 'Days of week for weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.'
+ 'Days of week for daily or weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.'
),
bysetpos: zod
.number()
@@ -288,7 +288,7 @@ export const SubscriptionsUpdateBody = /* @__PURE__ */ zod
)
.nullish()
.describe(
- 'Days of week for weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.'
+ 'Days of week for daily or weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.'
),
bysetpos: zod
.number()
@@ -462,7 +462,7 @@ export const SubscriptionsPartialUpdateBody = /* @__PURE__ */ zod
)
.nullish()
.describe(
- 'Days of week for weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.'
+ 'Days of week for daily or weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.'
),
bysetpos: zod
.number()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8e26808c6c80..8324977ec050 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -48368,7 +48368,7 @@ export namespace Schemas {
*/
interval: number;
/**
- * Days of week for weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.
+ * Days of week for daily or weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.
* @nullable
*/
byweekday?: SubscriptionByweekdayItem[] | null;
@@ -56538,7 +56538,7 @@ export namespace Schemas {
*/
interval?: number;
/**
- * Days of week for weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.
+ * Days of week for daily or weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.
* @nullable
*/
byweekday?: PatchedSubscriptionByweekdayItem[] | null;
diff --git a/services/mcp/src/generated/subscriptions/api.ts b/services/mcp/src/generated/subscriptions/api.ts
index ea99289928c2..c5451471572d 100644
--- a/services/mcp/src/generated/subscriptions/api.ts
+++ b/services/mcp/src/generated/subscriptions/api.ts
@@ -153,7 +153,7 @@ export const SubscriptionsCreateBody = /* @__PURE__ */ zod
)
.nullish()
.describe(
- 'Days of week for weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.'
+ 'Days of week for daily or weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.'
),
bysetpos: zod
.number()
@@ -340,7 +340,7 @@ export const SubscriptionsPartialUpdateBody = /* @__PURE__ */ zod
)
.nullish()
.describe(
- 'Days of week for weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.'
+ 'Days of week for daily or weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.'
),
bysetpos: zod
.number()
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.json
index 008403477f26..1caa4346754e 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.json
@@ -73,7 +73,7 @@
"type": "null"
}
],
- "description": "Days of week for weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday."
+ "description": "Days of week for daily or weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday."
},
"count": {
"anyOf": [
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-partial-update.json
index 61e4c2d572c5..ecb6aa6d9ba9 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-partial-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-partial-update.json
@@ -72,7 +72,7 @@
"type": "null"
}
],
- "description": "Days of week for weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday."
+ "description": "Days of week for daily or weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday."
},
"count": {
"anyOf": [