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(customer-analytics): remove email forwarding settings (#87899)

Arthur Moreira de Deusa5e7bed37c0b
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index 2653252b11af..895782cf04ac 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -55,7 +55,6 @@ import {
WarehousePersonPropertiesSetting,
} from 'products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting'
import { CalendarSyncConfig } from 'products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncConfig'
-import { CustomerEmailConfig } from 'products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/CustomerEmailConfig'
import { CustomerAnalyticsDashboardEvents } from 'products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/events/CustomerAnalyticsDashboardEvents'
import { ExceptionAutocaptureToggle } from 'products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/exception_autocapture/ExceptionAutocaptureSettings'
import { SuppressionRules } from 'products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/suppression_rules/SuppressionRules'
@@ -464,14 +463,6 @@ export const SETTINGS_MAP: SettingSection[] = [
flag: ['CUSTOMER_ANALYTICS', 'CUSTOMER_ANALYTICS_CSP'],
keywords: ['calendar', 'email', 'meetings', 'google', 'sync', 'accounts'],
},
- {
- id: 'customer-analytics-email-sync',
- title: 'Email forwarding',
- description: 'Manage existing email forwarding connections.',
- component: <CustomerEmailConfig />,
- flag: ['CUSTOMER_ANALYTICS', 'CUSTOMER_ANALYTICS_CSP'],
- keywords: ['email', 'inbox', 'forwarding', 'sync', 'accounts'],
- },
{
id: 'customer-analytics-event-stream',
title: 'Event stream',
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index 95497c063e41..e1583f172e7d 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -124,7 +124,6 @@ export type SettingId =
| 'customer-analytics-accounts'
| 'customer-analytics-calendar-sync'
| 'customer-analytics-dashboard-events'
- | 'customer-analytics-email-sync'
| 'customer-analytics-event-stream'
| 'customer-analytics-group-properties'
| 'customer-analytics-person-properties'
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/CustomerEmailConfig.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/CustomerEmailConfig.tsx
deleted file mode 100644
index 7672fd78f05b..000000000000
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/CustomerEmailConfig.tsx
+++ /dev/null
@@ -1,267 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { IconCheck, IconPlus, IconRefresh, IconTrash } from '@posthog/icons'
-import {
- LemonBanner,
- LemonButton,
- LemonCard,
- LemonCollapse,
- LemonInput,
- LemonLabel,
- LemonSkeleton,
- LemonTag,
-} from '@posthog/lemon-ui'
-
-import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
-
-import { EmailForwardingAddress } from 'products/conversations/frontend/components/EmailForwardingAddress'
-
-import { customerEmailConfigLogic } from './customerEmailConfigLogic'
-import type { CustomerEmailChannel } from './customerEmailConfigLogic'
-
-function ConnectedEmailContent({ channel }: { channel: CustomerEmailChannel }): JSX.Element {
- const {
- channelsLoading,
- disconnectingChannelId,
- openingConfirmationChannelId,
- verificationAwaitingChannelIds,
- verificationTimedOutChannelIds,
- verifyingChannelId,
- } = useValues(customerEmailConfigLogic)
- const { disconnectEmail, loadChannels, openGmailConfirmation, verifyForwarding } =
- useActions(customerEmailConfigLogic)
- const verificationAwaiting = verificationAwaitingChannelIds.includes(channel.id)
- const verificationTimedOut = verificationTimedOutChannelIds.includes(channel.id)
-
- return (
- <div className="flex flex-col gap-3 p-3">
- {channel.connection_status !== 'confirmation_expired' &&
- (channel.forwarding_address ? (
- <EmailForwardingAddress forwardingAddress={channel.forwarding_address} />
- ) : (
- <p className="mb-0 text-sm text-secondary">
- A forwarding address is not available. Ask your PostHog administrator to configure the inbound
- email domain.
- </p>
- ))}
- {channel.connection_status === 'pending_confirmation' && (
- <>
- {channel.confirmation_available ? (
- <LemonBanner type="success">
- <div className="flex flex-wrap items-center justify-between gap-2">
- <span>
- Gmail sent a forwarding confirmation. Open it, then enable forwarding and save your
- changes in Gmail.
- </span>
- <LemonButton
- type="primary"
- size="small"
- icon={<IconCheck />}
- loading={openingConfirmationChannelId === channel.id}
- disabledReason={
- openingConfirmationChannelId && openingConfirmationChannelId !== channel.id
- ? 'Another Gmail confirmation is opening'
- : undefined
- }
- onClick={() => openGmailConfirmation(channel.id)}
- >
- Open Gmail confirmation
- </LemonButton>
- </div>
- </LemonBanner>
- ) : (
- <LemonBanner type="info">
- <div className="flex flex-wrap items-center justify-between gap-2">
- <span>
- Gmail may ask you to confirm the forwarding address. If it does, check again after
- the confirmation email arrives.
- </span>
- <LemonButton
- type="secondary"
- size="small"
- icon={<IconRefresh />}
- loading={channelsLoading}
- onClick={() => loadChannels(true)}
- >
- Check again
- </LemonButton>
- </div>
- </LemonBanner>
- )}
- <LemonBanner type={verificationTimedOut ? 'warning' : 'info'}>
- <div className="flex flex-wrap items-center justify-between gap-2">
- <span>
- {verificationAwaiting
- ? 'Verification email sent. Waiting for Gmail to forward it to PostHog. PostHog checks every few seconds.'
- : verificationTimedOut
- ? "We haven't received the verification email. Check Gmail's spam folder and forwarding settings, then try again."
- : 'After you enable forwarding and save your changes in Gmail, verify that messages reach PostHog.'}
- </span>
- <div className="flex flex-wrap gap-2">
- <LemonButton
- type="secondary"
- size="small"
- icon={<IconRefresh />}
- loading={channelsLoading}
- onClick={() => loadChannels(true)}
- >
- Check status
- </LemonButton>
- {!verificationAwaiting && (
- <LemonButton
- type="primary"
- size="small"
- icon={<IconCheck />}
- loading={verifyingChannelId === channel.id}
- disabledReason={
- verifyingChannelId && verifyingChannelId !== channel.id
- ? 'Another email is being verified'
- : undefined
- }
- onClick={() => verifyForwarding(channel.id)}
- >
- Verify forwarding
- </LemonButton>
- )}
- </div>
- </div>
- </LemonBanner>
- </>
- )}
- {channel.connection_status === 'confirmation_expired' && (
- <LemonBanner type="error">
- This forwarding setup expired. Disconnect this email and add it again to restart setup.
- </LemonBanner>
- )}
- <div className="flex justify-end border-t pt-2">
- <LemonButton
- type="secondary"
- status="danger"
- size="small"
- icon={<IconTrash />}
- loading={disconnectingChannelId === channel.id}
- disabledReason={disconnectingChannelId ? 'Another email is being disconnected' : undefined}
- onClick={() => {
- LemonDialog.open({
- title: `Disconnect ${channel.from_email}?`,
- description: 'New messages sent to this email will stop appearing on customer accounts.',
- primaryButton: {
- children: 'Disconnect',
- status: 'danger',
- onClick: () => disconnectEmail(channel.id),
- },
- secondaryButton: { children: 'Cancel' },
- })
- }}
- >
- Disconnect
- </LemonButton>
- </div>
- </div>
- )
-}
-
-function connectedEmailHeader(channel: CustomerEmailChannel): JSX.Element {
- const status =
- channel.connection_status === 'active'
- ? { label: 'Connected', type: 'success' as const }
- : channel.connection_status === 'confirmation_expired'
- ? { label: 'Setup expired', type: 'danger' as const }
- : { label: 'Setup pending', type: 'warning' as const }
- return (
- <div className="flex min-w-0 items-center gap-2 text-left">
- <span className="truncate font-medium">{channel.from_email}</span>
- <LemonTag type={status.type} size="small" className="shrink-0">
- {status.label}
- </LemonTag>
- </div>
- )
-}
-
-function AddEmailForm(): JSX.Element {
- const { addEmailFormVisible, connecting, emailDraft } = useValues(customerEmailConfigLogic)
- const { connectEmail, setAddEmailFormVisible, setEmailDraft } = useActions(customerEmailConfigLogic)
-
- if (!addEmailFormVisible) {
- return (
- <LemonButton type="secondary" size="small" icon={<IconPlus />} onClick={() => setAddEmailFormVisible(true)}>
- Add email address
- </LemonButton>
- )
- }
-
- return (
- <LemonCard hoverEffect={false} className="flex flex-col gap-2 px-4 py-3">
- <LemonLabel>Connect new email</LemonLabel>
- <p className="mb-0 text-sm text-secondary">
- Enter the email address you use to talk to customers. After connecting it, forward incoming messages to
- the PostHog address shown here.
- </p>
- <LemonInput
- type="email"
- value={emailDraft}
- onChange={setEmailDraft}
- placeholder="[email protected]"
- fullWidth
- disabled={connecting}
- onPressEnter={connectEmail}
- />
- <div className="flex gap-2">
- <LemonButton
- type="primary"
- size="small"
- loading={connecting}
- disabledReason={emailDraft.trim() ? undefined : 'Enter your email address'}
- onClick={connectEmail}
- >
- Connect email
- </LemonButton>
- <LemonButton
- type="secondary"
- size="small"
- disabled={connecting}
- onClick={() => setAddEmailFormVisible(false)}
- >
- Cancel
- </LemonButton>
- </div>
- </LemonCard>
- )
-}
-
-export function CustomerEmailConfig(): JSX.Element {
- const { channels, channelsLoadFailed, channelsLoading, expandedChannelIds } = useValues(customerEmailConfigLogic)
- const { loadChannels, setExpandedChannelIds } = useActions(customerEmailConfigLogic)
-
- if (channelsLoading && channels.length === 0) {
- return <LemonSkeleton className="h-32 max-w-2xl" />
- }
- if (channelsLoadFailed && channels.length === 0) {
- return (
- <LemonBanner type="error" action={{ children: 'Try again', onClick: () => loadChannels(true) }}>
- Could not load your connected emails.
- </LemonBanner>
- )
- }
-
- return (
- <div className="flex max-w-2xl flex-col gap-3">
- {channels.length > 0 && (
- <LemonCollapse
- className="bg-surface-primary"
- multiple
- activeKeys={expandedChannelIds}
- onChange={setExpandedChannelIds}
- panels={channels.map((channel) => ({
- key: channel.id,
- header: connectedEmailHeader(channel),
- content: <ConnectedEmailContent channel={channel} />,
- }))}
- />
- )}
- <div className="flex">
- <AddEmailForm />
- </div>
- </div>
- )
-}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/customerEmailConfigLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/customerEmailConfigLogic.test.ts
deleted file mode 100644
index 1c0a506b4536..000000000000
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/customerEmailConfigLogic.test.ts
+++ /dev/null
@@ -1,218 +0,0 @@
-import { expectLogic } from 'kea-test-utils'
-
-import api from 'lib/api'
-import { userLogic } from 'scenes/userLogic'
-
-import { initKeaTests } from '~/test/init'
-import { UserType } from '~/types'
-
-import { customerEmailConfigLogic } from './customerEmailConfigLogic'
-import type { CustomerEmailChannel } from './customerEmailConfigLogic'
-
-describe('customerEmailConfigLogic', () => {
- let logic: ReturnType<typeof customerEmailConfigLogic.build>
- let getSpy: jest.SpyInstance
- let createSpy: jest.SpyInstance
-
- const channel: CustomerEmailChannel = {
- id: 'channel-1',
- from_email: '[email protected]',
- forwarding_address: '[email protected]',
- connection_status: 'pending_confirmation',
- setup_expires_at: '2026-08-13T12:00:00Z',
- confirmation_available: false,
- }
-
- beforeEach(() => {
- initKeaTests()
- jest.resetAllMocks()
- userLogic.actions.loadUserSuccess({
- id: 7,
- email: '[email protected]',
- first_name: 'Casey',
- last_name: 'Manager',
- } as UserType)
- getSpy = jest.spyOn(api, 'get').mockResolvedValue({ configs: [] })
- createSpy = jest.spyOn(api, 'create')
- logic = customerEmailConfigLogic()
- })
-
- afterEach(() => {
- logic.unmount()
- jest.useRealTimers()
- })
-
- it('loads only customer communication channels', async () => {
- getSpy.mockResolvedValue({ configs: [channel] })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
-
- expect(getSpy).toHaveBeenCalledWith('api/conversations/v1/email/status?kind=customer_communication')
- expect(logic.values.channels).toEqual([channel])
- expect(logic.values.channelsLoading).toBe(false)
- })
-
- it('opens an authenticated confirmation without activating the channel', async () => {
- const replace = jest.fn()
- jest.spyOn(window, 'open').mockReturnValue({
- opener: window,
- location: { replace },
- close: jest.fn(),
- } as unknown as Window)
- getSpy.mockResolvedValue({
- configs: [{ ...channel, confirmation_available: true }],
- })
- createSpy.mockResolvedValue({
- ok: true,
- confirmation_url: 'https://mail-settings.google.com/mail/vf-confirmation',
- })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
-
- logic.actions.openGmailConfirmation(channel.id)
- await expectLogic(logic).toFinishAllListeners()
-
- expect(createSpy).toHaveBeenCalledWith('api/conversations/v1/email/confirm-forwarding', {
- config_id: channel.id,
- })
- expect(window.open).toHaveBeenCalledWith('about:blank', '_blank')
- expect(replace).toHaveBeenCalledWith('https://mail-settings.google.com/mail/vf-confirmation')
- expect(logic.values.channels[0]).toEqual({ ...channel, confirmation_available: true })
- expect(logic.values.openingConfirmationChannelId).toBeNull()
- })
-
- it('sends a forwarding challenge and refreshes until the channel is active', async () => {
- jest.useFakeTimers()
- getSpy
- .mockResolvedValueOnce({ configs: [channel] })
- .mockResolvedValueOnce({ configs: [channel] })
- .mockResolvedValueOnce({
- configs: [
- {
- ...channel,
- connection_status: 'active',
- setup_expires_at: null,
- confirmation_available: false,
- },
- ],
- })
- createSpy.mockResolvedValue({ ok: true })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
-
- logic.actions.verifyForwarding(channel.id)
- await expectLogic(logic).toFinishAllListeners()
-
- expect(createSpy).toHaveBeenCalledWith('api/conversations/v1/email/verify-forwarding', {
- config_id: channel.id,
- })
- expect(logic.values.verifyingChannelId).toBeNull()
- expect(logic.values.verificationAwaitingChannelIds).toEqual([channel.id])
- expect(logic.values.channels[0].connection_status).toBe('pending_confirmation')
- expect(getSpy).toHaveBeenCalledTimes(2)
-
- await jest.advanceTimersByTimeAsync(3_000)
- await expectLogic(logic).toFinishAllListeners()
-
- expect(getSpy).toHaveBeenLastCalledWith('api/conversations/v1/email/status?kind=customer_communication')
- expect(getSpy).toHaveBeenCalledTimes(3)
- expect(logic.values.channels[0].connection_status).toBe('active')
- expect(logic.values.verificationAwaitingChannelIds).toEqual([])
- })
-
- it('does not overlap status refreshes', async () => {
- let runPoll = (): void => {}
- jest.spyOn(window, 'setInterval').mockImplementation((handler: TimerHandler): number => {
- if (typeof handler === 'function') {
- runPoll = () => handler()
- }
- return 1
- })
- getSpy.mockResolvedValue({ configs: [channel] })
- createSpy.mockResolvedValue({ ok: true })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
- logic.actions.verifyForwarding(channel.id)
- await expectLogic(logic).toFinishAllListeners()
-
- const completedRequestCount = getSpy.mock.calls.length
- let resolveRefresh!: (value: { configs: CustomerEmailChannel[] }) => void
- getSpy.mockReturnValueOnce(
- new Promise<{ configs: CustomerEmailChannel[] }>((resolve) => {
- resolveRefresh = resolve
- })
- )
- logic.actions.loadChannels(false)
-
- expect(logic.values.channelsLoading).toBe(true)
- runPoll()
- expect(getSpy).toHaveBeenCalledTimes(completedRequestCount + 1)
-
- resolveRefresh({ configs: [channel] })
- await expectLogic(logic).toFinishAllListeners()
- expect(logic.values.channelsLoading).toBe(false)
- })
-
- it('resets verification loading when sending the challenge fails', async () => {
- getSpy.mockResolvedValue({ configs: [channel] })
- createSpy.mockRejectedValue(new Error('queue unavailable'))
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
-
- logic.actions.verifyForwarding(channel.id)
- await expectLogic(logic).toFinishAllListeners()
-
- expect(logic.values.verifyingChannelId).toBeNull()
- expect(logic.values.verificationAwaitingChannelIds).toEqual([])
- })
-
- it('shows retry guidance when the forwarding challenge does not return', async () => {
- jest.useFakeTimers()
- getSpy.mockResolvedValue({ configs: [channel] })
- createSpy.mockResolvedValue({ ok: true })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
-
- logic.actions.verifyForwarding(channel.id)
- await expectLogic(logic).toFinishAllListeners()
- await jest.advanceTimersByTimeAsync(33_000)
- await expectLogic(logic).toFinishAllListeners()
-
- expect(logic.values.verificationAwaitingChannelIds).toEqual([])
- expect(logic.values.verificationTimedOutChannelIds).toEqual([channel.id])
- })
-
- it('connects and disconnects the current user email', async () => {
- createSpy.mockResolvedValueOnce({ config: channel }).mockResolvedValueOnce({ ok: true })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
-
- expect(logic.values.addEmailFormVisible).toBe(false)
- logic.actions.setAddEmailFormVisible(true)
- logic.actions.setEmailDraft(' [email protected] ')
- logic.actions.connectEmail()
- await expectLogic(logic).toFinishAllListeners()
-
- expect(createSpy).toHaveBeenNthCalledWith(1, 'api/conversations/v1/email/connect', {
- from_email: '[email protected]',
- from_name: 'Casey Manager',
- kind: 'customer_communication',
- owner_id: 7,
- })
- expect(logic.values.channels).toEqual([channel])
- expect(logic.values.emailDraft).toBe('')
- expect(logic.values.addEmailFormVisible).toBe(false)
- expect(logic.values.connecting).toBe(false)
- expect(logic.values.expandedChannelIds).toEqual([channel.id])
-
- logic.actions.disconnectEmail(channel.id)
- await expectLogic(logic).toFinishAllListeners()
-
- expect(createSpy).toHaveBeenNthCalledWith(2, 'api/conversations/v1/email/disconnect', {
- config_id: channel.id,
- })
- expect(logic.values.channels).toEqual([])
- expect(logic.values.expandedChannelIds).toEqual([])
- expect(logic.values.disconnectingChannelId).toBeNull()
- })
-})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/customerEmailConfigLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/customerEmailConfigLogic.ts
deleted file mode 100644
index 281217aaf272..000000000000
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/customerEmailConfigLogic.ts
+++ /dev/null
@@ -1,366 +0,0 @@
-import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'
-import posthog from 'posthog-js'
-
-import api from 'lib/api'
-import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { userLogic } from 'scenes/userLogic'
-
-import type { EmailConfigStatus } from 'products/conversations/frontend/scenes/settings/supportSettingsLogic'
-
-import type { UserType } from '../../../../../../frontend/src/types'
-
-export type CustomerEmailChannel = Pick<
- EmailConfigStatus,
- 'id' | 'from_email' | 'forwarding_address' | 'connection_status' | 'setup_expires_at' | 'confirmation_available'
->
-
-const FORWARDING_VERIFICATION_POLL_INTERVAL_MS = 3_000
-const FORWARDING_VERIFICATION_POLL_ATTEMPTS = 10
-
-function forwardingVerificationPollKey(channelId: string): string {
- return `forwardingVerificationPoll:${channelId}`
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface customerEmailConfigLogicValues {
- user: UserType | null // userLogic
- addEmailFormVisible: boolean
- channels: CustomerEmailChannel[]
- channelsLoadFailed: boolean
- channelsLoading: boolean
- connecting: boolean
- disconnectingChannelId: string | null
- emailDraft: string
- expandedChannelIds: string[]
- openingConfirmationChannelId: string | null
- verificationAwaitingChannelIds: string[]
- verificationTimedOutChannelIds: string[]
- verifyingChannelId: string | null
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface customerEmailConfigLogicActions {
- connectEmail: () => {
- value: true
- }
- connectEmailFailure: () => {
- value: true
- }
- connectEmailSuccess: (channel: CustomerEmailChannel) => {
- channel: CustomerEmailChannel
- }
- disconnectEmail: (channelId: string) => {
- channelId: string
- }
- disconnectEmailFailure: () => {
- value: true
- }
- disconnectEmailSuccess: (channelId: string) => {
- channelId: string
- }
- loadChannels: (showError: boolean) => {
- showError: boolean
- }
- loadChannelsFailure: () => {
- value: true
- }
- loadChannelsSuccess: (channels: CustomerEmailChannel[]) => {
- channels: CustomerEmailChannel[]
- }
- openGmailConfirmation: (channelId: string) => {
- channelId: string
- }
- openGmailConfirmationFailure: () => {
- value: true
- }
- openGmailConfirmationSuccess: () => {
- value: true
- }
- setAddEmailFormVisible: (visible: boolean) => {
- visible: boolean
- }
- setEmailDraft: (email: string) => {
- email: string
- }
- setExpandedChannelIds: (channelIds: string[]) => {
- channelIds: string[]
- }
- verificationPollingTimedOut: (channelId: string) => {
- channelId: string
- }
- verifyForwarding: (channelId: string) => {
- channelId: string
- }
- verifyForwardingFailure: () => {
- value: true
- }
- verifyForwardingSuccess: (channelId: string) => {
- channelId: string
- }
-}
-
-export type customerEmailConfigLogicType = MakeLogicType<
- customerEmailConfigLogicValues,
- customerEmailConfigLogicActions
->
-
-export const customerEmailConfigLogic = kea<customerEmailConfigLogicType>([
- path(['scenes', 'customerAnalytics', 'configuration', 'customerEmailConfigLogic']),
- connect(() => ({
- values: [userLogic, ['user']],
- })),
- actions({
- setAddEmailFormVisible: (visible: boolean) => ({ visible }),
- setEmailDraft: (email: string) => ({ email }),
- setExpandedChannelIds: (channelIds: string[]) => ({ channelIds }),
- loadChannels: (showError: boolean) => ({ showError }),
- loadChannelsSuccess: (channels: CustomerEmailChannel[]) => ({ channels }),
- loadChannelsFailure: true,
- connectEmail: true,
- connectEmailSuccess: (channel: CustomerEmailChannel) => ({ channel }),
- connectEmailFailure: true,
- openGmailConfirmation: (channelId: string) => ({ channelId }),
- openGmailConfirmationSuccess: true,
- openGmailConfirmationFailure: true,
- verifyForwarding: (channelId: string) => ({ channelId }),
- verifyForwardingSuccess: (channelId: string) => ({ channelId }),
- verifyForwardingFailure: true,
- verificationPollingTimedOut: (channelId: string) => ({ channelId }),
- disconnectEmail: (channelId: string) => ({ channelId }),
- disconnectEmailSuccess: (channelId: string) => ({ channelId }),
- disconnectEmailFailure: true,
- }),
- reducers({
- addEmailFormVisible: [
- false,
- {
- setAddEmailFormVisible: (_, { visible }) => visible,
- connectEmailSuccess: () => false,
- },
- ],
- expandedChannelIds: [
- [] as string[],
- {
- setExpandedChannelIds: (_, { channelIds }) => channelIds,
- connectEmailSuccess: (state, { channel }) => [...state, channel.id],
- disconnectEmailSuccess: (state, { channelId }) => state.filter((id) => id !== channelId),
- },
- ],
- emailDraft: [
- '',
- {
- setEmailDraft: (_, { email }) => email,
- connectEmailSuccess: () => '',
- },
- ],
- channels: [
- [] as CustomerEmailChannel[],
- {
- loadChannelsSuccess: (_, { channels }) => channels,
- connectEmailSuccess: (state, { channel }) => [...state, channel],
- disconnectEmailSuccess: (state, { channelId }) => state.filter((channel) => channel.id !== channelId),
- },
- ],
- channelsLoading: [
- true,
- {
- loadChannels: () => true,
- loadChannelsSuccess: () => false,
- loadChannelsFailure: () => false,
- },
- ],
- channelsLoadFailed: [
- false,
- {
- loadChannels: () => false,
- loadChannelsSuccess: () => false,
- loadChannelsFailure: () => true,
- },
- ],
- connecting: [
- false,
- {
- connectEmail: () => true,
- connectEmailSuccess: () => false,
- connectEmailFailure: () => false,
- },
- ],
- openingConfirmationChannelId: [
- null as string | null,
- {
- openGmailConfirmation: (_, { channelId }) => channelId,
- openGmailConfirmationSuccess: () => null,
- openGmailConfirmationFailure: () => null,
- },
- ],
- verifyingChannelId: [
- null as string | null,
- {
- verifyForwarding: (_, { channelId }) => channelId,
- verifyForwardingSuccess: () => null,
- verifyForwardingFailure: () => null,
- },
- ],
- verificationAwaitingChannelIds: [
- [] as string[],
- {
- verifyForwarding: (state, { channelId }) => state.filter((id) => id !== channelId),
- verifyForwardingSuccess: (state, { channelId }) => [...new Set([...state, channelId])],
- verificationPollingTimedOut: (state, { channelId }) => state.filter((id) => id !== channelId),
- loadChannelsSuccess: (state, { channels }) =>
- state.filter((id) =>
- channels.some(
- (channel) => channel.id === id && channel.connection_status === 'pending_confirmation'
- )
- ),
- disconnectEmailSuccess: (state, { channelId }) => state.filter((id) => id !== channelId),
- },
- ],
- verificationTimedOutChannelIds: [
- [] as string[],
- {
- verifyForwarding: (state, { channelId }) => state.filter((id) => id !== channelId),
- verificationPollingTimedOut: (state, { channelId }) => [...new Set([...state, channelId])],
- loadChannelsSuccess: (state, { channels }) =>
- state.filter((id) =>
- channels.some(
- (channel) => channel.id === id && channel.connection_status === 'pending_confirmation'
- )
- ),
- disconnectEmailSuccess: (state, { channelId }) => state.filter((id) => id !== channelId),
- },
- ],
- disconnectingChannelId: [
- null as string | null,
- {
- disconnectEmail: (_, { channelId }) => channelId,
- disconnectEmailSuccess: () => null,
- disconnectEmailFailure: () => null,
- },
- ],
- }),
- listeners(({ actions, cache, values }) => ({
- loadChannels: async ({ showError }) => {
- try {
- // nosemgrep: prefer-codegen-api
- const response = await api.get('api/conversations/v1/email/status?kind=customer_communication')
- actions.loadChannelsSuccess(response.configs ?? [])
- } catch (error) {
- posthog.captureException(error as Error, { scope: 'customerEmailConfigLogic.loadChannels' })
- actions.loadChannelsFailure()
- if (showError) {
- lemonToast.error('Could not refresh your connected emails. Try again.')
- }
- }
- },
- loadChannelsSuccess: ({ channels }) => {
- for (const channel of channels) {
- if (channel.connection_status !== 'pending_confirmation') {
- cache.disposables.dispose(forwardingVerificationPollKey(channel.id))
- }
- }
- },
- connectEmail: async () => {
- const email = values.emailDraft.trim().toLowerCase()
- if (!email || !values.user) {
- actions.connectEmailFailure()
- return
- }
- const displayName =
- [values.user.first_name, values.user.last_name].filter(Boolean).join(' ').trim() || values.user.email
- try {
- // nosemgrep: prefer-codegen-api
- const response = await api.create('api/conversations/v1/email/connect', {
- from_email: email,
- from_name: displayName,
- kind: 'customer_communication',
- owner_id: values.user.id,
- })
- actions.connectEmailSuccess(response.config)
- lemonToast.success('Forwarding setup started')
- } catch (error) {
- posthog.captureException(error as Error, { scope: 'customerEmailConfigLogic.connectEmail' })
- actions.connectEmailFailure()
- lemonToast.error('Could not connect this email. Check the address and try again.')
- }
- },
- openGmailConfirmation: async ({ channelId }) => {
- const confirmationWindow = window.open('about:blank', '_blank')
- try {
- // nosemgrep: prefer-codegen-api
- const response = await api.create('api/conversations/v1/email/confirm-forwarding', {
- config_id: channelId,
- })
- actions.openGmailConfirmationSuccess()
- if (confirmationWindow) {
- confirmationWindow.opener = null
- confirmationWindow.location.replace(response.confirmation_url)
- } else {
- window.location.assign(response.confirmation_url)
- }
- lemonToast.success('Gmail confirmation opened')
- } catch (error) {
- confirmationWindow?.close()
- posthog.captureException(error as Error, {
- scope: 'customerEmailConfigLogic.openGmailConfirmation',
- })
- actions.openGmailConfirmationFailure()
- lemonToast.error('Could not open the Gmail confirmation. Check the setup and try again.')
- }
- },
- verifyForwarding: async ({ channelId }) => {
- try {
- // nosemgrep: prefer-codegen-api
- await api.create('api/conversations/v1/email/verify-forwarding', {
- config_id: channelId,
- })
- if (cache.disposables.isDisposed) {
- return
- }
- actions.verifyForwardingSuccess(channelId)
- lemonToast.success('Verification email sent')
-
- let pollAttempts = 0
- cache.disposables.add(() => {
- const intervalId = window.setInterval(() => {
- if (values.channelsLoading) {
- return
- }
- pollAttempts += 1
- if (pollAttempts > FORWARDING_VERIFICATION_POLL_ATTEMPTS) {
- cache.disposables.dispose(forwardingVerificationPollKey(channelId))
- actions.verificationPollingTimedOut(channelId)
- return
- }
- actions.loadChannels(false)
- }, FORWARDING_VERIFICATION_POLL_INTERVAL_MS)
- return () => window.clearInterval(intervalId)
- }, forwardingVerificationPollKey(channelId))
- actions.loadChannels(false)
- } catch (error) {
- if (cache.disposables.isDisposed) {
- return
- }
- posthog.captureException(error as Error, { scope: 'customerEmailConfigLogic.verifyForwarding' })
- actions.verifyForwardingFailure()
- lemonToast.error('Could not send the verification email. Wait a moment and try again.')
- }
- },
- disconnectEmail: async ({ channelId }) => {
- try {
- // nosemgrep: prefer-codegen-api
- await api.create('api/conversations/v1/email/disconnect', { config_id: channelId })
- cache.disposables.dispose(forwardingVerificationPollKey(channelId))
- actions.disconnectEmailSuccess(channelId)
- lemonToast.success('Email disconnected')
- } catch (error) {
- posthog.captureException(error as Error, { scope: 'customerEmailConfigLogic.disconnectEmail' })
- actions.disconnectEmailFailure()
- lemonToast.error('Could not disconnect this email. Try again.')
- }
- },
- })),
- afterMount(({ actions }) => {
- actions.loadChannels(true)
- }),
-])