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.

fix(subscriptions): unblock saving an existing subscription (#101282)

Kyle Swank4be0d13451ca
diff --git a/ee/api/subscription.py b/ee/api/subscription.py
index fd65a440e828..50a499d3587f 100644
--- a/ee/api/subscription.py
+++ b/ee/api/subscription.py
@@ -93,6 +93,18 @@ AI_DELIVERY_DISPLAY_FIELDS = frozenset(
)
+def _capture_post_write_failure(exc: Exception) -> None:
+ """Report a failure that happens after the write is committed.
+
+ `capture_exception` reads query tags and logs, neither of which is guarded, so a fault in
+ reporting would propagate and fail a request whose write already landed.
+ """
+ try:
+ capture_exception(exc)
+ except Exception:
+ pass
+
+
def _summary_quota_cache_key(organization_id) -> str:
return f"subscription:summary_quota:org:{organization_id}"
@@ -776,8 +788,12 @@ class SubscriptionWriteSerializer(serializers.ModelSerializer):
raise ValidationError({"ai_prompt_config": ["AI report settings only apply to AI subscriptions."]})
if "contexts" in attrs:
if resource_type != Subscription.ResourceType.AI_PROMPT:
- raise ValidationError({"contexts": ["Context only applies to AI subscriptions."]})
- attrs["contexts"] = self._validate_contexts(attrs["contexts"])
+ if attrs["contexts"]:
+ raise ValidationError({"contexts": ["Context only applies to AI subscriptions."]})
+ # Every read carries an empty list here, so a client saving what it read sends one back.
+ attrs.pop("contexts")
+ else:
+ attrs["contexts"] = self._validate_contexts(attrs["contexts"])
validate_for_resource_type(attrs, existing)
self._validate_dashboard_export_subscription(attrs)
@@ -1191,51 +1207,56 @@ class SubscriptionWriteSerializer(serializers.ModelSerializer):
if not instance.enabled or not send_test_now:
return instance
- with slo_operation(
- spec=SloSpec(
- distinct_id=str(request.user.distinct_id),
- area=SloArea.ANALYTIC_PLATFORM,
- operation=SloOperation.SUBSCRIPTION_CREATE,
- team_id=instance.team_id,
- resource_id=str(instance.id),
- ),
- properties={
- "subscription_id": instance.id,
- "target_type": instance.target_type,
- "frequency": instance.frequency,
- "interval": instance.interval,
- "byweekday": instance.byweekday,
- "bysetpos": instance.bysetpos,
- "count": instance.count,
- "resource_type": instance.resource_type,
- "dashboard_export_insights_count": len(dashboard_export_insight_ids),
- "summary_enabled": instance.summary_enabled,
- "has_summary_prompt_guide": bool(instance.summary_prompt_guide),
- "has_until_date": instance.until_date is not None,
- "has_invite_message": bool(invite_message),
- },
- ):
- temporal = sync_connect()
- workflow_id = f"handle-subscription-value-change-{instance.id}-{uuid.uuid4()}"
- asyncio.run(
- temporal.start_workflow(
- "handle-subscription-value-change",
- ProcessSubscriptionWorkflowInputs(
- subscription_id=instance.id,
- team_id=instance.team_id,
- distinct_id=str(instance.created_by.distinct_id)
- if instance.created_by
- else str(instance.team_id),
- previous_target_value="",
- previous_value="",
- invite_message=invite_message,
- trigger_type=SubscriptionTriggerType.SUBSCRIPTION_CHANGE,
- resource_type=instance.resource_type,
- ),
- id=workflow_id,
- task_queue=settings.ANALYTICS_PLATFORM_TASK_QUEUE,
+ # The row is committed above and the schedule runs off next_delivery_date, so failing the
+ # request here would hide a subscription that exists and make the retry create a second one.
+ try:
+ with slo_operation(
+ spec=SloSpec(
+ distinct_id=str(request.user.distinct_id),
+ area=SloArea.ANALYTIC_PLATFORM,
+ operation=SloOperation.SUBSCRIPTION_CREATE,
+ team_id=instance.team_id,
+ resource_id=str(instance.id),
+ ),
+ properties={
+ "subscription_id": instance.id,
+ "target_type": instance.target_type,
+ "frequency": instance.frequency,
+ "interval": instance.interval,
+ "byweekday": instance.byweekday,
+ "bysetpos": instance.bysetpos,
+ "count": instance.count,
+ "resource_type": instance.resource_type,
+ "dashboard_export_insights_count": len(dashboard_export_insight_ids),
+ "summary_enabled": instance.summary_enabled,
+ "has_summary_prompt_guide": bool(instance.summary_prompt_guide),
+ "has_until_date": instance.until_date is not None,
+ "has_invite_message": bool(invite_message),
+ },
+ ):
+ temporal = sync_connect()
+ workflow_id = f"handle-subscription-value-change-{instance.id}-{uuid.uuid4()}"
+ asyncio.run(
+ temporal.start_workflow(
+ "handle-subscription-value-change",
+ ProcessSubscriptionWorkflowInputs(
+ subscription_id=instance.id,
+ team_id=instance.team_id,
+ distinct_id=str(instance.created_by.distinct_id)
+ if instance.created_by
+ else str(instance.team_id),
+ previous_target_value="",
+ previous_value="",
+ invite_message=invite_message,
+ trigger_type=SubscriptionTriggerType.SUBSCRIPTION_CHANGE,
+ resource_type=instance.resource_type,
+ ),
+ id=workflow_id,
+ task_queue=settings.ANALYTICS_PLATFORM_TASK_QUEUE,
+ )
)
- )
+ except Exception as exc:
+ _capture_post_write_failure(exc)
return instance
@@ -1340,7 +1361,6 @@ class SubscriptionWriteSerializer(serializers.ModelSerializer):
if not delivery_triggered:
return instance
- temporal = sync_connect()
if send_test_now:
# Explicit ask: deterministic ID so a caller spamming send_test_now dedupes to one
# in-flight delivery per subscription instead of fanning out real sends. Kept distinct
@@ -1351,6 +1371,7 @@ class SubscriptionWriteSerializer(serializers.ModelSerializer):
# consecutive edits both deliver instead of the second silently deduping.
workflow_id = f"handle-subscription-value-change-{instance.id}-{uuid.uuid4()}"
try:
+ temporal = sync_connect()
asyncio.run(
temporal.start_workflow(
"handle-subscription-value-change",
@@ -1374,6 +1395,8 @@ class SubscriptionWriteSerializer(serializers.ModelSerializer):
# A delivery for this subscription is already in flight; the update itself
# succeeded, so skip the duplicate send rather than failing the request.
pass
+ except Exception as exc:
+ _capture_post_write_failure(exc)
return instance
diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.py
index 3a415b60686c..9752a9267981 100644
--- a/ee/api/test/test_subscription.py
+++ b/ee/api/test/test_subscription.py
@@ -219,16 +219,55 @@ class TestSubscriptionTemporal(APILicensedTest):
else:
self.mock_temporal_client.start_workflow.assert_not_called()
- def test_update_send_test_now_skips_duplicate_in_flight_delivery(self):
+ @parameterized.expand(
+ [
+ ("a delivery is already in flight", "start_workflow"),
+ ("the workflow cannot be started", "start_workflow_raises"),
+ ("temporal cannot be reached", "connect_raises"),
+ ("reporting the failure also fails", "capture_raises"),
+ ]
+ )
+ def test_update_survives_a_confirmation_delivery_it_cannot_start(self, _name, failure):
sub_id = self._create_subscription().json()["id"]
self.mock_temporal_client.start_workflow.reset_mock()
- self.mock_temporal_client.start_workflow.side_effect = WorkflowAlreadyStartedError(
- f"send-test-now-subscription-{sub_id}", "handle-subscription-value-change"
+ if failure == "capture_raises":
+ self.mock_sync.side_effect = RuntimeError("Failed client connect: Connection refused")
+ capture_patcher = patch("ee.api.subscription.capture_exception", side_effect=RuntimeError("capture down"))
+ capture_patcher.start()
+ self.addCleanup(capture_patcher.stop)
+ elif failure == "start_workflow":
+ self.mock_temporal_client.start_workflow.side_effect = WorkflowAlreadyStartedError(
+ f"send-test-now-subscription-{sub_id}", "handle-subscription-value-change"
+ )
+ elif failure == "start_workflow_raises":
+ self.mock_temporal_client.start_workflow.side_effect = RuntimeError("workflow rejected")
+ else:
+ self.mock_sync.side_effect = RuntimeError("Failed client connect: Connection refused")
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/subscriptions/{sub_id}",
+ {"send_test_now": True, "title": "Renamed"},
)
- response = self.client.patch(f"/api/projects/{self.team.id}/subscriptions/{sub_id}", {"send_test_now": True})
- # A delivery already in flight must not fail the update or fan out a second send
assert response.status_code == status.HTTP_200_OK, response.content
+ assert Subscription.objects.get(id=sub_id).title == "Renamed"
+
+ @parameterized.expand(
+ [
+ ("the workflow cannot be started", "start_workflow_raises"),
+ ("temporal cannot be reached", "connect_raises"),
+ ]
+ )
+ def test_create_survives_a_confirmation_delivery_it_cannot_start(self, _name, failure):
+ if failure == "start_workflow_raises":
+ self.mock_temporal_client.start_workflow.side_effect = RuntimeError("workflow rejected")
+ else:
+ self.mock_sync.side_effect = RuntimeError("Failed client connect: Connection refused")
+
+ response = self._create_subscription(title="Made anyway")
+
+ assert response.status_code == status.HTTP_201_CREATED, response.content
+ assert Subscription.objects.get(id=response.json()["id"]).title == "Made anyway"
def test_update_inferred_deliveries_get_unique_workflow_ids(self):
# Only explicit send_test_now dedupes: two legitimate consecutive recipient edits must
@@ -3431,6 +3470,19 @@ class TestAISubscriptionAPI(APILicensedTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
assert response.json()["attr"] == "contexts"
+ def test_accepts_an_empty_contexts_list_on_a_traditional_subscription(self, mock_is_cloud, mock_flag, mock_sync):
+ self._mock_temporal(mock_sync)
+ created = self.client.post(f"/api/projects/{self.team.id}/subscriptions", self._insight_payload())
+ assert created.status_code == status.HTTP_201_CREATED, created.json()
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/subscriptions/{created.json()['id']}",
+ {"title": "Renamed", "contexts": [], "send_test_now": False},
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["title"] == "Renamed"
+
def test_context_replacement_rolls_back_subscription_and_rows(self, mock_is_cloud, mock_flag, mock_sync):
self._enable_ai()
self._mock_temporal(mock_sync)
diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts
index 5140b82c78bd..c82de2e77690 100644
--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts
+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts
@@ -241,6 +241,22 @@ describe('subscriptionLogic', () => {
bysetpos: 1,
byweekday: ['monday'],
})
+
+ // The day picker is hidden above a one-day interval, so an empty selection there is an
+ // error no visible control can clear.
+ newLogic.actions.setSubscriptionValue('interval', 7)
+ newLogic.actions.setSubscriptionValue('frequency', 'daily')
+ await expectLogic(newLogic).toFinishListeners()
+ expect(newLogic.values.subscription.byweekday).toEqual([
+ 'monday',
+ 'tuesday',
+ 'wednesday',
+ 'thursday',
+ 'friday',
+ 'saturday',
+ 'sunday',
+ ])
+ expect(newLogic.values.subscriptionValidationErrors.frequency).toBeNull()
})
it('records successful wizard-created subscriptions separately from the editor', async () => {
@@ -661,11 +677,24 @@ describe('subscriptionLogic', () => {
confirmSpy.mockRestore()
})
- it('does not toast when kea-forms reports client validation failure', async () => {
- await expectLogic(newLogic, () => {
- newLogic.actions.submitSubscriptionFailure(new Error('Validation Failed'), {})
- }).toFinishListeners()
- expect(lemonToast.error).not.toHaveBeenCalled()
+ // A schedule error has no field that renders it, so without this the button looks dead.
+ it('names the section to check when client validation blocks the save', async () => {
+ router.actions.push('/insights/123/subscriptions/new')
+ await expectLogic(newLogic).toFinishListeners()
+
+ newLogic.actions.setSubscriptionValues({
+ title: 'Weekly report',
+ target_value: '[email protected]',
+ byweekday: [],
+ })
+ newLogic.actions.submitSubscription()
+ await expectLogic(newLogic).toFinishListeners()
+
+ expect(lemonToast.error).toHaveBeenCalledWith('Check Recurrence before saving.')
+ expect(posthog.capture).toHaveBeenCalledWith(
+ 'subscription save blocked',
+ expect.objectContaining({ fields: ['frequency'] })
+ )
})
it('toasts and maps ApiError attr to manual errors on save failure', async () => {
@@ -681,6 +710,11 @@ describe('subscriptionLogic', () => {
expect(newLogic.values.subscriptionManualErrors).toEqual({
dashboard_export_insights: 'Select at least one insight',
})
+
+ // Untouchable otherwise: no field renders this error, so it would block every later submit.
+ newLogic.actions.setSubscriptionValue('title', 'Renamed after the failure')
+ await expectLogic(newLogic).toFinishListeners()
+ expect(newLogic.values.subscriptionManualErrors).toEqual({})
})
it.each<[string, Partial<SubscriptionType>, string[]]>([
@@ -858,6 +892,60 @@ describe('subscriptionLogic', () => {
expect(capturedBody?.target_value).toBeUndefined()
})
+ // Every read carries an empty `contexts`, and echoing it back made the API reject the rename.
+ it('does not send the read-only contexts when renaming an existing subscription', async () => {
+ let capturedBody: Partial<SubscriptionType> | undefined
+ useMocks({
+ get: {
+ '/api/environments/:team/subscriptions/1': {
+ ...fixtureSubscriptionResponse(1),
+ contexts: [],
+ },
+ },
+ patch: {
+ '/api/environments/:team/subscriptions/1': async ({ request }) => {
+ capturedBody = (await request.json()) as Partial<SubscriptionType>
+ return [200, fixtureSubscriptionResponse(1)]
+ },
+ },
+ })
+ existingLogic.actions.loadSubscription()
+ await expectLogic(existingLogic).toFinishListeners()
+
+ existingLogic.actions.setSubscriptionValue('title', 'Renamed')
+ existingLogic.actions.submitSubscription()
+ await expectLogic(existingLogic).toFinishListeners().toDispatchActions(['submitSubscriptionSuccess'])
+
+ expect(capturedBody).not.toHaveProperty('contexts')
+ expect(capturedBody?.title).toBe('Renamed')
+ })
+
+ it('keeps pending edits dirty when a default integration arrives late', async () => {
+ useMocks({
+ get: {
+ '/api/environments/:team/subscriptions/1': fixtureSubscriptionResponse(1, {
+ target_type: 'slack',
+ target_value: 'C123|#general',
+ integration_id: null,
+ }),
+ },
+ })
+ existingLogic.actions.loadSubscription()
+ await expectLogic(existingLogic).toFinishListeners()
+
+ existingLogic.actions.setSubscriptionValue('title', 'Renamed while connections load')
+ expect(existingLogic.values.subscriptionChanged).toBe(true)
+
+ existingLogic.actions.applyDefaultIntegration(7)
+ await expectLogic(existingLogic).toFinishListeners()
+
+ expect(existingLogic.values.subscription).toMatchObject({
+ title: 'Renamed while connections load',
+ integration_id: 7,
+ })
+ expect(existingLogic.values.subscriptionChanged).toBe(true)
+ })
+
it('asks for a URL again once the Teams webhook is being replaced', async () => {
useMocks({
get: {
diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts
index 2fa53780a3ac..4edbf585abb4 100644
--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts
+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts
@@ -196,6 +196,53 @@ function validateFrequency(subscription: Partial<SubscriptionType>): string | nu
return validateWeekdaySchedule(subscription)
}
+const FIELD_SECTION_LABELS: Record<string, string> = {
+ title: 'Name',
+ target_type: 'Destination',
+ target_value: 'Destination',
+ integration_id: 'Destination',
+ dashboard_export_insights: 'Insights to include',
+ prompt: 'Prompt',
+ ai_prompt_config: 'Analysis window',
+ frequency: 'Recurrence',
+ interval: 'Recurrence',
+ byweekday: 'Recurrence',
+ bysetpos: 'Recurrence',
+ start_date: 'Recurrence',
+}
+
+function holdsAnError(value: unknown): boolean {
+ if (Array.isArray(value)) {
+ return value.some(holdsAnError)
+ }
+ if (value && typeof value === 'object') {
+ return Object.values(value).some(holdsAnError)
+ }
+ return !!value
+}
+
+function invalidFieldNames(allErrors: Record<string, any> | undefined): string[] {
+ return Object.entries(allErrors ?? {})
+ .filter(([, value]) => holdsAnError(value))
+ .map(([key]) => key)
+}
+
+function blockedSaveMessage(fieldNames: string[]): string {
+ const sections: string[] = []
+ for (const name of fieldNames) {
+ const section = FIELD_SECTION_LABELS[name]
+ if (section && !sections.includes(section)) {
+ sections.push(section)
+ }
+ }
+ if (!sections.length) {
+ return 'Check the form before saving.'
+ }
+ const listed =
+ sections.length > 1 ? `${sections.slice(0, -1).join(', ')} and ${sections[sections.length - 1]}` : sections[0]
+ return `Check ${listed} before saving.`
+}
+
function subscriptionSaveErrorMessage(error: unknown): string {
if (error instanceof ApiError) {
const msg = (error.detail || error.message || '').trim()
@@ -272,9 +319,15 @@ export interface subscriptionLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface subscriptionLogicActions {
+ applyDefaultIntegration: (integrationId: number) => {
+ integrationId: number
+ }
applyDefaultSelectedInsights: (selectedIds: number[]) => {
selectedIds: number[]
}
+ clearStaleManualErrors: () => {
+ value: true
+ }
generatePreview: () => {
value: true
}
@@ -493,7 +546,9 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
setPreviewError: (error: string | null) => ({ error }),
setPreviewImageUrl: (url: string | null) => ({ url }),
applyDefaultSelectedInsights: (selectedIds: number[]) => ({ selectedIds }),
+ applyDefaultIntegration: (integrationId: number) => ({ integrationId }),
replaceTeamsWebhook: true,
+ clearStaleManualErrors: true,
selectAiExamplePrompt: (prompt: string, label: string) => ({
prompt,
label,
@@ -659,6 +714,8 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
// toggling resource_type back) would be rejected by the backend, so drop it.
prompt: isAi ? subscription.prompt?.trim() : undefined,
ai_prompt_config: isAi ? subscription.ai_prompt_config : undefined,
+ // No context editor here, and the API keeps stored contexts when the key is absent.
+ contexts: undefined,
}
breakpoint()
@@ -761,6 +818,13 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
replaceTeamsWebhook: () => {
actions.setSubscriptionValue('target_value', '')
},
+ // kea-forms clears a manual error only when its own field is touched, so one on a field this
+ // form does not render would block every later submit.
+ clearStaleManualErrors: () => {
+ if (Object.keys(values.subscriptionManualErrors).length) {
+ actions.setSubscriptionManualErrors({})
+ }
+ },
applyDefaultSelectedInsights: ({ selectedIds }) => {
if (cache.prefillBaseline) {
// Prefilled form: the auto-selection joins the programmatic baseline. A reset here
@@ -775,6 +839,19 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
// unsaved-changes warning; merge the IDs into the subscription to preserve them.
actions.resetSubscription({ ...values.subscription, dashboard_export_insights: selectedIds })
},
+ // Auto-selecting the only connected workspace is the form reconciling itself, not an edit.
+ applyDefaultIntegration: ({ integrationId }) => {
+ if (cache.prefillBaseline) {
+ actions.setSubscriptionValue('integration_id', integrationId)
+ cache.prefillBaseline = { ...cache.prefillBaseline, integration_id: integrationId }
+ return
+ }
+ if (values.subscriptionChanged) {
+ actions.setSubscriptionValue('integration_id', integrationId)
+ return
+ }
+ actions.resetSubscription({ ...values.subscription, integration_id: integrationId })
+ },
loadSummaryQuotaSuccess: ({ summaryQuota }) => {
// Nudge upsell, deferred until the quota answer exists: default the AI summary on for a
// nudge-prefilled create. Never for a non-consented org (the server rejects the create
@@ -817,8 +894,15 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
actions.setSubscriptionValues({ ai_prompt_config: { ...config, window } })
},
submitSubscriptionFailure: ({ error }) => {
- // Kea-forms emits this when client validation fails; fields already show errors.
+ // Not every error has a field that can render it, so name the section instead.
if (error instanceof Error && error.message === 'Validation Failed') {
+ const fields = invalidFieldNames(values.subscriptionAllErrors)
+ posthog.capture('subscription save blocked', {
+ fields,
+ is_new: props.id === 'new',
+ resource_type: values.subscription?.resource_type,
+ })
+ lemonToast.error(blockedSaveMessage(fields))
return
}
const message = subscriptionSaveErrorMessage(error)
@@ -828,13 +912,21 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
lemonToast.error(message)
},
+ setSubscriptionValues: () => {
+ actions.clearStaleManualErrors()
+ },
+
setSubscriptionValue: ({ name, value }, _breakpoint, _action, previousState) => {
+ actions.clearStaleManualErrors()
const key = Array.isArray(name) ? name[0] : name
if (key === 'frequency') {
if (value === 'daily') {
+ // The day picker only renders for a one-day interval, so a longer one has no
+ // control the user could correct an empty selection with.
+ const hiddenDayPicker = (values.subscription.interval ?? 1) > 1
actions.setSubscriptionValues({
bysetpos: null,
- byweekday: ALL_DAYS.slice(0, 5),
+ byweekday: hiddenDayPicker ? [...ALL_DAYS] : ALL_DAYS.slice(0, 5),
})
} else if (value === 'weekly') {
actions.setSubscriptionValues({
diff --git a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx
index ed7d188b2d0f..1a5765478531 100644
--- a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx
+++ b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx
@@ -263,6 +263,7 @@ function EditSubscriptionForm({
const {
subscription,
subscriptionLoading,
+ subscriptionErrors,
isSubscriptionSubmitting,
subscriptionChanged,
lastDelivery,
@@ -324,6 +325,13 @@ function EditSubscriptionForm({
const currentTimezone = parts?.find((part) => part.type === 'timeZoneName')?.value
const nextDeliveryDate = subscription ? getNextDeliveryDate(subscription) : null
+ let saveDisabledReason: string | undefined = undefined
+ if (aiGate.submitBlocked) {
+ saveDisabledReason = AI_NOT_ALLOWED_REASON
+ } else if (!subscriptionChanged) {
+ saveDisabledReason = id === 'new' ? 'Nothing to create yet' : 'No changes to save'
+ }
+
return (
<Form
logic={subscriptionLogic}
@@ -525,9 +533,13 @@ function EditSubscriptionForm({
integration="slack"
value={value}
onChange={(newValue) => {
+ // value === null is the initial auto-select
+ // rather than a user switch.
+ if (value === null && typeof newValue === 'number') {
+ logic.actions.applyDefaultIntegration(newValue)
+ return
+ }
onChange(newValue)
- // Only clear channel when user actively switches,
- // not on initial auto-select (value is null)
if (value !== null && newValue !== value) {
logic.actions.setSubscriptionValue('target_value', '')
}
@@ -682,6 +694,8 @@ function EditSubscriptionForm({
<LemonField name="interval">
<LemonSelect options={intervalOptions} />
</LemonField>
+ {/* The error renders under the box instead, because an error node
+ inside this inline row breaks the "Send every ... at ..." layout. */}
<LemonField name="frequency" renderError={() => null}>
<LemonSelect options={availableFrequencyOptions} />
</LemonField>
@@ -753,6 +767,11 @@ function EditSubscriptionForm({
</LemonField>
</div>
</div>
+ {typeof subscriptionErrors.frequency === 'string' && (
+ <div className="mt-1">
+ <LemonField.Error error={subscriptionErrors.frequency} />
+ </div>
+ )}
{nextDeliveryDate && (
<div className="text-sm text-secondary mt-1">
Next delivery:{' '}
@@ -945,7 +964,7 @@ function EditSubscriptionForm({
type="primary"
htmlType="submit"
loading={isSubscriptionSubmitting}
- disabled={!subscriptionChanged || subscriptionLoading || aiGate.submitBlocked}
+ disabledReason={saveDisabledReason}
>
{id === 'new' ? 'Create subscription' : 'Save'}
</LemonButton>
diff --git a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.unsavedChanges.test.tsx b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.unsavedChanges.test.tsx
new file mode 100644
index 000000000000..0cd64f558734
--- /dev/null
+++ b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.unsavedChanges.test.tsx
@@ -0,0 +1,144 @@
+import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_USER } from 'lib/api.mock'
+
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { Provider } from 'kea'
+import { router } from 'kea-router'
+
+import { userLogic } from 'scenes/userLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { DashboardType, SubscriptionType } from '~/types'
+
+import { EditSubscription } from './EditSubscription'
+
+const DASHBOARD = {
+ id: 5,
+ name: 'Weekly metrics',
+ tiles: [
+ { id: 1, insight: { id: 11, short_id: 'ins11', name: 'Pageviews' }, layouts: { sm: { x: 0, y: 0 } } },
+ { id: 2, insight: { id: 12, short_id: 'ins12', name: 'Sessions' }, layouts: { sm: { x: 0, y: 1 } } },
+ ],
+} as unknown as DashboardType<any>
+
+const SLACK_INTEGRATION = {
+ id: 7,
+ kind: 'slack',
+ config: { team: { id: '123', name: 'PostHog' } },
+ display_name: 'PostHog',
+ icon_url: '',
+ created_at: '2022-01-01T00:09:00',
+}
+
+// Mirrors every field the API returns, including the null ones: a field the form renders but the
+// response leaves null is where a controlled input can write itself a value.
+const subscriptionFixture = (overrides: Partial<SubscriptionType>): SubscriptionType =>
+ ({
+ id: 1,
+ title: 'Weekly dashboard snapshot',
+ resource_type: 'dashboard',
+ resource_name: 'Website',
+ dashboard: 5,
+ insight: null,
+ insight_short_id: null,
+ dashboard_export_insights: [11, 12],
+ contexts: [],
+ prompt: null,
+ ai_prompt_config: {},
+ ai_query_plan_status: null,
+ frequency: 'weekly',
+ interval: 1,
+ byweekday: ['monday'],
+ bysetpos: null,
+ count: null,
+ start_date: '2024-03-04T13:00:00.107000Z',
+ until_date: null,
+ next_delivery_date: '2024-03-11T13:00:00Z',
+ created_at: '2024-03-01T09:30:00.000000Z',
+ deleted: false,
+ enabled: true,
+ summary: 'sent every week on Monday',
+ summary_enabled: false,
+ summary_prompt_guide: '',
+ integration_id: null,
+ invite_message: null,
+ delivery_config: { post_all_insights_in_main_message: false },
+ ...overrides,
+ }) as unknown as SubscriptionType
+
+// The insight picker fills an empty selection and the destination picker selects the only
+// connected workspace. Neither is an edit, so neither may arm the unsaved-changes prompt.
+describe('EditSubscription unsaved changes', () => {
+ const saveButton = (): HTMLButtonElement => screen.getByText('Save').closest('button') as HTMLButtonElement
+ const isClean = (): boolean => saveButton().disabled || saveButton().getAttribute('aria-disabled') === 'true'
+
+ afterEach(() => cleanup())
+
+ it.each([
+ [
+ 'an email destination',
+ { target_type: 'email', target_value: '[email protected]', integration_id: null },
+ ],
+ ['a Slack destination', { target_type: 'slack', target_value: 'C1|#general', integration_id: 7 }],
+ [
+ 'a Slack destination with no stored connection',
+ { target_type: 'slack', target_value: 'C1|#general', integration_id: null },
+ ],
+ ])(
+ 'stays clean on open and after saving %s',
+ async (_label, overrides) => {
+ const subscription = subscriptionFixture(overrides as Partial<SubscriptionType>)
+ useMocks({
+ get: {
+ '/api/environments/:team/subscriptions/1': subscription,
+ '/api/environments/:team/subscriptions': { count: 0, results: [] },
+ '/api/projects/:team/subscriptions/1/deliveries/': { next: null, previous: null, results: [] },
+ '/api/projects/:team/integrations': { count: 1, results: [SLACK_INTEGRATION] },
+ '/api/projects/:team/integrations/:intId/channels': { channels: [] },
+ '/api/environments/:team/subscriptions/summary_quota': {
+ active_count: 0,
+ limit: null,
+ at_limit: false,
+ },
+ '/api/organizations/@current/': MOCK_DEFAULT_ORGANIZATION,
+ '/api/organizations/@current/members/': {
+ count: 1,
+ results: [
+ {
+ id: 'mem-1',
+ level: 8,
+ joined_at: '2022-01-01T00:09:00',
+ updated_at: '2022-01-01T00:09:00',
+ user: { ...MOCK_DEFAULT_USER, email: '[email protected]' },
+ },
+ ],
+ },
+ },
+ patch: { '/api/environments/:team/subscriptions/1': subscription },
+ })
+ initKeaTests()
+ userLogic.mount()
+ userLogic.actions.loadUserSuccess(MOCK_DEFAULT_USER)
+ router.actions.push('/dashboard/5/subscriptions/1')
+
+ render(
+ <Provider>
+ <EditSubscription id={1} dashboard={DASHBOARD} onCancel={jest.fn()} onDelete={jest.fn()} />
+ </Provider>
+ )
+
+ const name = await screen.findByPlaceholderText('e.g. Weekly team report', {}, { timeout: 10000 })
+ expect(isClean()).toBe(true)
+
+ await userEvent.type(name, ' renamed')
+ await waitFor(() => expect(isClean()).toBe(false))
+
+ await userEvent.click(saveButton())
+ await waitFor(() => expect(isClean()).toBe(true), { timeout: 10000 })
+ },
+ 30000
+ )
+})