Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(crm): optional backfill on enable, customer empty states (#4778)

Evan Hutnik9caf5ea6a095
diff --git a/apps/web/src/components/app/app-sidebar/sidebar.tsx b/apps/web/src/components/app/app-sidebar/sidebar.tsx
index a346c25e46..de9d3fd396 100644
--- a/apps/web/src/components/app/app-sidebar/sidebar.tsx
+++ b/apps/web/src/components/app/app-sidebar/sidebar.tsx
@@ -232,18 +232,6 @@ const SIDEBAR_LINKS = [
hotkey: 'c',
hotkeyToken: TOKENS.sidebar.goTo.channels,
},
- ...(ENABLE_CRM
- ? ([
- {
- id: 'companies',
- label: 'Companies',
- href: LIST_VIEW_PATHS.companies,
- icon: AnimatedCompanyIcon,
- hotkey: 'o',
- hotkeyToken: TOKENS.sidebar.goTo.companies,
- },
- ] satisfies SidebarItem[])
- : []),
] satisfies SidebarItem[];
export type SidebarState = 'hidden' | 'expanded' | 'slim';
@@ -925,6 +913,15 @@ const CALLS_LINK: SidebarItem = {
hotkeyToken: TOKENS.sidebar.goTo.calls,
};
+const COMPANIES_LINK: SidebarItem = {
+ id: 'companies',
+ label: 'Customers',
+ href: LIST_VIEW_PATHS.companies,
+ icon: AnimatedCompanyIcon,
+ hotkey: 'o',
+ hotkeyToken: TOKENS.sidebar.goTo.companies,
+};
+
const DASHBOARD_LINK: SidebarItem = {
id: 'home',
label: 'Home',
@@ -936,12 +933,12 @@ const DASHBOARD_LINK: SidebarItem = {
/**
* Assemble the ordered sidebar link list: the static links plus Home and the
- * flag-gated Calls entry in their correct positions. Shared by the rendered
- * sidebar (`AppSidebar.visibleLinks`) and the always-mounted `GoToHotkeys`
- * registrar so their link sets can't drift. Call from a reactive context — it
- * reads `ENABLE_CALLS()`. Rendered sections additionally drop
- * `hiddenFromSidebar`
- * entries, which have hotkeys but no sidebar row.
+ * flag-gated Calls and CRM entries in their correct positions. Shared by the
+ * rendered sidebar (`AppSidebar.visibleLinks`) and the always-mounted
+ * `GoToHotkeys` registrar so their link sets can't drift. Call from a reactive
+ * context — it reads `ENABLE_CALLS()` / `ENABLE_CRM()`. Rendered sections
+ * additionally drop `hiddenFromSidebar` entries, which have hotkeys but no
+ * sidebar row.
*/
const buildSidebarLinks = (): SidebarItem[] => {
let links: SidebarItem[] = [DASHBOARD_LINK, ...SIDEBAR_LINKS];
@@ -951,6 +948,17 @@ const buildSidebarLinks = (): SidebarItem[] => {
links = [...links.slice(0, idx + 1), CALLS_LINK, ...links.slice(idx + 1)];
}
+ if (ENABLE_CRM()) {
+ // Customers sits just after Channels (and Calls when present).
+ const anchorId = ENABLE_CALLS() ? 'calls' : 'channels';
+ const idx = links.findIndex((l) => l.id === anchorId);
+ links = [
+ ...links.slice(0, idx + 1),
+ COMPANIES_LINK,
+ ...links.slice(idx + 1),
+ ];
+ }
+
return links;
};
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsx
index 019f827189..fcfbedf083 100644
--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx
+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx
@@ -280,7 +280,7 @@ registerComponent(
withAuth(() => {
// Registered even when the CRM feature is off so direct navigation /
// restored splits redirect instead of throwing in resolveComponent.
- if (!ENABLE_CRM) {
+ if (!ENABLE_CRM()) {
return <RedirectSplit to={{ type: 'component', id: 'inbox' }} />;
}
usePageViewTracking('companies');
diff --git a/apps/web/src/features/next-soup/soup-view/empty-states.tsx b/apps/web/src/features/next-soup/soup-view/empty-states.tsx
index eec5fb4696..ce9b8791a5 100644
--- a/apps/web/src/features/next-soup/soup-view/empty-states.tsx
+++ b/apps/web/src/features/next-soup/soup-view/empty-states.tsx
@@ -2,6 +2,7 @@ import { DOCS_BASE } from '@app/constants/docs-links';
import type { ListView } from '@app/constants/list-views';
import { runCreateAction } from '@app/features/command/Launcher';
import type { BlockAlias, BlockName } from '@core/block';
+import { useSettingsState } from '@core/constant/SettingsState';
import { useAddInboxFlow, useEmailLinksStatus } from '@core/email-link';
import EmptyStateAiGraphic from '@design/empty-state-ai.svg';
import EmptyStateAutomationsGraphic from '@design/empty-state-automations.svg';
@@ -17,8 +18,9 @@ import EmptyStateNoFilterMatchGraphic from '@design/empty-state-no-filter-match.
import EmptyStateNoSearchMatchGraphic from '@design/empty-state-no-search-match.svg';
import EmptyStateTasksGraphic from '@design/empty-state-tasks.svg';
import PlusIcon from '@phosphor/plus.svg';
+import { useCurrentTeamQuery, useIsTeamAdmin } from '@queries/team/teams';
import { EmptyStatePanel, FilteredHiddenBanner } from '@ui';
-import { type Component, type JSXElement, Match, Switch } from 'solid-js';
+import { type Component, type JSXElement, Match, Show, Switch } from 'solid-js';
import { FolderDropZone } from './FolderDropZone';
import { useSoupView } from './soup-view-context';
@@ -71,6 +73,13 @@ export function EmptyState(props: {
const emailActive = useEmailLinksStatus();
const startAddInbox = useAddInboxFlow();
const soup = useSoupView();
+ const teamQuery = useCurrentTeamQuery();
+ const isTeamAdmin = useIsTeamAdmin();
+ const { openSettings } = useSettingsState();
+
+ // CRM is disabled by default per team; the companies list has a dedicated
+ // empty state that points admins to the toggle in Settings › CRM.
+ const crmEnabled = () => teamQuery.data?.team.crm_enabled ?? false;
const onConnectEmail = () => {
void startAddInbox();
@@ -229,11 +238,34 @@ export function EmptyState(props: {
</Match>
<Match when={props.listView === 'companies'}>
- <EmptyStatePanel
- graphic={EmptyStateCompaniesGraphic}
- title="No customers"
- description="Customers you add or sync into your CRM will appear here."
- />
+ <Show
+ when={crmEnabled()}
+ fallback={
+ <EmptyStatePanel
+ graphic={EmptyStateCompaniesGraphic}
+ title="CRM is disabled"
+ description={
+ isTeamAdmin()
+ ? 'Enable CRM in Settings > CRM to start tracking your customers.'
+ : 'Team owners and admins can enable CRM in Settings > CRM.'
+ }
+ primaryAction={
+ isTeamAdmin()
+ ? {
+ label: 'Open CRM settings',
+ onClick: () => openSettings('CRM'),
+ }
+ : undefined
+ }
+ />
+ }
+ >
+ <EmptyStatePanel
+ graphic={EmptyStateCompaniesGraphic}
+ title="No customers yet"
+ description="Customers your team emails will appear here."
+ />
+ </Show>
</Match>
<Match
diff --git a/apps/web/src/features/settings/Crm.tsx b/apps/web/src/features/settings/Crm.tsx
index fcebb83ede..ed50aaec43 100644
--- a/apps/web/src/features/settings/Crm.tsx
+++ b/apps/web/src/features/settings/Crm.tsx
@@ -90,13 +90,11 @@ function ConfirmDialog(props: {
*/
function usePatchTeamCrmSettingsMutation() {
return useMutation(() => ({
- mutationFn: async (enabled: boolean) =>
+ mutationFn: async (req: PatchTeamCrmSettingsRequest) =>
await throwOnErr(() =>
fetchWithAuth<PatchTeamCrmSettingsResponse>(`${authHost}/team/crm`, {
method: 'PATCH',
- body: JSON.stringify({
- enabled,
- } satisfies PatchTeamCrmSettingsRequest),
+ body: JSON.stringify(req),
})
),
onSuccess: (data: PatchTeamCrmSettingsResponse) => {
@@ -120,13 +118,16 @@ function CrmEnablementSection() {
// The mutation invalidates the team query on success, which refetches
// the authoritative flag.
const crmEnabled = () => teamQuery.data?.team.crm_enabled ?? false;
+ const [showEnableModal, setShowEnableModal] = createSignal(false);
+ const [enableChoice, setEnableChoice] = createSignal<'backfill' | 'fresh'>();
const [showDisableModal, setShowDisableModal] = createSignal(false);
const [disableConfirmation, setDisableConfirmation] = createSignal('');
const handleToggle = (next: boolean) => {
if (!isTeamAdmin() || patchCrmMutation.isPending) return;
if (next) {
- patchCrmMutation.mutate(true);
+ // Enabling asks whether to backfill from existing email history.
+ setShowEnableModal(true);
} else {
// Disabling purges the team's CRM data — force a typed confirmation.
setDisableConfirmation('');
@@ -134,18 +135,32 @@ function CrmEnablementSection() {
}
};
+ const handleEnable = (backfill: boolean) => {
+ setEnableChoice(backfill ? 'backfill' : 'fresh');
+ patchCrmMutation.mutate(
+ { enabled: true, backfill },
+ {
+ onSuccess: () => setShowEnableModal(false),
+ onSettled: () => setEnableChoice(undefined),
+ }
+ );
+ };
+
const handleDisable = () => {
- patchCrmMutation.mutate(false, {
- onSuccess: () => setShowDisableModal(false),
- });
+ patchCrmMutation.mutate(
+ { enabled: false, backfill: false },
+ {
+ onSuccess: () => setShowDisableModal(false),
+ }
+ );
};
return (
<SettingsSection title="General">
<SettingsCard>
<SettingsRow
- label="Enable CRM"
- description="Turns the CRM on for everyone on your team."
+ label={crmEnabled() ? 'Disable CRM' : 'Enable CRM'}
+ description={`Turn the CRM ${crmEnabled() ? 'off' : 'on'} for everyone on your team.`}
hideDescriptionOnMobile
>
<Show
@@ -178,6 +193,68 @@ function CrmEnablementSection() {
</SettingsRow>
</SettingsCard>
+ <Dialog
+ open={showEnableModal()}
+ onOpenChange={(open) => !open && setShowEnableModal(false)}
+ >
+ <Panel depth={2} class="max-h-[75vh] text-ink rounded-xl">
+ <Panel.Header class="px-2 gap-1">
+ <Dialog.CloseButton as={Button} variant="ghost" size="icon-sm">
+ <XIcon />
+ </Dialog.CloseButton>
+ <Dialog.Title as="span" class="text-sm font-medium p-0 m-0">
+ Enable CRM
+ </Dialog.Title>
+ </Panel.Header>
+ <Panel.Body class="p-3 flex flex-col gap-3">
+ <p>
+ Start the CRM from your team's existing email, or from a clean
+ slate.
+ </p>
+ <div class="flex justify-end gap-1 pt-2">
+ <Button
+ variant="ghost"
+ class="rounded-xs"
+ disabled={patchCrmMutation.isPending}
+ onClick={() => setShowEnableModal(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="base"
+ class="rounded-xs"
+ disabled={patchCrmMutation.isPending}
+ onClick={() => handleEnable(false)}
+ >
+ <Show
+ when={
+ enableChoice() === 'fresh' && patchCrmMutation.isPending
+ }
+ fallback="Start from now"
+ >
+ <SpinnerIcon class="size-4 animate-spin" />
+ </Show>
+ </Button>
+ <Button
+ variant="active"
+ class="rounded-xs"
+ disabled={patchCrmMutation.isPending}
+ onClick={() => handleEnable(true)}
+ >
+ <Show
+ when={
+ enableChoice() === 'backfill' && patchCrmMutation.isPending
+ }
+ fallback="Backfill existing emails"
+ >
+ <SpinnerIcon class="size-4 animate-spin" />
+ </Show>
+ </Button>
+ </div>
+ </Panel.Body>
+ </Panel>
+ </Dialog>
+
<ConfirmDialog
open={showDisableModal()}
title="Disable CRM"
@@ -190,7 +267,7 @@ function CrmEnablementSection() {
<p>
Disabling the CRM <span class="font-medium">permanently purges</span>{' '}
your team's CRM data — companies, contacts, and their history.
- Re-enabling later starts from a fresh backfill.
+ Re-enabling later lets you backfill again or start fresh.
</p>
<p class="text-sm text-ink-muted">
Type <span class="font-medium text-ink">{DISABLE_CRM_PHRASE}</span> to
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
index 2262861fbe..feee5df858 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
@@ -126,7 +126,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {
: undefined;
const customCompanies =
- ENABLE_CRM && props.entities
+ ENABLE_CRM() && props.entities
? useEntityMentionFromList({
items: props.entities,
buckets: ['crm_company'],
@@ -150,7 +150,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {
// CRM companies only surface in mentions when the feature is enabled —
// the mention hook isn't even wired up otherwise.
- const companyMention = ENABLE_CRM
+ const companyMention = ENABLE_CRM()
? (customCompanies ??
useEntityMention({
buckets: ['crm_company'],
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index ef37cd71c0..2ef8f433bc 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -132,8 +132,20 @@ export const ENABLE_EMAIL_SIGNATURES = resolveFeatureFlag(
// CRM companies & contacts frontend: the Companies view + sidebar entry, the
// company/contact detail blocks, CRM mentions / quick-access, and CRM rows in
-// global search. override with VITE_ENABLE_CRM.
-export const ENABLE_CRM = resolveFeatureFlag('ENABLE_CRM', DEV_MODE_ENV);
+// global search. PostHog-gated (currently targeted at the Macro team in prod)
+// with a dev-mode default; override with VITE_ENABLE_CRM.
+export const ENABLE_CRM_FLAG = 'enable-crm';
+export const ENABLE_CRM_OVERRIDE =
+ resolveFeatureFlag('ENABLE_CRM', DEV_MODE_ENV) || undefined;
+
+/**
+ * Non-reactive check for imperative call sites. For reactive UI, prefer
+ * `useFeatureFlag(ENABLE_CRM_FLAG, { enabledOverride: ENABLE_CRM_OVERRIDE })`.
+ */
+export function ENABLE_CRM(): boolean {
+ if (ENABLE_CRM_OVERRIDE !== undefined) return ENABLE_CRM_OVERRIDE;
+ return analytics.posthog.isFeatureEnabled(ENABLE_CRM_FLAG) ?? false;
+}
export const ENABLE_BLOCK_IN_BLOCK = resolveFeatureFlag(
'ENABLE_BLOCK_IN_BLOCK',
diff --git a/apps/web/src/lib/core/constant/settingsTabsConfig.tsx b/apps/web/src/lib/core/constant/settingsTabsConfig.tsx
index 55b221625a..0b76e4e04b 100644
--- a/apps/web/src/lib/core/constant/settingsTabsConfig.tsx
+++ b/apps/web/src/lib/core/constant/settingsTabsConfig.tsx
@@ -19,7 +19,8 @@ import {
BOT_MANAGEMENT_OVERRIDE,
DEV_MODE_ENV,
ENABLE_APP_STORE_QR_CODE,
- ENABLE_CRM,
+ ENABLE_CRM_FLAG,
+ ENABLE_CRM_OVERRIDE,
ENABLE_TEAMS_OVERRIDE,
} from './featureFlags';
import { PERMISSION_IDS } from './permissions';
@@ -144,6 +145,9 @@ export const useSettingsTabAvailable = () => {
const botManagementFlag = useFeatureFlag(BOT_MANAGEMENT_FLAG, {
enabledOverride: BOT_MANAGEMENT_OVERRIDE,
});
+ const crmFlag = useFeatureFlag(ENABLE_CRM_FLAG, {
+ enabledOverride: ENABLE_CRM_OVERRIDE,
+ });
const hasAdminPanel = useHasPermission(PERMISSION_IDS.WRITE_ADMIN_PANEL);
return (tab: SettingsTab): boolean => {
@@ -155,10 +159,10 @@ export const useSettingsTabAvailable = () => {
case 'Team':
return teamsFlag().enabled;
// CRM is still rolling out (Macro-internal only); keep the settings tab
- // behind the same ENABLE_CRM gate as every other CRM surface so it never
+ // behind the same enable-crm gate as every other CRM surface so it never
// leaks into teams that can't actually use the CRM.
case 'CRM':
- return teamsFlag().enabled && ENABLE_CRM;
+ return teamsFlag().enabled && crmFlag().enabled;
case 'Connected':
return true;
case 'Shortcuts':
diff --git a/apps/web/src/lib/queries/soup/quick-access-crm-companies.ts b/apps/web/src/lib/queries/soup/quick-access-crm-companies.ts
index 97dbe7745c..d71647c396 100644
--- a/apps/web/src/lib/queries/soup/quick-access-crm-companies.ts
+++ b/apps/web/src/lib/queries/soup/quick-access-crm-companies.ts
@@ -32,7 +32,7 @@ export function useQuickAccessCrmCompaniesQuery() {
crm_company_filters: undefined,
},
}),
- () => ({ staleTime: STALE_TIME, enabled: ENABLE_CRM })
+ () => ({ staleTime: STALE_TIME, enabled: ENABLE_CRM() })
);
const companies = createMemo<CrmCompanyEntity[]>(
diff --git a/apps/web/src/lib/queries/soup/recently-viewed.ts b/apps/web/src/lib/queries/soup/recently-viewed.ts
index c4f382553a..28ea98221f 100644
--- a/apps/web/src/lib/queries/soup/recently-viewed.ts
+++ b/apps/web/src/lib/queries/soup/recently-viewed.ts
@@ -18,65 +18,75 @@ const RECENTLY_VIEWED_LIMIT = 50;
const RECENTLY_VIEWED_STALE_TIME = 5 * 60 * 1000; // 5 minutes
const RECENTLY_VIEWED_GC_TIME = 10 * 60 * 1000; // 10 minutes
-const recentlyViewedArgs: SoupItemsQueryArgs = {
- params: { sort_method: 'viewed_at', limit: RECENTLY_VIEWED_LIMIT },
- body: {
- ...QUERY_FILTERS_BASE,
- channel_filters: undefined,
- chat_filters: undefined,
- document_filters: undefined,
- email_filters: undefined,
- project_filters: undefined,
- // CRM companies only surface in recently-viewed when the feature is enabled.
- ...(ENABLE_CRM ? { crm_company_filters: undefined } : {}),
- },
-};
+// Built at call time (not module load) so the CRM flag is read after PostHog
+// has hydrated. The flag is stable within a session, so the derived query key
+// is stable too — the hook and `updateRecentlyViewedItem` agree on it.
+function buildRecentlyViewedArgs(): SoupItemsQueryArgs {
+ return {
+ params: { sort_method: 'viewed_at', limit: RECENTLY_VIEWED_LIMIT },
+ body: {
+ ...QUERY_FILTERS_BASE,
+ channel_filters: undefined,
+ chat_filters: undefined,
+ document_filters: undefined,
+ email_filters: undefined,
+ project_filters: undefined,
+ // CRM companies only surface in recently-viewed when the feature is enabled.
+ ...(ENABLE_CRM() ? { crm_company_filters: undefined } : {}),
+ },
+ };
+}
-const recentlyViewedQueryKey = soupKeys.items(recentlyViewedArgs).queryKey;
+function recentlyViewedQueryKey() {
+ return soupKeys.items(buildRecentlyViewedArgs()).queryKey;
+}
export function useRecentlyViewedSoupQuery() {
- return useQuery(() => ({
- queryKey: recentlyViewedQueryKey,
- queryFn: async (): Promise<RecentlyViewedItem[]> => {
- const page = await throwOnErr(
- async () =>
- await storageServiceClient.getSoupItems({
- params: {},
- body: {
- ...recentlyViewedArgs.body,
- ...recentlyViewedArgs.params,
- },
- })
- );
- return page.items.flatMap((item): RecentlyViewedItem[] => {
- if (
- item.tag === 'call' ||
- item.tag === 'foreignEntity' ||
- item.tag === 'channelThread'
- ) {
- return [];
- }
+ return useQuery(() => {
+ const args = buildRecentlyViewedArgs();
+ return {
+ queryKey: soupKeys.items(args).queryKey,
+ queryFn: async (): Promise<RecentlyViewedItem[]> => {
+ const page = await throwOnErr(
+ async () =>
+ await storageServiceClient.getSoupItems({
+ params: {},
+ body: {
+ ...args.body,
+ ...args.params,
+ },
+ })
+ );
+ return page.items.flatMap((item): RecentlyViewedItem[] => {
+ if (
+ item.tag === 'call' ||
+ item.tag === 'foreignEntity' ||
+ item.tag === 'channelThread'
+ ) {
+ return [];
+ }
- return [
- {
- id: item.tag === 'channel' ? item.data.channel.id : item.data.id,
- viewedAt:
- (item.tag === 'channel'
- ? item.data.viewed_at
- : item.data.viewedAt) ?? undefined,
- },
- ];
- });
- },
- staleTime: RECENTLY_VIEWED_STALE_TIME,
- gcTime: RECENTLY_VIEWED_GC_TIME,
- placeholderData: (prev) => prev,
- }));
+ return [
+ {
+ id: item.tag === 'channel' ? item.data.channel.id : item.data.id,
+ viewedAt:
+ (item.tag === 'channel'
+ ? item.data.viewed_at
+ : item.data.viewedAt) ?? undefined,
+ },
+ ];
+ });
+ },
+ staleTime: RECENTLY_VIEWED_STALE_TIME,
+ gcTime: RECENTLY_VIEWED_GC_TIME,
+ placeholderData: (prev) => prev,
+ };
+ });
}
export function updateRecentlyViewedItem(itemId: string, viewedAt?: string) {
queryClient.setQueryData<RecentlyViewedItem[]>(
- recentlyViewedQueryKey,
+ recentlyViewedQueryKey(),
(prev) => {
const filtered = prev?.filter((item) => item.id !== itemId) ?? [];
const updatedItem = {
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/client.ts b/apps/web/src/lib/service-clients/service-auth/generated/client.ts
index 6aff93c358..0125899900 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/client.ts
@@ -2246,9 +2246,11 @@ export const patchTeam = async (
};
/**
- * @summary Enables or disables CRM for the team. On enable, kicks off a
-best-effort backfill that enqueues a `PopulateCrmForUser` message
-per team member (no-op if CRM is already enabled). On disable,
+ * @summary Enables or disables CRM for the team. On enable with `backfill`
+(the default), kicks off a best-effort backfill that enqueues a
+`PopulateCrmForUser` message per team member (no-op if CRM is
+already enabled); without `backfill` the CRM starts empty and fills
+from new activity only. On disable,
flips the flag and purges the team's CRM data (cascading through
`crm_companies` → `crm_domains` / `crm_contacts` /
`crm_contact_sources`). Requires the caller to be an Admin or
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/patchTeamCrmSettingsRequest.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/patchTeamCrmSettingsRequest.ts
index 78873c869e..e7e4366b0f 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/patchTeamCrmSettingsRequest.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/patchTeamCrmSettingsRequest.ts
@@ -9,6 +9,9 @@
* Request body for `PATCH /team/crm`.
*/
export interface PatchTeamCrmSettingsRequest {
+ /** On a disabled → enabled transition, whether to backfill the CRM
+from members' existing email history. Ignored when disabling. */
+ backfill?: boolean;
/** The desired CRM state for the team. */
enabled: boolean;
}
diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.json
index 57797a1994..a90dbc023d 100644
--- a/apps/web/src/lib/service-clients/service-auth/openapi.json
+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json
@@ -1886,7 +1886,7 @@
"/team/crm": {
"patch": {
"tags": ["teams::inbound::axum_router::patch_team_crm_settings"],
- "summary": "Enables or disables CRM for the team. On enable, kicks off a\nbest-effort backfill that enqueues a `PopulateCrmForUser` message\nper team member (no-op if CRM is already enabled). On disable,\nflips the flag and purges the team's CRM data (cascading through\n`crm_companies` → `crm_domains` / `crm_contacts` /\n`crm_contact_sources`). Requires the caller to be an Admin or\nOwner of the team.",
+ "summary": "Enables or disables CRM for the team. On enable with `backfill`\n(the default), kicks off a best-effort backfill that enqueues a\n`PopulateCrmForUser` message per team member (no-op if CRM is\nalready enabled); without `backfill` the CRM starts empty and fills\nfrom new activity only. On disable,\nflips the flag and purges the team's CRM data (cascading through\n`crm_companies` → `crm_domains` / `crm_contacts` /\n`crm_contact_sources`). Requires the caller to be an Admin or\nOwner of the team.",
"operationId": "patch_team_crm_settings",
"requestBody": {
"content": {
@@ -3968,6 +3968,11 @@
"description": "Request body for `PATCH /team/crm`.",
"required": ["enabled"],
"properties": {
+ "backfill": {
+ "type": "boolean",
+ "description": "On a disabled → enabled transition, whether to backfill the CRM\nfrom members' existing email history. Ignored when disabling.",
+ "default": true
+ },
"enabled": {
"type": "boolean",
"description": "The desired CRM state for the team."
diff --git a/crates/teams/src/domain/model.rs b/crates/teams/src/domain/model.rs
index 1837bb7dec..864dcf2212 100644
--- a/crates/teams/src/domain/model.rs
+++ b/crates/teams/src/domain/model.rs
@@ -127,6 +127,15 @@ pub struct TeamMembers {
pub struct PatchTeamCrmSettingsRequest {
/// The desired CRM state for the team.
pub enabled: bool,
+ /// On a disabled → enabled transition, whether to backfill the CRM
+ /// from members' existing email history. Ignored when disabling.
+ #[serde(default = "default_crm_backfill")]
+ #[cfg_attr(feature = "axum", schema(default = true))]
+ pub backfill: bool,
+}
+
+fn default_crm_backfill() -> bool {
+ true
}
/// Response for `PATCH /team/crm`. Reports both the resulting state
diff --git a/crates/teams/src/domain/team_repo.rs b/crates/teams/src/domain/team_repo.rs
index 1a1abe237f..09c03a4760 100644
--- a/crates/teams/src/domain/team_repo.rs
+++ b/crates/teams/src/domain/team_repo.rs
@@ -405,14 +405,17 @@ pub trait TeamService: Clone + Send + Sync + 'static {
> + Send;
/// Enables or disables CRM for a team. On a `false → true`
- /// transition, fans out a `PopulateCrmForUser` enqueue per current
- /// team member (best-effort, log-and-swallow). On any disable call,
- /// flips the flag and purges the team's `crm_companies` rows in a
- /// single transaction — the FK cascade clears the rest of the CRM
- /// tables. Idempotent in both directions.
+ /// transition with `backfill`, fans out a `PopulateCrmForUser`
+ /// enqueue per current team member (best-effort, log-and-swallow);
+ /// without `backfill` the flag flips and the CRM starts empty. On
+ /// any disable call, flips the flag and purges the team's
+ /// `crm_companies` rows in a single transaction — the FK cascade
+ /// clears the rest of the CRM tables. Idempotent in both
+ /// directions.
fn set_team_crm_enabled(
&self,
entity_access_receipt: EntityAccessReceipt<AdminTeamRole>,
enabled: bool,
+ backfill: bool,
) -> impl Future<Output = Result<PatchTeamCrmSettingsResponse, TeamError>> + Send;
}
diff --git a/crates/teams/src/domain/team_service.rs b/crates/teams/src/domain/team_service.rs
index 2590fd4d10..dde7741b0c 100644
--- a/crates/teams/src/domain/team_service.rs
+++ b/crates/teams/src/domain/team_service.rs
@@ -1159,6 +1159,7 @@ where
&self,
entity_access_receipt: EntityAccessReceipt<AdminTeamRole>,
enabled: bool,
+ backfill: bool,
) -> Result<PatchTeamCrmSettingsResponse, TeamError> {
let team_id =
macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();
@@ -1167,7 +1168,11 @@ where
// Fetch the members *before* flipping the flag so a member-list
// failure leaves the flag untouched — a retry will then re-run
// the full backfill instead of hitting the early-return below.
- let members = self.team_repository.get_team_members(&team_id).await?;
+ let members = if backfill {
+ self.team_repository.get_team_members(&team_id).await?
+ } else {
+ Vec::new()
+ };
let changed = self
.team_crm_settings_repository
diff --git a/crates/teams/src/domain/team_service/test.rs b/crates/teams/src/domain/team_service/test.rs
index b572cf3c79..5ac3e3a94a 100644
--- a/crates/teams/src/domain/team_service/test.rs
+++ b/crates/teams/src/domain/team_service/test.rs
@@ -21,7 +21,7 @@ use roles_and_permissions::domain::{
};
use crate::domain::{
- crm_enqueuer::NoOpCrmEnqueuer,
+ crm_enqueuer::{CrmEnqueuer, NoOpCrmEnqueuer},
team_analytics::{TeamAnalytics, TeamAnalyticsEvent},
team_crm_settings_repo::NoOpTeamCrmSettingsRepository,
};
@@ -1502,6 +1502,118 @@ async fn test_get_team_reports_crm_enabled() {
assert!(team.team.crm_enabled());
}
+/// CrmEnqueuer that records which users had a populate enqueued.
+#[derive(Clone, Default)]
+struct RecordingCrmEnqueuer {
+ populated: Arc<Mutex<Vec<String>>>,
+}
+
+impl CrmEnqueuer for RecordingCrmEnqueuer {
+ type Err = std::convert::Infallible;
+
+ async fn enqueue_populate_crm_for_user(
+ &self,
+ macro_id: &MacroUserIdStr<'_>,
+ ) -> Result<(), Self::Err> {
+ self.populated
+ .lock()
+ .unwrap()
+ .push(macro_id.as_ref().to_string());
+ Ok(())
+ }
+
+ async fn enqueue_depopulate_crm_for_user(
+ &self,
+ _: &uuid::Uuid,
+ _: &MacroUserIdStr<'_>,
+ ) -> Result<(), Self::Err> {
+ Ok(())
+ }
+}
+
+fn build_crm_enable_service(
+ team_id: uuid::Uuid,
+ member_ids: &[&str],
+) -> (impl TeamService, Arc<Mutex<Vec<String>>>) {
+ let members = member_ids
+ .iter()
+ .map(|id| TeamMember {
+ team_id,
+ user_id: MacroUserIdStr::parse_from_str(id).unwrap().into_owned(),
+ role: TeamRole::Member,
+ })
+ .collect();
+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));
+ let team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls)
+ .with_team_members(members);
+ let enqueuer = RecordingCrmEnqueuer::default();
+ let populated = enqueuer.populated.clone();
+ let notification_ingress = Arc::new(MockNotificationIngress::new(HashSet::new()));
+ let service = TeamServiceImpl::new(
+ team_repo,
+ MockCustomerRepository::default(),
+ MockTeamChannelsRepository::default(),
+ MockUserRolesAndPermissionsService::default(),
+ notification_ingress,
+ enqueuer,
+ // NoOp reports every enable_crm call as a fresh false → true flip.
+ NoOpTeamCrmSettingsRepository,
+ );
+ (service, populated)
+}
+
+/// Enabling with backfill enqueues a populate per team member.
+#[tokio::test]
+async fn test_enable_crm_with_backfill_enqueues_members() {
+ let team_id = uuid::Uuid::from_u128(7);
+ let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let (service, populated) = build_crm_enable_service(
+ team_id,
+ &["macro|[email protected]", "macro|[email protected]"],
+ );
+
+ let receipt = test_team_receipt::<AdminTeamRole>(team_id, &owner_id);
+ let response = service
+ .set_team_crm_enabled(receipt, true, true)
+ .await
+ .unwrap();
+
+ assert!(response.enabled);
+ assert!(response.changed);
+ assert_eq!(response.backfill_enqueued, 2);
+ assert_eq!(response.backfill_failed, 0);
+ assert_eq!(
+ *populated.lock().unwrap(),
+ vec![
+ "macro|[email protected]".to_string(),
+ "macro|[email protected]".to_string()
+ ]
+ );
+}
+
+/// Enabling without backfill flips the flag but enqueues nothing.
+#[tokio::test]
+async fn test_enable_crm_without_backfill_skips_enqueue() {
+ let team_id = uuid::Uuid::from_u128(7);
+ let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let (service, populated) = build_crm_enable_service(
+ team_id,
+ &["macro|[email protected]", "macro|[email protected]"],
+ );
+
+ let receipt = test_team_receipt::<AdminTeamRole>(team_id, &owner_id);
+ let response = service
+ .set_team_crm_enabled(receipt, true, false)
+ .await
+ .unwrap();
+
+ assert!(response.enabled);
+ assert!(response.changed);
+ assert_eq!(response.backfill_enqueued, 0);
+ assert_eq!(response.backfill_failed, 0);
+ assert!(populated.lock().unwrap().is_empty());
+}
+
fn build_service_with_team(
team: Team,
) -> (
diff --git a/crates/teams/src/inbound/axum_router/patch_team_crm_settings.rs b/crates/teams/src/inbound/axum_router/patch_team_crm_settings.rs
index dec5405d3a..a647b25454 100644
--- a/crates/teams/src/inbound/axum_router/patch_team_crm_settings.rs
+++ b/crates/teams/src/inbound/axum_router/patch_team_crm_settings.rs
@@ -12,9 +12,11 @@ use crate::domain::{
use super::TeamRouterState;
-/// Enables or disables CRM for the team. On enable, kicks off a
-/// best-effort backfill that enqueues a `PopulateCrmForUser` message
-/// per team member (no-op if CRM is already enabled). On disable,
+/// Enables or disables CRM for the team. On enable with `backfill`
+/// (the default), kicks off a best-effort backfill that enqueues a
+/// `PopulateCrmForUser` message per team member (no-op if CRM is
+/// already enabled); without `backfill` the CRM starts empty and fills
+/// from new activity only. On disable,
/// flips the flag and purges the team's CRM data (cascading through
/// `crm_companies` → `crm_domains` / `crm_contacts` /
/// `crm_contact_sources`). Requires the caller to be an Admin or
@@ -41,7 +43,7 @@ pub async fn handler<T: TeamService, Eas: EntityAccessService>(
) -> Result<Json<PatchTeamCrmSettingsResponse>, TeamError> {
let response = state
.service
- .set_team_crm_enabled(access.entity_access_receipt, req.enabled)
+ .set_team_crm_enabled(access.entity_access_receipt, req.enabled, req.backfill)
.await?;
Ok(Json(response))
}