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(customer-analytics): add account sidebar actions (#107738)

Arthur Moreira de Deus66580b2de2d2
diff --git a/docs/internal/customer-analytics/account-sidebar.md b/docs/internal/customer-analytics/account-sidebar.md
index 1a86545408a2..e949830d50fc 100644
--- a/docs/internal/customer-analytics/account-sidebar.md
+++ b/docs/internal/customer-analytics/account-sidebar.md
@@ -18,6 +18,11 @@ Only the panel that opened the selector renders it. Saving pins updates every mo
Dragging entries changes their saved display order. The sidebar scrolls independently of
the main account content on wide account scenes.
+At the top of the sidebar, the left action opens a modal where you add the account to your event stream. If your stream isn't set up or is turned off, the modal links to the event stream settings. The back arrow on the settings page returns to the account. The right action edits the account.
+The account editor includes the name, website domain, billing ID, Slack channel ID, Salesforce ID, email domains, and known emails.
+It also includes the Stripe ID when the account already has one. The external ID remains read-only.
+Saving refreshes the account title and breadcrumb. A failed save keeps the editor open for retry.
+
Pinned rows load current values for the selected account. Missing custom values display
"Not set" and relationships without current assignees display "Unassigned". Loading and
failed requests have separate states, with retry available after a failure.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f2ef98ca708f..ad5ba9834abc 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7913,9 +7913,9 @@ snapshots:
scenes-app-customer-analytics-account-detail--narrow--light:
hash: v1.k794b7964.5a6763d49a273274f686f1517da9d2ba4af64b5be6897a9886addc04f429c209.JZ6O0iGKO-5AKZyg0XnVZ8JoOZ2-Jg4i9E746aSUm2I
scenes-app-customer-analytics-account-detail--pinned-properties--dark:
- hash: v1.k794b7964.d9fbbd997fdf7c707918d0833d027023c6ffed3c9c18d1f313f36e6527b6ec38.Zf5I4t3cPK_y2k_-g3plUN06StdKyOFMPugt6m-pze4
+ hash: v1.k794b7964.c9bf124e1b6ac61c97cc341788244e25f32b5288b5cf45664b8759d0d0c384d9.5IUvjb3RB5_uobh_9zOjsFbiPbaCNeMwKTof3CDb2FI
scenes-app-customer-analytics-account-detail--pinned-properties--light:
- hash: v1.k794b7964.6880f033be7477a6cd253d31f1ccf452e079c4a3e116ef79f97cb400e319d5ed.NjlB4SZcP9qcG4uR8zI9Z2xnsnQ_UA6lIIFUeHWXI90
+ hash: v1.k794b7964.60d428d3b31111585e14a43eda01fa1bc1c598c04fb0ba12e895204ccf0421d2.Y2AJGXAEGUlItnKmh9gv5j2I_Epcl4ehUF_fCKC1ewc
scenes-app-customer-analytics-account-detail--pinned-properties-narrow--dark:
hash: v1.k794b7964.ff9da4647c64580046ded4d93bfd5d1f5b9ddeb91afa106e89b290b1294caba3.v7FVsOduvBV8A7I35N0H0rNRbTs70559gvkezl-TZJs
scenes-app-customer-analytics-account-detail--pinned-properties-narrow--light:
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 36730529ec09..ad8e0622987b 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -1273,8 +1273,9 @@ export const productUrls = {
customerAnalyticsFeatureRequests: (requestId?: string): string =>
`/customer_analytics/feature-requests${requestId ? `/${requestId}` : ''}`,
customerAnalyticsJourneys: (): string => '/customer_analytics/journeys',
- customerAnalyticsConfiguration: (tab?: string): string =>
- `/customer_analytics/configuration${tab ? `?tab=${tab}` : ''}`,
+ customerAnalyticsConfiguration: (tab?: string, returnTo?: string): string =>
+ combineUrl('/customer_analytics/configuration', { ...(tab ? { tab } : {}), ...(returnTo ? { returnTo } : {}) })
+ .url,
customerJourneyBuilder: (): string => '/customer_analytics/journeys/new',
customerJourneyTemplates: (): string => '/customer_analytics/journeys/templates',
customerJourneyEdit: (id: string): string => `/customer_analytics/journeys/${id}/edit`,
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index 3802722fd9f5..c1b6d0964ff3 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -158,6 +158,7 @@ The keyed scene logic loads the account through `accountsRetrieve` when it mount
The scene renders the account logo in `SceneTitleSection`.
Authenticated human viewers heartbeat `accountsPresenceCreate` immediately on mount and resume, then every 30 seconds. The Redis roster and each viewer profile expire after 90 seconds, collapses tabs per user, and returns only other viewers. The Accounts list batches teammate presence for its loaded rows, excludes the current viewer, and refreshes every 30 seconds through `cache.disposables`, including immediately after a hidden tab resumes. Empty results invalidate in-flight presence requests before clearing the avatars. `AccountPresence` renders up to five initial-only avatars before the detail actions. Presence failures clear the roster without affecting account loading or capturing analytics.
`AccountSidebar` holds editable tags and the account property configuration. It sits flush with the scene's left edge and uses only a right border.
+Its top actions open the event stream configuration in `AccountEventStreamModal` on the left and the account editor on the right. The modal shows `AccountEventStreamMembership` for the current account and, when the stream is missing or turned off, `AccountEventStreamSetupBanner` with a link to the event stream settings. Settings links built from `eventStreamLogic.settingsUrl` pass the current page as `returnTo`, and the configuration scene's back arrow returns there when the path is inside customer analytics. It has no config form. It mounts both only while open, so `eventStreamLogic` loads on demand. The editor exposes the account name, website domain, billing ID, Slack channel ID, Salesforce ID, an existing Stripe ID, email domains, and known emails in one section. It cleans the email lists with the same helpers as meeting matching. The external ID stays read-only. The scene logic sends only the fields the user edited, on top of freshly loaded properties, and applies the saved account from the response. A failed save keeps the editor open. The sidebar captures when each modal opens and when an account edit saves.
Tag edits save through `accountsPartialUpdate` and update optimistically. Only the latest save can replace or reload the account.
Pinned property preferences belong to the current user and project, never to an account. `accountSidebarConfigLogic({ projectId })` owns their load, draft, cancel, reorder, and save lifecycle through generated API functions. Keep that logic keyed by project so switching projects cannot briefly expose another project's preferences.
Omitting `pinned_properties` from a PATCH leaves existing pins unchanged; an explicit empty list clears them. Personal API keys and OAuth tokens need `account:write` for PATCH. Session-authenticated viewers can still personalize their own sidebar.
diff --git a/products/customer_analytics/frontend/components/Accounts/accountEmailMatching.ts b/products/customer_analytics/frontend/components/Accounts/accountEmailMatching.ts
new file mode 100644
index 000000000000..14ea8b012a0e
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/accountEmailMatching.ts
@@ -0,0 +1,15 @@
+import { OrganizationMembershipLevel } from 'lib/constants'
+
+import type { TeamPublicType, TeamType } from '~/types'
+
+export function cleanEmails(values: string[]): string[] {
+ return Array.from(new Set(values.map((value) => value.trim().toLowerCase()).filter(Boolean)))
+}
+
+export function cleanDomains(values: string[]): string[] {
+ return cleanEmails(values.map((value) => value.trim().replace(/^@/, '')))
+}
+
+export function canEditEmailMatching(team: TeamPublicType | TeamType | null): boolean {
+ return !!team?.effective_membership_level && team.effective_membership_level >= OrganizationMembershipLevel.Admin
+}
diff --git a/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.ts
index 11c1f24c0fe8..b5866501eb70 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.ts
@@ -2,7 +2,6 @@ import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path,
import { loaders } from 'kea-loaders'
import posthog from 'posthog-js'
-import { OrganizationMembershipLevel } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
@@ -19,6 +18,7 @@ import type {
PatchedAccountApiProperties,
} from 'products/customer_analytics/frontend/generated/api.schemas'
+import { canEditEmailMatching, cleanDomains, cleanEmails } from './accountEmailMatching'
import { accountLinksLogic } from './accountLinksLogic'
import { AccountsEvents } from './constants'
@@ -38,14 +38,6 @@ export interface AccountMeetingsResult {
// The view compares against this by reference to tell "not loaded yet" from a loaded empty result.
export const NOT_LOADED: AccountMeetingsResult = { meetings: null, count: 0 }
-function cleanEmails(values: string[]): string[] {
- return Array.from(new Set(values.map((value) => value.trim().toLowerCase()).filter(Boolean)))
-}
-
-function cleanDomains(values: string[]): string[] {
- return cleanEmails(values.map((value) => value.replace(/^@/, '')))
-}
-
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface accountMeetingsLogicValues {
account: AccountApi | null // accountLinksLogic
@@ -232,9 +224,7 @@ export const accountMeetingsLogic = kea<accountMeetingsLogicType>([
selectors({
canEditMeetingMatching: [
(selectors) => [selectors.currentTeam],
- (currentTeam: TeamPublicType | TeamType | null): boolean =>
- !!currentTeam?.effective_membership_level &&
- currentTeam.effective_membership_level >= OrganizationMembershipLevel.Admin,
+ (currentTeam: TeamPublicType | TeamType | null): boolean => canEditEmailMatching(currentTeam),
],
}),
listeners(({ actions, values, props }) => ({
diff --git a/products/customer_analytics/frontend/components/Accounts/constants.ts b/products/customer_analytics/frontend/components/Accounts/constants.ts
index 493161ccf8e4..cc5a97d7814f 100644
--- a/products/customer_analytics/frontend/components/Accounts/constants.ts
+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts
@@ -70,6 +70,9 @@ export const AccountsEvents = {
MeetingsSearched: 'customer analytics account meetings searched',
MeetingAttendeeClicked: 'customer analytics account meeting attendee clicked',
GongCallOpened: 'customer analytics account gong call opened',
+ AccountEditorOpened: 'customer analytics account editor opened',
+ AccountEdited: 'customer analytics account edited',
+ EventStreamModalOpened: 'customer analytics account event stream modal opened',
EventStreamMembershipToggled: 'customer analytics account event stream toggled',
EventStreamConfigSaved: 'customer analytics event stream config saved',
EventStreamTestMessageSent: 'customer analytics event stream test message sent',
diff --git a/products/customer_analytics/frontend/components/EventStream/AccountEventStreamMembership.tsx b/products/customer_analytics/frontend/components/EventStream/AccountEventStreamMembership.tsx
new file mode 100644
index 000000000000..26856f4f53b5
--- /dev/null
+++ b/products/customer_analytics/frontend/components/EventStream/AccountEventStreamMembership.tsx
@@ -0,0 +1,48 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonSwitch } from '@posthog/lemon-ui'
+
+import { eventStreamLogic } from './eventStreamLogic'
+
+export function AccountEventStreamMembership({
+ accountId,
+ externalId,
+}: {
+ accountId: string
+ externalId: string
+}): JSX.Element {
+ const { eventStream, eventStreamLoading, eventStreamLoadFailed, membershipUpdatingIds, isAccountInStream } =
+ useValues(eventStreamLogic)
+ const { setAccountMembership } = useActions(eventStreamLogic)
+
+ const included = isAccountInStream(accountId)
+ const updating = membershipUpdatingIds.includes(accountId)
+
+ return (
+ <div className="flex flex-col gap-2 items-start">
+ <p className="mb-0 text-secondary">Stream this customer's events to your Slack channel in real time.</p>
+ <LemonSwitch
+ checked={included}
+ onChange={(checked) => setAccountMembership(accountId, checked)}
+ disabledReason={
+ eventStreamLoadFailed && !eventStreamLoading
+ ? "Couldn't load your event stream"
+ : !eventStream && !eventStreamLoading
+ ? 'Set up your event stream in settings first'
+ : eventStreamLoading || updating
+ ? 'Updating…'
+ : undefined
+ }
+ label="Include in my event stream"
+ size="small"
+ bordered
+ data-attr="account-event-stream-membership"
+ />
+ {included && !externalId ? (
+ <span className="text-xs text-secondary">
+ This account has no external ID, so its events can't be matched and won't stream.
+ </span>
+ ) : null}
+ </div>
+ )
+}
diff --git a/products/customer_analytics/frontend/components/EventStream/AccountEventStreamSetupBanner.tsx b/products/customer_analytics/frontend/components/EventStream/AccountEventStreamSetupBanner.tsx
new file mode 100644
index 000000000000..be2191648a24
--- /dev/null
+++ b/products/customer_analytics/frontend/components/EventStream/AccountEventStreamSetupBanner.tsx
@@ -0,0 +1,44 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner } from '@posthog/lemon-ui'
+
+import { eventStreamLogic } from './eventStreamLogic'
+
+export function AccountEventStreamSetupBanner(): JSX.Element | null {
+ const { eventStream, eventStreamLoading, eventStreamLoadFailed, settingsUrl } = useValues(eventStreamLogic)
+ const { loadEventStream } = useActions(eventStreamLogic)
+
+ if (eventStreamLoading || eventStream?.enabled) {
+ return null
+ }
+
+ if (eventStreamLoadFailed) {
+ return (
+ <LemonBanner
+ type="error"
+ action={{
+ children: 'Try again',
+ onClick: loadEventStream,
+ 'data-attr': 'account-event-stream-retry',
+ }}
+ >
+ Couldn't load your event stream. Try again, and if it keeps happening, contact support.
+ </LemonBanner>
+ )
+ }
+
+ return (
+ <LemonBanner
+ type="info"
+ action={{
+ children: 'Go to settings',
+ to: settingsUrl,
+ 'data-attr': 'account-event-stream-setup',
+ }}
+ >
+ {eventStream
+ ? 'Your event stream is turned off. Turn it on in settings to send events to Slack.'
+ : "You haven't set up your event stream yet. Set it up in settings to send events to Slack."}
+ </LemonBanner>
+ )
+}
diff --git a/products/customer_analytics/frontend/components/EventStream/AccountEventStreamToggle.tsx b/products/customer_analytics/frontend/components/EventStream/AccountEventStreamToggle.tsx
index 47e6db2bbaae..45ac7f7b218a 100644
--- a/products/customer_analytics/frontend/components/EventStream/AccountEventStreamToggle.tsx
+++ b/products/customer_analytics/frontend/components/EventStream/AccountEventStreamToggle.tsx
@@ -1,10 +1,9 @@
-import { useActions, useValues } from 'kea'
+import { useValues } from 'kea'
import { IconGear } from '@posthog/icons'
-import { LemonButton, LemonSwitch } from '@posthog/lemon-ui'
-
-import { urls } from 'scenes/urls'
+import { LemonButton } from '@posthog/lemon-ui'
+import { AccountEventStreamMembership } from './AccountEventStreamMembership'
import { eventStreamLogic } from './eventStreamLogic'
// Rendered as flag-gated tab content (AccountNotebooksExpansion), so eventStreamLogic
@@ -16,11 +15,7 @@ export function AccountEventStreamToggle({
accountId: string
externalId: string
}): JSX.Element {
- const { eventStream, eventStreamLoading, membershipUpdatingIds, isAccountInStream } = useValues(eventStreamLogic)
- const { setAccountMembership } = useActions(eventStreamLogic)
-
- const included = isAccountInStream(accountId)
- const updating = membershipUpdatingIds.includes(accountId)
+ const { settingsUrl } = useValues(eventStreamLogic)
return (
<div className="flex flex-col gap-2 items-start">
@@ -32,29 +27,10 @@ export function AccountEventStreamToggle({
icon={<IconGear />}
tooltip="Configure the event stream"
data-attr="configure-event-stream"
- to={urls.customerAnalyticsConfiguration('customer-analytics-event-stream')}
+ to={settingsUrl}
/>
</div>
- <p className="mb-0 text-secondary">Stream this customer's events to your Slack channel in real time.</p>
- <LemonSwitch
- checked={included}
- onChange={(checked) => setAccountMembership(accountId, checked)}
- disabledReason={
- !eventStream && !eventStreamLoading
- ? 'Set up your event stream in settings first'
- : eventStreamLoading || updating
- ? 'Updating…'
- : undefined
- }
- label="Include in my event stream"
- size="small"
- bordered
- />
- {included && !externalId ? (
- <span className="text-xs text-secondary">
- This account has no external ID, so its events can't be matched and won't stream.
- </span>
- ) : null}
+ <AccountEventStreamMembership accountId={accountId} externalId={externalId} />
</div>
)
}
diff --git a/products/customer_analytics/frontend/components/EventStream/eventStreamLogic.ts b/products/customer_analytics/frontend/components/EventStream/eventStreamLogic.ts
index cb62cba78ff4..a835e4002ff9 100644
--- a/products/customer_analytics/frontend/components/EventStream/eventStreamLogic.ts
+++ b/products/customer_analytics/frontend/components/EventStream/eventStreamLogic.ts
@@ -1,11 +1,14 @@
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
+import { router } from 'kea-router'
import posthog from 'posthog-js'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { objectsEqual } from 'lib/utils/objects'
import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
import type { IntegrationType } from '~/types'
@@ -51,6 +54,7 @@ export interface eventStreamLogicValues {
currentTeamId: number | null // teamLogic
draft: EventStreamDraft
eventStream: EventStreamApi | null
+ eventStreamLoadFailed: boolean
eventStreamLoading: boolean
hasChanges: boolean
integrations: IntegrationType[]
@@ -59,6 +63,7 @@ export interface eventStreamLogicValues {
memberCount: number
membershipUpdatingIds: string[]
selectedIntegration: IntegrationType | null
+ settingsUrl: string
slackChannelValue: string | undefined
testMessage: EventStreamTestMessageApi | null
testMessageDisabledReason: string | undefined
@@ -142,6 +147,7 @@ export interface eventStreamLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface eventStreamLogicMeta {
__keaTypeGenInternalSelectorTypes: {
+ settingsUrl: (location: { hash: string; pathname: string; search: string }) => string
hasChanges: (draft: EventStreamDraft, eventStream: EventStreamApi | null) => boolean
isAccountInStream: (eventStream: EventStreamApi | null) => (accountId: string) => boolean
isInitialLoading: (
@@ -221,6 +227,14 @@ export const eventStreamLogic = kea<eventStreamLogicType>([
saveEventStreamSuccess: (_, { eventStream }) => draftFromStream(eventStream),
},
],
+ eventStreamLoadFailed: [
+ false,
+ {
+ loadEventStream: () => false,
+ loadEventStreamSuccess: () => false,
+ loadEventStreamFailure: () => true,
+ },
+ ],
membershipUpdatingIds: [
[] as string[],
{
@@ -230,6 +244,14 @@ export const eventStreamLogic = kea<eventStreamLogicType>([
],
}),
selectors({
+ settingsUrl: [
+ () => [router.selectors.location],
+ (location: { pathname: string; search: string }): string =>
+ urls.customerAnalyticsConfiguration(
+ 'customer-analytics-event-stream',
+ removeProjectIdIfPresent(location.pathname) + location.search
+ ),
+ ],
hasChanges: [
(s) => [s.draft, s.eventStream],
(draft: EventStreamDraft, eventStream: EventStreamApi | null): boolean =>
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountEditModal.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountEditModal.tsx
new file mode 100644
index 000000000000..616b6eae0c43
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountEditModal.tsx
@@ -0,0 +1,96 @@
+import { useActions, useValues } from 'kea'
+import { Form } from 'kea-forms'
+
+import { LemonButton, LemonInput, LemonInputSelect, LemonModal } from '@posthog/lemon-ui'
+
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { canEditEmailMatching } from 'products/customer_analytics/frontend/components/Accounts/accountEmailMatching'
+
+import { ACCOUNT_ID_FIELDS, customerAnalyticsAccountSceneLogic } from './customerAnalyticsAccountSceneLogic'
+
+export function AccountEditModal(): JSX.Element {
+ const { account, accountEditorOpen, accountFormHasErrors, isAccountFormSubmitting } = useValues(
+ customerAnalyticsAccountSceneLogic
+ )
+ const { closeAccountEditor, submitAccountForm } = useActions(customerAnalyticsAccountSceneLogic)
+ const { currentTeam } = useValues(teamLogic)
+ const emailMatchingDisabledReason = canEditEmailMatching(currentTeam)
+ ? undefined
+ : 'Only project admins can edit email domains and known emails.'
+
+ return (
+ <LemonModal
+ isOpen={accountEditorOpen}
+ onClose={isAccountFormSubmitting ? undefined : closeAccountEditor}
+ title="Edit account"
+ width={600}
+ footer={
+ <>
+ <LemonButton
+ type="secondary"
+ onClick={closeAccountEditor}
+ disabledReason={isAccountFormSubmitting ? 'Saving account' : undefined}
+ >
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={submitAccountForm}
+ loading={isAccountFormSubmitting}
+ disabledReason={accountFormHasErrors ? 'Enter a valid account name' : undefined}
+ data-attr="save-account-name"
+ >
+ Save
+ </LemonButton>
+ </>
+ }
+ >
+ <Form logic={customerAnalyticsAccountSceneLogic} formKey="accountForm" enableFormOnSubmit>
+ <div className="flex flex-col gap-3">
+ <LemonField name="name" label="Name">
+ <LemonInput autoFocus fullWidth maxLength={400} />
+ </LemonField>
+ <div className="grid grid-cols-2 gap-x-4 gap-y-3">
+ {ACCOUNT_ID_FIELDS.filter(
+ (field) => field.key !== 'stripe_customer_id' || account?.properties?.stripe_customer_id
+ ).map((field) => (
+ <LemonField key={field.key} name={field.key} label={field.label}>
+ <LemonInput fullWidth placeholder={field.placeholder} />
+ </LemonField>
+ ))}
+ </div>
+ <LemonField name="email_domains" label="Email domains">
+ {({ value, onChange }) => (
+ <LemonInputSelect
+ mode="multiple"
+ allowCustomValues
+ disableFiltering
+ value={value}
+ onChange={onChange}
+ placeholder="example.com"
+ disabledReason={emailMatchingDisabledReason}
+ data-attr="account-edit-email-domains"
+ />
+ )}
+ </LemonField>
+ <LemonField name="known_emails" label="Known emails">
+ {({ value, onChange }) => (
+ <LemonInputSelect
+ mode="multiple"
+ allowCustomValues
+ disableFiltering
+ value={value}
+ onChange={onChange}
+ placeholder="[email protected]"
+ disabledReason={emailMatchingDisabledReason}
+ data-attr="account-edit-known-emails"
+ />
+ )}
+ </LemonField>
+ </div>
+ </Form>
+ </LemonModal>
+ )
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountEventStreamModal.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountEventStreamModal.tsx
new file mode 100644
index 000000000000..501b5aea5b3b
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountEventStreamModal.tsx
@@ -0,0 +1,23 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonModal } from '@posthog/lemon-ui'
+
+import { AccountEventStreamMembership } from '../../components/EventStream/AccountEventStreamMembership'
+import { AccountEventStreamSetupBanner } from '../../components/EventStream/AccountEventStreamSetupBanner'
+import { customerAnalyticsAccountSceneLogic } from './customerAnalyticsAccountSceneLogic'
+
+export function AccountEventStreamModal(): JSX.Element {
+ const { account, eventStreamModalOpen } = useValues(customerAnalyticsAccountSceneLogic)
+ const { closeEventStreamModal } = useActions(customerAnalyticsAccountSceneLogic)
+
+ return (
+ <LemonModal isOpen={eventStreamModalOpen} onClose={closeEventStreamModal} title="Event stream" width={480}>
+ {eventStreamModalOpen && account && (
+ <div className="flex flex-col gap-4">
+ <AccountEventStreamMembership accountId={account.id} externalId={account.external_id ?? ''} />
+ <AccountEventStreamSetupBanner />
+ </div>
+ )}
+ </LemonModal>
+ )
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountSidebar.test.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountSidebar.test.tsx
index 9f0889b87ef3..6c1da82241a2 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountSidebar.test.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountSidebar.test.tsx
@@ -2,9 +2,11 @@ import '@testing-library/jest-dom'
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { BindLogic } from 'kea'
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import { projectLogic } from 'scenes/projectLogic'
+import { urls } from 'scenes/urls'
import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
import { useMocks } from '~/mocks/jest'
@@ -20,25 +22,93 @@ jest.mock('lib/utils/accessControlUtils', () => ({
userHasAccess: () => true,
}))
-describe('AccountSidebar refresh recovery', () => {
+const account: AccountApi = {
+ id: 'account-1',
+ name: 'Example account',
+ notebooks: [],
+ ignored_at: null,
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: null,
+ updated_at: null,
+ tags: [],
+ properties: { stripe_customer_id: 'cus_example' },
+}
+
+describe('AccountSidebar', () => {
afterEach(() => {
cleanup()
resumeKeaLoadersErrors()
})
+ it('opens event stream setup and account editing from the sidebar actions', async () => {
+ initKeaTests()
+ router.actions.push(urls.customerAnalyticsAccount(account.id))
+ useMocks({
+ get: {
+ '/api/projects/:project_id/accounts/:account_id/': account,
+ '/api/projects/:project_id/user_customer_analytics_config/@me/': { pinned_properties: [] },
+ '/api/projects/:project_id/custom_property_definitions/': { count: 0, results: [] },
+ '/api/projects/:project_id/account_relationship_definitions/': { count: 0, results: [] },
+ '/api/projects/:project_id/event_streams/': [],
+ },
+ post: {
+ '/api/projects/:project_id/accounts/:account_id/presence/': [],
+ },
+ })
+ const { container } = render(
+ <BindLogic
+ logic={customerAnalyticsAccountSceneLogic}
+ props={{ accountId: account.id, projectId: projectLogic.values.currentProjectId! }}
+ >
+ <AccountSidebar account={account} />
+ </BindLogic>
+ )
+ await act(async () => {
+ await expectLogic(
+ customerAnalyticsAccountSceneLogic({
+ accountId: account.id,
+ projectId: projectLogic.values.currentProjectId!,
+ })
+ ).toFinishAllListeners()
+ })
+
+ const actions = container.querySelectorAll(
+ '[data-attr="account-sidebar-event-stream"], [data-attr="account-sidebar-edit"]'
+ )
+ expect(actions).toHaveLength(2)
+ expect(actions[0]).not.toHaveAttribute('href')
+ fireEvent.click(actions[0])
+ expect(await screen.findByText("You haven't set up your event stream yet.", { exact: false })).toBeVisible()
+ expect(screen.getByText('Include in my event stream')).toBeVisible()
+ expect(screen.queryByText('Events to stream')).not.toBeInTheDocument()
+ expect(document.querySelectorAll('[data-attr="account-event-stream-setup"]')[0]).toHaveAttribute(
+ 'href',
+ expect.stringContaining(
+ urls.customerAnalyticsConfiguration(
+ 'customer-analytics-event-stream',
+ urls.customerAnalyticsAccount(account.id)
+ )
+ )
+ )
+ fireEvent.click(screen.getByLabelText('close'))
+ expect(actions[1]).toHaveAttribute('aria-label', 'Edit account')
+ fireEvent.click(actions[1])
+ expect(screen.getByDisplayValue(account.name)).toBeVisible()
+ expect(screen.getByText('Website domain')).toBeVisible()
+ expect(screen.getByText('Billing ID')).toBeVisible()
+ expect(screen.getByText('Slack channel ID')).toBeVisible()
+ expect(screen.getByText('Salesforce ID')).toBeVisible()
+ expect(screen.getByText('Stripe ID')).toBeVisible()
+ expect(screen.getByText('Email domains')).toBeVisible()
+ expect(screen.getByText('Known emails')).toBeVisible()
+ expect(screen.queryByText('External ID')).not.toBeInTheDocument()
+ expect(screen.queryByText('Usage dashboard link')).not.toBeInTheDocument()
+ expect(screen.queryByText('Metabase link')).not.toBeInTheDocument()
+ })
+
it('keeps the typed draft mounted when a refresh fails', async () => {
initKeaTests()
silenceKeaLoadersErrors()
- const account: AccountApi = {
- id: 'account-1',
- name: 'Example account',
- notebooks: [],
- ignored_at: null,
- created_at: '2026-01-01T00:00:00Z',
- created_by: null,
- updated_at: null,
- tags: [],
- }
const definition: CustomPropertyDefinitionApi = {
id: 'property-1',
name: 'Plan',
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountSidebar.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountSidebar.tsx
index f3eb7f671426..1aa2e8a402f5 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountSidebar.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountSidebar.tsx
@@ -1,18 +1,21 @@
import { useActions, useValues } from 'kea'
-import { LemonDivider } from '@posthog/lemon-ui'
+import { IconLive, IconPencil } from '@posthog/icons'
+import { LemonButton, LemonDivider } from '@posthog/lemon-ui'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { tagsModel } from '~/models/tagsModel'
import type { AccountApi } from '../../generated/api.schemas'
+import { AccountEditModal } from './AccountEditModal'
+import { AccountEventStreamModal } from './AccountEventStreamModal'
import { AccountPinnedPropertiesPanel } from './components/AccountPinnedPropertiesPanel'
import { customerAnalyticsAccountSceneLogic } from './customerAnalyticsAccountSceneLogic'
export function AccountSidebar({ account }: { account: AccountApi }): JSX.Element {
const { tagsSaving } = useValues(customerAnalyticsAccountSceneLogic)
- const { updateTags } = useActions(customerAnalyticsAccountSceneLogic)
+ const { updateTags, openAccountEditor, openEventStreamModal } = useActions(customerAnalyticsAccountSceneLogic)
const { tags: tagsAvailable, tagsLoading } = useValues(tagsModel)
const { loadTagsIfNeeded } = useActions(tagsModel)
@@ -21,6 +24,27 @@ export function AccountSidebar({ account }: { account: AccountApi }): JSX.Elemen
className="w-full shrink-0 @max-[60rem]:border @max-[60rem]:rounded border-r rounded-r bg-surface-primary flex flex-col @min-[60rem]/account-detail:h-full @min-[60rem]/account-detail:min-h-0 @min-[60rem]/account-detail:w-60 @min-[60rem]/account-detail:overflow-y-auto"
data-attr="account-sidebar"
>
+ <div className="flex justify-center gap-2 p-2">
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconLive />}
+ tooltip="Set up event stream"
+ aria-label="Set up event stream"
+ data-attr="account-sidebar-event-stream"
+ onClick={openEventStreamModal}
+ />
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconPencil />}
+ tooltip="Edit account"
+ aria-label="Edit account"
+ data-attr="account-sidebar-edit"
+ onClick={openAccountEditor}
+ />
+ </div>
+ <LemonDivider className="my-0" />
<div className="flex flex-col gap-1 p-4" data-attr="account-rail-tags">
<span className="secondary text-secondary">Tags</span>
<ObjectTags
@@ -34,6 +58,8 @@ export function AccountSidebar({ account }: { account: AccountApi }): JSX.Elemen
</div>
<LemonDivider className="my-0" />
<AccountPinnedPropertiesPanel accountId={account.id} />
+ <AccountEditModal />
+ <AccountEventStreamModal />
</aside>
)
}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts
index a5884972ca34..a1064c23e9a0 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts
@@ -275,6 +275,100 @@ describe('customerAnalyticsAccountSceneLogic', () => {
expect(logic.values.account).toEqual(account)
})
+ describe('account editor', () => {
+ beforeEach(async () => {
+ mockAccountsRetrieve.mockResolvedValue(account)
+ mountLogic()
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ it('saves only edited fields without replacing concurrent or unrelated properties', async () => {
+ const currentAccount = {
+ ...account,
+ properties: {
+ hubspot_deal_id: 'deal-1',
+ usage_dashboard_link: 'https://example.com/usage',
+ metabase_link: 'https://example.com/metabase',
+ stripe_customer_id: 'stripe-old',
+ sfdc_id: 'salesforce-concurrent',
+ billing_id: 'billing-concurrent',
+ known_emails: ['[email protected]'],
+ },
+ }
+ const updatedAccount = {
+ ...currentAccount,
+ name: 'Renamed account',
+ }
+ mockAccountsRetrieve.mockResolvedValueOnce(currentAccount)
+ mockAccountsPartialUpdate.mockResolvedValue(updatedAccount)
+
+ logic.actions.openAccountEditor()
+ expect(logic.values.accountForm.name).toBe(account.name)
+ logic.actions.loadAccountSuccess(currentAccount)
+ logic.actions.setAccountFormValues({
+ name: ' Renamed account ',
+ website_domain: 'example.com',
+ billing_id: '',
+ slack_channel_id: 'C123',
+ sfdc_id: '',
+ stripe_customer_id: 'stripe-new',
+ email_domains: [' @Example.com', 'example.com'],
+ known_emails: [],
+ })
+ logic.actions.submitAccountForm()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockAccountsPartialUpdate).toHaveBeenCalledWith(String(PROJECT_ID), ACCOUNT_ID, {
+ name: 'Renamed account',
+ properties: {
+ hubspot_deal_id: 'deal-1',
+ usage_dashboard_link: 'https://example.com/usage',
+ metabase_link: 'https://example.com/metabase',
+ stripe_customer_id: 'stripe-new',
+ website_domain: 'example.com',
+ billing_id: 'billing-concurrent',
+ slack_channel_id: 'C123',
+ sfdc_id: 'salesforce-concurrent',
+ known_emails: ['[email protected]'],
+ email_domains: ['example.com'],
+ },
+ })
+ expect(logic.values.accountEditorOpen).toBe(false)
+ expect(logic.values.breadcrumbs.at(-1)?.name).toBe('Renamed account')
+ })
+
+ it('leaves untouched email lists alone when stored values are not normalized', async () => {
+ const storedAccount = { ...account, properties: { known_emails: ['[email protected]'] } }
+ logic.actions.loadAccountSuccess(storedAccount)
+ mockAccountsRetrieve.mockResolvedValueOnce(storedAccount)
+ mockAccountsPartialUpdate.mockResolvedValue(storedAccount)
+
+ logic.actions.openAccountEditor()
+ logic.actions.setAccountFormValue('name', 'Renamed account')
+ logic.actions.submitAccountForm()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockAccountsPartialUpdate).toHaveBeenCalledWith(String(PROJECT_ID), ACCOUNT_ID, {
+ name: 'Renamed account',
+ properties: { known_emails: ['[email protected]'] },
+ })
+ })
+
+ it('keeps the draft open when the save fails', async () => {
+ mockAccountsPartialUpdate.mockRejectedValue(new ApiError('Unavailable', 500))
+ jest.spyOn(posthog, 'captureException').mockImplementation()
+
+ logic.actions.openAccountEditor()
+ logic.actions.setAccountFormValue('name', 'Draft account')
+ logic.actions.submitAccountForm()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.accountEditorOpen).toBe(true)
+ expect(logic.values.accountForm.name).toBe('Draft account')
+ expect(logic.values.account?.name).toBe(account.name)
+ })
+ })
+
describe('tag updates', () => {
beforeEach(async () => {
mockAccountsRetrieve.mockResolvedValue(account)
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts
index d231c4801107..40dea2b45468 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts
@@ -12,6 +12,8 @@ import {
reducers,
selectors,
} from 'kea'
+import { forms } from 'kea-forms'
+import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { actionToUrl, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'
@@ -19,12 +21,17 @@ import { ApiError } from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic, FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
+import { objectsEqual } from 'lib/utils/objects'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
import { tagsModel } from '~/models/tagsModel'
import { Breadcrumb } from '~/types'
+import {
+ cleanDomains,
+ cleanEmails,
+} from 'products/customer_analytics/frontend/components/Accounts/accountEmailMatching'
import {
AccountExpansionTab,
DEFAULT_ACCOUNT_TAB,
@@ -37,12 +44,47 @@ import {
accountsPresenceCreate,
accountsRetrieve,
} from 'products/customer_analytics/frontend/generated/api'
-import type { AccountApi, AccountPresenceViewerApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+import type {
+ AccountApi,
+ AccountPresenceViewerApi,
+ PatchedAccountApiProperties,
+} from 'products/customer_analytics/frontend/generated/api.schemas'
import { EXTERNAL_ACCOUNT_ROUTE_PATTERN, parseExternalAccountPath } from './customerAnalyticsAccountSceneUtils'
const ACCOUNT_PRESENCE_POLL_INTERVAL_MS = 30_000
+export const ACCOUNT_ID_FIELDS = [
+ { key: 'website_domain', label: 'Website domain', placeholder: 'example.com' },
+ { key: 'billing_id', label: 'Billing ID', placeholder: 'e.g. cus_acme_123' },
+ { key: 'slack_channel_id', label: 'Slack channel ID', placeholder: 'e.g. C0123456789' },
+ { key: 'sfdc_id', label: 'Salesforce ID', placeholder: 'e.g. 0011t00000AbCdEfGhI' },
+ { key: 'stripe_customer_id', label: 'Stripe ID', placeholder: 'e.g. cus_acme_123' },
+] as const
+
+type AccountIdFieldKey = (typeof ACCOUNT_ID_FIELDS)[number]['key']
+
+export type AccountEditFormValues = Record<AccountIdFieldKey, string> & {
+ name: string
+ email_domains: string[]
+ known_emails: string[]
+}
+
+function getAccountEditFormValues(account: AccountApi | null): AccountEditFormValues {
+ return {
+ name: account?.name ?? '',
+ website_domain: account?.properties?.website_domain ?? '',
+ billing_id: account?.properties?.billing_id ?? '',
+ slack_channel_id: account?.properties?.slack_channel_id ?? '',
+ sfdc_id: account?.properties?.sfdc_id ?? '',
+ stripe_customer_id: account?.properties?.stripe_customer_id ?? '',
+ email_domains: account?.properties?.email_domains ?? [],
+ known_emails: account?.properties?.known_emails ?? [],
+ }
+}
+
+const EMPTY_ACCOUNT_EDIT_FORM = getAccountEditFormValues(null)
+
export interface CustomerAnalyticsAccountSceneLogicProps {
accountId?: string
externalId?: string
@@ -65,14 +107,29 @@ export interface customerAnalyticsAccountSceneLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
receivedFeatureFlags: boolean // featureFlagLogic
account: AccountApi | null
+ accountEditorOpen: boolean
+ accountEditorOpenedValues: AccountEditFormValues
+ accountForm: AccountEditFormValues
+ accountFormAllErrors: Record<string, any>
+ accountFormChanged: boolean
+ accountFormErrors: DeepPartialMap<AccountEditFormValues, ValidationErrorType>
+ accountFormHasErrors: boolean
+ accountFormManualErrors: Record<string, any>
+ accountFormTouched: boolean
+ accountFormTouches: Record<string, boolean>
+ accountFormValidationErrors: DeepPartialMap<AccountEditFormValues, ValidationErrorType>
accountLoadError: unknown
accountLoading: boolean
accountPresenceError: unknown
accountPresenceViewers: AccountPresenceViewerApi[]
activeTab: AccountExpansionTab
breadcrumbs: Breadcrumb[]
+ eventStreamModalOpen: boolean
+ isAccountFormSubmitting: boolean
+ isAccountFormValid: boolean
isAccountMissing: boolean
requestedTab: string
+ showAccountFormErrors: boolean
tagsSaving: boolean
}
@@ -85,6 +142,12 @@ export interface customerAnalyticsAccountSceneLogicActions {
flags: string[]
variants: Record<string, boolean | string>
} // featureFlagLogic
+ closeAccountEditor: () => {
+ value: true
+ }
+ closeEventStreamModal: () => {
+ value: true
+ }
loadAccount: () => {
value: true
}
@@ -103,15 +166,56 @@ export interface customerAnalyticsAccountSceneLogicActions {
loadAccountSuccess: (account: AccountApi) => {
account: AccountApi
}
+ openAccountEditor: () => {
+ value: true
+ }
+ openEventStreamModal: () => {
+ value: true
+ }
+ resetAccountForm: (values?: AccountEditFormValues) => {
+ values?: AccountEditFormValues
+ }
restoreActiveTab: (tab: string | undefined) => {
tab: string
}
+ setAccountFormManualErrors: (errors: Record<string, any>) => {
+ errors: Record<string, any>
+ }
+ setAccountFormValue: (
+ key: FieldName,
+ value: any
+ ) => {
+ name: FieldName
+ value: any
+ }
+ setAccountFormValues: (values: DeepPartial<AccountEditFormValues>) => {
+ values: DeepPartial<AccountEditFormValues>
+ }
setActiveTab: (tab: AccountExpansionTab) => {
tab: AccountExpansionTab
}
startAccountPresencePolling: (accountId: string) => {
accountId: string
}
+ submitAccountForm: () => {
+ value: boolean
+ }
+ submitAccountFormFailure: (
+ error: Error,
+ errors: Record<string, any>
+ ) => {
+ error: Error
+ errors: Record<string, any>
+ }
+ submitAccountFormRequest: (accountForm: AccountEditFormValues) => {
+ accountForm: AccountEditFormValues
+ }
+ submitAccountFormSuccess: (accountForm: AccountEditFormValues) => {
+ accountForm: AccountEditFormValues
+ }
+ touchAccountFormField: (key: string) => {
+ key: string
+ }
updateTags: (tags: string[]) => {
tags: string[]
}
@@ -173,7 +277,63 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
restoreActiveTab: (tab: string | undefined) => ({ tab: tab ?? DEFAULT_ACCOUNT_TAB }),
updateTags: (tags: string[]) => ({ tags }),
updateTagsDone: (account: AccountApi | null) => ({ account }),
+ openAccountEditor: true,
+ closeAccountEditor: true,
+ openEventStreamModal: true,
+ closeEventStreamModal: true,
}),
+ forms(({ actions, props, values }) => ({
+ accountForm: {
+ defaults: EMPTY_ACCOUNT_EDIT_FORM,
+ errors: ({ name }: AccountEditFormValues) => ({
+ name: !name.trim()
+ ? 'Enter an account name'
+ : name.length > 400
+ ? 'Use 400 characters or fewer'
+ : undefined,
+ }),
+ submit: async (formValues: AccountEditFormValues) => {
+ if (!props.projectId || !values.account) {
+ throw new Error('Could not determine the current project or account.')
+ }
+ const projectId = String(props.projectId)
+ const openedValues = values.accountEditorOpenedValues
+ const changedPropertyKeys = ACCOUNT_ID_FIELDS.map(({ key }) => key).filter(
+ (key) => formValues[key] !== openedValues[key]
+ )
+ const name = formValues.name.trim()
+ const currentAccount = await accountsRetrieve(projectId, values.account.id)
+ // Sending only edited fields keeps concurrent edits to the other fields.
+ const listCleaners = { email_domains: cleanDomains, known_emails: cleanEmails }
+ const cleanedLists = {
+ email_domains: cleanDomains(formValues.email_domains),
+ known_emails: cleanEmails(formValues.known_emails),
+ }
+ const changedListKeys = (['email_domains', 'known_emails'] as const).filter(
+ (key) => !objectsEqual(cleanedLists[key], listCleaners[key](openedValues[key]))
+ )
+ const changedProperties = {
+ ...Object.fromEntries(
+ changedPropertyKeys
+ .filter(
+ (key) => key !== 'stripe_customer_id' || currentAccount.properties?.stripe_customer_id
+ )
+ .map((key) => [key, formValues[key].trim() || null])
+ ),
+ ...Object.fromEntries(changedListKeys.map((key) => [key, cleanedLists[key]])),
+ }
+ const updatedAccount = await accountsPartialUpdate(projectId, values.account.id, {
+ ...(name !== openedValues.name ? { name } : {}),
+ properties: { ...currentAccount.properties, ...changedProperties } as PatchedAccountApiProperties,
+ })
+ actions.loadAccountSuccess(updatedAccount)
+ posthog.capture(AccountsEvents.AccountEdited, {
+ name_changed: name !== openedValues.name,
+ changed_fields: [...changedPropertyKeys, ...changedListKeys],
+ })
+ },
+ },
+ })),
reducers({
account: [
null as AccountApi | null,
@@ -228,6 +388,12 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
updateTagsDone: () => false,
},
],
+ accountEditorOpen: [false, { openAccountEditor: () => true, closeAccountEditor: () => false }],
+ accountEditorOpenedValues: [
+ EMPTY_ACCOUNT_EDIT_FORM,
+ { resetAccountForm: (_, { values }) => values ?? EMPTY_ACCOUNT_EDIT_FORM },
+ ],
+ eventStreamModalOpen: [false, { openEventStreamModal: () => true, closeEventStreamModal: () => false }],
}),
selectors({
activeTab: [
@@ -262,6 +428,22 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
],
}),
listeners(({ actions, cache, props, values }) => ({
+ openAccountEditor: () => {
+ actions.resetAccountForm(getAccountEditFormValues(values.account))
+ posthog.capture(AccountsEvents.AccountEditorOpened)
+ },
+ openEventStreamModal: () => {
+ posthog.capture(AccountsEvents.EventStreamModalOpened)
+ },
+ submitAccountFormSuccess: () => {
+ actions.closeAccountEditor()
+ },
+ submitAccountFormFailure: ({ error }) => {
+ lemonToast.error("Couldn't save the account. Try again.")
+ posthog.captureException(error instanceof Error ? error : new Error('Could not update account'), {
+ scope: 'customerAnalyticsAccountSceneLogic.submitAccountForm',
+ })
+ },
setFeatureFlags: (_, __, ___, previousState) => {
const previousFeatureFlags = featureFlagLogic.selectors.featureFlags(previousState)
const previouslyReceivedFlags = featureFlagLogic.selectors.receivedFeatureFlags(previousState)
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/CustomerAnalyticsConfigurationScene.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/CustomerAnalyticsConfigurationScene.tsx
index b4e7a00403f4..76d7a78172f1 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/CustomerAnalyticsConfigurationScene.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/CustomerAnalyticsConfigurationScene.tsx
@@ -1,3 +1,5 @@
+import { useValues } from 'kea'
+
import { SceneExport } from 'scenes/sceneTypes'
import { Settings } from 'scenes/settings/Settings'
@@ -15,10 +17,12 @@ export const scene: SceneExport = {
}
export function CustomerAnalyticsConfigurationScene(): JSX.Element {
+ const { backTarget } = useValues(customerAnalyticsConfigurationSceneLogic)
+
return (
<FeaturePreviewSceneGate config={customerAnalyticsFeaturePreviewGate}>
<div className="mb-2 -ml-[var(--button-padding-x-lg)]">
- <SceneBreadcrumbBackButton />
+ <SceneBreadcrumbBackButton forceBackTo={backTarget ?? undefined} />
</div>
<Settings
logicKey={CUSTOMER_ANALYTICS_LOGIC_KEY}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneLogic.ts
index ea1831d57e1e..57f715ee1e1b 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneLogic.ts
@@ -9,6 +9,7 @@ import { Breadcrumb } from '~/types'
import type { SettingId } from '../../../../../frontend/src/scenes/settings/types'
import { CUSTOMER_ANALYTICS_LOGIC_KEY } from '../../utils'
+import { getConfigurationBackTarget } from './customerAnalyticsConfigurationSceneUtils'
export type ConfigurationSceneTabType =
| 'group-analytics'
@@ -24,6 +25,7 @@ export interface CustomerAnalyticsConfigurationSceneLogicProps {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface customerAnalyticsConfigurationSceneLogicValues {
+ backTarget: Breadcrumb | null
breadcrumbs: Breadcrumb[]
tab: ConfigurationSceneTabType
}
@@ -41,6 +43,7 @@ export interface customerAnalyticsConfigurationSceneLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface customerAnalyticsConfigurationSceneLogicMeta {
__keaTypeGenInternalSelectorTypes: {
+ backTarget: (searchParams: Record<string, any>) => Breadcrumb | null
breadcrumbs: (tab: ConfigurationSceneTabType) => Breadcrumb[]
}
}
@@ -81,6 +84,10 @@ export const customerAnalyticsConfigurationSceneLogic = kea<customerAnalyticsCon
})),
selectors({
+ backTarget: [
+ () => [router.selectors.searchParams],
+ (searchParams: Record<string, any>): Breadcrumb | null => getConfigurationBackTarget(searchParams.returnTo),
+ ],
breadcrumbs: [
(s) => [s.tab],
(tab: ConfigurationSceneTabType): Breadcrumb[] => [
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneUtils.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneUtils.test.ts
new file mode 100644
index 000000000000..102211cac0f0
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneUtils.test.ts
@@ -0,0 +1,17 @@
+import { getConfigurationBackTarget } from './customerAnalyticsConfigurationSceneUtils'
+
+describe('getConfigurationBackTarget', () => {
+ test.each([
+ ['/customer_analytics/accounts/account-1?tab=notes', 'Account'],
+ ['/customer_analytics/dashboard', 'Customer analytics'],
+ ])('returns to %s', (returnTo, name) => {
+ expect(getConfigurationBackTarget(returnTo)).toMatchObject({ path: returnTo, name })
+ })
+
+ test.each([undefined, '', '/settings/project', 'https://example.com/customer_analytics/', '//example.com'])(
+ 'falls back to the breadcrumb for %p',
+ (returnTo) => {
+ expect(getConfigurationBackTarget(returnTo)).toBeNull()
+ }
+ )
+})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneUtils.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneUtils.ts
new file mode 100644
index 000000000000..00a53f7c43f5
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneUtils.ts
@@ -0,0 +1,18 @@
+import { Scene } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
+
+import { Breadcrumb } from '~/types'
+
+// Only paths inside customer analytics are accepted, so a crafted link can't send the back arrow to another site.
+export function getConfigurationBackTarget(returnTo: unknown): Breadcrumb | null {
+ if (typeof returnTo !== 'string' || !returnTo.startsWith(`${urls.customerAnalytics()}/`)) {
+ return null
+ }
+ const isAccountDetail = returnTo.startsWith(`${urls.customerAnalyticsAccounts()}/`)
+ return {
+ key: isAccountDetail ? Scene.CustomerAnalyticsAccount : Scene.CustomerAnalytics,
+ name: isAccountDetail ? 'Account' : 'Customer analytics',
+ path: returnTo,
+ iconType: 'cohort',
+ }
+}
diff --git a/products/customer_analytics/manifest.tsx b/products/customer_analytics/manifest.tsx
index e6bcafad22b3..f20aadc7592d 100644
--- a/products/customer_analytics/manifest.tsx
+++ b/products/customer_analytics/manifest.tsx
@@ -113,8 +113,11 @@ export const manifest: ProductManifest = {
customerAnalyticsFeatureRequests: (requestId?: string): string =>
`/customer_analytics/feature-requests${requestId ? `/${requestId}` : ''}`,
customerAnalyticsJourneys: (): string => '/customer_analytics/journeys',
- customerAnalyticsConfiguration: (tab?: string): string =>
- `/customer_analytics/configuration${tab ? `?tab=${tab}` : ''}`,
+ customerAnalyticsConfiguration: (tab?: string, returnTo?: string): string =>
+ combineUrl('/customer_analytics/configuration', {
+ ...(tab ? { tab } : {}),
+ ...(returnTo ? { returnTo } : {}),
+ }).url,
customerJourneyBuilder: (): string => '/customer_analytics/journeys/new',
customerJourneyTemplates: (): string => '/customer_analytics/journeys/templates',
customerJourneyEdit: (id: string): string => `/customer_analytics/journeys/${id}/edit`,