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
feat(web): deal stages editor in CRM settings (#6244)
Panat Taranatd8ff468ff13e
diff --git a/apps/web/src/components/app/ItemDragAndDrop.tsx b/apps/web/src/components/app/ItemDragAndDrop.tsxindex fa39064dd9..1d38951c14 100644--- a/apps/web/src/components/app/ItemDragAndDrop.tsx+++ b/apps/web/src/components/app/ItemDragAndDrop.tsx@@ -87,6 +87,7 @@ function ItemDragOverlay() {if (data.dragType === 'favorite') {return data.iconType as EntityIconSelector;}+ if (data.dragType === 'stage') return 'default';return getEntityIconType(data as EntityDragData);});@@ -98,6 +99,12 @@ function ItemDragOverlay() {return data.dmRecipientId as string | undefined;});+ // Deal stage rows in CRM settings (see StageDragData in settings/Crm)+ // carry no entity; their chip is the stage dot plus the label.+ const isStage = createMemo(+ () => activeDraggable()?.data.dragType === 'stage'+ );+const centeredOnPointerStyle = createMemo(() => {const overlay = state?.active.overlay;const sensor = state?.active.sensor;@@ -116,17 +123,24 @@ function ItemDragOverlay() {><div class="flex flex-row items-center gap-2"><Show- when={dmRecipientId()}- fallback={<EntityIcon size="xs" targetType={iconType()} />}+ when={!isStage()}+ fallback={+ <span class="size-2 shrink-0 rounded-full bg-accent/70" />+ }>- {(recipientId) => (- <UserIcon- id={recipientId()}- size="sm"- suppressClick- showTooltip={false}- />- )}+ <Show+ when={dmRecipientId()}+ fallback={<EntityIcon size="xs" targetType={iconType()} />}+ >+ {(recipientId) => (+ <UserIcon+ id={recipientId()}+ size="sm"+ suppressClick+ showTooltip={false}+ />+ )}+ </Show></Show><TruncatedText size="xs">{activeDraggable()?.data.name}diff --git a/apps/web/src/features/companies/crm/deal-stages.ts b/apps/web/src/features/companies/crm/deal-stages.tsindex 5838b1d7d0..9af36b16dd 100644--- a/apps/web/src/features/companies/crm/deal-stages.ts+++ b/apps/web/src/features/companies/crm/deal-stages.ts@@ -3,12 +3,12 @@** The builtin Stage property is a system definition whose options cannot be* modified through the API, so team customization works by giving the team- * its own team-scoped `Stage` property definition (created from CRM- * settings). When that definition exists, every stage surface — kanban- * columns, list cells, filters, grouping, the company panel — reads and- * writes it instead of the system property; otherwise the seeded system- * stages apply. `useDealStages` is the single source of truth for which set- * is active.+ * its own team-scoped `Deal Stage` property definition, written only through+ * `PUT /crm/stages` from CRM settings. When that definition exists, every+ * stage surface (kanban columns, list cells, filters, grouping, the company+ * panel) reads and writes it instead of the system property; otherwise the+ * seeded system stages apply. `useDealStages` is the single source of truth+ * for which set is active.*/// Imports come from the concrete @entity modules, not the barrel: this@@ -73,6 +73,8 @@ export type DealStages = {/** Label for an option id in the active set (legacy system ids included). */stageLabel: (optionId: string) => string | undefined;isLoading: Accessor<boolean>;+ /** The definitions failed to load and nothing is cached. */+ isError: Accessor<boolean>;};/** Minimal company shape needed to read stage values. */@@ -296,5 +298,7 @@ export function useDealStages(): DealStages {stageLabel,isLoading: () =>teamDefinitionsQuery.isLoading || teamCrmConfig.isLoading(),+ isError: () =>+ teamDefinitionsQuery.isError && teamDefinitionsQuery.data === undefined,};}diff --git a/apps/web/src/features/companies/crm/team-crm-config.ts b/apps/web/src/features/companies/crm/team-crm-config.tsindex d1c6ad3e64..8cd93436ab 100644--- a/apps/web/src/features/companies/crm/team-crm-config.ts+++ b/apps/web/src/features/companies/crm/team-crm-config.ts@@ -21,7 +21,7 @@ import type { UpdateCrmTeamSettingsRequest } from '@service-storage/generated/scimport { useMutation, useQuery, useQueryClient } from '@tanstack/solid-query';import { type Accessor, createMemo } from 'solid-js';-const CRM_TEAM_SETTINGS_QUERY_KEY = ['crm', 'team-settings'] as const;+export const CRM_TEAM_SETTINGS_QUERY_KEY = ['crm', 'team-settings'] as const;/*** Minimum team role required for a CRM capability. Team members are@@ -53,7 +53,8 @@ export type TeamCrmConfig = {/*** 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.+ * 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. */@@ -157,6 +158,7 @@ export function useTeamCrmConfig() {return {config,isLoading: () => settingsQuery.isLoading,+ isError: () => settingsQuery.isError && settingsQuery.data === undefined,update: updateMutation,};}@@ -235,7 +237,7 @@ export function useClosedStageIds(const { config } = useTeamCrmConfig();return createMemo(() => {const explicit = config().closedStageIds;- if (explicit && explicit.length > 0) return new Set(explicit);+ if (explicit) return new Set(explicit);return new Set(stages().filter((stage) => DEFAULT_CLOSED_STAGE_LABEL.test(stage.label))diff --git a/apps/web/src/features/settings/Crm.tsx b/apps/web/src/features/settings/Crm.tsxindex aca2958177..a092219b50 100644--- a/apps/web/src/features/settings/Crm.tsx+++ b/apps/web/src/features/settings/Crm.tsx@@ -1,10 +1,27 @@-/** CRM settings tab: team admins enable or disable the CRM here. */+/** CRM settings tab: enablement, deal stages, and the closed-stage set. */+import { type DealStage, useDealStages } from '@companies/crm/deal-stages';+import {+ useClosedStageIds,+ useCrmPermissions,+ useTeamCrmConfig,+} from '@companies/crm/team-crm-config';import { toast } from '@core/component/Toast/Toast';import { SERVER_HOSTS } from '@core/constant/servers';+import { isTouchDevice } from '@core/mobile/isTouchDevice';import { throwOnErr } from '@core/util/result';+import CaretDownIcon from '@phosphor/caret-down.svg';+import CaretUpIcon from '@phosphor/caret-up.svg';+import CheckIcon from '@phosphor/check.svg';+import DotsSixVerticalIcon from '@phosphor/dots-six-vertical.svg';+import PlusIcon from '@phosphor/plus.svg';import SpinnerIcon from '@phosphor/spinner.svg';+import TrashIcon from '@phosphor/trash.svg';import XIcon from '@phosphor/x.svg';+import {+ useReplaceCrmStagesMutation,+ useResetCrmStagesMutation,+} from '@queries/crm/stages';import {invalidateUserTeams,useCurrentTeamQuery,@@ -13,9 +30,26 @@ import {import { fetchWithAuth } from '@service-auth/fetch';import type { PatchTeamCrmSettingsRequest } from '@service-auth/generated/schemas/patchTeamCrmSettingsRequest';import type { PatchTeamCrmSettingsResponse } from '@service-auth/generated/schemas/patchTeamCrmSettingsResponse';+import type { CrmStageInput } from '@service-storage/generated/schemas/crmStageInput';+import type { CrmStagesResponse } from '@service-storage/generated/schemas/crmStagesResponse';import { useMutation } from '@tanstack/solid-query';-import { Button, Dialog, Panel, Tooltip } from '@ui';-import { createSignal, type JSX, Show, Suspense } from 'solid-js';+import {+ createSortable,+ maybeTransformStyle,+ SortableProvider,+ useDragDropContext,+ useSortableContext,+} from '@thisbeyond/solid-dnd';+import { Button, Checkbox, cn, Dialog, Panel, Tooltip } from '@ui';+import {+ createMemo,+ createSignal,+ For,+ type JSX,+ Show,+ Suspense,+} from 'solid-js';+import { createStore } from 'solid-js/store';import {SettingsCard,SettingsPage,@@ -290,6 +324,577 @@ function CrmEnablementSection() {);}+/* ------------------------------------------------------------------ */+/* Deal stages */+/* ------------------------------------------------------------------ */++function StageDot() {+ return <span class="size-2 shrink-0 rounded-full bg-accent/70" />;+}++/**+ * Drag data carried by stage row sortables. Distinct from `EntityDragData`+ * so entity drop consumers ignore stage drags; the global `ItemDragOverlay`+ * branches on it to render the stage chip.+ */+export type StageDragData = {+ dragType: 'stage';+ name: string;+};++/**+ * Reordering follows the GOV.UK reorderable list: a drag handle with pointer+ * drag and arrow-key moves on desktop, plain up/down buttons on touch. The+ * pointer sensor in solid-dnd listens to mouse events only, so touch gets the+ * buttons rather than a handle that would fight the page scroll.+ */+function useStageReorderMode(): 'drag' | 'buttons' {+ const canDrag =+ useDragDropContext() !== null && useSortableContext() !== null;+ return canDrag && !isTouchDevice() ? 'drag' : 'buttons';+}++/** Wraps the rows in a sortable context when the app-wide drag provider is present. */+function StageList(props: { ids: string[]; children: JSX.Element }) {+ const dnd = useDragDropContext();+ return (+ <Show when={dnd !== null} fallback={props.children}>+ <SortableProvider ids={props.ids}>{props.children}</SortableProvider>+ </Show>+ );+}++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;+ onMove: (direction: -1 | 1) => void;+ onDelete: () => void;+}) {+ const value = () => props.draft ?? props.label;+ const hasChanged = () => {+ const edited = props.draft;+ return (+ edited !== undefined &&+ edited.trim() !== '' &&+ edited.trim() !== props.label+ );+ };+ const commit = () => {+ if (!hasChanged() || props.pending) return;+ props.onRename(value().trim());+ };+ const cancel = () => props.onDraft(undefined);+ const isEditing = () => props.draft !== undefined;+ 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() ?? [];+ const sortable =+ reorderMode === 'drag'+ ? createSortable(props.id, {+ dragType: 'stage',+ get name() {+ return props.label;+ },+ } satisfies StageDragData)+ : undefined;++ const handleKeyDown = (e: KeyboardEvent) => {+ if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return;+ e.preventDefault();+ if (!canMove()) return;+ if (e.key === 'ArrowUp' && !isFirst()) props.onMove(-1);+ if (e.key === 'ArrowDown' && !isLast()) props.onMove(1);+ };++ return (+ <div+ ref={sortable?.ref}+ style={sortable ? maybeTransformStyle(sortable.transform) : undefined}+ class={cn(+ 'flex items-center gap-2 px-6 py-2.5',+ // 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 />}>+ <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="rounded-xs -ml-1.5 cursor-grab touch-none active:cursor-grabbing"+ onKeyDown={handleKeyDown}+ >+ <DotsSixVerticalIcon class="size-4" />+ </Button>+ </Tooltip>+ </Show>+ <input+ type="text"+ value={value()}+ disabled={props.disabled}+ onInput={(e) => props.onDraft(e.currentTarget.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ commit();+ } else if (e.key === 'Escape') {+ cancel();+ 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="rounded-xs 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="rounded-xs shrink-0"+ disabled={props.pending}+ onClick={cancel}+ >+ <XIcon class="size-4" />+ </Button>+ </Tooltip>+ </Show>+ <div class="flex items-center gap-0.5 shrink-0">+ <Show when={reorderMode === 'buttons'}>+ <Tooltip label="Move up">+ <Button+ aria-label={`Move ${props.label} up`}+ variant="ghost"+ size="icon-sm"+ class="rounded-xs"+ disabled={!canMove() || isFirst()}+ onClick={() => props.onMove(-1)}+ >+ <CaretUpIcon class="size-4" />+ </Button>+ </Tooltip>+ <Tooltip label="Move down">+ <Button+ aria-label={`Move ${props.label} down`}+ variant="ghost"+ size="icon-sm"+ class="rounded-xs"+ disabled={!canMove() || isLast()}+ onClick={() => props.onMove(1)}+ >+ <CaretDownIcon class="size-4" />+ </Button>+ </Tooltip>+ </Show>+ <Tooltip+ label={+ isLastStage() ? 'At least one stage is required' : 'Delete stage'+ }+ >+ <Button+ aria-label={`Delete ${props.label}`}+ variant="ghost"+ size="icon-sm"+ class="rounded-xs"+ disabled={props.disabled || props.pending || isLastStage()}+ onClick={() => props.onDelete()}+ >+ <TrashIcon class="size-4" />+ </Button>+ </Tooltip>+ </div>+ </div>+ );+}++function toStageInputs(stages: DealStage[]): CrmStageInput[] {+ return stages.map((stage) => ({ id: stage.id, label: stage.label }));+}++function DealStagesSection() {+ const dealStages = useDealStages();+ const crmPermissions = useCrmPermissions();+ const teamCrmConfig = useTeamCrmConfig();+ const closedStageIds = useClosedStageIds(dealStages.stages);+ const replaceMutation = useReplaceCrmStagesMutation();+ const resetMutation = useResetCrmStagesMutation();++ const [newStageName, setNewStageName] = createSignal('');+ const [stageToDelete, setStageToDelete] = createSignal<DealStage | null>(+ null+ );+ const [showResetModal, setShowResetModal] = createSignal(false);++ const canEdit = () => crmPermissions.canEditStages();+ 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 [drafts, setDrafts] = createStore<Record<string, string | undefined>>(+ {}+ );++ // Row objects are reused across refetches when their id and label are+ // unchanged, so `<For>` keeps each row's DOM (and a focused reorder handle)+ // instead of remounting the whole list after every save.+ const stableStages = createMemo<DealStage[]>((previous) => {+ const byId = new Map(previous.map((stage) => [stage.id, stage]));+ return dealStages.stages().map((stage) => {+ const existing = byId.get(stage.id);+ return existing?.label === stage.label ? existing : stage;+ });+ }, []);++ // Order shown while a reorder is in flight, so a drop or arrow-key move+ // lands immediately instead of snapping back until the refetch resolves.+ const [pendingOrder, setPendingOrder] = createSignal<string[] | null>(null);+ const orderedStages = createMemo<DealStage[]>(() => {+ const stages = stableStages();+ const order = pendingOrder();+ if (!order) return stages;+ const byId = new Map(stages.map((stage) => [stage.id, stage]));+ const ordered = order.flatMap((id) => byId.get(id) ?? []);+ return ordered.length === stages.length ? ordered : stages;+ });+ const stageIds = () => orderedStages().map((stage) => stage.id);++ /** Screen reader announcement for keyboard and drag reorders. */+ const [announcement, setAnnouncement] = createSignal('');++ const replace = (+ stages: CrmStageInput[],+ options?: {+ onSuccess?: (result: CrmStagesResponse) => void;+ onSettled?: () => void;+ successMessage?: string;+ }+ ) => {+ if (blocked()) return;+ replaceMutation.mutate(stages, {+ onSuccess: (result) => {+ if (options?.successMessage) toast.success(options.successMessage);+ options?.onSuccess?.(result);+ },+ onSettled: () => options?.onSettled?.(),+ });+ };++ 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;+ 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),+ });+ },+ }+ );+ };++ const handleRename = (index: number, label: string) => {+ const stages = toStageInputs(orderedStages());+ const stage = stages[index];+ if (!stage?.id) return;+ const id = stage.id;+ stages[index] = { ...stage, label };+ replace(stages, { onSuccess: () => setDrafts(id, undefined) });+ };++ const reorder = (fromIndex: number, toIndex: number) => {+ const stages = orderedStages();+ const moved = stages[fromIndex];+ if (!moved || toIndex < 0 || toIndex >= stages.length) return;+ if (fromIndex === toIndex || blocked()) return;+ const next = stages.slice();+ next.splice(toIndex, 0, ...next.splice(fromIndex, 1));+ setPendingOrder(next.map((stage) => stage.id));+ setAnnouncement(+ `${moved.label} moved to position ${toIndex + 1} of ${stages.length}`+ );+ replace(toStageInputs(next), { onSettled: () => setPendingOrder(null) });+ };++ const handleMove = (index: number, direction: -1 | 1) =>+ reorder(index, index + direction);++ // Settings render inside the app-wide DragDropProvider (ItemDndProvider);+ // register on its events rather than mounting a nested provider.+ const [, dndActions] = useDragDropContext() ?? [];+ dndActions?.onDragEnd(({ draggable, droppable }) => {+ if (draggable.data.dragType !== 'stage') return;+ // Dropping outside the list leaves the order unchanged.+ if (!droppable || droppable.data.dragType !== 'stage') return;+ const ids = stageIds();+ reorder(+ ids.indexOf(String(draggable.id)),+ ids.indexOf(String(droppable.id))+ );+ });++ const handleAddStage = () => {+ const label = newStageName().trim();+ if (label === '') return;+ replace([...toStageInputs(orderedStages()), { label }], {+ onSuccess: () => setNewStageName(''),+ });+ };++ const handleDeleteStage = () => {+ const stage = stageToDelete();+ if (!stage) return;+ replace(toStageInputs(orderedStages().filter((s) => s.id !== stage.id)), {+ onSuccess: () => setStageToDelete(null),+ });+ };++ const handleReset = () => {+ if (blocked()) return;+ resetMutation.mutate(undefined, {+ onSuccess: () => {+ setShowResetModal(false);+ toast.success('Stages reset to Macro defaults');+ },+ });+ };++ 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 (+ <SettingsSection+ title="Deal stages"+ description="The pipeline stages deals move through on the CRM board."+ actions={+ <Show when={dealStages.isCustomized() && canEdit()}>+ <Button+ variant="outline"+ size="sm"+ class="rounded-xs"+ disabled={blocked()}+ onClick={() => setShowResetModal(true)}+ >+ Reset to defaults+ </Button>+ </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="rounded-xs shrink-0"+ disabled={busy()}+ onClick={handleCustomize}+ >+ <Show when={pending()} fallback="Customize stages">+ <SpinnerIcon class="size-4 animate-spin" />+ </Show>+ </Button>+ </Show>+ </div>+ </SettingsCard>+ }+ >+ <SettingsCard>+ <StageList ids={stageIds()}>+ <For each={orderedStages()}>+ {(stage, index) => (+ <StageEditorRow+ id={stage.id}+ label={stage.label}+ draft={drafts[stage.id]}+ index={index()}+ count={orderedStages().length}+ disabled={!canEdit()}+ pending={busy()}+ onDraft={(value) => setDrafts(stage.id, value)}+ onRename={(label) => handleRename(index(), label)}+ onMove={(direction) => handleMove(index(), direction)}+ onDelete={() => setStageToDelete(stage)}+ />+ )}+ </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="rounded-xs 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>+ </SettingsRow>+ </SettingsCard>+ </Show>++ <ConfirmDialog+ open={!!stageToDelete()}+ title="Delete Stage"+ confirmLabel="Delete Stage"+ 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>++ <ConfirmDialog+ open={showResetModal()}+ title="Reset Stages"+ 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>+ </SettingsSection>+ );+}+/* ------------------------------------------------------------------ *//* Page *//* ------------------------------------------------------------------ */@@ -315,9 +920,12 @@ function CrmContent() {<Show when={teamQuery.data} fallback={<NoTeamState />}><SettingsPagetitle="CRM"- description="Enable or disable your team's CRM."+ description="Enable your team's CRM and shape its deal pipeline."><CrmEnablementSection />+ <Show when={teamQuery.data?.team.crm_enabled}>+ <DealStagesSection />+ </Show></SettingsPage></Show>);diff --git a/apps/web/src/lib/queries/crm/stages.ts b/apps/web/src/lib/queries/crm/stages.tsnew file mode 100644index 0000000000..c66ade3741--- /dev/null+++ b/apps/web/src/lib/queries/crm/stages.ts@@ -0,0 +1,43 @@+import { CRM_TEAM_SETTINGS_QUERY_KEY } from '@companies/crm/team-crm-config';+import { toast } from '@core/component/Toast/Toast';+import { throwOnErr } from '@core/util/result';+import { storageServiceClient } from '@service-storage/client';+import type { CrmStageInput } from '@service-storage/generated/schemas/crmStageInput';+import { useMutation } from '@tanstack/solid-query';+import { queryClient } from '../client';+import { soupKeys } from '../soup/keys';++function invalidateStageReaders() {+ return Promise.all([+ queryClient.invalidateQueries({+ predicate: ({ queryKey }) =>+ queryKey.includes('properties') && queryKey.includes('definitions'),+ }),+ queryClient.invalidateQueries({ queryKey: soupKeys._def }),+ queryClient.invalidateQueries({ queryKey: CRM_TEAM_SETTINGS_QUERY_KEY }),+ ]);+}++export function useReplaceCrmStagesMutation() {+ return useMutation(() => ({+ mutationFn: (stages: CrmStageInput[]) =>+ throwOnErr(() => storageServiceClient.replaceCrmTeamStages({ stages })),+ onSuccess: () => invalidateStageReaders(),+ onError: (error: Error) => {+ console.error('Failed to update deal stages', error);+ toast.failure('Failed to update deal stages');+ },+ }));+}++export function useResetCrmStagesMutation() {+ return useMutation(() => ({+ mutationFn: () =>+ throwOnErr(() => storageServiceClient.resetCrmTeamStages()),+ onSuccess: () => invalidateStageReaders(),+ onError: (error: Error) => {+ console.error('Failed to reset deal stages', error);+ toast.failure('Failed to reset deal stages');+ },+ }));+}diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.tsindex a4a07f9783..3d59803edd 100644--- a/apps/web/src/lib/service-clients/service-storage/client.ts+++ b/apps/web/src/lib/service-clients/service-storage/client.ts@@ -85,6 +85,7 @@ import type { CrmCommentEntityType } from './generated/schemas/crmCommentEntityTimport type { CrmCommentThread } from './generated/schemas/crmCommentThread';import type { CrmCompanyResponse } from './generated/schemas/crmCompanyResponse';import type { CrmContactResponse } from './generated/schemas/crmContactResponse';+import type { CrmStagesResponse } from './generated/schemas/crmStagesResponse';import type { CrmTeamSettingsResponse } from './generated/schemas/crmTeamSettingsResponse';import type { DeleteCommentResponse } from './generated/schemas/deleteCommentResponse';import type { DeleteCrmCommentResult } from './generated/schemas/deleteCrmCommentResult';@@ -150,6 +151,7 @@ import type { RemindersList } from './generated/schemas/remindersList';import type { RemoveParticipantsRequest } from './generated/schemas/removeParticipantsRequest';import type { ReorderFavoritesRequest } from './generated/schemas/reorderFavoritesRequest';import type { ReorderPinRequest } from './generated/schemas/reorderPinRequest';+import type { ReplaceCrmStagesRequest } from './generated/schemas/replaceCrmStagesRequest';import type { SaveDocumentResponseData } from './generated/schemas/saveDocumentResponseData';import type { SetCompanyNameRequest } from './generated/schemas/setCompanyNameRequest';import type { SetContactNameRequest } from './generated/schemas/setContactNameRequest';@@ -2674,6 +2676,15 @@ export const storageServiceClient = {body: JSON.stringify(body),});},+ async replaceCrmTeamStages(body: ReplaceCrmStagesRequest) {+ return await dssFetch<CrmStagesResponse>('/crm/stages', {+ method: 'PUT',+ body: JSON.stringify(body),+ });+ },+ async resetCrmTeamStages() {+ return await dssFetch('/crm/stages', { method: 'DELETE' });+ },crmComments: {async list({entityType,diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex 9af3fe2dfe..e40665c9e6 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -163,7 +163,11 @@ Left nav: General → `Account` (profile, delete account), `API Keys` (create /list / delete personal keys; the secret is shown only once and is sent as`x-macro-user-api-key`), `Notifications`, `Billing`,`Appearance`, `Mobile App`, `Shortcuts` (interactive keyboard visualization, not a list);-Workspace → `Team`, `Tags`, `CRM`, `Connections` (email/tool OAuth), `MCP server`+Workspace → `Team`, `Tags`, `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`),+`Connections` (email/tool OAuth), `MCP server`(setup snippets for Claude Code / Codex CLI / Claude.ai / ChatGPT / IDE), `Agents`, `Bots`, `Harness`;`Log out`.`Agents` lists team and private agents with `Create agent` / `Edit <name>` dialogs grouped