Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(crm): make CRM settings match the rest of Settings (#8446)
gbirman6e8ccef4685f
diff --git a/apps/web/src/features/crm/components/stage-icon.tsx b/apps/web/src/features/crm/components/stage-icon.tsxindex a18cae878e..1af6d6d056 100644--- a/apps/web/src/features/crm/components/stage-icon.tsx+++ b/apps/web/src/features/crm/components/stage-icon.tsx@@ -27,10 +27,6 @@ const STAGE_TINT_PALETTE = ['text-failure-ink',] as const;-export function CrmStageDot() {- return <span class="size-2 shrink-0 rounded-full bg-accent/70" />;-}-export function CrmStageIcon(props: {optionId: string;index?: number;diff --git a/apps/web/src/features/crm/context/crm-context.tsx b/apps/web/src/features/crm/context/crm-context.tsxindex 414d88df98..067483b207 100644--- a/apps/web/src/features/crm/context/crm-context.tsx+++ b/apps/web/src/features/crm/context/crm-context.tsx@@ -133,9 +133,6 @@ export type CrmContext = {createTeamConfigSource(): TeamConfigSource;createCapabilities(): CrmCapabilities;createDealStages(): DealStages;- createClosedStageIds(- stages: Accessor<{ id: string; label: string }[]>- ): Accessor<Set<string>>;createPersonalViews(): PersonalViewsSource;createTeamViews(): TeamViewsSource;createLists(teamId: Accessor<string | undefined>): ListsSource;diff --git a/apps/web/src/features/crm/core/team-config.ts b/apps/web/src/features/crm/core/team-config.tsindex bbbdc4b4c9..ba84bffb73 100644--- a/apps/web/src/features/crm/core/team-config.ts+++ b/apps/web/src/features/crm/core/team-config.ts@@ -25,13 +25,6 @@ export type TeamCrmSavedView = {export type TeamCrmConfig = {permissions?: CrmPermissions;- /**- * Stage option ids that count as "closed" deals (used by the- * move-closed-deals permission). When unset, stages labeled like- * closed/won/lost states are treated as closed; an empty list means- * none are.- */- closedStageIds?: string[];/** System stage option id to team stage option id for seeded stages. */legacyStageIds?: Record<string, string>;teamViews?: TeamCrmSavedView[];@@ -41,16 +34,14 @@ export type TeamCrmConfig = {/*** Field-wise partial update of the shared config. Omitted fields keep- * their current values; `null` clears `closedStageIds` /- * `defaultTeamViewId`; `teamViews` replaces the whole list. Pass a- * function for `teamViews` to derive the new list from the latest- * cached value at execution time — mutations are serialized (shared- * scope), so queued updates see the previous write instead of a stale- * snapshot.+ * their current values; `null` clears `defaultTeamViewId`; `teamViews`+ * replaces the whole list. Pass a function for `teamViews` to derive the+ * new list from the latest cached value at execution time — mutations are+ * serialized (shared scope), so queued updates see the previous write+ * instead of a stale snapshot.*/export type TeamCrmConfigPatch = {permissions?: Partial<CrmPermissions>;- closedStageIds?: string[] | null;teamViews?:| TeamCrmSavedView[]| ((current: TeamCrmSavedView[]) => TeamCrmSavedView[]);@@ -63,9 +54,6 @@ export const DEFAULT_CRM_PERMISSIONS: CrmPermissions = {deleteRecords: 'admin',};-/** Labels treated as closed when no explicit closed set is configured. */-const DEFAULT_CLOSED_STAGE_LABEL = /customer|churned|closed|won|lost/i;-export type CrmTeamRole = 'owner' | 'admin' | 'member';export function roleSatisfies(@@ -75,15 +63,3 @@ export function roleSatisfies(if (role === 'owner') return true;return role === 'admin' && required === 'admin';}--export function closedStageIds(- stages: readonly { id: string; label: string }[],- explicit?: readonly string[]-): Set<string> {- return new Set(- explicit ??- stages- .filter((stage) => DEFAULT_CLOSED_STAGE_LABEL.test(stage.label))- .map((stage) => stage.id)- );-}diff --git a/apps/web/src/features/crm/crm-adapter.ts b/apps/web/src/features/crm/crm-adapter.tsindex 9c3744e5e5..d5723f1bf1 100644--- a/apps/web/src/features/crm/crm-adapter.ts+++ b/apps/web/src/features/crm/crm-adapter.ts@@ -45,10 +45,7 @@ import {} from './navigation-adapter';import { PipelineDatabaseEditor, PipelineShare } from './pipeline-adapter';import { createCrmPipelineEntries } from './pipeline-entries-adapter';-import {- createClosedStageIds,- createCrmPermissions,-} from './primitives/team-config';+import { createCrmPermissions } from './primitives/team-config';import {createCompanyImporter,useCompanyQuery,@@ -276,8 +273,6 @@ export function createAppCrmContext(): CrmContext {createCapabilities: () =>createCrmPermissions(userId, useCurrentTeamQuery(), createSettings()),createDealStages: createAppDealStages,- createClosedStageIds: (stages) =>- createClosedStageIds(createSettings(), stages),createPersonalViews: () => usePersonalCrmViews(deps),createTeamViews: () => useTeamCrmViews(deps, userId, createSettings()),createLists: (teamId) => useCrmLists(deps, teamId),diff --git a/apps/web/src/features/crm/primitives/stage-editor.ts b/apps/web/src/features/crm/primitives/stage-editor.tsindex 392461a171..3597dede4b 100644--- a/apps/web/src/features/crm/primitives/stage-editor.ts+++ b/apps/web/src/features/crm/primitives/stage-editor.ts@@ -1,4 +1,4 @@-import { type Accessor, createMemo, createSignal } from 'solid-js';+import { createMemo, createSignal } from 'solid-js';import { createStore } from 'solid-js/store';import type {CrmCapabilities,@@ -16,8 +16,7 @@ function toStageInputs(stages: DealStage[]): CrmStageInput[] {export function createStageEditor(input: {dealStages: DealStages;crmPermissions: Pick<CrmCapabilities, 'canEditStages'>;- teamCrmConfig: TeamConfigSource;- closedStageIds: Accessor<Set<string>>;+ teamCrmConfig: Pick<TeamConfigSource, 'isLoading' | 'isError'>;replaceMutation: CrmMutation<CrmStageInput[], CrmStagesResponse>;resetMutation: CrmMutation<void>;onSuccess(message: string): void;@@ -26,7 +25,6 @@ export function createStageEditor(input: {dealStages,crmPermissions,teamCrmConfig,- closedStageIds,replaceMutation,resetMutation,} = input;@@ -40,8 +38,7 @@ export function createStageEditor(input: {const pending = () => replaceMutation.isPending || resetMutation.isPending;const loading = () => dealStages.isLoading() || teamCrmConfig.isLoading();const failed = () => dealStages.isError() || teamCrmConfig.isError();- const busy = () => pending() || teamCrmConfig.update.isPending;- const blocked = () => busy() || loading() || failed();+ const blocked = () => pending() || loading() || failed();const [drafts, setDrafts] = createStore<Record<string, string | undefined>>({});@@ -91,29 +88,11 @@ export function createStageEditor(input: {});};- const handleCustomize = () => {- const seed = dealStages.stages();- const closedLabels = new Set(- seed- .filter((stage) => closedStageIds().has(stage.id))- .map((stage) => stage.label)- );- const explicitClosed = teamCrmConfig.config().closedStageIds !== undefined;+ const handleCustomize = () =>replace(- seed.map((stage) => ({ label: stage.label })),- {- successMessage: 'Stages are now customizable',- onSuccess: (result) => {- if (!explicitClosed) return;- teamCrmConfig.update.mutate({- closedStageIds: result.stages- .filter((stage) => closedLabels.has(stage.label))- .map((stage) => stage.id),- });- },- }+ dealStages.stages().map((stage) => ({ label: stage.label })),+ { successMessage: 'Stages are now customizable' });- };const handleRename = (index: number, label: string) => {const stages = toStageInputs(orderedStages());@@ -167,17 +146,6 @@ export function createStageEditor(input: {});};- const toggleClosedStage = (stageId: string) => {- if (blocked()) return;- const next = new Set(closedStageIds());- if (next.has(stageId)) {- next.delete(stageId);- } else {- next.add(stageId);- }- teamCrmConfig.update.mutate({ closedStageIds: [...next] });- };-return {newStageName,setNewStageName,@@ -189,7 +157,6 @@ export function createStageEditor(input: {pending,loading,failed,- busy,blocked,drafts,setDrafts,@@ -203,6 +170,5 @@ export function createStageEditor(input: {handleAddStage,handleDeleteStage,handleReset,- toggleClosedStage,};}diff --git a/apps/web/src/features/crm/primitives/team-config.ts b/apps/web/src/features/crm/primitives/team-config.tsindex a16f44db03..263a16aecb 100644--- a/apps/web/src/features/crm/primitives/team-config.ts+++ b/apps/web/src/features/crm/primitives/team-config.ts@@ -3,7 +3,6 @@ import type { TeamConfigSource, TeamSource } from '../context/crm-sources';import {type CrmPermissions,type CrmTeamRole,- closedStageIds,DEFAULT_CRM_PERMISSIONS,roleSatisfies,} from '../core/team-config';@@ -50,15 +49,3 @@ export function createCrmPermissions(),};}--/**- * The set of stage option ids considered "closed" — explicit config when- * present, else a label heuristic over the active stages.- */-export function createClosedStageIds(- settings: TeamConfigSource,- stages: Accessor<Array<{ id: string; label: string }>>-): Accessor<Set<string>> {- const { config } = settings;- return createMemo(() => closedStageIds(stages(), config().closedStageIds));-}diff --git a/apps/web/src/features/crm/queries/team-config.ts b/apps/web/src/features/crm/queries/team-config.tsindex 91aefab946..02c0bd6a0b 100644--- a/apps/web/src/features/crm/queries/team-config.ts+++ b/apps/web/src/features/crm/queries/team-config.ts@@ -11,16 +11,16 @@ export type {} from '../core/team-config';/**- * Team-shared CRM configuration (permissions, closed-stage set, team saved- * views, display defaults).+ * Team-shared CRM configuration (permissions, team saved views, display+ * defaults).** Stored on `team_crm_settings` and served by GET/PUT `/crm/settings`* (document storage service). Any team member can read and can update* the views fields (`teamViews`, `defaultTeamViewId`); the governance- * fields (permission thresholds, `closedStageIds`) are admin/owner-gated- * server-side. Updates are field-wise partial: omitted fields keep their- * current values, `null` clears the nullable ones, and `teamViews` is- * replaced whole (last write wins).+ * fields (permission thresholds) are admin/owner-gated server-side.+ * Updates are field-wise partial: omitted fields keep their current+ * values, `null` clears the nullable ones, and `teamViews` is replaced+ * whole (last write wins).*/import { throwOnErr } from '@core/util/result';@@ -56,7 +56,6 @@ export function useTeamCrmConfig(deps: CrmQueryDependencies) {moveClosedDeals: data.move_closed_deals_role,deleteRecords: data.delete_records_role,},- closedStageIds: data.closed_stage_ids ?? undefined,legacyStageIds: data.legacy_stage_ids ?? undefined,teamViews: parseTeamViews(data.team_views),defaultTeamViewId: data.default_team_view_id ?? undefined,@@ -85,9 +84,6 @@ export function useTeamCrmConfig(deps: CrmQueryDependencies) {edit_stages_role: patch.permissions?.editStages,move_closed_deals_role: patch.permissions?.moveClosedDeals,delete_records_role: patch.permissions?.deleteRecords,- ...(patch.closedStageIds !== undefined- ? { closed_stage_ids: patch.closedStageIds }- : {}),...(teamViews !== undefined ? { team_views: teamViews } : {}),...(patch.defaultTeamViewId !== undefined? { default_team_view_id: patch.defaultTeamViewId }diff --git a/apps/web/src/features/crm/views/crm-settings.test.tsx b/apps/web/src/features/crm/views/crm-settings.test.tsxnew file mode 100644index 0000000000..5080e8fa22--- /dev/null+++ b/apps/web/src/features/crm/views/crm-settings.test.tsx@@ -0,0 +1,169 @@+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { CrmTeamRole } from '../core/team-config';+import { Crm } from './crm-settings';++const DEFAULT_STAGES = [+ { id: 'lead', label: 'Lead' },+ { id: 'demo', label: 'Demo' },+ { id: 'customer', label: 'Customer' },+];++const state = vi.hoisted(() => ({+ role: 'admin' as CrmTeamRole,+ crmEnabled: true,+ customized: false,+ patch: vi.fn(),+ replace: vi.fn(),+ reset: vi.fn(),+}));++vi.mock('../components/stage-icon', () => ({ CrmStageIcon: () => null }));+vi.mock('../context/crm-context', () => ({+ useCrmContext: () => ({ feedback: { success: vi.fn() } }),+}));+vi.mock('./use-crm', () => {+ const canEdit = () => state.role !== 'member';+ return {+ useCurrentTeamQuery: () => ({+ data: {+ team: { id: 'team', crm_enabled: state.crmEnabled },+ members: [{ user_id: 'me', role: state.role }],+ },+ }),+ useIsTeamAdmin: () => canEdit,+ usePatchTeamCrmSettingsMutation: () => ({+ mutate: state.patch,+ isPending: false,+ }),+ useCrmPermissions: () => ({+ canEditStages: canEdit,+ permissions: () => ({+ editStages: 'admin',+ moveClosedDeals: 'admin',+ deleteRecords: 'admin',+ }),+ }),+ useTeamCrmConfig: () => ({+ isLoading: () => false,+ isError: () => false,+ }),+ useDealStages: () => ({+ stages: () => DEFAULT_STAGES,+ isCustomized: () => state.customized,+ isLoading: () => false,+ isError: () => false,+ }),+ useReplaceCrmStagesMutation: () => ({+ mutate: state.replace,+ isPending: false,+ }),+ useResetCrmStagesMutation: () => ({+ mutate: state.reset,+ isPending: false,+ }),+ };+});++beforeEach(() => {+ vi.stubGlobal('scrollTo', vi.fn());+ state.role = 'admin';+ state.crmEnabled = true;+ state.customized = false;+ state.patch.mockReset();+ state.replace.mockReset();+ state.reset.mockReset();+});++afterEach(cleanup);++function teamCrmSwitch() {+ return screen.getByRole('switch', { name: 'Team CRM' });+}++it('asks an admin how to start the CRM before turning it on', async () => {+ state.crmEnabled = false;+ render(() => <Crm />);++ fireEvent.click(teamCrmSwitch());+ fireEvent.click(+ await screen.findByRole('button', { name: 'Backfill existing emails' })+ );++ expect(state.patch).toHaveBeenCalledWith(+ { enabled: true, backfill: true },+ expect.anything()+ );+ expect(screen.queryByText('Stages')).toBeNull();+});++it('turns the CRM off only after the phrase is typed', async () => {+ render(() => <Crm />);++ fireEvent.click(teamCrmSwitch());+ const confirm = await screen.findByRole('button', { name: 'Disable CRM' });+ expect(confirm).toHaveProperty('disabled', true);++ fireEvent.input(screen.getByPlaceholderText('Disable CRM'), {+ target: { value: 'Disable CRM' },+ });+ fireEvent.click(confirm);++ expect(state.patch).toHaveBeenCalledWith(+ { enabled: false, backfill: false },+ expect.anything()+ );+});++it('shows members the stages without letting them change anything', () => {+ state.role = 'member';+ render(() => <Crm />);++ expect(teamCrmSwitch()).toHaveProperty('disabled', true);+ expect(+ screen.getByText(/Only team admins can turn it on or off/)+ ).toBeTruthy();+ expect(screen.getByText(/Only team admins can change them/)).toBeTruthy();+ expect(screen.getByText('Demo')).toBeTruthy();+ expect(screen.queryByRole('textbox')).toBeNull();+ expect(screen.queryByRole('button', { name: 'Customize' })).toBeNull();+ expect(screen.queryByText('Closed stages')).toBeNull();+});++it('copies the default stages when an admin customizes them', () => {+ render(() => <Crm />);++ fireEvent.click(screen.getByRole('button', { name: 'Customize' }));++ expect(state.replace).toHaveBeenCalledWith(+ [{ label: 'Lead' }, { label: 'Demo' }, { label: 'Customer' }],+ expect.anything()+ );+});++it('renames and deletes customized stages', async () => {+ state.customized = true;+ render(() => <Crm />);++ const demo = screen.getByRole('textbox', { name: 'Rename Demo' });+ fireEvent.input(demo, { target: { value: 'Discovery' } });+ fireEvent.keyDown(demo, { key: 'Enter' });+ expect(state.replace).toHaveBeenLastCalledWith(+ [+ { id: 'lead', label: 'Lead' },+ { id: 'demo', label: 'Discovery' },+ { id: 'customer', label: 'Customer' },+ ],+ expect.anything()+ );++ fireEvent.click(screen.getByRole('button', { name: 'Delete Customer' }));+ fireEvent.click(await screen.findByRole('button', { name: 'Delete' }));+ expect(state.replace).toHaveBeenLastCalledWith(+ [+ { id: 'lead', label: 'Lead' },+ { id: 'demo', label: 'Demo' },+ ],+ expect.anything()+ );+});diff --git a/apps/web/src/features/crm/views/crm-settings.tsx b/apps/web/src/features/crm/views/crm-settings.tsxindex cd5aa3137b..1b0effd047 100644--- a/apps/web/src/features/crm/views/crm-settings.tsx+++ b/apps/web/src/features/crm/views/crm-settings.tsx@@ -15,19 +15,34 @@ import {useDragDropContext,useSortableContext,} from '@thisbeyond/solid-dnd';-import { Button, Checkbox, cn, Dialog, Panel, Tooltip } from '@ui';-import { createSignal, For, type JSX, Show, Suspense } from 'solid-js';+import {+ Button,+ ConfirmDialog,+ cn,+ Dialog,+ Panel,+ ToggleSwitch,+ Tooltip,+} from '@ui';+import {+ createSignal,+ For,+ type JSX,+ Match,+ Show,+ Suspense,+ Switch,+} from 'solid-js';import {SettingsCard,SettingsPage,SettingsRow,SettingsSection,} from '../../settings/primitives';-import { CrmStageDot as StageDot } from '../components/stage-icon';+import { CrmStageIcon } from '../components/stage-icon';import { useCrmContext } from '../context/crm-context';import { createStageEditor } from '../primitives/stage-editor';import {- useClosedStageIds,useCrmPermissions,useCurrentTeamQuery,useDealStages,@@ -39,19 +54,19 @@ import {} from './use-crm';/* ------------------------------------------------------------------ */-/* Shared bits */+/* CRM enablement *//* ------------------------------------------------------------------ */-/** Confirm dialog matching the Team tab's destructive-action dialogs. */-function ConfirmDialog(props: {+const DISABLE_CRM_PHRASE = 'Disable CRM';++/** Typed confirmation matching the Team tab's Delete Team dialog. */+function DisableCrmDialog(props: {open: boolean;- title: string;- confirmLabel: string;- pending?: boolean;- confirmDisabled?: boolean;+ pending: boolean;+ confirmation: string;+ onConfirmationInput: (value: string) => void;onConfirm: () => void;onClose: () => void;- children: JSX.Element;}) {return (<Dialog open={props.open} onOpenChange={(open) => !open && props.onClose()}>@@ -61,11 +76,27 @@ function ConfirmDialog(props: {<XIcon /></Dialog.CloseButton><Dialog.Title as="span" class="text-sm font-medium p-0 m-0">- {props.title}+ Disable CRM</Dialog.Title></Panel.Header><Panel.Body class="p-3 flex flex-col gap-3">- {props.children}+ <p>+ Disabling the CRM{' '}+ <span class="font-medium">permanently purges</span> your team's CRM+ data — companies, contacts, and their history. 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 confirm.+ </p>+ <input+ type="text"+ value={props.confirmation}+ onInput={(e) => props.onConfirmationInput(e.currentTarget.value)}+ placeholder={DISABLE_CRM_PHRASE}+ class="settings-input w-full"+ /><div class="flex justify-end gap-1 pt-2"><Buttonvariant="ghost"@@ -76,10 +107,12 @@ function ConfirmDialog(props: {</Button><Buttonvariant="strong"- disabled={props.pending || props.confirmDisabled}+ disabled={+ props.pending || props.confirmation !== DISABLE_CRM_PHRASE+ }onClick={props.onConfirm}>- <Show when={props.pending} fallback={props.confirmLabel}>+ <Show when={props.pending} fallback={DISABLE_CRM_PHRASE}><SpinnerIcon class="size-4 animate-spin" /></Show></Button>@@ -90,19 +123,14 @@ function ConfirmDialog(props: {);}-/* ------------------------------------------------------------------ */-/* CRM enablement */-/* ------------------------------------------------------------------ */--const DISABLE_CRM_PHRASE = 'Disable CRM';-function CrmEnablementSection() {const isTeamAdmin = useIsTeamAdmin();const teamQuery = useCurrentTeamQuery();const patchCrmMutation = usePatchTeamCrmSettingsMutation();// The mutation invalidates the team query on success, which refetches- // the authoritative flag.+ // the authoritative flag. The switch stays on that flag until a dialog+ // confirms the change.const crmEnabled = () => teamQuery.data?.team.crm_enabled ?? false;const [showEnableModal, setShowEnableModal] = createSignal(false);const [enableChoice, setEnableChoice] = createSignal<'backfill' | 'fresh'>();@@ -145,36 +173,24 @@ function CrmEnablementSection() {<SettingsSection title="General"><SettingsCard><SettingsRow- label={crmEnabled() ? 'Disable CRM' : 'Enable CRM'}- description={`Turn the CRM ${crmEnabled() ? 'off' : 'on'} for everyone on your team.`}- hideDescriptionOnMobile+ label="Team CRM"+ description={+ isTeamAdmin()+ ? 'Companies, contacts, and pipelines for everyone on your team.'+ : 'Companies, contacts, and pipelines for everyone on your team. Only team admins can turn it on or off.'+ }>- <Show- when={isTeamAdmin()}- fallback={- <Tooltip label="Only team admins can change CRM settings.">- <span>- <Button variant="outline" size="sm" disabled>- Admins only- </Button>- </span>- </Tooltip>- }- >- <div class="flex items-center gap-2">- <Show when={patchCrmMutation.isPending}>- <SpinnerIcon class="size-4 animate-spin text-ink-muted" />- </Show>- <Button- variant={crmEnabled() ? 'danger' : 'accent'}- size="sm"- disabled={patchCrmMutation.isPending}- onClick={() => handleToggle(!crmEnabled())}- >- {crmEnabled() ? 'Disable CRM' : 'Enable CRM'}- </Button>- </div>+ <Show when={patchCrmMutation.isPending}>+ <SpinnerIcon class="size-4 animate-spin text-ink-muted" /></Show>+ <ToggleSwitch+ size="md"+ label="Team CRM"+ labelClass="sr-only"+ checked={crmEnabled()}+ disabled={!isTeamAdmin() || patchCrmMutation.isPending}+ onChange={handleToggle}+ /></SettingsRow></SettingsCard>@@ -237,45 +253,27 @@ function CrmEnablementSection() {</Panel></Dialog>- <ConfirmDialog+ <DisableCrmDialogopen={showDisableModal()}- title="Disable CRM"- confirmLabel="Disable CRM"pending={patchCrmMutation.isPending}- confirmDisabled={disableConfirmation() !== DISABLE_CRM_PHRASE}+ confirmation={disableConfirmation()}+ onConfirmationInput={setDisableConfirmation}onConfirm={handleDisable}onClose={() => setShowDisableModal(false)}- >- <p>- Disabling the CRM <span class="font-medium">permanently purges</span>{' '}- your team's CRM data — companies, contacts, and their history.- 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- confirm.- </p>- <input- type="text"- value={disableConfirmation()}- onInput={(e) => setDisableConfirmation(e.currentTarget.value)}- placeholder={DISABLE_CRM_PHRASE}- class="settings-input w-full"- />- </ConfirmDialog>+ /></SettingsSection>);}/* ------------------------------------------------------------------ */-/* Deal stages */+/* Stages *//* ------------------------------------------------------------------ *//*** Drag data carried by stage row sortables. Distinct from `EntityDragData`* so entity drop consumers ignore stage drags. Supplies its own overlay icon.*/-export type StageDragData = ItemDragOverlayData & {+type StageDragData = ItemDragOverlayData & {dragType: 'stage';name: string;};@@ -302,13 +300,49 @@ function StageList(props: { ids: string[]; children: JSX.Element }) {);}+/** Same colored icon the CRM list groups and filters show for a stage. */+function StageIcon(props: { id: string; index: number }) {+ return (+ <CrmStageIcon optionId={props.id} index={props.index} class="size-3.5" />+ );+}++function StageRow(props: { id: string; label: string; index: number }) {+ return (+ <div class="flex min-h-12 items-center gap-3 px-4 py-3">+ <StageIcon id={props.id} index={props.index} />+ <span class="min-w-0 truncate text-sm text-ink">{props.label}</span>+ </div>+ );+}++/** Reads as plain text until hovered or focused, so the list stays a list. */+function InlineStageInput(props: {+ value: string;+ placeholder: string;+ label: string;+ onInput: (value: string) => void;+ onKeyDown: (e: KeyboardEvent & { currentTarget: HTMLInputElement }) => void;+}) {+ return (+ <input+ type="text"+ value={props.value}+ aria-label={props.label}+ placeholder={props.placeholder}+ onInput={(e) => props.onInput(e.currentTarget.value)}+ onKeyDown={(e) => props.onKeyDown(e)}+ class="-mx-2 h-8 min-w-0 flex-1 truncate rounded-md bg-transparent px-2 text-sm text-ink outline-none transition-colors placeholder:text-ink-placeholder not-touch:hover:bg-hover focus:bg-control focus-visible:ring-2 focus-visible:ring-edge-muted"+ />+ );+}+function StageEditorRow(props: {id: string;label: string;draft: string | undefined;index: number;count: number;- disabled: boolean;pending: boolean;onDraft: (value: string | undefined) => void;onRename: (value: string) => void;@@ -333,7 +367,6 @@ function StageEditorRow(props: {const isLastStage = () => props.count <= 1;const isFirst = () => props.index === 0;const isLast = () => props.index === props.count - 1;- const canMove = () => !props.disabled && !props.pending;const reorderMode = useStageReorderMode();const [dndState] = useDragDropContext() ?? [];@@ -341,7 +374,7 @@ function StageEditorRow(props: {reorderMode === 'drag'? createSortable(props.id, {dragType: 'stage',- overlayIcon: StageDot,+ overlayIcon: () => <StageIcon id={props.id} index={props.index} />,get name() {return props.label;},@@ -351,7 +384,7 @@ function StageEditorRow(props: {const handleKeyDown = (e: KeyboardEvent) => {if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return;e.preventDefault();- if (!canMove()) return;+ if (props.pending) return;if (e.key === 'ArrowUp' && !isFirst()) props.onMove(-1);if (e.key === 'ArrowDown' && !isLast()) props.onMove(1);};@@ -361,32 +394,33 @@ function StageEditorRow(props: {ref={sortable?.ref}style={sortable ? maybeTransformStyle(sortable.transform) : undefined}class={cn(- 'flex items-center gap-2 px-6 py-2.5',+ 'flex min-h-12 items-center gap-3 px-4 py-2',// Shift rows out of the way while a drag is live; snap when it ends// so the settled order doesn't animate twice.!!dndState?.active.draggable && 'transition-transform',sortable?.isActiveDraggable && 'opacity-40')}>- <Show when={sortable && !props.disabled} fallback={<StageDot />}>+ <Show when={sortable}><Tooltip label="Drag to reorder, or use the arrow keys"><Button{...(sortable?.dragActivators ?? {})}aria-label={`Reorder ${props.label}. Press the up or down arrow keys to move it.`}variant="ghost"size="icon-sm"- class="-ml-1.5 cursor-grab touch-none active:cursor-grabbing"+ class="-mx-1.5 cursor-grab touch-none text-ink-extra-muted active:cursor-grabbing"onKeyDown={handleKeyDown}><DotsSixVerticalIcon class="size-4" /></Button></Tooltip></Show>- <input- type="text"+ <StageIcon id={props.id} index={props.index} />+ <InlineStageInputvalue={value()}- disabled={props.disabled}- onInput={(e) => props.onDraft(e.currentTarget.value)}+ label={`Rename ${props.label}`}+ placeholder="Stage name"+ onInput={(next) => props.onDraft(next)}onKeyDown={(e) => {if (e.key === 'Enter') {commit();@@ -395,45 +429,44 @@ function StageEditorRow(props: {e.currentTarget.blur();}}}- placeholder="Stage name"- class="settings-input flex-1 min-w-0"/>- <Show when={isEditing()}>- <Tooltip label="Save">- <Button- aria-label="Save stage name"- variant="accent"- size="icon-sm"- class="shrink-0"- disabled={props.pending || !hasChanged()}- onClick={commit}- >- <Show when={props.pending} fallback={<CheckIcon class="size-4" />}>- <SpinnerIcon class="size-4 animate-spin" />- </Show>- </Button>- </Tooltip>- <Tooltip label="Cancel">- <Button- aria-label="Cancel rename"- variant="ghost"- size="icon-sm"- class="shrink-0"- disabled={props.pending}- onClick={cancel}- >- <XIcon class="size-4" />- </Button>- </Tooltip>- </Show>- <div class="flex items-center gap-0.5 shrink-0">+ <div class="flex shrink-0 items-center gap-0.5">+ <Show when={isEditing()}>+ <Tooltip label="Save">+ <Button+ aria-label="Save stage name"+ variant="accent"+ size="icon-sm"+ disabled={props.pending || !hasChanged()}+ onClick={commit}+ >+ <Show+ when={props.pending}+ fallback={<CheckIcon class="size-4" />}+ >+ <SpinnerIcon class="size-4 animate-spin" />+ </Show>+ </Button>+ </Tooltip>+ <Tooltip label="Cancel">+ <Button+ aria-label="Cancel rename"+ variant="ghost"+ size="icon-sm"+ disabled={props.pending}+ onClick={cancel}+ >+ <XIcon class="size-4" />+ </Button>+ </Tooltip>+ </Show><Show when={reorderMode === 'buttons'}><Tooltip label="Move up"><Buttonaria-label={`Move ${props.label} up`}variant="ghost"size="icon-sm"- disabled={!canMove() || isFirst()}+ disabled={props.pending || isFirst()}onClick={() => props.onMove(-1)}><CaretUpIcon class="size-4" />@@ -444,7 +477,7 @@ function StageEditorRow(props: {aria-label={`Move ${props.label} down`}variant="ghost"size="icon-sm"- disabled={!canMove() || isLast()}+ disabled={props.pending || isLast()}onClick={() => props.onMove(1)}><CaretDownIcon class="size-4" />@@ -460,7 +493,8 @@ function StageEditorRow(props: {aria-label={`Delete ${props.label}`}variant="ghost"size="icon-sm"- disabled={props.disabled || props.pending || isLastStage()}+ class="text-ink-extra-muted not-touch:hover:text-failure"+ disabled={props.pending || isLastStage()}onClick={() => props.onDelete()}><TrashIcon class="size-4" />@@ -471,11 +505,10 @@ function StageEditorRow(props: {);}-function DealStagesSection() {+function StagesSection() {const dealStages = useDealStages();const crmPermissions = useCrmPermissions();const teamCrmConfig = useTeamCrmConfig();- const closedStageIds = useClosedStageIds(dealStages.stages);const replaceMutation = useReplaceCrmStagesMutation();const resetMutation = useResetCrmStagesMutation();@@ -490,7 +523,6 @@ function DealStagesSection() {pending,loading,failed,- busy,blocked,drafts,setDrafts,@@ -504,12 +536,10 @@ function DealStagesSection() {handleAddStage,handleDeleteStage,handleReset,- toggleClosedStage,} = createStageEditor({dealStages,crmPermissions,teamCrmConfig,- closedStageIds,replaceMutation,resetMutation,onSuccess: useCrmContext().feedback.success,@@ -529,76 +559,62 @@ function DealStagesSection() {);});+ const editing = () => dealStages.isCustomized() && canEdit();+ const description = () => {+ const scope =+ 'The Stage options on companies. New pipelines start with these stages.';+ if (loading() || canEdit()) return scope;+ return crmPermissions.permissions().editStages === 'owner'+ ? `${scope} Only the team owner can change them.`+ : `${scope} Only team admins can change them.`;+ };+return (<SettingsSection- title="Deal stages"- description="The pipeline stages deals move through on the CRM board."+ title="Stages"+ description={description()}actions={- <Show when={dealStages.isCustomized() && canEdit()}>- <Button- variant="outline"- size="sm"- disabled={blocked()}- onClick={() => setShowResetModal(true)}+ <Show when={canEdit() && !loading() && !failed()}>+ <Show+ when={dealStages.isCustomized()}+ fallback={+ <Button+ variant="outline"+ size="sm"+ disabled={pending()}+ onClick={handleCustomize}+ >+ <Show when={pending()} fallback="Customize">+ <SpinnerIcon class="size-4 animate-spin" />+ </Show>+ </Button>+ }>- Reset to defaults- </Button>+ <Button+ variant="outline"+ size="sm"+ disabled={blocked()}+ onClick={() => setShowResetModal(true)}+ >+ Reset to defaults+ </Button>+ </Show></Show>}>- <Show- when={!loading() && !failed()}- fallback={- <SettingsCard>- <Show- when={failed()}- fallback={- <div class="animate-pulse bg-skeleton rounded h-4 w-32 m-6" />- }- >- <div class="px-6 py-4 text-sm text-ink-muted">- Deal stages could not be loaded. Reload to try again.- </div>- </Show>- </SettingsCard>- }- >- <Show- when={dealStages.isCustomized()}- fallback={- <SettingsCard>- <div class="flex flex-col gap-1 px-6 py-4">- <For each={dealStages.stages()}>- {(stage) => (- <div class="flex items-center gap-2 py-1">- <StageDot />- <span class="text-sm text-ink">{stage.label}</span>- </div>- )}- </For>- </div>- <div class="flex items-center justify-between gap-4 px-6 py-3.5">- <p class="text-xs text-ink-muted">- Stages are Macro's defaults. Customize them for your team.- </p>- <Show when={canEdit()}>- <Button- variant="outline"- size="sm"- class="shrink-0"- disabled={busy()}- onClick={handleCustomize}- >- <Show when={pending()} fallback="Customize stages">- <SpinnerIcon class="size-4 animate-spin" />- </Show>- </Button>- </Show>- </div>- </SettingsCard>- }- >- <SettingsCard>+ <SettingsCard>+ <Switch>+ <Match when={failed()}>+ <div class="px-4 py-4 text-sm text-ink-muted">+ Stages could not be loaded. Reload to try again.+ </div>+ </Match>+ <Match when={loading()}>+ <div class="px-4 py-4">+ <div class="h-4 w-32 animate-pulse rounded bg-skeleton" />+ </div>+ </Match>+ <Match when={editing()}><StageList ids={stageIds()}><For each={orderedStages()}>{(stage, index) => (@@ -608,8 +624,7 @@ function DealStagesSection() {draft={drafts[stage.id]}index={index()}count={orderedStages().length}- disabled={!canEdit()}- pending={busy()}+ pending={pending()}onDraft={(value) => setDrafts(stage.id, value)}onRename={(label) => handleRename(index(), label)}onMove={(direction) => handleMove(index(), direction)}@@ -618,98 +633,77 @@ function DealStagesSection() {)}</For></StageList>- <Show when={canEdit()}>- <div class="flex items-center gap-2 px-6 py-2.5">- <PlusIcon class="size-4 shrink-0 text-ink-muted" />- <input- type="text"- value={newStageName()}- onInput={(e) => setNewStageName(e.currentTarget.value)}- onKeyDown={(e) => {- if (e.key === 'Enter') handleAddStage();- }}- placeholder="Add stage"- class="settings-input flex-1 min-w-0"- />- <Button- variant="outline"- size="sm"- class="shrink-0"- disabled={newStageName().trim() === '' || busy()}- onClick={handleAddStage}- >- Add- </Button>- </div>- </Show>- </SettingsCard>- </Show>- <div aria-live="polite" class="sr-only">- {announcement()}- </div>-- <SettingsCard>- <SettingsRow- align="start"- label="Closed stages"- description="Stages that count as closed deals. Moving deals out of a closed stage can be restricted under Permissions."- >- <div class="flex flex-col items-start gap-1.5">- <For each={orderedStages()}>- {(stage) => (- <Checkbox- checked={closedStageIds().has(stage.id)}- onChange={() => toggleClosedStage(stage.id)}- disabled={!canEdit() || blocked()}- class="cursor-default"- >- <Checkbox.Control>- <Checkbox.Indicator />- </Checkbox.Control>- <Checkbox.Label class="text-sm text-ink">- {stage.label}- </Checkbox.Label>- </Checkbox>- )}- </For>+ <div class="flex min-h-12 items-center gap-3 px-4 py-2">+ <PlusIcon class="size-3.5 shrink-0 text-ink-muted" />+ <InlineStageInput+ value={newStageName()}+ label="New stage name"+ placeholder="Add stage"+ onInput={setNewStageName}+ onKeyDown={(e) => {+ if (e.key === 'Enter') handleAddStage();+ }}+ />+ <Button+ variant="outline"+ size="sm"+ class="shrink-0"+ disabled={newStageName().trim() === '' || pending()}+ onClick={handleAddStage}+ >+ Add+ </Button></div>- </SettingsRow>- </SettingsCard>- </Show>+ </Match>+ <Match when={true}>+ <For each={dealStages.stages()}>+ {(stage, index) => (+ <StageRow id={stage.id} label={stage.label} index={index()} />+ )}+ </For>+ </Match>+ </Switch>+ </SettingsCard>+ <div aria-live="polite" class="sr-only">+ {announcement()}+ </div><ConfirmDialogopen={!!stageToDelete()}- title="Delete Stage"- confirmLabel="Delete Stage"+ onOpenChange={(open) => !open && setStageToDelete(null)}+ title="Delete stage"+ tone="danger"+ confirmLabel="Delete"pending={replaceMutation.isPending}onConfirm={handleDeleteStage}- onClose={() => setStageToDelete(null)}- >- <p>- Are you sure you want to delete{' '}- <span class="font-medium">{stageToDelete()?.label ?? ''}</span>?- Companies currently in this stage lose it and show under No stage on- the board.- </p>- </ConfirmDialog>+ body={+ <>+ Companies at{' '}+ <span class="font-medium text-ink">+ {stageToDelete()?.label ?? ''}+ </span>{' '}+ lose their stage and show under No stage. Pipelines keep their own+ stages.+ </>+ }+ /><ConfirmDialogopen={showResetModal()}- title="Reset Stages"- confirmLabel="Reset to Defaults"+ onOpenChange={setShowResetModal}+ title="Reset stages"+ tone="danger"+ confirmLabel="Reset to defaults"pending={resetMutation.isPending}onConfirm={handleReset}- onClose={() => setShowResetModal(false)}- >- <p>- This removes your team's custom stage set and returns everyone to- Macro's default stages.- </p>- <p class="text-sm text-ink-muted">- Companies keep their stored stage values, and stages whose names match- a default continue to display as before.- </p>- </ConfirmDialog>+ body={+ <>+ Your team returns to Macro's default stages. Companies keep their+ stored stage values, and stages whose names match a default display+ as before.+ </>+ }+ /></SettingsSection>);}@@ -739,11 +733,11 @@ function CrmContent() {<Show when={teamQuery.data} fallback={<NoTeamState />}><SettingsPagetitle="CRM"- description="Enable your team's CRM and shape its deal pipeline."+ description="Turn your team's CRM on or off and choose its stages."><CrmEnablementSection /><Show when={teamQuery.data?.team.crm_enabled}>- <DealStagesSection />+ <StagesSection /></Show></SettingsPage></Show>diff --git a/apps/web/src/features/crm/views/use-crm.ts b/apps/web/src/features/crm/views/use-crm.tsindex 9ef2171023..fb6e0d0c23 100644--- a/apps/web/src/features/crm/views/use-crm.ts+++ b/apps/web/src/features/crm/views/use-crm.ts@@ -20,9 +20,6 @@ export const useCrmPermissions = (export const useDealStages = (...args: Parameters<CrmContext['createDealStages']>) => useCrmContext().createDealStages(...args);-export const useClosedStageIds = (- ...args: Parameters<CrmContext['createClosedStageIds']>-) => useCrmContext().createClosedStageIds(...args);export const usePersonalCrmViews = (...args: Parameters<CrmContext['createPersonalViews']>) => useCrmContext().createPersonalViews(...args);diff --git a/apps/web/src/features/settings/core/settings-search.ts b/apps/web/src/features/settings/core/settings-search.tsindex 1be422c0ec..99d258c315 100644--- a/apps/web/src/features/settings/core/settings-search.ts+++ b/apps/web/src/features/settings/core/settings-search.ts@@ -22,15 +22,15 @@ export type SettingsSearchResult = Setting & {const SETTINGS: Setting[] = [{tab: 'CRM',- title: 'Deal stages',- target: 'Deal stages',- keywords: 'pipeline reorder status closed stages sales',+ title: 'Stages',+ target: 'Stages',+ keywords: 'company deal pipeline reorder rename status sales',},{tab: 'CRM',- title: 'Enable CRM',- target: 'General',- keywords: 'disable customers contacts companies team',+ title: 'Team CRM',+ target: 'Team CRM',+ keywords: 'enable disable customers contacts companies team',},{tab: 'Shortcuts',diff --git a/docs/agent-guide/settings.md b/docs/agent-guide/settings.mdindex 33af39d05a..83d0d57870 100644--- a/docs/agent-guide/settings.md+++ b/docs/agent-guide/settings.md@@ -431,10 +431,11 @@ and admins/owners can move a seat between Pro and Max with the `Seat plan`menu; Max upgrades are immediate and prorated, Pro downgrades start at renewal.**Keep Max** appears only for a confirmed pending downgrade and cancels it;failed scheduled-plan reads offer **Try again**, while teams without applicable-scheduled plans show no retry notice). CRM (enable/disable; once enabled, a `Deal stages` section-with `Customize stages`, inline rename, reorder by drag handle or arrow keys (up/down-buttons on touch), delete, `Add stage`, `Reset to defaults`, and `Closed stages`-checkboxes, editable by the role set as `edit_stages_role`)+scheduled plans show no retry notice). CRM (a `Team CRM` switch that admins use to enable or disable it;+once enabled, a `Stages` section for the company Stage options that new pipelines+also start with, with `Customize`, inline rename, reorder by drag handle or arrow+keys (up/down buttons on touch), delete, `Add stage`, and `Reset to defaults`,+editable by the role set as `edit_stages_role`)`Agents` unifies agent definitions and runtime configuration in one page, also used by the Agents workspace. Its `Agents` section lists team and private agents. `New agent` / `Edit <name>` open full-page forms groupedProfile, Behavior, Runtime, Connections, Channels, Share. Connections is a radio pair: