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
refactor(web): isolate CRM in the feature architecture (#7256)
teo74deeccf9fba
diff --git a/apps/web/src/components/app/ItemDragAndDrop.tsx b/apps/web/src/components/app/ItemDragAndDrop.tsxindex 40b6fe5898..0dc367120a 100644--- a/apps/web/src/components/app/ItemDragAndDrop.tsx+++ b/apps/web/src/components/app/ItemDragAndDrop.tsx@@ -28,6 +28,10 @@ type DragOperationContextValue = {isAltKey: Accessor<boolean>;};+export type ItemDragOverlayData = {+ overlayIcon?: () => JSXElement;+};+const DragOperationContext = createContext<DragOperationContextValue>();export function useDragOperation() {@@ -43,6 +47,8 @@ function ItemDragOverlay() {const activeDraggable = createMemo(() => {return state?.active.draggable;});+ const overlayIcon = () =>+ (activeDraggable()?.data as ItemDragOverlayData | undefined)?.overlayIcon;const iconType = createMemo((): EntityIconSelector => {const data = activeDraggable()?.data;@@ -52,16 +58,10 @@ function ItemDragOverlay() {if (data.dragType === 'channel-label') {return data.iconType as EntityIconSelector;}- if (data.dragType === 'stage') return 'default';+ if (overlayIcon()) return 'default';return getEntityIconType(data as EntityDragData);});- // 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;@@ -80,12 +80,10 @@ function ItemDragOverlay() {><div class="flex flex-row items-center gap-2"><Show- when={!isStage()}- fallback={- <span class="size-2 shrink-0 rounded-full bg-accent/70" />- }+ when={overlayIcon()}+ fallback={<EntityIcon size="xs" targetType={iconType()} />}>- <EntityIcon size="xs" targetType={iconType()} />+ {(icon) => icon()()}</Show><TruncatedText size="xs">{activeDraggable()?.data.name}diff --git a/apps/web/src/components/app/Layout.tsx b/apps/web/src/components/app/Layout.tsxindex dbd33a3c32..6e7e846822 100644--- a/apps/web/src/components/app/Layout.tsx+++ b/apps/web/src/components/app/Layout.tsx@@ -12,8 +12,10 @@ import {setCreateMenuOpen,} from '@app/features/command/Launcher';import { SearchState } from '@app/features/command/mobile/mobileSearchState';-import { CreateCompanyModal } from '@app/features/companies/CreateCompanyModal';-import { CreateContactModal } from '@app/features/companies/CreateContactModal';+import {+ CreateCompanyModal,+ CreateContactModal,+} from '@app/features/crm/crm-create';import { DevStatusBar } from '@app/features/devtools/DevStatusBar';import { GlobalBulkEditEntityModal } from '@app/features/entity/bulk-edit/BulkEditEntityModal';import {diff --git a/apps/web/src/components/app/mobile/MobilePageActionRow.test.tsx b/apps/web/src/components/app/mobile/MobilePageActionRow.test.tsxindex 6fc7a1ac84..58b145ba99 100644--- a/apps/web/src/components/app/mobile/MobilePageActionRow.test.tsx+++ b/apps/web/src/components/app/mobile/MobilePageActionRow.test.tsx@@ -49,7 +49,7 @@ vi.mock(vi.mock('@app/features/calendar/hooks/use-calendar-ui-flag', () => ({useCalendarUiFlag: () => () => true,}));-vi.mock('@app/features/companies/CreateCompanyModal', () => ({+vi.mock('@app/features/crm/crm-create', () => ({openCreateCompanyModal: mocks.openCompany,}));vi.mock('@core/mobile/haptics', () => ({ hapticImpact: vi.fn() }));diff --git a/apps/web/src/components/app/mobile/MobilePageCreateButton.test.tsx b/apps/web/src/components/app/mobile/MobilePageCreateButton.test.tsxindex 9aff4b4055..29e38e7b1c 100644--- a/apps/web/src/components/app/mobile/MobilePageCreateButton.test.tsx+++ b/apps/web/src/components/app/mobile/MobilePageCreateButton.test.tsx@@ -31,7 +31,7 @@ vi.mock(useOpenEventComposer: () => sources.openEvent,}));-vi.mock('@app/features/companies/CreateCompanyModal', () => ({+vi.mock('@app/features/crm/crm-create', () => ({openCreateCompanyModal: sources.openCompany,}));vi.mock('@core/mobile/haptics', () => ({ hapticImpact: vi.fn() }));diff --git a/apps/web/src/components/app/mobile/MobilePageCreateButton.tsx b/apps/web/src/components/app/mobile/MobilePageCreateButton.tsxindex 224781d1ea..3f4541dbbb 100644--- a/apps/web/src/components/app/mobile/MobilePageCreateButton.tsx+++ b/apps/web/src/components/app/mobile/MobilePageCreateButton.tsx@@ -4,7 +4,7 @@ import {setCreateMenuOpen,useCreateMenuBlocks,} from '@app/features/command/Launcher';-import { openCreateCompanyModal } from '@app/features/companies/CreateCompanyModal';+import { openCreateCompanyModal } from '@app/features/crm/crm-create';import { hapticImpact } from '@core/mobile/haptics';import { virtualKeyboardVisible } from '@core/mobile/virtualKeyboard';import BellIcon from '@phosphor/bell.svg';diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsxindex f368e85b19..35875568cb 100644--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx@@ -6,7 +6,7 @@ import type { EventEditorInitialValues } from '@app/features/calendar/componentsimport type { CalendarEvent } from '@app/features/calendar/types';import { CalendarRouteView } from '@app/features/calendar-view/route';import { ChannelsRouteView } from '@app/features/channels-view/route';-import { CompaniesRouteView } from '@app/features/companies/route';+import { CompaniesRouteView } from '@app/features/crm/route';import { DriveRouteView } from '@app/features/drive-view/route';import { EmailCompose } from '@app/features/email-compose/email-compose';import { MailRouteView } from '@app/features/email-view/route';@@ -66,6 +66,7 @@ type ComponentFactory = (params: ComponentParams) => JSXElement;export type ComponentMeta = {kind?: string;splitPanelLayout?: 'legacy' | 'composable';+ ownsCollectionState?: boolean;};export type UnifiedListMeta = ComponentMeta & {@@ -262,7 +263,10 @@ registerComponent('calls', () => <CallsRouteView />);registerComponent('companies',() => <CompaniesRouteView />,- () => (isTouchDevice() ? undefined : { splitPanelLayout: 'composable' })+ () => ({+ ownsCollectionState: true,+ ...(isTouchDevice() ? {} : { splitPanelLayout: 'composable' as const }),+ }));registerComponent('folders', () => <FoldersRouteView />);registerComponent('search', () => <SearchRouteView />);diff --git a/apps/web/src/components/app/split-layout/components/SplitPanel.tsx b/apps/web/src/components/app/split-layout/components/SplitPanel.tsxindex 111f1b80a9..20cb4e55b8 100644--- a/apps/web/src/components/app/split-layout/components/SplitPanel.tsx+++ b/apps/web/src/components/app/split-layout/components/SplitPanel.tsx@@ -190,12 +190,27 @@ export function SplitPanel(props: SplitPanelProps) {}}><Suspense fallback={<ContentLoading />}>- <SoupViewContextProvider soup={nextSoup}>+ <Show+ when={+ props.split.mount.kind === 'component' &&+ props.split.mount.meta.ownsCollectionState+ }+ fallback={+ <SoupViewContextProvider soup={nextSoup}>+ <SplitRouter.Outlet+ splitId={props.handle.id}+ fallback={() => (+ <Dynamic component={props.split.mount.element} />+ )}+ />+ </SoupViewContextProvider>+ }+ ><SplitRouter.OutletsplitId={props.handle.id}fallback={() => <Dynamic component={props.split.mount.element} />}/>- </SoupViewContextProvider>+ </Show></Suspense></SplitPanelControllerProvider>);diff --git a/apps/web/src/components/app/split-layout/split-router/app-routes.ts b/apps/web/src/components/app/split-layout/split-router/app-routes.tsindex d87ce97421..c4120f8a1d 100644--- a/apps/web/src/components/app/split-layout/split-router/app-routes.ts+++ b/apps/web/src/components/app/split-layout/split-router/app-routes.ts@@ -9,7 +9,7 @@ import { callDetailRoute } from '@app/features/block-call/route';import { prDetailRoute } from '@app/features/block-pr/route';import { calendarSplitRoute } from '@app/features/calendar-view/route';import { channelsSplitRoute } from '@app/features/channels-view/route';-import { companiesRoute } from '@app/features/companies/route';+import { companiesRoute } from '@app/features/crm/route';import { driveSplitRoute } from '@app/features/drive-view/route';import { emailSplitRoute } from '@app/features/email-view/route';import { gettingStartedRoute } from '@app/features/getting-started/route';diff --git a/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx b/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsxindex 73ba24891c..8005e752a1 100644--- a/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx+++ b/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx@@ -129,7 +129,7 @@ vi.mock('@block-calendar/components/EventComposerSplit', () => ({}));vi.mock('@block-channel/component/Compose', () => ({}));vi.mock('@block-md/component/ComposeSkill', () => ({}));vi.mock('@block-md/component/ComposeTask', () => ({}));-vi.mock('@companies/crm/saved-views', () => ({}));+vi.mock('@app/features/crm/queries/saved-views', () => ({}));vi.mock('@core/context/user', () => ({}));vi.mock('@core/mobile/isTouchDevice', () => ({isTouchDevice: () => state.touch(),diff --git a/apps/web/src/features/activity/core/group-events.test.ts b/apps/web/src/features/activity/core/group-events.test.tsindex da31e1b363..de1f79a0e9 100644--- a/apps/web/src/features/activity/core/group-events.test.ts+++ b/apps/web/src/features/activity/core/group-events.test.ts@@ -1,4 +1,4 @@-import { describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { entryHead } from './collapse-runs';import type { ActivityEvent } from './event';import { groupEventsByDay } from './group-events';@@ -22,15 +22,24 @@ function event(const ids = (entries: ReturnType<typeof groupEventsByDay>[number]['entries']) =>entries.map((entry) => entryHead(entry).id);+const todayAt = (hour: number) => new Date(2026, 7, 21, hour).toISOString();+describe('groupEventsByDay', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date(2026, 7, 21, 12));+ });++ afterEach(() => vi.useRealTimers());+it('returns an empty list for no events', () => {expect(groupEventsByDay([])).toEqual([]);});it('keeps consecutive events that share a date bucket in one group', () => {const groups = groupEventsByDay([- event('a', '2026-08-21T10:00:00.000Z', { action: { kind: 'edited' } }),- event('b', '2026-08-21T11:00:00.000Z'),+ event('a', todayAt(10), { action: { kind: 'edited' } }),+ event('b', todayAt(11)),]);expect(groups).toHaveLength(1);@@ -39,20 +48,20 @@ describe('groupEventsByDay', () => {it('starts a new group when the date bucket changes', () => {const groups = groupEventsByDay([- event('today', '2026-08-21T10:00:00.000Z'),+ event('today', todayAt(10)),event('older', '2020-01-01T10:00:00.000Z'),]);expect(groups).toHaveLength(2);expect(ids(groups[0].entries)).toEqual(['today']);expect(ids(groups[1].entries)).toEqual(['older']);- expect(groups[0].key).not.toBe(groups[1].key);+ expect(groups.map((group) => group.key)).toEqual(['today', 'older']);});it('collapses same-entity runs inside a day but never across a day header', () => {const groups = groupEventsByDay([- event('a', '2026-08-21T12:00:00.000Z', { action: { kind: 'edited' } }),- event('b', '2026-08-21T11:00:00.000Z', { action: { kind: 'edited' } }),+ event('a', todayAt(12), { action: { kind: 'edited' } }),+ event('b', todayAt(11), { action: { kind: 'edited' } }),event('c', '2020-01-01T10:00:00.000Z', { action: { kind: 'edited' } }),]);diff --git a/apps/web/src/features/block-company/component/CompanyBlockAdapter.tsx b/apps/web/src/features/block-company/component/CompanyBlockAdapter.tsxindex 6594939476..9509adfa02 100644--- a/apps/web/src/features/block-company/component/CompanyBlockAdapter.tsx+++ b/apps/web/src/features/block-company/component/CompanyBlockAdapter.tsx@@ -1,5 +1,5 @@-import { Company } from '@companies/Company/Company';-import { CrmCopyLinkButton } from '@companies/components/CrmCopyLinkButton';+import { Company } from '@app/features/crm/crm-company';+import { CrmCopyLinkButton } from '@app/features/crm/crm-link';import { HeaderIsland } from '@components/app/split-layout/components/HeaderIsland';import { SplitHeaderRight } from '@components/app/split-layout/components/SplitHeader';import { useBlockId } from '@core/block';diff --git a/apps/web/src/features/block-contact/component/ContactBlockAdapter.tsx b/apps/web/src/features/block-contact/component/ContactBlockAdapter.tsxindex 01798a8a58..c17d4a6050 100644--- a/apps/web/src/features/block-contact/component/ContactBlockAdapter.tsx+++ b/apps/web/src/features/block-contact/component/ContactBlockAdapter.tsx@@ -1,7 +1,7 @@-import { CrmCopyLinkButton } from '@companies/components/CrmCopyLinkButton';+import { Contact } from '@app/features/crm/crm-contact';+import { CrmCopyLinkButton } from '@app/features/crm/crm-link';import { HeaderIsland } from '@components/app/split-layout/components/HeaderIsland';import { SplitHeaderRight } from '@components/app/split-layout/components/SplitHeader';-import { Contact } from '@contacts/Contact/Contact';import { useBlockId } from '@core/block';import {createParamsState,diff --git a/apps/web/src/features/companies/crm/display-options.ts b/apps/web/src/features/companies/crm/display-options.tsdeleted file mode 100644index 50ae15423f..0000000000--- a/apps/web/src/features/companies/crm/display-options.ts+++ /dev/null@@ -1,60 +0,0 @@-/**- * Personal display options for the CRM Customers view: which property- * columns show in the list. Persisted per-user (localStorage preference),- * same mechanism as other sticky view settings.- */--import { makePersisted } from '@solid-primitives/storage';-import { createSignal } from 'solid-js';--export type CrmListColumnId = 'stage' | 'owner' | 'revenue';--export type CrmDisplayOptions = {- /** Visible list columns (order stays fixed; this only hides/shows). */- listColumns: Record<CrmListColumnId, boolean>;-};--export const DEFAULT_CRM_DISPLAY_OPTIONS: CrmDisplayOptions = {- listColumns: { stage: true, owner: true, revenue: true },-};--export const CRM_LIST_COLUMN_LABELS: Record<CrmListColumnId, string> = {- stage: 'Stage',- owner: 'Owner',- revenue: 'Revenue',-};--// One shared signal for the whole app (module-level), so toggling in the-// Display menu re-renders every consumer (list, kanban) immediately.-// `usePreference` would give each component its own signal that only-// shares the localStorage key — updates would not propagate until reload.-const [displayOptions, setDisplayOptions] = makePersisted(- createSignal<CrmDisplayOptions>(DEFAULT_CRM_DISPLAY_OPTIONS),- { name: 'macro:pref:crm:display' }-);--export function useCrmDisplayOptions() {- const [options, setOptions] = [displayOptions, setDisplayOptions];-- // Merge with defaults so options saved by older builds keep working- // when new fields are added.- const merged = (): CrmDisplayOptions => ({- listColumns: {- ...DEFAULT_CRM_DISPLAY_OPTIONS.listColumns,- ...options().listColumns,- },- });-- const toggleListColumn = (column: CrmListColumnId) => {- const current = merged();- setOptions({- ...current,- listColumns: {- ...current.listColumns,- [column]: !current.listColumns[column],- },- });- };-- return { options: merged, toggleListColumn };-}diff --git a/apps/web/src/features/companies/crm/saved-views.ts b/apps/web/src/features/companies/crm/saved-views.tsdeleted file mode 100644index e9d73bdc29..0000000000--- a/apps/web/src/features/companies/crm/saved-views.ts+++ /dev/null@@ -1,270 +0,0 @@-/**- * CRM saved views: named snapshots of the Customers view state.- *- * - Personal views persist per-user through the existing `/saved_views`- * API (arbitrary JSON config, frontend-owned shape).- * - Team views live in the shared team CRM config (see team-crm-config)- * so every team member sees them.- * - Any view can be shared as a link: the config is base64url-encoded in- * the `crmView` search param of the Customers URL, so anyone on the- * team can open it (the link carries only view state, never data).- */--import { toast } from '@core/component/Toast/Toast';-import { useUserId } from '@core/context/user';-import { throwOnErr } from '@core/util/result';-import { storageServiceClient } from '@service-storage/client';-import type { View } from '@service-storage/generated/schemas/view';-import { useMutation, useQuery, useQueryClient } from '@tanstack/solid-query';-import { createMemo } from 'solid-js';-import { type TeamCrmSavedView, useTeamCrmConfig } from './team-crm-config';--/** Snapshot of the Customers view state. Fields are all optional so old- * links/views keep working as the shape evolves. */-export type CrmViewConfig = {- kind: 'crm';- /** Server query filters (soup `Query`). */- filters?: unknown;- /** Client predicate ids ({ and, or }). */- clientFilters?: { and?: string[]; or?: string[] };- searchText?: string;- /** Group-by id (e.g. `property:<definition-id>`); null = no grouping. */- groupBy?: string | null;- /** Sort ids (soup sort state). */- sort?: string[];- viewMode?: 'list' | 'board';- /** Stage option ids selected in the Stage filter (may include NO_STAGE). */- stageFilter?: string[];- /** Owner ids selected in the Owner filter. */- ownerFilter?: string[];- activeTab?: string;- /** Personal views only: applied by default when opening the Customers view. */- isDefault?: boolean;-};--export function isCrmViewConfig(value: unknown): value is CrmViewConfig {- return (- typeof value === 'object' &&- value !== null &&- 'kind' in value &&- (value as { kind: unknown }).kind === 'crm'- );-}--export const CRM_VIEW_URL_PARAM = 'crmView';--/** Base64url-encode a view config for the share link. */-export function encodeCrmViewParam(config: CrmViewConfig): string {- const json = JSON.stringify(config);- const base64 = btoa(String.fromCharCode(...new TextEncoder().encode(json)));- return base64.replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');-}--export function decodeCrmViewParam(param: string): CrmViewConfig | undefined {- try {- const base64 = param.replaceAll('-', '+').replaceAll('_', '/');- const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));- const parsed: unknown = JSON.parse(new TextDecoder().decode(bytes));- return isCrmViewConfig(parsed) ? parsed : undefined;- } catch {- return undefined;- }-}--/** Share link for a view config: /companies?crmView=<encoded>. */-export function buildCrmViewShareUrl(config: CrmViewConfig): string {- const url = new URL('/companies', window.location.origin);- url.searchParams.set(CRM_VIEW_URL_PARAM, encodeCrmViewParam(config));- return url.toString();-}--const CRM_SAVED_VIEWS_QUERY_KEY = ['crm', 'saved-views'] as const;--export type PersonalCrmView = View & { config: CrmViewConfig };--/** Personal saved views (server-persisted via /saved_views). */-export function usePersonalCrmViews() {- const queryClient = useQueryClient();-- const viewsQuery = useQuery(() => ({- queryKey: CRM_SAVED_VIEWS_QUERY_KEY,- queryFn: async () =>- await throwOnErr(- async () => await storageServiceClient.views.getSavedViews()- ),- }));-- const views = createMemo((): PersonalCrmView[] =>- (viewsQuery.isSuccess ? viewsQuery.data.views : []).filter(- (view): view is PersonalCrmView => isCrmViewConfig(view.config)- )- );-- const defaultView = () => views().find((view) => view.config.isDefault);-- const invalidate = () =>- queryClient.invalidateQueries({ queryKey: CRM_SAVED_VIEWS_QUERY_KEY });-- const createMutation = useMutation(() => ({- mutationFn: async (vars: { name: string; config: CrmViewConfig }) =>- await throwOnErr(- async () =>- await storageServiceClient.views.createSavedView({- name: vars.name,- config: vars.config,- })- ),- onSuccess: () => invalidate(),- onError: (error: Error) => {- console.error('Failed to save view', error);- toast.failure('Failed to save view');- },- }));-- const renameMutation = useMutation(() => ({- mutationFn: async (vars: { id: string; name: string }) =>- await throwOnErr(- async () =>- await storageServiceClient.views.patchView({- saved_view_id: vars.id,- name: vars.name,- })- ),- onSuccess: () => invalidate(),- onError: (error: Error) => {- console.error('Failed to rename view', error);- toast.failure('Failed to rename view');- },- }));-- const deleteMutation = useMutation(() => ({- mutationFn: async (vars: { id: string }) =>- await throwOnErr(- async () =>- await storageServiceClient.views.deleteView({ savedViewId: vars.id })- ),- onSuccess: () => invalidate(),- onError: (error: Error) => {- console.error('Failed to delete view', error);- toast.failure('Failed to delete view');- },- }));-- // The backend PATCH shallow-merges into the stored config, so sending just- // `{isDefault}` flips the flag without touching the rest of the snapshot.- const setDefaultMutation = useMutation(() => ({- mutationFn: async (vars: { id: string | undefined }) => {- const { id } = vars;- const previous = defaultView();- if (previous && previous.id !== id) {- await throwOnErr(- async () =>- await storageServiceClient.views.patchView({- saved_view_id: previous.id,- config: { isDefault: false },- })- );- }- if (id !== undefined) {- await throwOnErr(- async () =>- await storageServiceClient.views.patchView({- saved_view_id: id,- config: { isDefault: true },- })- );- }- },- onSuccess: () => invalidate(),- onError: (error: Error) => {- console.error('Failed to set default view', error);- toast.failure('Failed to set default view');- },- }));-- return {- views,- defaultView,- isLoading: () => viewsQuery.isLoading,- create: createMutation,- rename: renameMutation,- remove: deleteMutation,- setDefault: setDefaultMutation,- };-}--/** Team-shared saved views (stored in the shared team CRM config). */-export function useTeamCrmViews() {- const userId = useUserId();- const { config, update, isLoading } = useTeamCrmConfig();-- const views = createMemo((): TeamCrmSavedView[] =>- (config().teamViews ?? []).filter((view) => isCrmViewConfig(view.config))- );-- const defaultViewId = () => config().defaultTeamViewId;-- const defaultView = () => views().find((view) => view.id === defaultViewId());-- const setDefault = (id: string | undefined) => {- update.mutate(- { defaultTeamViewId: id ?? null },- {- onError: (error: Error) => {- console.error('Failed to set default team view', error);- toast.failure('Failed to set default team view');- },- }- );- };-- const add = (name: string, viewConfig: CrmViewConfig) => {- const view: TeamCrmSavedView = {- id: crypto.randomUUID(),- name,- config: viewConfig,- createdBy: userId(),- createdAt: new Date().toISOString(),- };- update.mutate(- // Updater form: derives from the latest cache when the (serialized)- // mutation actually runs, so rapid saves don't drop each other.- { teamViews: (current) => [...current, view] },- {- onError: (error: Error) => {- console.error('Failed to save team view', error);- toast.failure('Failed to save team view');- },- }- );- };-- const remove = (id: string) => {- update.mutate(- {- teamViews: (current) => current.filter((view) => view.id !== id),- // A deleted view can't stay the team default.- ...(config().defaultTeamViewId === id- ? { defaultTeamViewId: null }- : {}),- },- {- onError: (error: Error) => {- console.error('Failed to delete team view', error);- toast.failure('Failed to delete team view');- },- }- );- };-- return {- views,- defaultViewId,- defaultView,- add,- remove,- setDefault,- isLoading,- isSaving: () => update.isPending,- };-}diff --git a/apps/web/src/features/companies/crm/team-crm-config.ts b/apps/web/src/features/companies/crm/team-crm-config.tsdeleted file mode 100644index 7bb537f1c9..0000000000--- a/apps/web/src/features/companies/crm/team-crm-config.ts+++ /dev/null@@ -1,247 +0,0 @@-/**- * Team-shared CRM configuration (permissions, closed-stage set, 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).- */--import { useUserId } from '@core/context/user';-import { throwOnErr } from '@core/util/result';-import { useCurrentTeamQuery } from '@queries/team/teams';-import { TeamRole } from '@service-auth/generated/schemas/teamRole';-import { storageServiceClient } from '@service-storage/client';-import type { CrmTeamSettingsResponse } from '@service-storage/generated/schemas/crmTeamSettingsResponse';-import type { UpdateCrmTeamSettingsRequest } from '@service-storage/generated/schemas/updateCrmTeamSettingsRequest';-import { useMutation, useQuery, useQueryClient } from '@tanstack/solid-query';-import { type Accessor, createMemo } from 'solid-js';--export const CRM_TEAM_SETTINGS_QUERY_KEY = ['crm', 'team-settings'] as const;--/**- * Minimum team role required for a CRM capability. Team members are- * view-only at the platform level (the backend maps member → View access- * on companies), so the configurable range is admin (default) vs owner.- */-export type CrmPermissionRole = 'admin' | 'owner';--export type CrmPermissions = {- /** Who can change the deal stage set in CRM settings. */- editStages: CrmPermissionRole;- /** Who can move deals out of a closed stage. */- moveClosedDeals: CrmPermissionRole;- /** Who can delete (hide) CRM records. */- deleteRecords: CrmPermissionRole;-};--export type TeamCrmSavedView = {- id: string;- name: string;- /** Serialized CRM view state (see crm/saved-views). */- config: unknown;- createdBy?: string;- createdAt?: string;-};--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[];- /** Team view applied by default when a member opens the Customers view. */- defaultTeamViewId?: string;-};--/**- * 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.- */-export type TeamCrmConfigPatch = {- permissions?: Partial<CrmPermissions>;- closedStageIds?: string[] | null;- teamViews?:- | TeamCrmSavedView[]- | ((current: TeamCrmSavedView[]) => TeamCrmSavedView[]);- defaultTeamViewId?: string | null;-};--export const DEFAULT_CRM_PERMISSIONS: CrmPermissions = {- editStages: 'admin',- moveClosedDeals: 'admin',- 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 function useTeamCrmConfig() {- const queryClient = useQueryClient();-- const settingsQuery = useQuery(() => ({- queryKey: CRM_TEAM_SETTINGS_QUERY_KEY,- queryFn: async () =>- await throwOnErr(() => storageServiceClient.getCrmTeamSettings()),- }));-- const config = createMemo((): TeamCrmConfig => {- const data = settingsQuery.isSuccess ? settingsQuery.data : undefined;- if (!data) return {};- return {- permissions: {- editStages: data.edit_stages_role,- moveClosedDeals: data.move_closed_deals_role,- deleteRecords: data.delete_records_role,- },- closedStageIds: data.closed_stage_ids ?? undefined,- legacyStageIds: data.legacy_stage_ids ?? undefined,- teamViews: (data.team_views as TeamCrmSavedView[]) ?? [],- defaultTeamViewId: data.default_team_view_id ?? undefined,- };- });-- const updateMutation = useMutation(() => ({- // Serialize updates: with whole-list team_views writes, concurrent- // PUTs would clobber each other. Scoped mutations run one at a time,- // and updater-style teamViews patches read the cache only once the- // previous mutation's response has been written back.- scope: { id: 'crm-team-settings' },- mutationFn: async (patch: TeamCrmConfigPatch) => {- const teamViews =- typeof patch.teamViews === 'function'- ? patch.teamViews(- (queryClient.getQueryData<CrmTeamSettingsResponse>(- CRM_TEAM_SETTINGS_QUERY_KEY- )?.team_views as TeamCrmSavedView[]) ?? []- )- : patch.teamViews;- const body: UpdateCrmTeamSettingsRequest = {- 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 }- : {}),- };- return await throwOnErr(() =>- storageServiceClient.updateCrmTeamSettings(body)- );- },- onSuccess: (settings) => {- // The PUT returns the resulting row — seed the cache with it.- queryClient.setQueryData(CRM_TEAM_SETTINGS_QUERY_KEY, settings);- },- onSettled: () =>- queryClient.invalidateQueries({ queryKey: CRM_TEAM_SETTINGS_QUERY_KEY }),- }));-- return {- config,- isLoading: () => settingsQuery.isLoading,- isError: () => settingsQuery.isError && settingsQuery.data === undefined,- update: updateMutation,- };-}--/** Whether `role` satisfies a required minimum capability role. */-function roleSatisfies(- role: TeamRole | undefined,- required: CrmPermissionRole-): boolean {- if (role === TeamRole.owner) return true;- if (role === TeamRole.admin) return required === 'admin';- return false;-}--/**- * Effective CRM capabilities for the current user, combining the team's- * configured permission thresholds with the platform-level rule that any- * team member can edit CRM data (governance actions stay admin/owner).- */-export function useCrmPermissions() {- const userId = useUserId();- const teamQuery = useCurrentTeamQuery();- const { config, isLoading } = useTeamCrmConfig();-- const role = createMemo((): TeamRole | undefined => {- const uid = userId();- const team = teamQuery.data;- if (!uid || !team) return undefined;- return team.members.find((member) => member.user_id === uid)?.role;- });-- const permissions = createMemo(- (): CrmPermissions => ({- ...DEFAULT_CRM_PERMISSIONS,- ...config().permissions,- })- );-- return {- role,- permissions,- isLoading,- /** Can edit CRM data at all (platform rule: any team member). */- canEditCrm: () => role() !== undefined,- canEditStages: createMemo(() =>- roleSatisfies(role(), permissions().editStages)- ),- canMoveClosedDeals: createMemo(() =>- roleSatisfies(role(), permissions().moveClosedDeals)- ),- canDeleteRecords: createMemo(() =>- roleSatisfies(role(), permissions().deleteRecords)- ),- };-}--/**- * True once the current-team query resolves to no team (null) or a team- * with CRM disabled — the companies views swap in an explanatory empty- * state and keep bottom chrome like the AI bar. Stays false while the- * query loads so enabled teams don't flash the empty state.- */-export function useCrmUnavailable(): Accessor<boolean> {- const teamQuery = useCurrentTeamQuery();- return () =>- teamQuery.data === null || teamQuery.data?.team.crm_enabled === false;-}--/**- * The set of stage option ids considered "closed" — explicit config when- * present, else a label heuristic over the active stages.- */-export function useClosedStageIds(- stages: Accessor<Array<{ id: string; label: string }>>-): Accessor<Set<string>> {- const { config } = useTeamCrmConfig();- return createMemo(() => {- const explicit = config().closedStageIds;- if (explicit) return new Set(explicit);- return new Set(- stages()- .filter((stage) => DEFAULT_CLOSED_STAGE_LABEL.test(stage.label))- .map((stage) => stage.id)- );- });-}diff --git a/apps/web/src/features/crm/README.md b/apps/web/src/features/crm/README.mdnew file mode 100644index 0000000000..1471eeef00--- /dev/null+++ b/apps/web/src/features/crm/README.md@@ -0,0 +1,43 @@+# CRM ownership++CRM company and contact screens, settings, filters, saved views, lists, import,+export, and company actions belong here. The dependency rules are enforced by+`architecture.test.ts` and the feature rules in `rules/ast-grep`.++```text+crm/+ core/ Domain types, permissions, stage resolution, CSV and view validation+ context/ Explicit source/action contracts and scoped providers+ queries/ CRM query factories, cache updates, transport decoding+ primitives/ Reactive workflows: board, filters, stages, views, import, export+ components/ Props-driven presentation and column definitions+ views/ Screens composed from context, primitives, and components+ tests/ Cross-layer CSV integration coverage+ crm.tsx Company workspace composition+ crm-company.tsx / crm-contact.tsx / crm-settings.tsx+ crm-create.tsx / crm-link.tsx+ crm-actions.ts / crm-hide-action.ts / crm-action-items.ts / crm-user-action.tsx+ crm-search.ts / crm-tool-renderers.tsx+ route.tsx Authenticated route and shared-view decoding+ *-adapter.* Production sources, navigation, persistence, download, collection wiring+```++App code imports explicit entry points at this directory's root. It must not+import `views`, `primitives`, `queries`, `components`, `core`, or `context`+directly. Avoid adding a catch-all barrel that obscures these entry points.++The root adapters construct production dependencies. `context` defines the+capabilities; it does not import their implementations. Views consume these+capabilities, primitives receive narrow inputs, and components render props.+Core modules remain independent of Solid, service clients, and app state.++Shared entity representations, transport clients, property editors, and+collection mechanics remain shared. CRM owns its record queries and cache updates.+CRM supplies row/header/empty state slots, filter choices, grouping policy, and+its own collection state to the shared collection renderer. Shared collection code must not acquire CRM hooks or+CRM-specific state again.++When changing behavior, test the responsible primitive or pure function. When+moving behavior, retain query keys, persistence keys, mutation ordering, loading+boundaries, routes, and markup. Run CRM tests plus affected shared collection and+user-card tests, TypeScript checking, `just check`, and the real CRM browser flows.diff --git a/apps/web/src/features/crm/architecture.test.ts b/apps/web/src/features/crm/architecture.test.tsnew file mode 100644index 0000000000..91bb4a62fd--- /dev/null+++ b/apps/web/src/features/crm/architecture.test.ts@@ -0,0 +1,87 @@+// @vitest-environment node+import { readdirSync, readFileSync } from 'node:fs';+import { dirname, join, relative, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { describe, expect, it } from 'vitest';++const feature = dirname(fileURLToPath(import.meta.url));+const source = resolve(feature, '../..');+function files(path: string): string[] {+ return readdirSync(path, { withFileTypes: true }).flatMap((entry) =>+ entry.isDirectory()+ ? files(join(path, entry.name))+ : /\.tsx?$/.test(entry.name) && !/\.test\./.test(entry.name)+ ? [join(path, entry.name)]+ : []+ );+}+function imports(file: string) {+ return [+ ...readFileSync(file, 'utf8').matchAll(+ /(?:from\s*|import\s*\()['"]([^'"]+)['"]/g+ ),+ ].map((match) => match[1]);+}+function crmTarget(file: string, path: string) {+ const absolute = path.startsWith('.')+ ? resolve(dirname(file), path)+ : path.startsWith('@app/')+ ? resolve(source, path.slice(5))+ : '';+ return absolute.startsWith(`${feature}/`)+ ? relative(feature, absolute)+ : undefined;+}++describe('CRM ownership boundaries', () => {+ it('keeps app consumers on explicit CRM entry points', () => {+ const leaks = files(source)+ .filter((file) => !file.startsWith(`${feature}/`))+ .flatMap((file) =>+ imports(file).flatMap((path) => {+ const target = crmTarget(file, path);+ return target &&+ /^(core|context|queries|primitives|components|views)\//.test(target)+ ? [`${relative(source, file)} -> ${path}`]+ : [];+ })+ );+ expect(leaks).toEqual([]);+ });+ it('keeps core pure and reactive consumers independent of production wiring', () => {+ const leaks = files(feature).flatMap((file) => {+ const layer = relative(feature, file).split('/')[0];+ return imports(file).flatMap((path) => {+ const target = crmTarget(file, path);+ const concrete =+ /^(?:@queries\/|@service-|@core\/context\/|@app\/lib\/analytics)/.test(+ path+ );+ const rootAdapter =+ target && !target.includes('/') && /adapter|^crm(?:-|$)/.test(target);+ const otherLayer = target?.split('/')[0];+ const invalid =+ layer === 'core'+ ? /^(?:solid-js|@queries\/|@service-|@core\/context\/)/.test(+ path+ ) ||+ (otherLayer && otherLayer !== 'core')+ : ['primitives', 'context'].includes(layer)+ ? concrete ||+ rootAdapter ||+ ['queries', 'views', 'components'].includes(otherLayer ?? '')+ : layer === 'views'+ ? concrete || rootAdapter || otherLayer === 'queries'+ : layer === 'components'+ ? concrete ||+ rootAdapter ||+ ['queries', 'views', 'primitives'].includes(+ otherLayer ?? ''+ )+ : false;+ return invalid ? [`${relative(feature, file)} -> ${path}`] : [];+ });+ });+ expect(leaks).toEqual([]);+ });+});diff --git a/apps/web/src/features/crm/collection-filters.ts b/apps/web/src/features/crm/collection-filters.tsnew file mode 100644index 0000000000..ff3892f97c--- /dev/null+++ b/apps/web/src/features/crm/collection-filters.ts@@ -0,0 +1,132 @@+import { type EntityData, getCompanyOwnerId } from '@entity';+import { getCompanyStageOptionId } from '@entity/utils/company-properties';+import { getPropertyOptionLabel } from '@entity/utils/task-properties';+import {+ config,+ NO_ASSIGNEE,+ NO_STAGE,+} from '../next-soup/filters/configs/base';+import { defineQueryFilters } from '../next-soup/filters/filter-store/compile';+import {+ matchesInteractionWindow,+ needsCompanyFollowUp,+} from './core/navigation';++// Companies are fetched via the dedicated CRM soup request (capped at 500+// per team) rather than the dynamic filter AST, which has no property+// support for the `ccf` target — so stage/owner filters are client-side+// predicates with a no-op server query.++/**+ * Stage filter for the Customers view, driven by the view's stage+ * selection (`ctx.stages`, option ids from the team's active deal-stage+ * set plus the `NO_STAGE` sentinel). Mirrors `companyOwnerFilter`.+ */+export const companyStageFilter = config({+ id: 'company-stage',+ predicate: (e, ctx) =>+ companyStagePredicate(() => ctx.stages, ctx.resolveCompanyStage)(e),+ query: {},+});++export const companyOwnerFilter = config({+ id: 'company-owner',+ predicate: (e, ctx) => companyOwnedByUsersFilter(() => ctx.owners)(e),+ query: {},+});++export const companyNeedsFollowUpFilter = config({+ id: 'company-needs-follow-up',+ predicate: (entity, ctx) => {+ if (entity.type !== 'crm_company') return false;+ const stageId = ctx.resolveCompanyStage+ ? ctx.resolveCompanyStage(entity)+ : getCompanyStageOptionId(entity);+ const label = stageId+ ? (ctx.companyStageLabel ?? getPropertyOptionLabel)(stageId)+ : undefined;+ return needsCompanyFollowUp(entity.updatedAt, label);+ },+ query: {},+});++export const companyRecentlyActiveFilter = config({+ id: 'company-recently-active',+ predicate: (entity) =>+ entity.type === 'crm_company' &&+ matchesInteractionWindow(entity.updatedAt, 'recently-active'),+ query: {},+});++/**+ * Stage filter for companies, driven by the view's stage selection+ * (`ctx.stages`). `NO_STAGE` matches companies without a Stage set. Stage+ * resolution goes through `resolveStage` (the team's active deal-stage+ * set, from `ctx.resolveCompanyStage`) when supplied, so the filter+ * buckets companies exactly like the kanban — legacy system-stage values+ * included; otherwise it falls back to the raw system Stage value.+ */+function companyStagePredicate(+ stageIds: () => string[] | undefined,+ resolveStage?: (entity: EntityData) => string | undefined+) {+ return (entity: EntityData): boolean => {+ const stages = stageIds();+ if (!stages?.length) return true;+ if (entity.type !== 'crm_company') return false;+ const stageId = resolveStage+ ? resolveStage(entity)+ : getCompanyStageOptionId(entity);+ return stages.some((id) =>+ id === NO_STAGE ? stageId === undefined : stageId === id+ );+ };+}++/**+ * Owner filter for companies, driven by the view's owner selection+ * (`ctx.owners`). `NO_OWNER` matches companies without an Owner set.+ */+function companyOwnedByUsersFilter(ownerIds: () => string[] | undefined) {+ return (entity: EntityData): boolean => {+ const owners = ownerIds();+ if (!owners?.length) return true;+ if (entity.type !== 'crm_company') return false;+ const ownerId = getCompanyOwnerId(entity);+ return owners.some((id) =>+ id === NO_ASSIGNEE ? ownerId === undefined : ownerId === id+ );+ };+}++function crmCompanyPredicate(entity: EntityData): boolean {+ return entity.type === 'crm_company';+}+function crmCompanyActivePredicate(entity: EntityData): boolean {+ return entity.type === 'crm_company' && !entity.hidden;+}+function crmCompanyHiddenPredicate(entity: EntityData): boolean {+ return entity.type === 'crm_company' && entity.hidden;+}++export const crmCompanyFilter = config({+ id: 'crm-company',+ predicate: crmCompanyPredicate,+ query: defineQueryFilters({}, { skipTargets: ['ccf'] }),+});+export const crmCompanyActiveFilter = config({+ id: 'crm-company-active',+ predicate: crmCompanyActivePredicate,+ query: defineQueryFilters(+ { include: { crmCompanyHidden: false } },+ { skipTargets: ['ccf'] }+ ),+});+export const crmCompanyHiddenFilter = config({+ id: 'crm-company-hidden',+ predicate: crmCompanyHiddenPredicate,+ query: defineQueryFilters(+ { include: { crmCompanyHidden: true } },+ { skipTargets: ['ccf'] }+ ),+});diff --git a/apps/web/src/features/crm/collection-presets.ts b/apps/web/src/features/crm/collection-presets.tsnew file mode 100644index 0000000000..f23daedcdb--- /dev/null+++ b/apps/web/src/features/crm/collection-presets.ts@@ -0,0 +1,30 @@+import { SYSTEM_PROPERTY_IDS } from '@property/constants';+import { defineQueryFilters } from '../next-soup/filters/filter-store';+import type { ViewTabConfig } from '../next-soup/sidebar/soup-filter-presets';+export const CRM_TAB_PRESETS: ViewTabConfig = {+ default: 'active',+ tabs: {+ active: () => ({+ filters: defineQueryFilters(+ { include: { crmCompanyHidden: false } },+ { skipTargets: ['ccf'] }+ ),+ clientFilters: { and: ['crm-company-active'] },+ groupBy: `property:${SYSTEM_PROPERTY_IDS.STAGE}`,+ }),+ // Admin/owner only — the BE rejects `hidden: true` requests from+ // non-admins with 403. Returning `undefined` hides the tab for+ // non-admins via the same pattern context-required views use.+ hidden: (ctx) => {+ if (!ctx.isTeamAdmin) return undefined;+ return {+ filters: defineQueryFilters(+ { include: { crmCompanyHidden: true } },+ { skipTargets: ['ccf'] }+ ),+ clientFilters: { and: ['crm-company-hidden'] },+ groupBy: `property:${SYSTEM_PROPERTY_IDS.STAGE}`,+ };+ },+ },+};diff --git a/apps/web/src/features/next-soup/soup-view/views/companies/company-grid-template.ts b/apps/web/src/features/crm/components/company-grid-template.tssimilarity index 89%rename from apps/web/src/features/next-soup/soup-view/views/companies/company-grid-template.tsrename to apps/web/src/features/crm/components/company-grid-template.tsindex 1e22f9b70a..4d21e5176a 100644--- a/apps/web/src/features/next-soup/soup-view/views/companies/company-grid-template.ts+++ b/apps/web/src/features/crm/components/company-grid-template.ts@@ -1,6 +1,4 @@import { SYSTEM_PROPERTY_IDS } from '@property/constants';-import { DataType } from '@service-storage/generated/schemas/dataType';-import { EntityType } from '@service-storage/generated/schemas/entityType';/*** Property columns for the Customers (CRM companies) list, mirroring@@ -12,7 +10,7 @@ export const COMPANY_GRID_COLUMNS = [id: 'stage',label: 'Stage',defId: SYSTEM_PROPERTY_IDS.STAGE,- dataType: DataType.SELECT_STRING,+ dataType: 'SELECT_STRING',isMultiSelect: false,specificEntityType: null,width: 'var(--company-col-stage, 8rem)',@@ -21,16 +19,16 @@ export const COMPANY_GRID_COLUMNS = [id: 'owner',label: 'Owner',defId: SYSTEM_PROPERTY_IDS.COMPANY_OWNER,- dataType: DataType.ENTITY,+ dataType: 'ENTITY',isMultiSelect: false,- specificEntityType: EntityType.USER,+ specificEntityType: 'USER',width: 'var(--company-col-owner, 8rem)',},{id: 'revenue',label: 'Revenue',defId: SYSTEM_PROPERTY_IDS.REVENUE,- dataType: DataType.NUMBER,+ dataType: 'NUMBER',isMultiSelect: false,specificEntityType: null,width: 'var(--company-col-revenue, 7rem)',diff --git a/apps/web/src/features/companies/components/CrmListDialog.tsx b/apps/web/src/features/crm/components/company-list-dialog.tsxsimilarity index 100%rename from apps/web/src/features/companies/components/CrmListDialog.tsxrename to apps/web/src/features/crm/components/company-list-dialog.tsxdiff --git a/apps/web/src/features/companies/components/CrmSidebar.tsx b/apps/web/src/features/crm/components/crm-sidebar.tsxsimilarity index 99%rename from apps/web/src/features/companies/components/CrmSidebar.tsxrename to apps/web/src/features/crm/components/crm-sidebar.tsxindex d8e8fdcff5..56c1e43f61 100644--- a/apps/web/src/features/companies/components/CrmSidebar.tsx+++ b/apps/web/src/features/crm/components/crm-sidebar.tsx@@ -11,7 +11,7 @@ import ImportIcon from '@phosphor/upload-simple.svg';import { Button, Tooltip } from '@ui';import { tourTarget } from '@ui/components/Tour';import { createSignal, For, Show } from 'solid-js';-import { CRM_VIEWS } from '../core/crm-navigation';+import { CRM_VIEWS } from '../core/navigation';import { COMPANIES_TOUR } from '../tour';export function CrmSidebar(props: {diff --git a/apps/web/src/features/crm/components/export-columns.ts b/apps/web/src/features/crm/components/export-columns.tsnew file mode 100644index 0000000000..804751dd8f--- /dev/null+++ b/apps/web/src/features/crm/components/export-columns.ts@@ -0,0 +1,18 @@+import { SYSTEM_PROPERTY_IDS } from '@property/constants';+import type { ExportColumn } from '../core/export';+export const COMPANY_EXPORT_COLUMNS: ExportColumn[] = [+ { id: 'name', label: 'Company', default: true },+ { id: 'domains', label: 'Domains', default: true },+ { id: 'stage', label: 'Stage', default: true },+ { id: 'owner', label: 'Owner', default: true },+ {+ id: `property:${SYSTEM_PROPERTY_IDS.REVENUE}`,+ label: 'Revenue',+ default: true,+ },+ { id: 'lastInteraction', label: 'Last interaction', default: true },+ { id: 'firstInteraction', label: 'First interaction' },+ { id: 'description', label: 'Description' },+ { id: 'emailSync', label: 'Email sync' },+ { id: 'id', label: 'Company ID' },+];diff --git a/apps/web/src/features/companies/crm/StageIcon.tsx b/apps/web/src/features/crm/components/stage-icon.tsxsimilarity index 94%rename from apps/web/src/features/companies/crm/StageIcon.tsxrename to apps/web/src/features/crm/components/stage-icon.tsxindex 1af6d6d056..a18cae878e 100644--- a/apps/web/src/features/companies/crm/StageIcon.tsx+++ b/apps/web/src/features/crm/components/stage-icon.tsx@@ -27,6 +27,10 @@ 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/components/tool-companies.tsx b/apps/web/src/features/crm/components/tool-companies.tsxnew file mode 100644index 0000000000..fa4bae188d--- /dev/null+++ b/apps/web/src/features/crm/components/tool-companies.tsx@@ -0,0 +1,115 @@+import { Tool } from '@core/component/AI/component/tool/Tool';+import Buildings from '@phosphor-icons/core/regular/buildings.svg';+import { For, Show } from 'solid-js';++type CompanyListItem = {+ id: string;+ name?: string | null;+ domains: string[];+ stage?: { label: string } | null;+};+type ListCompaniesResponse = { companies: CompanyListItem[] };+type GetCompanyResponse = CompanyListItem & {+ description?: string | null;+ ownerUserId?: string | null;+ revenue?: number | null;+ contacts: unknown[];+};++export const pluralize = (+ count: number,+ singular: string,+ plural = `${singular}s`+) => `${count} ${count === 1 ? singular : plural}`;++function companySubtitle(company: CompanyListItem) {+ const parts: string[] = [];+ const domain = company.domains[0];+ if (domain) parts.push(domain);+ if (company.stage) parts.push(company.stage.label);+ return parts.join(' · ');+}++function CompanyRow(props: { company: CompanyListItem }) {+ return (+ <Tool.ListItem icon={<Buildings class="size-4" />}>+ <div class="min-w-0 flex-1">+ <div class="truncate text-xs text-ink">+ {props.company.name ?? props.company.domains[0] ?? props.company.id}+ </div>+ <Show when={companySubtitle(props.company)}>+ {(subtitle) => (+ <div class="truncate text-xs text-ink-placeholder">+ {subtitle()}+ </div>+ )}+ </Show>+ </div>+ </Tool.ListItem>+ );+}++export function ListCompaniesToolResponse(props: ListCompaniesResponse) {+ return (+ <Tool.List>+ <Show+ when={props.companies.length > 0}+ fallback={<Tool.ListItem>No matching CRM companies.</Tool.ListItem>}+ >+ <For each={props.companies}>+ {(company) => <CompanyRow company={company} />}+ </For>+ </Show>+ </Tool.List>+ );+}++export function GetCompanyToolResponse(props: GetCompanyResponse) {+ const details = () => {+ const rows: { label: string; value: string }[] = [];+ if (props.domains.length > 0) {+ rows.push({ label: 'Domains', value: props.domains.join(', ') });+ }+ if (props.stage) rows.push({ label: 'Stage', value: props.stage.label });+ if (props.ownerUserId) {+ rows.push({ label: 'Owner', value: props.ownerUserId });+ }+ if (props.revenue !== undefined && props.revenue !== null) {+ rows.push({ label: 'Revenue', value: `$${props.revenue}` });+ }+ rows.push({+ label: 'Contacts',+ value: pluralize(props.contacts.length, 'contact'),+ });+ return rows;+ };++ return (+ <Tool.List>+ <Tool.ListItem icon={<Buildings class="size-4" />}>+ <div class="min-w-0 flex-1">+ <div class="truncate text-xs text-ink">+ {props.name ?? props.domains[0] ?? props.id}+ </div>+ <Show when={props.description}>+ {(description) => (+ <div class="truncate text-xs text-ink-placeholder">+ {description()}+ </div>+ )}+ </Show>+ </div>+ </Tool.ListItem>+ <For each={details()}>+ {(row) => (+ <Tool.ListItem>+ <div class="flex min-w-0 flex-1 gap-2 text-xs">+ <span class="shrink-0 text-ink-placeholder">{row.label}</span>+ <span class="min-w-0 truncate text-ink">{row.value}</span>+ </div>+ </Tool.ListItem>+ )}+ </For>+ </Tool.List>+ );+}diff --git a/apps/web/src/features/crm/context/company-board-source.ts b/apps/web/src/features/crm/context/company-board-source.tsnew file mode 100644index 0000000000..727d5ccd3f--- /dev/null+++ b/apps/web/src/features/crm/context/company-board-source.ts@@ -0,0 +1,15 @@+import type { Accessor } from 'solid-js';+import type { DealStage } from '../core/stages';++export type CompanyBoardSource<T extends { id: string }> = {+ companies: Accessor<T[]>;+ stages: Accessor<DealStage[]>;+ filterStages: Accessor<DealStage[]>;+ selectedStages: Accessor<string[]>;+ noStageFilter: string;+ resolveStage(company: T): string | undefined;+ canEdit: Accessor<boolean>;+ canMoveClosed: Accessor<boolean>;+ closedStages: Accessor<ReadonlySet<string>>;+ saveStage(id: string, stage: string, onError: () => void): void;+};diff --git a/apps/web/src/features/crm/context/crm-context.tsx b/apps/web/src/features/crm/context/crm-context.tsxnew file mode 100644index 0000000000..ace031b908--- /dev/null+++ b/apps/web/src/features/crm/context/crm-context.tsx@@ -0,0 +1,121 @@+import type { CrmCompanyEntity } from '@entity';+import { type Accessor, createContext, useContext } from 'solid-js';+import type {+ CrmDisplayOptions,+ CrmListColumnId,+} from '../core/display-options';+import type {+ CompanySource,+ ContactSource,+ CrmCapabilities,+ CrmEmailScope,+ CrmEmailSignal,+ CrmMutation,+ CrmStageInput,+ CrmStagesResult,+ DealStages,+ EmailSource,+ ExportDefinitionsSource,+ ListsSource,+ PersonalViewsSource,+ PropertyCommands,+ TeamConfigSource,+ TeamSource,+ TeamViewsSource,+} from './crm-sources';++export type CrmContext = {+ downloadCsv(content: string, filename: string): Promise<{ saved: boolean }>;+ contactInitials(name: string | null | undefined, email: string): string;+ userEmail(id: string): string;+ copyViewLink(config: import('../core/saved-view').CrmViewConfig): void;+ copyRecordLink(target: {+ type: 'company' | 'contact';+ id: string;+ }): Promise<void>;+ createNavigation(): {+ splitId: string | undefined;+ openWithSplit(+ target: { type: 'company' | 'contact'; id: string },+ options?: { activate?: boolean; preferNewSplit?: boolean }+ ): void;+ showCompanies(): void;+ openEmail(entity: import('@entity').EntityData): void;+ };+ listsEnabled(): Accessor<boolean>;++ feedback: { success(message: string): void; failure(message: string): void };+ createCompanyEmails(+ domains: Accessor<string[]>,+ scope: Accessor<CrmEmailScope>,+ signal: Accessor<CrmEmailSignal>+ ): EmailSource;+ createContactEmails(+ email: Accessor<string | undefined>,+ scope: Accessor<CrmEmailScope>,+ signal: Accessor<CrmEmailSignal>+ ): EmailSource;+ createPropertyCommands(): PropertyCommands;+ hydrateCompany(company: CrmCompanyEntity): CrmCompanyEntity;+ createSettingsCommands(): CrmMutation<+ { enabled: boolean; backfill?: boolean },+ { enabled: boolean }+ >;+ createReplaceStages(): CrmMutation<CrmStageInput[], CrmStagesResult>;+ createResetStages(): CrmMutation<void>;+ createExportDefinitions(enabled: Accessor<boolean>): ExportDefinitionsSource;+ createCompanySuggestions(): {+ companies: Accessor<{ id: string; name: string }[]>;+ query: { readonly isLoading: boolean };+ };+ exportCompanies(+ signal: AbortSignal,+ progress: (count: number) => void+ ): Promise<CrmCompanyEntity[]>;++ createDisplayOptions(): {+ options: Accessor<CrmDisplayOptions>;+ toggleListColumn(column: CrmListColumnId): void;+ };+ openCreateCompany(): void;+ openCreateContact(companyId: string, domain: string): void;+ userId: Accessor<string | undefined>;+ isTeamAdmin: () => Accessor<boolean>;+ createCompanySource(id: Accessor<string>): CompanySource;+ createContactSource(id: Accessor<string>): ContactSource;+ createTeamSource(): TeamSource;+ createTeamConfigSource(): TeamConfigSource;+ createCapabilities(): CrmCapabilities;+ createDealStages(): DealStages;+ createUnavailable(): Accessor<boolean>;+ createClosedStageIds(+ stages: Accessor<{ id: string; label: string }[]>+ ): Accessor<Set<string>>;+ createPersonalViews(): PersonalViewsSource;+ createTeamViews(): TeamViewsSource;+ createLists(teamId: Accessor<string | undefined>): ListsSource;+ createCompany(): CrmMutation<+ { name: string; domain: string },+ { id: string }+ >;+ createContact(): CrmMutation<+ { companyId: string; name: string; email: string },+ { id: string }+ >;+ renameCompany(): CrmMutation<{ companyId: string; name: string }>;+ renameContact(): CrmMutation<{+ contactId: string;+ companyId: string;+ name: string;+ }>;+ hideCompany(): CrmMutation<{ companyId: string; hidden: boolean }>;+ hideContact(): CrmMutation<{ contactId: string; hidden: boolean }>;+ setEmailSync(): CrmMutation<{ companyId: string; emailSync: boolean }>;+};+const Context = createContext<CrmContext>();+export const CrmProvider = Context.Provider;+export function useCrmContext(): CrmContext {+ const context = useContext(Context);+ if (!context) throw new Error('CRM views require a CrmProvider');+ return context;+}diff --git a/apps/web/src/features/crm/context/crm-sources.ts b/apps/web/src/features/crm/context/crm-sources.tsnew file mode 100644index 0000000000..a84225cb31--- /dev/null+++ b/apps/web/src/features/crm/context/crm-sources.ts@@ -0,0 +1,164 @@+import type { Property } from '@property/types';+import type { Accessor } from 'solid-js';+import type { CrmCompany } from '../core/company';+import type { CrmContact } from '../core/contact';+import type { CrmListConfig } from '../core/navigation';+import type { CrmViewConfig } from '../core/saved-view';+import type {+ CrmPermissions,+ CrmTeamRole,+ TeamCrmConfig,+ TeamCrmConfigPatch,+ TeamCrmSavedView,+} from '../core/team-config';++/** Query availability without exposing a cache client or transport result. */+export type CrmQuery<T> = {+ readonly data: T | undefined;+ readonly isPending: boolean;+ readonly isSuccess: boolean;+ readonly isLoading: boolean;+ readonly isError: boolean;+ refetch(): Promise<unknown>;+};+export type CrmMutation<Input, Output = unknown> = {+ readonly isPending: boolean;+ mutate(+ input: Input,+ options?: {+ onSuccess?: (value: Output) => void;+ onError?: (error: Error) => void;+ onSettled?: () => void;+ }+ ): void;+ mutateAsync(input: Input): Promise<Output>;+};+export type CompanySource = {+ query: CrmQuery<unknown>;+ company: Accessor<CrmCompany | undefined>;+ contacts: Accessor<CrmContact[]>;+};+export type ContactSource = CrmQuery<CrmContact>;+export type TeamSource = CrmQuery<{+ team: { id: string; crm_enabled: boolean };+ members: { user_id: string; role: CrmTeamRole }[];+} | null>;+export type TeamConfigSource = {+ config: Accessor<TeamCrmConfig>;+ isLoading: Accessor<boolean>;+ isError: Accessor<boolean>;+ update: CrmMutation<TeamCrmConfigPatch>;+};+export type CrmCapabilities = {+ role: Accessor<CrmTeamRole | undefined>;+ permissions: Accessor<CrmPermissions>;+ isLoading: Accessor<boolean>;+ canEditCrm: Accessor<boolean>;+ canEditStages: Accessor<boolean>;+ canMoveClosedDeals: Accessor<boolean>;+ canDeleteRecords: Accessor<boolean>;+};++import type { DealStage } from '../core/stages';++export type { DealStage } from '../core/stages';+export type DealStages = {+ stages: Accessor<DealStage[]>;+ filterStages: Accessor<DealStage[]>;+ isCustomized: Accessor<boolean>;+ stageDefinitionId: Accessor<string>;+ stageProperty: Accessor<Property>;+ resolveStage: (company: {+ properties?: { definition: { id: string }; value?: unknown }[] | null;+ }) => string | undefined;+ stageLabel: (id: string) => string | undefined;+ isLoading: Accessor<boolean>;+ isError: Accessor<boolean>;+};+export type PersonalCrmView = {+ id: string;+ name: string;+ config: CrmViewConfig;+};+export type PersonalViewsSource = {+ views: Accessor<PersonalCrmView[]>;+ defaultView: Accessor<PersonalCrmView | undefined>;+ isLoading: Accessor<boolean>;+ create: CrmMutation<{ name: string; config: CrmViewConfig }>;+ rename: CrmMutation<{ id: string; name: string }>;+ remove: CrmMutation<{ id: string }>;+ setDefault: CrmMutation<{ id: string | undefined }>;+};+export type TeamViewsSource = {+ views: Accessor<TeamCrmSavedView[]>;+ defaultViewId: Accessor<string | undefined>;+ defaultView: Accessor<TeamCrmSavedView | undefined>;+ add(name: string, config: CrmViewConfig): void;+ remove(id: string): void;+ setDefault(id: string | undefined): void;+ isLoading: Accessor<boolean>;+ isSaving: Accessor<boolean>;+};+export type ListsSource = {+ query: CrmQuery<unknown>;+ lists: Accessor<{ id: string; name: string; config: CrmListConfig }[]>;+ save: CrmMutation<+ { id?: string; name: string; companyIds: string[] },+ string+ >;+ remove: CrmMutation<string>;+ setMembership: CrmMutation<{+ listId: string;+ companyId: string;+ included: boolean;+ }>;+};++export type CrmEmailScope = 'team' | 'me';+export type CrmEmailSignal = 'signal' | 'all';+export type EmailSource = {+ readonly isLoading: boolean;+ readonly data: { entities: import('@entity').EntityData[] } | undefined;+ readonly hasNextPage: boolean;+ readonly isFetchingNextPage: boolean;+ fetchNextPage(): Promise<unknown>;+};+export type CompanyPropertySave = {+ properties: {+ entityId: string;+ entityType: 'COMPANY';+ property: Property;+ apiValues: import('@property/types').PropertyApiValues;+ }[];+};+export type PropertyCommands = {+ mutate(value: CompanyPropertySave): void;+ mutateAsync(value: CompanyPropertySave): Promise<void>;+};+export type CrmStageInput = { id?: string | null; label: string };+export type CrmStagesResult = {+ definition_id: string;+ stages: { id: string; label: string }[];+};+export type ExportDefinition = {+ definition: { id: string; display_name: string; is_metadata: boolean };+ property_options: { id: string; value: { value: unknown } }[];+};+export type ExportDefinitionsSource = {+ readonly isPending: boolean;+ readonly isSuccess: boolean;+ readonly isError: boolean;+ readonly data: ExportDefinition[];+};++export type PeopleSource = {+ people: Accessor<import('../core/people').CrmPerson[]>;+ query: {+ readonly isError: boolean;+ readonly isFetching: boolean;+ readonly hasNextPage: boolean;+ readonly isFetchNextPageError: boolean;+ fetchNextPage(): Promise<unknown>;+ refetch(): Promise<unknown>;+ };+};diff --git a/apps/web/src/features/crm/context/view-commands.ts b/apps/web/src/features/crm/context/view-commands.tsnew file mode 100644index 0000000000..ecd764485c--- /dev/null+++ b/apps/web/src/features/crm/context/view-commands.ts@@ -0,0 +1,13 @@+import type { CrmViewConfig } from '../core/saved-view';+export type CrmViewCommands = {+ setActiveTab(value: string): void;+ replaceFilters(value: CrmViewConfig['filters']): void;+ replacePredicates(value: NonNullable<CrmViewConfig['clientFilters']>): void;+ setSearchText(value: string): void;+ setGroupBy(value: string | undefined): void;+ setSort(value: string[]): void;+ setStageFilter(value: string[]): void;+ setOwnerFilter(value: string[]): void;+ setViewMode(value: 'list' | 'board'): void;+ defaultMode(): 'list' | 'board';+};diff --git a/apps/web/src/features/crm/context/workspace-context.tsx b/apps/web/src/features/crm/context/workspace-context.tsxnew file mode 100644index 0000000000..f0a4c124af--- /dev/null+++ b/apps/web/src/features/crm/context/workspace-context.tsx@@ -0,0 +1,60 @@+import type { EntityData } from '@entity';+import {+ type Accessor,+ createContext,+ type Setter,+ useContext,+} from 'solid-js';+import type { EntityActionListState } from '../../next-soup/actions/entity-action-context';+import type { SoupState } from '../../next-soup/create-soup-state';+import type { QueryStore } from '../../next-soup/filters/filter-store/query-store';++/** Collection capabilities consumed by CRM views, supplied by the host adapter. */+export type CrmWorkspace = {+ host: {+ scopeId: string;+ isActive: Accessor<boolean>;+ focus(): void;+ captureEntryState(): void;+ openCompany(entity: EntityData, newSplit: boolean): void;+ openSettings(): void;+ openTeamSettings(): void;+ };++ soup: EntityActionListState & {+ selection: Pick<SoupState['selection'], 'clear' | 'selected'>;+ predicates: Pick<+ SoupState['predicates'],+ 'set' | 'isActive' | 'toggle' | 'andIds' | 'orIds'+ >;+ sort: Pick<SoupState['sort'], 'setAll' | 'active' | 'flip'>;+ grouping: Pick<SoupState['grouping'], 'activeGroupId' | 'setActiveGroupId'>;+ };+ source: {+ error: Accessor<Error | undefined | null>;+ data: Accessor<EntityData[]>;+ isLoading: Accessor<boolean>;+ isFetching: Accessor<boolean>;+ hasNextPage: Accessor<boolean>;+ fetchNextPage(): Promise<void>;+ };+ queryFilters: Pick<QueryStore, 'state' | 'replace'>;+ searchText: Accessor<string>;+ setSearchText(value: string): void;+ activeTab: Accessor<string | undefined>;+ setActiveTab: Setter<string | undefined>;+ stageFilter: Accessor<string[]>;+ setStageFilter: Setter<string[]>;+ ownerFilter: Accessor<string[]>;+ setOwnerFilter: Setter<string[]>;+ viewMode: Accessor<'list' | 'board'>;+ setViewMode: Setter<'list' | 'board'>;+};+const Context = createContext<CrmWorkspace>();+export const CrmWorkspaceProvider = Context.Provider;+export function useCrmWorkspace(): CrmWorkspace {+ const value = useContext(Context);+ if (!value)+ throw new Error('CRM workspace views require a CrmWorkspaceProvider');+ return value;+}diff --git a/apps/web/src/features/crm/core/company.ts b/apps/web/src/features/crm/core/company.tsnew file mode 100644index 0000000000..a280102bef--- /dev/null+++ b/apps/web/src/features/crm/core/company.ts@@ -0,0 +1,19 @@+/** Values consumed by company detail surfaces. */+export type CrmCompany = {+ type: 'crm_company';+ id: string;+ name: string;+ ownerId: string;+ teamId: string;+ description?: string;+ hidden: boolean;+ emailSync?: boolean;+ createdAt?: string | Date | null;+ updatedAt?: string | Date | null;+ domains: {+ id: string;+ companyId: string;+ domain: string;+ createdAt?: string | Date | null;+ }[];+};diff --git a/apps/web/src/features/crm/core/contact.ts b/apps/web/src/features/crm/core/contact.tsnew file mode 100644index 0000000000..2501d87f9f--- /dev/null+++ b/apps/web/src/features/crm/core/contact.ts@@ -0,0 +1,12 @@+/** CRM contact values, independent of the transport schema. */+export type CrmContact = {+ id: string;+ companyId: string;+ name?: string | null;+ email: string;+ hidden: boolean;+ firstInteraction: string;+ lastInteraction: string;+ createdAt: string;+ updatedAt: string;+};diff --git a/apps/web/src/features/crm/core/display-options.ts b/apps/web/src/features/crm/core/display-options.tsnew file mode 100644index 0000000000..65fcafa7f5--- /dev/null+++ b/apps/web/src/features/crm/core/display-options.ts@@ -0,0 +1,16 @@+export type CrmListColumnId = 'stage' | 'owner' | 'revenue';++export type CrmDisplayOptions = {+ /** Visible list columns (order stays fixed; this only hides/shows). */+ listColumns: Record<CrmListColumnId, boolean>;+};++export const DEFAULT_CRM_DISPLAY_OPTIONS: CrmDisplayOptions = {+ listColumns: { stage: true, owner: true, revenue: true },+};++export const CRM_LIST_COLUMN_LABELS: Record<CrmListColumnId, string> = {+ stage: 'Stage',+ owner: 'Owner',+ revenue: 'Revenue',+};diff --git a/apps/web/src/features/companies/core/crm-export.ts b/apps/web/src/features/crm/core/export.tssimilarity index 69%rename from apps/web/src/features/companies/core/crm-export.tsrename to apps/web/src/features/crm/core/export.tsindex 322268b3f4..48edc5f4b8 100644--- a/apps/web/src/features/companies/core/crm-export.ts+++ b/apps/web/src/features/crm/core/export.ts@@ -1,24 +1,7 @@-import type { CrmCompanyEntity } from '@entity';-import { SYSTEM_PROPERTY_IDS } from '@property/constants';-import type { CrmPerson } from './crm-people';+import type { CrmCompany } from './company';+import type { CrmPerson } from './people';export type ExportColumn = { id: string; label: string; default?: boolean };-export const COMPANY_EXPORT_COLUMNS: ExportColumn[] = [- { id: 'name', label: 'Company', default: true },- { id: 'domains', label: 'Domains', default: true },- { id: 'stage', label: 'Stage', default: true },- { id: 'owner', label: 'Owner', default: true },- {- id: `property:${SYSTEM_PROPERTY_IDS.REVENUE}`,- label: 'Revenue',- default: true,- },- { id: 'lastInteraction', label: 'Last interaction', default: true },- { id: 'firstInteraction', label: 'First interaction' },- { id: 'description', label: 'Description' },- { id: 'emailSync', label: 'Email sync' },- { id: 'id', label: 'Company ID' },-];export const PEOPLE_EXPORT_COLUMNS: ExportColumn[] = [{ id: 'name', label: 'Name', default: true },{ id: 'email', label: 'Email', default: true },@@ -54,13 +37,11 @@ export function createCrmCsv(columns: ExportColumn[], rows: ExportRecord[]) {);}-export function companyExportRecord(- company: CrmCompanyEntity,+export function companyExportRecord<P extends { definition: { id: string } }>(+ company: CrmCompany & { properties?: P[] },stage: string,owner: string,- propertyValue: (- property: NonNullable<CrmCompanyEntity['properties']>[number]- ) => string | number | boolean+ propertyValue: (property: P) => string | number | boolean): ExportRecord {return {id: company.id,diff --git a/apps/web/src/features/crm/core/import-companies.ts b/apps/web/src/features/crm/core/import-companies.tsnew file mode 100644index 0000000000..16921d5143--- /dev/null+++ b/apps/web/src/features/crm/core/import-companies.ts@@ -0,0 +1,37 @@+export type CompanyImportRow = { name: string; domain: string };+export function normalizeCompanyImport(+ records: readonly Record<string, string>[]+):+ | { rows: CompanyImportRow[]; error?: never }+ | { error: string; rows?: never } {+ const normalized = records.map((row) =>+ Object.fromEntries(+ Object.entries(row).map(([key, value]) => [+ key.toLowerCase(),+ value.trim(),+ ])+ )+ );+ if (+ !normalized.length ||+ normalized.length > 100 ||+ normalized.some(+ (row) =>+ !row.name ||+ !/^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/i.test(+ row.domain ?? ''+ )+ )+ ) {+ return {+ error:+ 'Use name and domain columns, with 1–100 companies and domains like acme.com.',+ };+ }+ return {+ rows: normalized.map((row) => ({+ name: row.name,+ domain: row.domain.toLowerCase(),+ })),+ };+}diff --git a/apps/web/src/features/companies/core/crm-navigation.test.ts b/apps/web/src/features/crm/core/navigation.test.tssimilarity index 98%rename from apps/web/src/features/companies/core/crm-navigation.test.tsrename to apps/web/src/features/crm/core/navigation.test.tsindex 8eeab0243c..6b0a69fd92 100644--- a/apps/web/src/features/companies/core/crm-navigation.test.ts+++ b/apps/web/src/features/crm/core/navigation.test.ts@@ -3,7 +3,7 @@ import {isCrmListConfig,matchesInteractionWindow,needsCompanyFollowUp,-} from './crm-navigation';+} from './navigation';const now = Date.parse('2026-09-16T12:00:00Z');const daysAgo = (days: number) => new Date(now - days * 86400000).toISOString();diff --git a/apps/web/src/features/companies/core/crm-navigation.ts b/apps/web/src/features/crm/core/navigation.tssimilarity index 100%rename from apps/web/src/features/companies/core/crm-navigation.tsrename to apps/web/src/features/crm/core/navigation.tsdiff --git a/apps/web/src/features/companies/core/crm-people.test.ts b/apps/web/src/features/crm/core/people.test.tssimilarity index 96%rename from apps/web/src/features/companies/core/crm-people.test.tsrename to apps/web/src/features/crm/core/people.test.tsindex ca26d35b2e..8af1670717 100644--- a/apps/web/src/features/companies/core/crm-people.test.ts+++ b/apps/web/src/features/crm/core/people.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { type CrmPerson, filterAndSortPeople } from './crm-people';+import { type CrmPerson, filterAndSortPeople } from './people';const person = (id: string, overrides: Partial<CrmPerson> = {}): CrmPerson => ({id,diff --git a/apps/web/src/features/companies/core/crm-people.ts b/apps/web/src/features/crm/core/people.tssimilarity index 84%rename from apps/web/src/features/companies/core/crm-people.tsrename to apps/web/src/features/crm/core/people.tsindex 51010e6c6d..6fd6531e29 100644--- a/apps/web/src/features/companies/core/crm-people.ts+++ b/apps/web/src/features/crm/core/people.ts@@ -1,6 +1,6 @@-import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';+import type { CrmContact } from './contact';-export type CrmPerson = CrmContactResponse & { companyName: string };+export type CrmPerson = CrmContact & { companyName: string };export type PeopleSort =| 'name'| 'companyName'diff --git a/apps/web/src/features/crm/core/saved-view.ts b/apps/web/src/features/crm/core/saved-view.tsnew file mode 100644index 0000000000..c97131a5a4--- /dev/null+++ b/apps/web/src/features/crm/core/saved-view.ts@@ -0,0 +1,68 @@+/** Snapshot of the Customers view state. Fields are all optional so old+ * links/views keep working as the shape evolves. */+export type CrmViewConfig = {+ kind: 'crm';+ /** Server query filters (soup `Query`). */+ filters?: unknown;+ /** Client predicate ids ({ and, or }). */+ clientFilters?: { and?: string[]; or?: string[] };+ searchText?: string;+ /** Group-by id (e.g. `property:<definition-id>`); null = no grouping. */+ groupBy?: string | null;+ /** Sort ids (soup sort state). */+ sort?: string[];+ viewMode?: 'list' | 'board';+ /** Stage option ids selected in the Stage filter (may include NO_STAGE). */+ stageFilter?: string[];+ /** Owner ids selected in the Owner filter. */+ ownerFilter?: string[];+ activeTab?: string;+ /** Personal views only: applied by default when opening the Customers view. */+ isDefault?: boolean;+};++const record = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);+const optionalStrings = (value: unknown): boolean =>+ value === undefined ||+ (Array.isArray(value) && value.every((item) => typeof item === 'string'));+/** Accept older snapshots and future fields, but never install malformed known state. */+export function isCrmViewConfig(value: unknown): value is CrmViewConfig {+ if (!record(value) || value.kind !== 'crm') return false;+ if (+ value.filters !== undefined &&+ value.filters !== null &&+ !record(value.filters)+ )+ return false;+ if (+ value.clientFilters !== undefined &&+ (!record(value.clientFilters) ||+ !optionalStrings(value.clientFilters.and) ||+ !optionalStrings(value.clientFilters.or))+ )+ return false;+ if (value.searchText !== undefined && typeof value.searchText !== 'string')+ return false;+ if (value.activeTab !== undefined && typeof value.activeTab !== 'string')+ return false;+ if (+ value.groupBy !== undefined &&+ value.groupBy !== null &&+ typeof value.groupBy !== 'string'+ )+ return false;+ if (+ value.viewMode !== undefined &&+ value.viewMode !== 'list' &&+ value.viewMode !== 'board'+ )+ return false;+ if (value.isDefault !== undefined && typeof value.isDefault !== 'boolean')+ return false;+ return (+ optionalStrings(value.sort) &&+ optionalStrings(value.stageFilter) &&+ optionalStrings(value.ownerFilter)+ );+}diff --git a/apps/web/src/features/crm/core/stages.ts b/apps/web/src/features/crm/core/stages.tsnew file mode 100644index 0000000000..56e8efe0c1--- /dev/null+++ b/apps/web/src/features/crm/core/stages.ts@@ -0,0 +1,57 @@+export type DealStage = { id: string; label: string };+export const NO_STAGE_KEY = '';+export type StageColumn = { key: string; label: string };++export function boardStageColumns(+ stages: readonly DealStage[],+ filterStages: readonly DealStage[],+ selected: readonly string[],+ noStageFilter: string+): StageColumn[] {+ const candidates = [+ ...filterStages.map((stage) => ({ key: stage.id, label: stage.label })),+ { key: NO_STAGE_KEY, label: 'No stage' },+ ];+ if (selected.length === 0) {+ const active = new Set(stages.map((stage) => stage.id));+ return candidates.filter(+ (column) => column.key === NO_STAGE_KEY || active.has(column.key)+ );+ }+ return candidates.filter((column) =>+ selected.includes(column.key === NO_STAGE_KEY ? noStageFilter : column.key)+ );+}++export function canDragCompanyStage(+ stageKey: string,+ canEdit: boolean,+ closed: ReadonlySet<string>,+ canMoveClosed: boolean+): boolean {+ return (+ canEdit &&+ (stageKey === NO_STAGE_KEY || !closed.has(stageKey) || canMoveClosed)+ );+}++export function resolveCompanyStage(input: {+ direct: string | undefined;+ customized: boolean;+ stages: readonly DealStage[];+ legacy: string | undefined;+ legacyMapping?: Readonly<Record<string, string>>;+ legacyLabel: (id: string) => string | undefined;+}): string | undefined {+ const { direct, customized, stages, legacy, legacyMapping, legacyLabel } =+ input;+ if (direct && stages.some((stage) => stage.id === direct)) return direct;+ if (!customized) return direct;+ if (!legacy) return undefined;+ const mapped = legacyMapping?.[legacy];+ if (mapped && stages.some((stage) => stage.id === mapped)) return mapped;+ const label = legacyLabel(legacy)?.toLowerCase();+ return label+ ? stages.find((stage) => stage.label.toLowerCase() === label)?.id+ : undefined;+}diff --git a/apps/web/src/features/crm/core/team-config.ts b/apps/web/src/features/crm/core/team-config.tsnew file mode 100644index 0000000000..bbbdc4b4c9--- /dev/null+++ b/apps/web/src/features/crm/core/team-config.ts@@ -0,0 +1,89 @@+/**+ * Minimum team role required for a CRM capability. Team members are+ * view-only at the platform level (the backend maps member → View access+ * on companies), so the configurable range is admin (default) vs owner.+ */+export type CrmPermissionRole = 'admin' | 'owner';++export type CrmPermissions = {+ /** Who can change the deal stage set in CRM settings. */+ editStages: CrmPermissionRole;+ /** Who can move deals out of a closed stage. */+ moveClosedDeals: CrmPermissionRole;+ /** Who can delete (hide) CRM records. */+ deleteRecords: CrmPermissionRole;+};++export type TeamCrmSavedView = {+ id: string;+ name: string;+ /** Serialized CRM view state (see crm/saved-views). */+ config: unknown;+ createdBy?: string;+ createdAt?: string;+};++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[];+ /** Team view applied by default when a member opens the Customers view. */+ defaultTeamViewId?: string;+};++/**+ * 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.+ */+export type TeamCrmConfigPatch = {+ permissions?: Partial<CrmPermissions>;+ closedStageIds?: string[] | null;+ teamViews?:+ | TeamCrmSavedView[]+ | ((current: TeamCrmSavedView[]) => TeamCrmSavedView[]);+ defaultTeamViewId?: string | null;+};++export const DEFAULT_CRM_PERMISSIONS: CrmPermissions = {+ editStages: 'admin',+ moveClosedDeals: 'admin',+ 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(+ role: CrmTeamRole | undefined,+ required: CrmPermissionRole+): boolean {+ 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/creation-adapter.ts b/apps/web/src/features/crm/creation-adapter.tsnew file mode 100644index 0000000000..09ec9b1c2e--- /dev/null+++ b/apps/web/src/features/crm/creation-adapter.ts@@ -0,0 +1,33 @@+import { useFocusLock } from '@core/util/createControlledOpenSignal';+import { createSignal } from 'solid-js';++// App-level launchers connect global create actions to the one mounted dialog host.+const [companyOpen, setCompanyOpen] = createSignal(false);+const [contactTarget, setContactTarget] = createSignal<{+ companyId: string;+ domain: string;+}>();+const companyLock = useFocusLock('create-company');+const contactLock = useFocusLock('create-contact');+export function openCreateCompanyModal() {+ companyLock.acquire();+ setCompanyOpen(true);+}+export function openCreateContactModal(companyId: string, domain: string) {+ contactLock.acquire();+ setContactTarget({ companyId, domain });+}+export const companyCreation = {+ open: companyOpen,+ close() {+ companyLock.release();+ setCompanyOpen(false);+ },+};+export const contactCreation = {+ target: contactTarget,+ close() {+ contactLock.release();+ setContactTarget(undefined);+ },+};diff --git a/apps/web/src/features/crm/crm-action-items.ts b/apps/web/src/features/crm/crm-action-items.tsnew file mode 100644index 0000000000..ce7bc1d632--- /dev/null+++ b/apps/web/src/features/crm/crm-action-items.ts@@ -0,0 +1,63 @@+import type { EntityData } from '@entity';+import type { EntityActionListState } from '../next-soup/actions/entity-action-context';+import { makeSetCompanyPropertyAction } from './crm-actions';+import { makeHideCompanyAction } from './crm-hide-action';+import { useSetCompanyHiddenMutation } from './record-adapter';++type CrmEntityActionItem = {+ id: string;+ label: string;+ onClick: () => void | Promise<void>;+};+/** CRM actions contributed to shared entity menus. */+export function createCrmEntityActionItems() {+ const hiddenMutation = useSetCompanyHiddenMutation();+ const hideCompanyAction = makeHideCompanyAction({+ setHidden: (companyId, hidden) =>+ hiddenMutation.mutateAsync({ companyId, hidden }),+ });+ const setCompanyPropertyAction = makeSetCompanyPropertyAction();++ return (+ entities: EntityData[],+ soup: EntityActionListState+ ): CrmEntityActionItem[] => {+ const canExecuteAll = (canExecute: (entity: EntityData) => boolean) =>+ entities.length > 0 && entities.every(canExecute);+ // CRM group: Set stage/owner/revenue on the whole company+ // selection, Hide / Unhide for a single company.+ const crmItems: CrmEntityActionItem[] = [];++ for (const [field, label] of [+ ['stage', 'Set stage'],+ ['owner', 'Set owner'],+ ['revenue', 'Set revenue'],+ ] as const) {+ if (+ !canExecuteAll((entity) =>+ setCompanyPropertyAction.canExecute(entity, field)+ )+ )+ continue;+ crmItems.push({+ id: `set-${field}`,+ label,+ onClick: () => setCompanyPropertyAction.execute(entities, field),+ });+ }++ const singleEntity = entities.length === 1 ? entities[0] : undefined;+ if (+ singleEntity?.type === 'crm_company' &&+ hideCompanyAction.canExecute(singleEntity)+ ) {+ crmItems.push({+ id: 'hide-company',+ label: singleEntity.hidden ? 'Unhide' : 'Hide',+ onClick: () => hideCompanyAction.executeWithSoup(entities, soup),+ });+ }++ return crmItems;+ };+}diff --git a/apps/web/src/features/crm/crm-actions.ts b/apps/web/src/features/crm/crm-actions.tsnew file mode 100644index 0000000000..432efb769e--- /dev/null+++ b/apps/web/src/features/crm/crm-actions.ts@@ -0,0 +1,47 @@+import { openPropertyEditor } from '@app/features/property/editor/state/propertyEditor';+import type { EntityData } from '@entity';+import { buildCompanyDefaultProperties } from '@entity/extractors-property';+import { SYSTEM_PROPERTY_IDS } from '@property/constants';+import type { Property } from '@property/types';+import { createAppDealStages } from './stage-adapter';++/** Builtin CRM company fields settable from entity action menus. */+export type CompanyCrmField = 'stage' | 'owner' | 'revenue';++/**+ * "Set stage / owner / revenue" for CRM company rows: opens the global+ * property editor (the same one task status/priority/assignee commands+ * use) targeting the builtin CRM property, editing the whole selection.+ * Available to all team members; the backend enforces write access on+ * property saves.+ */+export const makeSetCompanyPropertyAction = () => {+ const dealStages = createAppDealStages();++ const canExecute = (entity: EntityData, field: CompanyCrmField): boolean =>+ entity.type === 'crm_company' &&+ (field !== 'stage' || !dealStages.isLoading());++ const propertyFor = (field: CompanyCrmField): Property | undefined => {+ // Stage resolves through the active deal-stage set (the team's own+ // definition when customized) so edits write to the active definition.+ if (field === 'stage') return dealStages.stageProperty();+ const definitionId =+ field === 'owner'+ ? SYSTEM_PROPERTY_IDS.COMPANY_OWNER+ : SYSTEM_PROPERTY_IDS.REVENUE;+ return buildCompanyDefaultProperties().find(+ (property) => property.propertyDefinitionId === definitionId+ );+ };++ const execute = (entities: EntityData[], field: CompanyCrmField) => {+ // Stages are lazy: don't open an editor against system defaults before+ // the team's active definition has resolved.+ if (field === 'stage' && dealStages.isLoading()) return;+ const property = propertyFor(field);+ if (property) openPropertyEditor(entities, 'direct', property);+ };++ return { canExecute, execute };+};diff --git a/apps/web/src/features/crm/crm-adapter.ts b/apps/web/src/features/crm/crm-adapter.tsnew file mode 100644index 0000000000..bb83b62048--- /dev/null+++ b/apps/web/src/features/crm/crm-adapter.ts@@ -0,0 +1,161 @@+import { useQuickAccessCrmCompaniesQuery } from '@app/features/crm/crm-search';+import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { toast } from '@core/component/Toast/Toast';+import { enableCrmLists } from '@core/constant/featureFlags';+import { useUserId } from '@core/context/user';+import { getInitialsFromName } from '@core/user';+import { idToEmail } from '@core/user/util';+import { useListPropertiesQuery } from '@queries/properties/definitions';+import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';+import { useSoupAstItemsQuery } from '@queries/soup/items';+import { getSoupEntityById } from '@queries/soup/normalized-cache';+import {+ invalidateUserTeams,+ useCurrentTeamQuery,+ useIsTeamAdmin,+} from '@queries/team/teams';+import { patchTeamCrmSettings } from '@service-auth/crm';+import { storageServiceClient } from '@service-storage/client';+import { useQueryClient } from '@tanstack/solid-query';+import type { CrmContext } from './context/crm-context';+import {+ openCreateCompanyModal,+ openCreateContactModal,+} from './creation-adapter';+import { createAppCrmDisplayOptions } from './display-adapter';+import { downloadCrmCsv } from './download-adapter';+import {+ copyCrmRecordLink,+ copyCrmViewLink,+ createAppCrmNavigation,+} from './navigation-adapter';+import {+ createClosedStageIds,+ createCrmPermissions,+ createCrmUnavailable,+} from './primitives/team-config';+import {+ useCompanyQuery,+ useCreateCompanyMutation,+ useCreateContactMutation,+ useSetCompanyHiddenMutation,+ useSetCompanyNameMutation,+ useSetEmailSyncMutation,+} from './queries/companies';+import { useCompanyEmailsQuery } from './queries/company-emails';+import { useContactEmailsQuery } from './queries/contact-emails';+import {+ useContactQuery,+ useSetContactHiddenMutation,+ useSetContactNameMutation,+} from './queries/contacts';+import { fetchCrmExportCompanies } from './queries/export';+import { useCrmLists } from './queries/lists';+import { usePersonalCrmViews, useTeamCrmViews } from './queries/saved-views';+import { usePatchTeamCrmSettingsMutation } from './queries/settings-commands';+import {+ useReplaceCrmStagesMutation,+ useResetCrmStagesMutation,+} from './queries/stages';+import { useTeamCrmConfig } from './queries/team-config';+import { createAppDealStages } from './stage-adapter';++/** Only this app-facing adapter constructs production capabilities. */+export function createAppCrmContext(): CrmContext {+ const deps = {+ client: useQueryClient(),+ storage: storageServiceClient,+ feedback: toast,+ };+ const userId = useUserId();+ const createSettings = () => useTeamCrmConfig(deps);+ return {+ feedback: toast,+ downloadCsv: downloadCrmCsv,+ contactInitials: getInitialsFromName,+ userEmail: idToEmail,+ createNavigation: createAppCrmNavigation,+ copyRecordLink: copyCrmRecordLink,+ copyViewLink: copyCrmViewLink,+ listsEnabled() {+ const flag = useFeatureFlag(enableCrmLists);+ return () => flag().enabled;+ },+ createCompanyEmails: (...args) =>+ useCompanyEmailsQuery(useSoupAstItemsQuery, ...args),+ createContactEmails: (...args) =>+ useContactEmailsQuery(useSoupAstItemsQuery, ...args),+ createPropertyCommands: useBulkSaveEntityPropertiesMutation,+ createSettingsCommands: () =>+ usePatchTeamCrmSettingsMutation({+ ...deps,+ patch: patchTeamCrmSettings,+ invalidateTeams: invalidateUserTeams,+ }),+ createReplaceStages: () => useReplaceCrmStagesMutation(deps),+ createResetStages: () => useResetCrmStagesMutation(deps),+ exportCompanies: (...args) =>+ fetchCrmExportCompanies(deps.storage, ...args),+ createCompanySuggestions: useQuickAccessCrmCompaniesQuery,+ hydrateCompany(company) {+ if (company.properties) return company;+ const cached = getSoupEntityById(company.id);+ return cached?.tag === 'crmCompany'+ ? { ...company, properties: cached.data.properties }+ : company;+ },+ createExportDefinitions(enabled) {+ const query = useListPropertiesQuery(+ () => ({+ scope: 'all',+ includeOptions: true,+ forEntityType: 'COMPANY',+ }),+ enabled+ );+ return {+ get isPending() {+ return query.isPending;+ },+ get isSuccess() {+ return query.isSuccess;+ },+ get isError() {+ return query.isError;+ },+ get data() {+ return (query.data ?? []).map((entry) =>+ 'definition' in entry+ ? entry+ : { definition: entry, property_options: [] }+ );+ },+ };+ },+ createDisplayOptions: createAppCrmDisplayOptions,+ openCreateCompany: openCreateCompanyModal,+ openCreateContact: openCreateContactModal,+ userId,+ isTeamAdmin: useIsTeamAdmin,+ createCompanySource: (...args) => useCompanyQuery(deps, ...args),+ createContactSource: (...args) => useContactQuery(deps, ...args),+ createTeamSource: useCurrentTeamQuery,+ createTeamConfigSource: createSettings,+ createCapabilities: () =>+ createCrmPermissions(userId, useCurrentTeamQuery(), createSettings()),+ createDealStages: createAppDealStages,+ createUnavailable: () => createCrmUnavailable(useCurrentTeamQuery()),+ createClosedStageIds: (stages) =>+ createClosedStageIds(createSettings(), stages),+ createPersonalViews: () => usePersonalCrmViews(deps),+ createTeamViews: () => useTeamCrmViews(deps, userId, createSettings()),+ createLists: (teamId) => useCrmLists(deps, teamId),+ createCompany: (...args) => useCreateCompanyMutation(deps, ...args),+ createContact: (...args) => useCreateContactMutation(deps, ...args),+ renameCompany: (...args) => useSetCompanyNameMutation(deps, ...args),+ renameContact: (...args) => useSetContactNameMutation(deps, ...args),+ hideCompany: (...args) => useSetCompanyHiddenMutation(deps, ...args),+ hideContact: (...args) => useSetContactHiddenMutation(deps, ...args),+ setEmailSync: (...args) => useSetEmailSyncMutation(deps, ...args),+ };+}diff --git a/apps/web/src/features/crm/crm-company.tsx b/apps/web/src/features/crm/crm-company.tsxnew file mode 100644index 0000000000..11ce99059e--- /dev/null+++ b/apps/web/src/features/crm/crm-company.tsx@@ -0,0 +1,11 @@+import type { ComponentProps } from 'solid-js';+import { CrmProvider } from './context/crm-context';+import { createAppCrmContext } from './crm-adapter';+import { Company as View } from './views/company-detail';+export function Company(props: ComponentProps<typeof View>) {+ return (+ <CrmProvider value={createAppCrmContext()}>+ <View {...props} />+ </CrmProvider>+ );+}diff --git a/apps/web/src/features/crm/crm-contact.tsx b/apps/web/src/features/crm/crm-contact.tsxnew file mode 100644index 0000000000..898e02ce2a--- /dev/null+++ b/apps/web/src/features/crm/crm-contact.tsx@@ -0,0 +1,11 @@+import type { ComponentProps } from 'solid-js';+import { CrmProvider } from './context/crm-context';+import { createAppCrmContext } from './crm-adapter';+import { Contact as View } from './views/contact-detail';+export function Contact(props: ComponentProps<typeof View>) {+ return (+ <CrmProvider value={createAppCrmContext()}>+ <View {...props} />+ </CrmProvider>+ );+}diff --git a/apps/web/src/features/crm/crm-create.tsx b/apps/web/src/features/crm/crm-create.tsxnew file mode 100644index 0000000000..71510ec847--- /dev/null+++ b/apps/web/src/features/crm/crm-create.tsx@@ -0,0 +1,35 @@+import { useSplitLayout } from '@components/app/split-layout/layout';+import { CrmProvider } from './context/crm-context';+import { companyCreation, contactCreation } from './creation-adapter';+import { createAppCrmContext } from './crm-adapter';+import { CreateCompanyModal as CompanyDialog } from './views/create-company';+import { CreateContactModal as ContactDialog } from './views/create-contact';++export {+ openCreateCompanyModal,+ openCreateContactModal,+} from './creation-adapter';+export function CreateCompanyModal() {+ const { replaceOrInsertSplit } = useSplitLayout();+ return (+ <CrmProvider value={createAppCrmContext()}>+ <CompanyDialog+ open={companyCreation.open()}+ onClose={companyCreation.close}+ onCreated={(id) => replaceOrInsertSplit({ type: 'company', id })}+ />+ </CrmProvider>+ );+}+export function CreateContactModal() {+ const { replaceOrInsertSplit } = useSplitLayout();+ return (+ <CrmProvider value={createAppCrmContext()}>+ <ContactDialog+ target={contactCreation.target()}+ onClose={contactCreation.close}+ onCreated={(id) => replaceOrInsertSplit({ type: 'contact', id })}+ />+ </CrmProvider>+ );+}diff --git a/apps/web/src/features/crm/crm-hide-action.ts b/apps/web/src/features/crm/crm-hide-action.tsnew file mode 100644index 0000000000..264d5b1420--- /dev/null+++ b/apps/web/src/features/crm/crm-hide-action.ts@@ -0,0 +1,46 @@+import { toast } from '@core/component/Toast/Toast';+import type { EntityData } from '@entity';+import type { EntityActionListState } from '../next-soup/actions/entity-action-context';+import { restoreSoupFocus } from '../next-soup/utils';++type MakeHideCompanyOptions = {+ // Available to all team members; the backend enforces+ // EditAccessLevel on PUT /crm/companies/{id}/hidden.+ setHidden: (companyId: string, hidden: boolean) => Promise<unknown>;+};++export const makeHideCompanyAction = (options: MakeHideCompanyOptions) => {+ const { setHidden } = options;++ const canExecute = (entity: EntityData): boolean =>+ entity.type === 'crm_company';++ const executeWithSoup = async (+ entities: EntityData[],+ soup: EntityActionListState+ ) => {+ const entity = entities[0];+ if (entity?.type !== 'crm_company') return;++ // The row leaves (Hide) or joins (Unhide) the active list once soup+ // refetches, so move focus to a neighbour first — same as delete.+ const currentIndex = soup.focus.index();+ const nextRow =+ soup.items.at(currentIndex + 1) ?? soup.items.at(currentIndex - 1);+ const hidden = entity.hidden;++ soup.selection.clear();+ if (nextRow) soup.focus.set(nextRow.id);++ try {+ await setHidden(entity.id, !hidden);+ toast.success(hidden ? 'Unhidden' : 'Hidden');+ } catch {+ toast.failure(hidden ? 'Failed to unhide' : 'Failed to hide');+ }++ await restoreSoupFocus(nextRow?.id);+ };++ return { canExecute, executeWithSoup };+};diff --git a/apps/web/src/features/crm/crm-link.tsx b/apps/web/src/features/crm/crm-link.tsxnew file mode 100644index 0000000000..6287bca6da--- /dev/null+++ b/apps/web/src/features/crm/crm-link.tsx@@ -0,0 +1,13 @@+import { CrmProvider } from './context/crm-context';+import { createAppCrmContext } from './crm-adapter';+import { CrmCopyLinkButton as View } from './views/copy-link-button';+export function CrmCopyLinkButton(props: {+ type: 'company' | 'contact';+ id: string;+}) {+ return (+ <CrmProvider value={createAppCrmContext()}>+ <View {...props} />+ </CrmProvider>+ );+}diff --git a/apps/web/src/features/crm/crm-search.ts b/apps/web/src/features/crm/crm-search.tsnew file mode 100644index 0000000000..9afc3c1f3e--- /dev/null+++ b/apps/web/src/features/crm/crm-search.ts@@ -0,0 +1,10 @@+export { materializeCachedGraphqlCrmCompanies } from './queries/graphql';++import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { enableCrm } from '@core/constant/featureFlags';+import { useSoupItemsQuery } from '@queries/soup/items';+import { useQuickAccessCrmCompaniesQuery as createSuggestions } from './queries/company-suggestions';+export function useQuickAccessCrmCompaniesQuery() {+ const flag = useFeatureFlag(enableCrm);+ return createSuggestions(useSoupItemsQuery, () => flag().enabled);+}diff --git a/apps/web/src/features/crm/crm-settings.tsx b/apps/web/src/features/crm/crm-settings.tsxnew file mode 100644index 0000000000..a34d850206--- /dev/null+++ b/apps/web/src/features/crm/crm-settings.tsx@@ -0,0 +1,11 @@+import type { ComponentProps } from 'solid-js';+import { CrmProvider } from './context/crm-context';+import { createAppCrmContext } from './crm-adapter';+import { Crm as View } from './views/crm-settings';+export function CrmSettings(props: ComponentProps<typeof View>) {+ return (+ <CrmProvider value={createAppCrmContext()}>+ <View {...props} />+ </CrmProvider>+ );+}diff --git a/apps/web/src/features/crm/crm-tool-renderers.tsx b/apps/web/src/features/crm/crm-tool-renderers.tsxnew file mode 100644index 0000000000..18edaf456b--- /dev/null+++ b/apps/web/src/features/crm/crm-tool-renderers.tsx@@ -0,0 +1,95 @@+import { BaseTool } from '@core/component/AI/component/tool/BaseTool';+import { createToolRenderer } from '@core/component/AI/component/tool/ToolRenderer';+import Buildings from '@phosphor-icons/core/regular/buildings.svg';+import { Show } from 'solid-js';+import {+ GetCompanyToolResponse,+ ListCompaniesToolResponse,+ pluralize,+} from './components/tool-companies';++const listCompaniesHandler = createToolRenderer({+ name: 'ListCompanies',+ render: (ctx) => {+ const companies = () => ctx.response?.data.companies ?? [];+ const statusText = () => {+ if (!ctx.response) return undefined;+ if (companies().length === 0) return 'No results';+ return pluralize(companies().length, 'company', 'companies');+ };++ return (+ <BaseTool+ icon={Buildings}+ renderContext={ctx.renderContext}+ type="call"+ response={+ ctx.response ? (+ <ListCompaniesToolResponse {...ctx.response.data} />+ ) : undefined+ }+ >+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3 overflow-hidden">+ <span class="min-w-0 truncate">+ List CRM companies+ <Show when={ctx.tool.data.search}>+ {(search) => <> matching "{search()}"</>}+ </Show>+ <Show when={ctx.tool.data.stage}>+ {(stage) => <> in stage {stage()}</>}+ </Show>+ </span>+ <Show when={statusText()}>+ {(text) => (+ <span class="shrink-0 whitespace-nowrap text-xs text-ink-extra-muted">+ {text()}+ </span>+ )}+ </Show>+ </div>+ </BaseTool>+ );+ },+});++const getCompanyHandler = createToolRenderer({+ name: 'GetCompany',+ render: (ctx) => {+ const statusText = () => {+ if (!ctx.response) return undefined;+ const data = ctx.response.data;+ return data.stage?.label ?? data.domains[0];+ };++ return (+ <BaseTool+ icon={Buildings}+ renderContext={ctx.renderContext}+ type="call"+ response={+ ctx.response ? (+ <GetCompanyToolResponse {...ctx.response.data} />+ ) : undefined+ }+ >+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3 overflow-hidden">+ <span class="min-w-0 truncate">+ Read CRM company+ <Show when={ctx.response?.data.name}>+ {(name) => <> {name()}</>}+ </Show>+ </span>+ <Show when={statusText()}>+ {(text) => (+ <span class="shrink-0 whitespace-nowrap text-xs text-ink-extra-muted">+ {text()}+ </span>+ )}+ </Show>+ </div>+ </BaseTool>+ );+ },+});++export { getCompanyHandler, listCompaniesHandler };diff --git a/apps/web/src/features/crm/crm-user-action.tsx b/apps/web/src/features/crm/crm-user-action.tsxnew file mode 100644index 0000000000..d4b77165b4--- /dev/null+++ b/apps/web/src/features/crm/crm-user-action.tsx@@ -0,0 +1,51 @@+import { useCrmContactByEmailQuery } from '@app/features/crm/record-adapter';+import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { useSplitLayout } from '@components/app/split-layout/layout';+import type { UserCardAction } from '@core/component/userCardActions';+import { enableCrm } from '@core/constant/featureFlags';+import WideContact from '@phosphor/address-book.svg';+import { useCurrentTeamQuery } from '@queries/team/teams';+import type { Accessor } from 'solid-js';++export function createCrmUserCardAction(+ email: Accessor<string | undefined>+): Accessor<UserCardAction | undefined> {+ const crmFlag = useFeatureFlag(enableCrm);+ const { openWithSplit } = useSplitLayout();+ // Only the CRM contact lookup needs the team, so a card on a workspace+ // without CRM never fetches one.+ const currentTeamQuery = useCurrentTeamQuery(() => crmFlag().enabled);+ // Guarded reads: an unguarded `data` suspends whoever renders the card, and+ // a card that suspends takes its hover surface or sheet down with it.+ const team = () =>+ currentTeamQuery.isSuccess ? currentTeamQuery.data?.team : undefined;+ const crmEnabled = () => crmFlag().enabled && team()?.crm_enabled === true;+ const contactQuery = useCrmContactByEmailQuery(+ () => team()?.id ?? '',+ () => email() ?? '',+ crmEnabled+ );+ const crmContact = () =>+ crmEnabled() && contactQuery.isSuccess ? contactQuery.data : undefined;++ const openContact = (event: MouseEvent, contactId: string) => {+ event.preventDefault();+ event.stopPropagation();+ openWithSplit(+ { type: 'contact', id: contactId },+ { preferNewSplit: event.shiftKey, reopen: 'latest' }+ );+ };++ return () => {+ const contact = crmContact();+ return contact+ ? {+ id: 'open-contact',+ label: 'Open contact',+ icon: WideContact,+ onSelect: (event) => openContact(event, contact.id),+ }+ : undefined;+ };+}diff --git a/apps/web/src/features/crm/crm.tsx b/apps/web/src/features/crm/crm.tsxnew file mode 100644index 0000000000..f80bd2ebfd--- /dev/null+++ b/apps/web/src/features/crm/crm.tsx@@ -0,0 +1,29 @@+import { Show } from 'solid-js';+import { SoupViewStateProvider } from '../next-soup/soup-view/soup-view-context';+import { ViewTour } from '../tours/ViewTour';+import { CrmProvider } from './context/crm-context';+import { CrmWorkspaceProvider } from './context/workspace-context';+import type { CrmViewConfig } from './core/saved-view';+import { createAppCrmContext } from './crm-adapter';+import { companiesTour } from './tour';+import { Companies } from './views/companies';+import { CrmDefaultViewLoader } from './views/default-view';+import { createCrmWorkspace } from './workspace-adapter';++export function Crm(props: { initialView?: CrmViewConfig }) {+ const crm = createAppCrmContext();+ const workspace = createCrmWorkspace(crm, props.initialView);+ return (+ <CrmProvider value={crm}>+ <SoupViewStateProvider state={workspace.state}>+ <CrmWorkspaceProvider value={workspace.context}>+ <Show when={workspace.applyDefaultCrmView}>+ <CrmDefaultViewLoader />+ </Show>+ <Companies />+ <ViewTour tour={companiesTour} />+ </CrmWorkspaceProvider>+ </SoupViewStateProvider>+ </CrmProvider>+ );+}diff --git a/apps/web/src/features/crm/display-adapter.ts b/apps/web/src/features/crm/display-adapter.tsnew file mode 100644index 0000000000..f9c261db72--- /dev/null+++ b/apps/web/src/features/crm/display-adapter.ts@@ -0,0 +1,15 @@+import { makePersisted } from '@solid-primitives/storage';+import { createSignal } from 'solid-js';+import {+ type CrmDisplayOptions,+ DEFAULT_CRM_DISPLAY_OPTIONS,+} from './core/display-options';+import { createCrmDisplayOptions } from './primitives/display-options';++// One app preference keeps every mounted CRM surface in sync.+const [options, setOptions] = makePersisted(+ createSignal<CrmDisplayOptions>(DEFAULT_CRM_DISPLAY_OPTIONS),+ { name: 'macro:pref:crm:display' }+);+export const createAppCrmDisplayOptions = () =>+ createCrmDisplayOptions(options, setOptions);diff --git a/apps/web/src/features/crm/download-adapter.ts b/apps/web/src/features/crm/download-adapter.tsnew file mode 100644index 0000000000..9c631b5545--- /dev/null+++ b/apps/web/src/features/crm/download-adapter.ts@@ -0,0 +1,6 @@+import { downloadFile } from '@filesystem/download';++export function downloadCrmCsv(content: string, filename: string) {+ const blob = new Blob([content], { type: 'text/csv;charset=utf-8' });+ return downloadFile(blob, filename);+}diff --git a/apps/web/src/features/crm/filter-adapter.tsx b/apps/web/src/features/crm/filter-adapter.tsxnew file mode 100644index 0000000000..950a5a22a7--- /dev/null+++ b/apps/web/src/features/crm/filter-adapter.tsx@@ -0,0 +1,239 @@+import { makeFlaggedPersisted } from '@app/preferences/make-flagged-persisted';+import { useEntryState } from '@components/app/split-layout/entry-state';+import { UserIcon } from '@core/component/UserIcon';+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import { idToDisplayName } from '@core/user/util';+import CircleDashedIcon from '@phosphor/circle-dashed.svg';+import { useContacts } from '@queries/contacts/contacts';+import { createLazyMemo } from '@solid-primitives/memo';+import { type Accessor, createEffect, type JSX } from 'solid-js';+import type { SoupState } from '../next-soup/create-soup-state';+import { NO_ASSIGNEE, NO_STAGE } from '../next-soup/filters/configs';+import type { CollectionSelectFilter } from '../next-soup/soup-view/collection-select-filter';+import type { SearchableOption } from '../next-soup/soup-view/filters-bar/searchable-multi-select';+import { buildContactLabel } from '../next-soup/soup-view/filters-bar/unified-filter-dropdown';+import { CrmStageIcon } from './components/stage-icon';+import type { CrmContext } from './context/crm-context';+import type { DealStages } from './context/crm-sources';+import { createCrmFilterSelections } from './primitives/filter-selections';++export function createCrmCollectionFilters(+ crm: CrmContext,+ soup: SoupState,+ persist: Accessor<boolean>,+ dealStages: DealStages+) {+ const [ownerFilter, setOwnerFilter] = makeFlaggedPersisted(+ useEntryState<string[]>('soup.ownerFilter', { default: [] }),+ { enabled: persist, name: 'soup-view-owner-filter-v2' }+ );+ const [stageFilter, setStageFilter] = makeFlaggedPersisted(+ useEntryState<string[]>('soup.stageFilter', { default: [] }),+ { enabled: persist, name: 'soup-view-stage-filter-v2' }+ );+ const [viewMode, setViewMode] = useEntryState<'list' | 'board'>(+ 'soup.viewMode',+ { default: isTouchDevice() ? 'list' : 'board' }+ );+ const userId = crm.userId;+ const currentUserId = userId;+ const teamQuery = crm.createTeamSource();+ const contacts = useContacts();+ const ownerOptions = createLazyMemo((): SearchableOption[] => {+ const currentUserId = userId();+ const noOwnerOption: SearchableOption = {+ id: NO_ASSIGNEE,+ label: 'No owner',+ icon: () => <CircleDashedIcon class="size-3.5 text-ink-muted" />,+ };+ let meOption: SearchableOption | undefined;+ const memberOptions: SearchableOption[] = [];+ for (const member of (teamQuery.isSuccess+ ? teamQuery.data?.members+ : undefined) ?? []) {+ const id = member.user_id;+ const opt: SearchableOption = {+ id,+ label: buildContactLabel(+ { id, name: idToDisplayName(id) },+ currentUserId+ ),+ icon: () => (+ <UserIcon id={id} size="sm" suppressClick showTooltip={false} />+ ),+ };+ if (id === currentUserId) {+ meOption = opt;+ } else {+ memberOptions.push(opt);+ }+ }+ memberOptions.sort((a, b) => a.label.localeCompare(b.label));+ return [...(meOption ? [meOption] : []), noOwnerOption, ...memberOptions];+ });++ const stageOptions = createLazyMemo((): SearchableOption[] => [+ ...dealStages.filterStages().map((stage, index) => ({+ id: stage.id,+ label: stage.label,+ icon: () => (+ <CrmStageIcon optionId={stage.id} index={index} class="size-3.5" />+ ),+ })),+ {+ id: NO_STAGE,+ label: 'No stage',+ icon: () => <CircleDashedIcon class="size-3.5 text-ink-muted" />,+ },+ ]);++ const ownerOptionsMap = createLazyMemo(+ (): Map<string, { label: string; icon?: () => JSX.Element }> => {+ const uid = currentUserId();+ const map = new Map<+ string,+ { label: string; icon?: () => JSX.Element }+ >();+ map.set(NO_ASSIGNEE, {+ label: 'No owner',+ icon: () => <CircleDashedIcon class="size-3 text-ink-muted" />,+ });+ for (const contact of contacts()) {+ map.set(contact.id, {+ label: buildContactLabel(contact, uid),+ icon: () => (+ <UserIcon+ id={contact.id}+ size="sm"+ suppressClick+ showTooltip={false}+ />+ ),+ });+ }+ return map;+ }+ );++ const ownerSearchableOptions = createLazyMemo((): SearchableOption[] => {+ const uid = currentUserId();+ const noOwnerOption: SearchableOption = {+ id: NO_ASSIGNEE,+ label: 'No owner',+ icon: () => <CircleDashedIcon class="size-3.5 text-ink-muted" />,+ };+ let meOption: SearchableOption | undefined;+ const otherContactOptions: SearchableOption[] = [];+ for (const contact of contacts()) {+ const opt: SearchableOption = {+ id: contact.id,+ label: buildContactLabel(contact, uid),+ icon: () => (+ <UserIcon+ id={contact.id}+ size="sm"+ suppressClick+ showTooltip={false}+ />+ ),+ };+ if (contact.id === uid) {+ meOption = opt;+ } else {+ otherContactOptions.push(opt);+ }+ }+ return [+ ...(meOption ? [meOption] : []),+ noOwnerOption,+ ...otherContactOptions,+ ];+ });++ const stageOptionsMap = createLazyMemo(+ (): Map<string, { label: string; icon?: () => JSX.Element }> => {+ const map = new Map<+ string,+ { label: string; icon?: () => JSX.Element }+ >();+ for (const option of stageOptions()) {+ map.set(option.id, { label: option.label, icon: option.icon });+ }+ return map;+ }+ );++ const actions = createCrmFilterSelections({+ ownerFilter,+ setOwnerFilter,+ stageFilter,+ setStageFilter,+ defaultStages: () => [+ ...dealStages.stages().map((stage) => stage.id),+ NO_STAGE,+ ],+ isActive: soup.predicates.isActive,+ toggle: (id) => soup.predicates.toggle({ and: [id] }),+ });+ // Leaving company presets clears their sub-filters, matching the legacy view lifecycle.+ createEffect(() => {+ if (+ !soup.predicates.isActive('crm-company-active') &&+ !soup.predicates.isActive('crm-company-hidden')+ ) {+ setOwnerFilter([]);+ setStageFilter([]);+ }+ });+ const facets: CollectionSelectFilter[] = [+ {+ id: 'stage',+ label: 'Stage',+ placeholder: 'Filter stages...',+ values: stageFilter,+ effectiveValues: actions.effectiveStages,+ options: stageOptions,+ chipOptions: stageOptions,+ chipValues: () =>+ stageFilter().map((id) => ({+ id,+ label: stageOptionsMap().get(id)?.label ?? id,+ icon: stageOptionsMap().get(id)?.icon,+ })),+ change: actions.changeStage,+ changeChip: actions.changeStageChip,+ clear: () => setStageFilter([]),+ active: () => stageFilter().length > 0,+ preserveOrder: true,+ },+ {+ id: 'owner',+ label: 'Owner',+ placeholder: 'Search owners...',+ values: ownerFilter,+ effectiveValues: ownerFilter,+ options: ownerOptions,+ chipOptions: ownerSearchableOptions,+ chipValues: () =>+ ownerFilter().map((id) => ({+ id,+ label: ownerOptionsMap().get(id)?.label ?? id,+ icon: ownerOptionsMap().get(id)?.icon,+ })),+ change: actions.changeOwner,+ changeChip: actions.changeOwner,+ clear: () => setOwnerFilter([]),+ },+ ];+ return {+ facets,+ state: {+ ownerFilter,+ setOwnerFilter,+ stageFilter,+ setStageFilter,+ viewMode,+ setViewMode,+ },+ };+}diff --git a/apps/web/src/features/crm/group-options.ts b/apps/web/src/features/crm/group-options.tsnew file mode 100644index 0000000000..f7a45eff45--- /dev/null+++ b/apps/web/src/features/crm/group-options.ts@@ -0,0 +1,7 @@+import { SYSTEM_PROPERTY_IDS } from '@property/constants';+import type { GroupOption } from '../next-soup/soup-view/group-options';+export const COMPANY_GROUP_OPTIONS: GroupOption[] = [+ { value: 'none', label: 'None' },+ { value: `property:${SYSTEM_PROPERTY_IDS.STAGE}`, label: 'Stage' },+ { value: `property:${SYSTEM_PROPERTY_IDS.COMPANY_OWNER}`, label: 'Owner' },+];diff --git a/apps/web/src/features/crm/navigation-adapter.ts b/apps/web/src/features/crm/navigation-adapter.tsnew file mode 100644index 0000000000..d4958bc7ca--- /dev/null+++ b/apps/web/src/features/crm/navigation-adapter.ts@@ -0,0 +1,52 @@+import { useSplitLayout } from '@components/app/split-layout/layout';+import { useSplitPanel } from '@components/app/split-layout/layoutUtils';+import { toast } from '@core/component/Toast/Toast';+import { buildSimpleEntityUrl } from '@core/util/url';+import { openEntityInSplitFromUnifiedList } from '../next-soup/utils';+import type { CrmContext } from './context/crm-context';+import type { CrmViewConfig } from './core/saved-view';+import {+ CRM_VIEW_URL_PARAM,+ encodeCrmViewParam,+} from './queries/saved-view-codec';+/** Share link for a view config: /companies?crmView=<encoded>. */+export function buildCrmViewShareUrl(config: CrmViewConfig): string {+ const url = new URL('/companies', window.location.origin);+ url.searchParams.set(CRM_VIEW_URL_PARAM, encodeCrmViewParam(config));+ return url.toString();+}++export function copyCrmViewLink(config: CrmViewConfig) {+ navigator.clipboard+ .writeText(buildCrmViewShareUrl(config))+ .then(() => toast.success('Link copied to clipboard'))+ .catch(() => toast.failure('Failed to copy link'));+}+export async function copyCrmRecordLink(target: {+ type: 'company' | 'contact';+ id: string;+}) {+ try {+ await navigator.clipboard.writeText(buildSimpleEntityUrl(target));+ toast.success('Link copied to clipboard');+ } catch {+ toast.failure('Could not copy link. Please try again.');+ }+}+export function createAppCrmNavigation(): ReturnType<+ CrmContext['createNavigation']+> {+ const layout = useSplitLayout();+ return {+ splitId: useSplitPanel()?.handle.id,+ openWithSplit: (target, options) => {+ layout.openWithSplit(target, options);+ },+ showCompanies: () => {+ layout.replaceOrInsertSplit({ type: 'component', id: 'companies' });+ },+ openEmail: (entity) => {+ void openEntityInSplitFromUnifiedList(entity, {});+ },+ };+}diff --git a/apps/web/src/features/crm/preview-adapter.ts b/apps/web/src/features/crm/preview-adapter.tsnew file mode 100644index 0000000000..92c50bdc40--- /dev/null+++ b/apps/web/src/features/crm/preview-adapter.ts@@ -0,0 +1,5 @@+import { storageServiceClient } from '@service-storage/client';+import { fetchCrmCompanyPreviews as fetchPreviews } from './queries/previews';+export function fetchCrmCompanyPreviews(ids: string[]) {+ return fetchPreviews((input) => storageServiceClient.getCompany(input), ids);+}diff --git a/apps/web/src/features/crm/primitives/apply-view.ts b/apps/web/src/features/crm/primitives/apply-view.tsnew file mode 100644index 0000000000..cb4cc53027--- /dev/null+++ b/apps/web/src/features/crm/primitives/apply-view.ts@@ -0,0 +1,19 @@+import { batch } from 'solid-js';+import type { CrmViewCommands } from '../context/view-commands';+import type { CrmViewConfig } from '../core/saved-view';+/** Apply an entire snapshot atomically, preserving explicit ungrouped layouts. */+export function createApplyCrmView(commands: CrmViewCommands) {+ return (config: CrmViewConfig) =>+ batch(() => {+ if (config.activeTab !== undefined)+ commands.setActiveTab(config.activeTab);+ commands.replaceFilters(config.filters);+ commands.replacePredicates(config.clientFilters ?? {});+ commands.setSearchText(config.searchText ?? '');+ commands.setGroupBy(config.groupBy ?? undefined);+ commands.setSort(config.sort?.length ? config.sort : ['updated_at']);+ commands.setStageFilter(config.stageFilter ?? []);+ commands.setOwnerFilter(config.ownerFilter ?? []);+ commands.setViewMode(config.viewMode ?? commands.defaultMode());+ });+}diff --git a/apps/web/src/features/crm/primitives/company-board.test.ts b/apps/web/src/features/crm/primitives/company-board.test.tsnew file mode 100644index 0000000000..def38847bc--- /dev/null+++ b/apps/web/src/features/crm/primitives/company-board.test.ts@@ -0,0 +1,73 @@+import { createRoot, createSignal } from 'solid-js';+import { describe, expect, it, vi } from 'vitest';+import { createCompanyBoard } from './company-board';++describe('company board', () => {+ it('retains a newer drag when an earlier request fails, then accepts remote updates', () => {+ const [companies, setCompanies] = createSignal([+ { id: 'acme', stage: 'lead' },+ ]);+ const failures: (() => void)[] = [];+ const { board, dispose } = createRoot((dispose) => ({+ dispose,+ board: createCompanyBoard({+ companies,+ stages: () =>+ ['lead', 'active', 'closed'].map((id) => ({ id, label: id })),+ filterStages: () => [],+ selectedStages: () => [],+ noStageFilter: 'NO_STAGE',+ resolveStage: (company) => company.stage,+ canEdit: () => true,+ canMoveClosed: () => false,+ closedStages: () => new Set(['closed']),+ saveStage: (_id, _stage, failed) => failures.push(failed),+ }),+ }));+ board.moveToStage('acme', 'active');+ board.moveToStage('acme', 'closed');+ failures[0]();+ expect(board.effectiveStage(companies()[0])).toBe('closed');+ setCompanies([{ id: 'acme', stage: 'closed' }]);+ setCompanies([{ id: 'acme', stage: 'lead' }]);+ expect(board.effectiveStage(companies()[0])).toBe('lead');+ expect(board.canDragFrom('closed')).toBe(false);+ expect(board.canDragFrom('lead')).toBe(true);+ dispose();+ });+ it('shows selected legacy and no-stage columns in pipeline order', () => {+ const stages = [{ id: 'new', label: 'New' }];+ const legacy = { id: 'legacy', label: 'Legacy' };+ const saveStage = vi.fn();+ const { board, dispose } = createRoot((dispose) => ({+ dispose,+ board: createCompanyBoard({+ companies: () => [+ { id: 'a', stage: 'legacy' },+ { id: 'b', stage: undefined },+ ],+ stages: () => stages,+ filterStages: () => [...stages, legacy],+ selectedStages: () => ['NO_STAGE', 'legacy'],+ noStageFilter: 'NO_STAGE',+ resolveStage: (company) => company.stage,+ canEdit: () => false,+ canMoveClosed: () => true,+ closedStages: () => new Set<string>(),+ saveStage,+ }),+ }));+ expect(+ board+ .columns()+ .map((column) => [column.key, column.entities.map((e) => e.id)])+ ).toEqual([+ ['legacy', ['a']],+ ['', ['b']],+ ]);+ board.moveToStage('a', 'legacy');+ expect(saveStage).not.toHaveBeenCalled();+ expect(board.canDragFrom('')).toBe(false);+ dispose();+ });+});diff --git a/apps/web/src/features/crm/primitives/company-board.ts b/apps/web/src/features/crm/primitives/company-board.tsnew file mode 100644index 0000000000..9380487ca5--- /dev/null+++ b/apps/web/src/features/crm/primitives/company-board.ts@@ -0,0 +1,69 @@+import { createEffect, createMemo, createSignal } from 'solid-js';+import type { CompanyBoardSource } from '../context/company-board-source';+import {+ boardStageColumns,+ canDragCompanyStage,+ NO_STAGE_KEY,+} from '../core/stages';++/** Keeps board moves visible during search and protects newer moves from stale failures. */+export function createCompanyBoard<T extends { id: string }>(+ source: CompanyBoardSource<T>+) {+ const [overrides, setOverrides] = createSignal<ReadonlyMap<string, string>>(+ new Map()+ );+ const clearOverride = (id: string, stage: string) =>+ setOverrides((previous) => {+ if (previous.get(id) !== stage) return previous;+ const next = new Map(previous);+ next.delete(id);+ return next;+ });+ const effectiveStage = (company: T) =>+ overrides().get(company.id) ?? source.resolveStage(company) ?? NO_STAGE_KEY;+ const stageColumns = createMemo(() =>+ boardStageColumns(+ source.stages(),+ source.filterStages(),+ source.selectedStages(),+ source.noStageFilter+ )+ );+ // Acknowledged server/cache values retire the optimistic overlay.+ createEffect(() => {+ const pending = overrides();+ if (!pending.size) return;+ for (const company of source.companies()) {+ const stage = source.resolveStage(company) ?? NO_STAGE_KEY;+ if (pending.get(company.id) === stage) clearOverride(company.id, stage);+ }+ });+ const columns = createMemo(() => {+ const buckets = new Map<string, T[]>(+ stageColumns().map((column) => [column.key, []])+ );+ for (const company of source.companies()) {+ const key = effectiveStage(company);+ (buckets.get(buckets.has(key) ? key : NO_STAGE_KEY) ?? []).push(company);+ }+ return stageColumns().map((column) => ({+ ...column,+ entities: buckets.get(column.key) ?? [],+ }));+ });+ const canDragFrom = (stage: string) =>+ canDragCompanyStage(+ stage,+ source.canEdit(),+ source.closedStages(),+ source.canMoveClosed()+ );+ const moveToStage = (id: string, stage: string) => {+ const company = source.companies().find((company) => company.id === id);+ if (!company || effectiveStage(company) === stage) return;+ setOverrides((previous) => new Map(previous).set(id, stage));+ source.saveStage(id, stage, () => clearOverride(id, stage));+ };+ return { columns, stageColumns, effectiveStage, canDragFrom, moveToStage };+}diff --git a/apps/web/src/features/crm/primitives/default-view.test.ts b/apps/web/src/features/crm/primitives/default-view.test.tsnew file mode 100644index 0000000000..e5ae600187--- /dev/null+++ b/apps/web/src/features/crm/primitives/default-view.test.ts@@ -0,0 +1,75 @@+import { createRoot, createSignal } from 'solid-js';+import { describe, expect, it, vi } from 'vitest';+import type { CrmViewConfig } from '../core/saved-view';+import { createDefaultCrmView } from './default-view';++const config: CrmViewConfig = {+ kind: 'crm',+ viewMode: 'board',+ searchText: 'Acme',+};++describe('default CRM view', () => {+ it.each([true, false])(+ 'retains filters and uses the correct layout on mobile=%s',+ (mobile) => {+ const apply = vi.fn();+ const dispose = createRoot((dispose) => {+ createDefaultCrmView({+ personalLoading: () => false,+ teamLoading: () => false,+ personal: () => config,+ team: () => undefined,+ mobile: () => mobile,+ apply,+ });+ return dispose;+ });+ expect(apply).toHaveBeenCalledWith({+ ...config,+ viewMode: mobile ? 'list' : 'board',+ });+ expect(config.viewMode).toBe('board');+ dispose();+ }+ );+ it('waits for both sources, prefers personal, and never reapplies on refetch', () => {+ const apply = vi.fn();+ const [loading, setLoading] = createSignal(true);+ const [personal, setPersonal] = createSignal<CrmViewConfig | undefined>();+ const dispose = createRoot((dispose) => {+ createDefaultCrmView({+ personalLoading: loading,+ teamLoading: () => false,+ personal,+ team: () => ({ kind: 'crm', searchText: 'team' }),+ mobile: () => false,+ apply,+ });+ return dispose;+ });+ expect(apply).not.toHaveBeenCalled();+ setPersonal(config);+ setLoading(false);+ expect(apply).toHaveBeenCalledExactlyOnceWith(config);+ setPersonal({ ...config, searchText: 'changed' });+ expect(apply).toHaveBeenCalledTimes(1);+ dispose();+ });+ it('falls back to the team default', () => {+ const apply = vi.fn();+ const dispose = createRoot((dispose) => {+ createDefaultCrmView({+ personalLoading: () => false,+ teamLoading: () => false,+ personal: () => undefined,+ team: () => config,+ mobile: () => false,+ apply,+ });+ return dispose;+ });+ expect(apply).toHaveBeenCalledExactlyOnceWith(config);+ dispose();+ });+});diff --git a/apps/web/src/features/crm/primitives/default-view.ts b/apps/web/src/features/crm/primitives/default-view.tsnew file mode 100644index 0000000000..3dbb969ced--- /dev/null+++ b/apps/web/src/features/crm/primitives/default-view.ts@@ -0,0 +1,21 @@+import { type Accessor, createEffect } from 'solid-js';+import type { CrmViewConfig } from '../core/saved-view';++export function createDefaultCrmView(input: {+ personalLoading: Accessor<boolean>;+ teamLoading: Accessor<boolean>;+ personal: Accessor<CrmViewConfig | undefined>;+ team: Accessor<CrmViewConfig | undefined>;+ mobile: Accessor<boolean>;+ apply(config: CrmViewConfig): void;+}) {+ let applied = false;+ // Synchronize asynchronously loaded preferences into the live workspace once.+ createEffect(() => {+ if (applied || input.personalLoading() || input.teamLoading()) return;+ applied = true;+ const config = input.personal() ?? input.team();+ if (config)+ input.apply(input.mobile() ? { ...config, viewMode: 'list' } : config);+ });+}diff --git a/apps/web/src/features/crm/primitives/display-options.ts b/apps/web/src/features/crm/primitives/display-options.tsnew file mode 100644index 0000000000..3b4dea4c85--- /dev/null+++ b/apps/web/src/features/crm/primitives/display-options.ts@@ -0,0 +1,32 @@+import type { Accessor, Setter } from 'solid-js';+import {+ type CrmDisplayOptions,+ type CrmListColumnId,+ DEFAULT_CRM_DISPLAY_OPTIONS,+} from '../core/display-options';+export function createCrmDisplayOptions(+ currentOptions: Accessor<CrmDisplayOptions>,+ setOptions: Setter<CrmDisplayOptions>+) {+ // Merge with defaults so options saved by older builds keep working+ // when new fields are added.+ const merged = (): CrmDisplayOptions => ({+ listColumns: {+ ...DEFAULT_CRM_DISPLAY_OPTIONS.listColumns,+ ...currentOptions().listColumns,+ },+ });++ const toggleListColumn = (column: CrmListColumnId) => {+ const current = merged();+ setOptions({+ ...current,+ listColumns: {+ ...current.listColumns,+ [column]: !current.listColumns[column],+ },+ });+ };++ return { options: merged, toggleListColumn };+}diff --git a/apps/web/src/features/crm/primitives/export-companies.ts b/apps/web/src/features/crm/primitives/export-companies.tsnew file mode 100644index 0000000000..b3860e479a--- /dev/null+++ b/apps/web/src/features/crm/primitives/export-companies.ts@@ -0,0 +1,170 @@+import type { CrmCompanyEntity } from '@entity';+import { createMemo, createSignal, onCleanup } from 'solid-js';+import type {+ DealStages,+ ExportDefinitionsSource,+} from '../context/crm-sources';+import {+ companyExportRecord,+ type ExportColumn,+ type ExportRecord,+ personExportRecord,+} from '../core/export';+import type { CrmPerson } from '../core/people';++export type CrmExportOptions = {+ kind: 'companies' | 'people';+ currentView: string;+ onLoad: (+ scope: 'current' | 'all',+ signal: AbortSignal,+ progress: (count: number) => void+ ) => Promise<{ companies?: CrmCompanyEntity[]; people?: CrmPerson[] }>;+};+export function createCrmExport(+ props: CrmExportOptions,+ dependencies: {+ baseColumns: ExportColumn[];+ definitions: ExportDefinitionsSource;+ stages: DealStages;+ userEmail(id: string): string;+ ownerId(company: CrmCompanyEntity): string | undefined;+ stageId: string;+ ownerPropertyId: string;+ }+) {+ const { definitions, stages, userEmail: idToEmail } = dependencies;+ const baseColumns = dependencies.baseColumns;+ const [scope, setScope] = createSignal<'current' | 'all'>('current');+ const [selected, setSelected] = createSignal(+ baseColumns.filter((column) => column.default).map((column) => column.id)+ );+ const [rows, setRows] = createSignal<ExportRecord[]>();+ const [pending, setPending] = createSignal(false);+ const [progress, setProgress] = createSignal(0);+ const [error, setError] = createSignal('');+ let controller: AbortController | undefined;+ onCleanup(() => controller?.abort());+ const propertyDefinitions = () =>+ props.kind === 'companies' && definitions.isSuccess ? definitions.data : [];+ const columns = createMemo<ExportColumn[]>(() => [+ ...baseColumns,+ ...propertyDefinitions().flatMap((entry) => {+ const definition = 'definition' in entry ? entry.definition : entry;+ if (+ definition.is_metadata ||+ baseColumns.some(+ (column) => column.id === `property:${definition.id}`+ ) ||+ [+ dependencies.stageId,+ dependencies.ownerPropertyId,+ stages.stageDefinitionId(),+ ].includes(definition.id)+ )+ return [];+ return [+ { id: `property:${definition.id}`, label: definition.display_name },+ ];+ }),+ ]);+ const selectedColumns = () =>+ columns().filter((column) => selected().includes(column.id));+ const options = createMemo(+ () =>+ new Map(+ propertyDefinitions().flatMap((entry) =>+ 'property_options' in entry+ ? entry.property_options.map(+ (option) => [option.id, String(option.value.value)] as const+ )+ : []+ )+ )+ );+ const formatProperty = (+ property: NonNullable<CrmCompanyEntity['properties']>[number]+ ) => {+ const value = property.value;+ if (!value) return '';+ if (value.type === 'SelectOption')+ return value.value.map((id) => options().get(id) ?? id).join('; ');+ if (value.type === 'EntityReference')+ return value.value+ .map((ref) =>+ ref.entity_id.startsWith('macro|')+ ? idToEmail(ref.entity_id)+ : ref.entity_id+ )+ .join('; ');+ return Array.isArray(value.value) ? value.value.join('; ') : value.value;+ };+ const metadataLoading = () =>+ props.kind === 'companies' && (definitions.isPending || stages.isLoading());+ const metadataError = () =>+ props.kind === 'companies' && (definitions.isError || stages.isError());+ const filename = () =>+ `macro-${+ scope() === 'all'+ ? `all-${props.kind}`+ : props.currentView+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-|-$/g, '') || props.kind+ }-${new Date().toISOString().slice(0, 10)}.csv`;+ async function prepare() {+ if (pending()) return;+ controller = new AbortController();+ const signal = controller.signal;+ setPending(true);+ setError('');+ setProgress(0);+ setRows(undefined);+ try {+ const result = await props.onLoad(scope(), signal, setProgress);+ signal.throwIfAborted();+ setRows(+ result.people+ ? result.people.map(personExportRecord)+ : (result.companies ?? []).map((company) => {+ const stageId = stages.resolveStage(company);+ const owner = dependencies.ownerId(company);+ return companyExportRecord(+ company,+ stageId ? (stages.stageLabel(stageId) ?? stageId) : '',+ owner ? idToEmail(owner) : '',+ formatProperty+ );+ })+ );+ } catch (cause) {+ if (!signal.aborted)+ setError(+ cause instanceof Error+ ? cause.message+ : 'Could not prepare the export. Please retry.'+ );+ } finally {+ if (!signal.aborted) setPending(false);+ }+ }+ return {+ baseColumns,+ scope,+ setScope,+ selected,+ setSelected,+ rows,+ setRows,+ pending,+ progress,+ error,+ setError,+ columns,+ selectedColumns,+ metadataLoading,+ metadataError,+ filename,+ prepare,+ };+}diff --git a/apps/web/src/features/crm/primitives/export-source.test.ts b/apps/web/src/features/crm/primitives/export-source.test.tsnew file mode 100644index 0000000000..de75b86d28--- /dev/null+++ b/apps/web/src/features/crm/primitives/export-source.test.ts@@ -0,0 +1,99 @@+import type { CrmCompanyEntity, EntityData } from '@entity';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { CrmWorkspace } from '../context/workspace-context';+import { createCrmExportLoader } from './export-source';++const company = (id: string, loaded = true): CrmCompanyEntity => ({+ type: 'crm_company',+ id,+ name: id,+ ownerId: 'owner',+ teamId: 'team',+ hidden: false,+ domains: [],+ ...(loaded ? { properties: [] } : {}),+});+const isCompany = (entity: EntityData): entity is CrmCompanyEntity =>+ entity.type === 'crm_company';+const source = (+ overrides: Partial<CrmWorkspace['source']> = {}+): CrmWorkspace['source'] => ({+ error: () => undefined,+ data: () => [],+ isLoading: () => false,+ isFetching: () => false,+ hasNextPage: () => false,+ fetchNextPage: async () => {},+ ...overrides,+});+afterEach(() => vi.useRealTimers());++describe('current-view export loading', () => {+ it('loads all pages and hydrates only the companies in the selected view', async () => {+ vi.useFakeTimers();+ let next = true;+ let rows = [company('a', false)];+ const progress = vi.fn();+ const loadAll = vi.fn(async () => [+ company('a'),+ company('b'),+ company('other'),+ ]);+ const load = createCrmExportLoader(+ source({+ data: () => rows,+ hasNextPage: () => next,+ fetchNextPage: async () => {+ rows = [...rows, company('b')];+ next = false;+ },+ }),+ loadAll,+ isCompany+ );+ const result = load('current', new AbortController().signal, progress);+ await vi.runAllTimersAsync();+ expect((await result).companies).toEqual([company('a'), company('b')]);+ expect(progress).toHaveBeenCalledWith(2);+ expect(loadAll).toHaveBeenCalledOnce();+ });+ it('rejects failed pagination instead of downloading a partial view', async () => {+ vi.useFakeTimers();+ let error: Error | undefined;+ const loadAll = vi.fn();+ const load = createCrmExportLoader(+ source({+ error: () => error,+ hasNextPage: () => true,+ fetchNextPage: async () => {+ error = new Error('offline');+ },+ }),+ loadAll,+ isCompany+ );+ const result = expect(+ load('current', new AbortController().signal, vi.fn())+ ).rejects.toThrow('entire view');+ await vi.runAllTimersAsync();+ await result;+ expect(loadAll).not.toHaveBeenCalled();+ });+ it('stops while waiting for an in-flight view request when cancelled', async () => {+ vi.useFakeTimers();+ const controller = new AbortController();+ const fetchNextPage = vi.fn();+ const load = createCrmExportLoader(+ source({ isFetching: () => true, fetchNextPage }),+ vi.fn(),+ isCompany+ );+ const result = expect(+ load('current', controller.signal, vi.fn())+ ).rejects.toThrow();+ controller.abort();+ await vi.runAllTimersAsync();+ await result;+ expect(fetchNextPage).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/features/crm/primitives/export-source.ts b/apps/web/src/features/crm/primitives/export-source.tsnew file mode 100644index 0000000000..3043541454--- /dev/null+++ b/apps/web/src/features/crm/primitives/export-source.ts@@ -0,0 +1,48 @@+import type { CrmCompanyEntity, EntityData } from '@entity';+import type { CrmWorkspace } from '../context/workspace-context';+export function createCrmExportLoader(+ source: CrmWorkspace['source'],+ loadAll: (+ signal: AbortSignal,+ progress: (count: number) => void+ ) => Promise<CrmCompanyEntity[]>,+ isCompany: (entity: EntityData) => entity is CrmCompanyEntity+) {+ return async (+ scope: 'current' | 'all',+ signal: AbortSignal,+ progress: (count: number) => void+ ) => {+ const wait = async () => {+ signal.throwIfAborted();+ await new Promise((resolve) => setTimeout(resolve, 100));+ };+ if (scope === 'all')+ return {+ companies: await loadAll(signal, progress),+ };+ while (source.isFetching()) await wait();+ if (source.error())+ throw new Error('Could not load this view. Please retry.');+ while (source.hasNextPage()) {+ signal.throwIfAborted();+ await source.fetchNextPage();+ await wait();+ if (source.error())+ throw new Error('Could not load the entire view. Please retry.');+ progress(source.data().length);+ }+ signal.throwIfAborted();+ let current = source.data().filter(isCompany);+ if (current.some((company) => !company.properties)) {+ const full = new Map(+ (await loadAll(signal, progress)).map((company) => [+ company.id,+ company,+ ])+ );+ current = current.map((company) => full.get(company.id) ?? company);+ }+ return { companies: current };+ };+}diff --git a/apps/web/src/features/crm/primitives/filter-selections.test.ts b/apps/web/src/features/crm/primitives/filter-selections.test.tsnew file mode 100644index 0000000000..5466d20e37--- /dev/null+++ b/apps/web/src/features/crm/primitives/filter-selections.test.ts@@ -0,0 +1,67 @@+import { createRoot, createSignal } from 'solid-js';+import { describe, expect, it, vi } from 'vitest';+import { createCrmFilterSelections } from './filter-selections';++describe('CRM filter selection semantics', () => {+ it('does not read pending stage metadata while constructing filter state', () => {+ const defaultStages = vi.fn(() => ['active']);+ const { state, dispose } = createRoot((dispose) => {+ const [stageFilter, setStageFilter] = createSignal<string[]>([]);+ const [ownerFilter, setOwnerFilter] = createSignal<string[]>([]);+ return {+ dispose,+ state: createCrmFilterSelections({+ stageFilter,+ setStageFilter,+ ownerFilter,+ setOwnerFilter,+ defaultStages,+ isActive: () => false,+ toggle: () => {},+ }),+ };+ });+ expect(defaultStages).not.toHaveBeenCalled();+ expect(state.effectiveStages()).toEqual(['active']);+ expect(defaultStages).toHaveBeenCalledOnce();+ dispose();+ });+ it('treats the active default set as no filter and keeps legacy stages opt-in', () => {+ const { state, selected, active, dispose } = createRoot((dispose) => {+ const [stageFilter, setStageFilter] = createSignal<string[]>([]);+ const [ownerFilter, setOwnerFilter] = createSignal<string[]>([]);+ const active = new Set<string>();+ return {+ dispose,+ selected: stageFilter,+ active,+ state: createCrmFilterSelections({+ stageFilter,+ setStageFilter,+ ownerFilter,+ setOwnerFilter,+ defaultStages: () => ['active', 'NO_STAGE'],+ isActive: (id) => active.has(id),+ toggle: (id) => {+ if (active.has(id)) active.delete(id);+ else active.add(id);+ },+ }),+ };+ });+ expect(state.effectiveStages()).toEqual(['active', 'NO_STAGE']);+ state.changeStage(['active', 'legacy', 'NO_STAGE']);+ expect(selected()).toEqual(['active', 'legacy', 'NO_STAGE']);+ expect(active.has('company-stage')).toBe(true);+ state.changeStage(['NO_STAGE', 'active']);+ expect(selected()).toEqual([]);+ expect(active.has('company-stage')).toBe(false);+ state.changeStageChip(['active', 'NO_STAGE']);+ expect(selected()).toEqual(['active', 'NO_STAGE']);+ state.changeOwner(['teammate']);+ expect(active.has('company-owner')).toBe(true);+ state.changeOwner([]);+ expect(active.has('company-owner')).toBe(false);+ dispose();+ });+});diff --git a/apps/web/src/features/crm/primitives/filter-selections.ts b/apps/web/src/features/crm/primitives/filter-selections.tsnew file mode 100644index 0000000000..b52ef3ac33--- /dev/null+++ b/apps/web/src/features/crm/primitives/filter-selections.ts@@ -0,0 +1,39 @@+import { type Accessor, batch, type Setter } from 'solid-js';+export function createCrmFilterSelections(input: {+ stageFilter: Accessor<string[]>;+ setStageFilter: Setter<string[]>;+ ownerFilter: Accessor<string[]>;+ setOwnerFilter: Setter<string[]>;+ defaultStages: Accessor<string[]>;+ isActive(id: string): boolean;+ toggle(id: string): void;+}) {+ const defaultIds = () => new Set(input.defaultStages());+ const set = (+ kind: 'company-stage' | 'company-owner',+ ids: string[],+ update: Setter<string[]>+ ) =>+ batch(() => {+ update(ids);+ if (ids.length > 0 !== input.isActive(kind)) input.toggle(kind);+ });+ const changeStageChip = (ids: string[]) =>+ set('company-stage', ids, input.setStageFilter);+ const changeOwner = (ids: string[]) =>+ set('company-owner', ids, input.setOwnerFilter);+ return {+ changeOwner,+ changeStageChip,+ changeStage(ids: string[]) {+ changeStageChip(+ ids.length === defaultIds().size &&+ ids.every((id) => defaultIds().has(id))+ ? []+ : ids+ );+ },+ effectiveStages: () =>+ input.stageFilter().length ? input.stageFilter() : [...defaultIds()],+ };+}diff --git a/apps/web/src/features/crm/primitives/import-companies.test.ts b/apps/web/src/features/crm/primitives/import-companies.test.tsnew file mode 100644index 0000000000..a134ca27c1--- /dev/null+++ b/apps/web/src/features/crm/primitives/import-companies.test.ts@@ -0,0 +1,50 @@+import { createRoot } from 'solid-js';+import { describe, expect, it, vi } from 'vitest';+import { createCompanyImport } from './import-companies';++const file = (text: string) => ({ size: text.length, text: async () => text });++describe('company import', () => {+ it('retries only failed rows and preserves the successful count', async () => {+ let fail = true;+ const create = vi.fn(async (row: { name: string; domain: string }) => {+ if (row.name === 'Retry' && fail) throw new Error('temporary failure');+ });+ const { state, dispose } = createRoot((dispose) => ({+ state: createCompanyImport(create),+ dispose,+ }));+ await state.read(+ file('Name,Domain\nDone,DONE.EXAMPLE\nRetry,retry.example')+ );+ expect(state.error()).toBe('');+ await state.run();+ expect(state.completed()).toBe(1);+ expect(state.rows()).toEqual([{ name: 'Retry', domain: 'retry.example' }]);+ expect(state.error()).toContain('Successful rows will not be retried');+ fail = false;+ await state.run();+ expect(state.completed()).toBe(2);+ expect(state.rows()).toEqual([]);+ expect(create.mock.calls.map(([row]) => row.name)).toEqual([+ 'Done',+ 'Retry',+ 'Retry',+ ]);+ dispose();+ });+ it('rejects oversized and invalid files before any mutation', async () => {+ const create = vi.fn();+ const { state, dispose } = createRoot((dispose) => ({+ state: createCompanyImport(create),+ dispose,+ }));+ await state.read(file('x'.repeat(1024 * 1024 + 1)));+ expect(state.error()).toContain('smaller than 1 MB');+ await state.read(file('name,domain\nInvalid,https://example.com'));+ await state.run();+ expect(create).not.toHaveBeenCalled();+ expect(state.rows()).toEqual([]);+ dispose();+ });+});diff --git a/apps/web/src/features/crm/primitives/import-companies.ts b/apps/web/src/features/crm/primitives/import-companies.tsnew file mode 100644index 0000000000..cceba8aa7f--- /dev/null+++ b/apps/web/src/features/crm/primitives/import-companies.ts@@ -0,0 +1,57 @@+import { parseCsv } from '@core/util/csv';+import { createSignal } from 'solid-js';+import { normalizeCompanyImport } from '../core/import-companies';+export function createCompanyImport(+ createCompany: (input: { name: string; domain: string }) => Promise<unknown>+) {+ const [rows, setRows] = createSignal<{ name: string; domain: string }[]>([]);+ const [error, setError] = createSignal('');+ const [pending, setPending] = createSignal(false);+ const [completed, setCompleted] = createSignal(0);+ async function read(file?: Pick<File, 'size' | 'text'>) {+ setError('');+ setRows([]);+ setCompleted(0);+ if (!file) return;+ if (file.size > 1024 * 1024) {+ setError('Choose a CSV smaller than 1 MB.');+ return;+ }+ try {+ const parsed = parseCsv((await file.text()).replace(/^\uFEFF/, ''));+ if (!parsed.ok) {+ setError(parsed.error);+ return;+ }+ const normalized = normalizeCompanyImport(parsed.records);+ if (normalized.error !== undefined) {+ setError(normalized.error);+ return;+ }+ setRows(normalized.rows);+ } catch {+ setError('Could not read that file. Please try again.');+ }+ }+ async function run() {+ if (pending() || !rows().length) return;+ setPending(true);+ setError('');+ const failed: { name: string; domain: string }[] = [];+ for (const row of rows()) {+ try {+ await createCompany(row);+ setCompleted((n) => n + 1);+ } catch {+ failed.push(row);+ }+ }+ setRows(failed);+ setPending(false);+ if (failed.length)+ setError(+ `${failed.length} could not be imported. They may already exist or use an unsupported domain. Successful rows will not be retried.`+ );+ }+ return { rows, error, pending, completed, read, run };+}diff --git a/apps/web/src/features/crm/primitives/stage-editor.ts b/apps/web/src/features/crm/primitives/stage-editor.tsnew file mode 100644index 0000000000..392461a171--- /dev/null+++ b/apps/web/src/features/crm/primitives/stage-editor.ts@@ -0,0 +1,208 @@+import { type Accessor, createMemo, createSignal } from 'solid-js';+import { createStore } from 'solid-js/store';+import type {+ CrmCapabilities,+ CrmMutation,+ CrmStageInput,+ CrmStagesResult as CrmStagesResponse,+ DealStages,+ TeamConfigSource,+} from '../context/crm-sources';+import type { DealStage } from '../core/stages';++function toStageInputs(stages: DealStage[]): CrmStageInput[] {+ return stages.map((stage) => ({ id: stage.id, label: stage.label }));+}+export function createStageEditor(input: {+ dealStages: DealStages;+ crmPermissions: Pick<CrmCapabilities, 'canEditStages'>;+ teamCrmConfig: TeamConfigSource;+ closedStageIds: Accessor<Set<string>>;+ replaceMutation: CrmMutation<CrmStageInput[], CrmStagesResponse>;+ resetMutation: CrmMutation<void>;+ onSuccess(message: string): void;+}) {+ const {+ dealStages,+ crmPermissions,+ teamCrmConfig,+ closedStageIds,+ replaceMutation,+ resetMutation,+ } = input;+ 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) input.onSuccess(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);++ 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);+ input.onSuccess('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 {+ newStageName,+ setNewStageName,+ stageToDelete,+ setStageToDelete,+ showResetModal,+ setShowResetModal,+ canEdit,+ pending,+ loading,+ failed,+ busy,+ blocked,+ drafts,+ setDrafts,+ orderedStages,+ stageIds,+ announcement,+ handleCustomize,+ handleRename,+ reorder,+ handleMove,+ 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.tsnew file mode 100644index 0000000000..eae1965f71--- /dev/null+++ b/apps/web/src/features/crm/primitives/team-config.ts@@ -0,0 +1,75 @@+import { type Accessor, createMemo } from 'solid-js';+import type { TeamConfigSource, TeamSource } from '../context/crm-sources';+import {+ type CrmPermissions,+ type CrmTeamRole,+ closedStageIds,+ DEFAULT_CRM_PERMISSIONS,+ roleSatisfies,+} from '../core/team-config';+/**+ * Effective CRM capabilities for the current user, combining the team's+ * configured permission thresholds with the platform-level rule that any+ * team member can edit CRM data (governance actions stay admin/owner).+ */+export function createCrmPermissions(+ userId: Accessor<string | undefined>,+ teamQuery: TeamSource,+ settings: TeamConfigSource+) {+ const { config, isLoading } = settings;++ const role = createMemo((): CrmTeamRole | undefined => {+ const uid = userId();+ const team = teamQuery.data;+ if (!uid || !team) return undefined;+ return team.members.find((member) => member.user_id === uid)?.role;+ });++ const permissions = createMemo(+ (): CrmPermissions => ({+ ...DEFAULT_CRM_PERMISSIONS,+ ...config().permissions,+ })+ );++ return {+ role,+ permissions,+ isLoading,+ /** Can edit CRM data at all (platform rule: any team member). */+ canEditCrm: () => role() !== undefined,+ canEditStages: createMemo(() =>+ roleSatisfies(role(), permissions().editStages)+ ),+ canMoveClosedDeals: createMemo(() =>+ roleSatisfies(role(), permissions().moveClosedDeals)+ ),+ canDeleteRecords: createMemo(() =>+ roleSatisfies(role(), permissions().deleteRecords)+ ),+ };+}++/**+ * True once the current-team query resolves to no team (null) or a team+ * with CRM disabled — the companies views swap in an explanatory empty+ * state and keep bottom chrome like the AI bar. Stays false while the+ * query loads so enabled teams don't flash the empty state.+ */+export function createCrmUnavailable(teamQuery: TeamSource): Accessor<boolean> {+ return () =>+ teamQuery.data === null || teamQuery.data?.team.crm_enabled === false;+}++/**+ * 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/lib/queries/crm/companies.ts b/apps/web/src/features/crm/queries/companies.tssimilarity index 51%rename from apps/web/src/lib/queries/crm/companies.tsrename to apps/web/src/features/crm/queries/companies.tsindex 74e384b56a..7714569f4a 100644--- a/apps/web/src/lib/queries/crm/companies.ts+++ b/apps/web/src/features/crm/queries/companies.ts@@ -1,13 +1,12 @@import { NIL_UUID } from '@app/features/next-soup/filters/filter-store';import { throwOnErr } from '@core/util/result';import type { CrmCompanyEntity } from '@entity';-import { storageServiceClient } from '@service-storage/client';+import { soupKeys } from '@queries/soup/keys';import type { CrmCompanyResponse } from '@service-storage/generated/schemas/crmCompanyResponse';import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';import { type QueryKey, useMutation, useQuery } from '@tanstack/solid-query';import { type Accessor, createMemo } from 'solid-js';-import { queryClient } from '../client';-import { soupKeys } from '../soup/keys';+import type { CrmRecordDependencies } from './dependencies';import { crmKeys } from './keys';const COMPANY_STALE_TIME = 60 * 1000;@@ -26,23 +25,27 @@ export type CompanyContact = CrmContactResponse;* a sentinel placeholder before their own data loads without firing a* doomed 404.*/-export function useCompanyQuery(companyId: Accessor<string>) {- const query = useQuery(() => {- const id = companyId();- return {- queryKey: crmKeys.company(id).queryKey,- queryFn: () => {- if (!id) {- throw new Error('company id is required to fetch company');- }- return throwOnErr(() =>- storageServiceClient.getCompany({ companyId: id })- );- },- staleTime: COMPANY_STALE_TIME,- enabled: !!companyId() && companyId() !== NIL_UUID,- };- });+export function useCompanyQuery(+ deps: CrmRecordDependencies,+ companyId: Accessor<string>+) {+ const query = useQuery(+ () => {+ const id = companyId();+ return {+ queryKey: crmKeys.company(id).queryKey,+ queryFn: () => {+ if (!id) {+ throw new Error('company id is required to fetch company');+ }+ return throwOnErr(() => deps.storage.getCompany({ companyId: id }));+ },+ staleTime: COMPANY_STALE_TIME,+ enabled: !!companyId() && companyId() !== NIL_UUID,+ };+ },+ () => deps.client+ );const company = createMemo<CrmCompanyEntity | undefined>(() => {const data = query.isSuccess ? query.data : undefined;@@ -84,7 +87,7 @@ function responseToEntity(response: CrmCompanyResponse): CrmCompanyEntity {}// Matches the company-email soup queries built by `useCompanyEmailsQuery`-// (src/features/companies/Company): the Team view's `ecd` domain widener and the+// (features/crm/queries/company-emails.ts): the Team view's `ecd` domain widener and the// Me view's `ef` tree, both keyed on the company's email domains. astItems key// shape is ['soup', 'astItems', params, body, groupBy], so the body is at [3].function isCompanyEmailQueryKey(@@ -111,14 +114,17 @@ function isCompanyEmailQueryKey(// keeps serving the stale rows — and won't refetch once the panel navigates// away on hide — so toggling hidden/email-sync left old emails on screen until// a full refresh. Removing forces a cold reload, the same as that refresh did.-function wipeCompanyEmailCache(companyId: string): void {- const company = queryClient.getQueryData<CrmCompanyResponse>(+function wipeCompanyEmailCache(+ deps: CrmRecordDependencies,+ companyId: string+): void {+ const company = deps.client.getQueryData<CrmCompanyResponse>(crmKeys.company(companyId).queryKey);const domains = company?.domains.map((d) => d.domain) ?? [];if (domains.length === 0) return;- queryClient.removeQueries({+ deps.client.removeQueries({queryKey: soupKeys.astItems._def,predicate: (query) => isCompanyEmailQueryKey(query.queryKey, domains),});@@ -132,15 +138,18 @@ function wipeCompanyEmailCache(companyId: string): void {* team already tracks the domain, 403 when CRM is disabled for the team,* 400 on a malformed/generic-provider domain.*/-export function useCreateCompanyMutation() {- return useMutation(() => ({- mutationFn: ({ name, domain }: { name: string; domain: string }) =>- throwOnErr(() => storageServiceClient.createCompany({ name, domain })),- onSuccess: (data) => {- queryClient.setQueryData(crmKeys.company(data.id).queryKey, data);- return queryClient.invalidateQueries({ queryKey: soupKeys._def });- },- }));+export function useCreateCompanyMutation(deps: CrmRecordDependencies) {+ return useMutation(+ () => ({+ mutationFn: ({ name, domain }: { name: string; domain: string }) =>+ throwOnErr(() => deps.storage.createCompany({ name, domain })),+ onSuccess: (data) => {+ deps.client.setQueryData(crmKeys.company(data.id).queryKey, data);+ return deps.client.invalidateQueries({ queryKey: soupKeys._def });+ },+ }),+ () => deps.client+ );}/**@@ -151,28 +160,31 @@ export function useCreateCompanyMutation() {* the company already tracks the email, 404 when the company isn't* visible to the caller, 403 when CRM is disabled for the team.*/-export function useCreateContactMutation() {- return useMutation(() => ({- mutationFn: ({- companyId,- name,- email,- }: {- companyId: string;- name: string;- email: string;- }) =>- throwOnErr(() =>- storageServiceClient.createContact({ companyId, name, email })- ),- onSuccess: (_data, { companyId }) =>- Promise.all([- queryClient.invalidateQueries({- queryKey: crmKeys.company(companyId).queryKey,- }),- queryClient.invalidateQueries({ queryKey: soupKeys._def }),- ]),- }));+export function useCreateContactMutation(deps: CrmRecordDependencies) {+ return useMutation(+ () => ({+ mutationFn: ({+ companyId,+ name,+ email,+ }: {+ companyId: string;+ name: string;+ email: string;+ }) =>+ throwOnErr(() =>+ deps.storage.createContact({ companyId, name, email })+ ),+ onSuccess: (_data, { companyId }) =>+ Promise.all([+ deps.client.invalidateQueries({+ queryKey: crmKeys.company(companyId).queryKey,+ }),+ deps.client.invalidateQueries({ queryKey: soupKeys._def }),+ ]),+ }),+ () => deps.client+ );}/**@@ -183,45 +195,46 @@ export function useCreateContactMutation() {* the title flips immediately, then invalidates it plus soup so the Customers* listings pick up the new name.*/-export function useSetCompanyNameMutation() {- return useMutation(() => ({- mutationFn: ({ companyId, name }: { companyId: string; name: string }) =>- throwOnErr(() =>- storageServiceClient.setCompanyName({ companyId, name })- ),- onMutate: async ({ companyId, name }) => {- const queryKey = crmKeys.company(companyId).queryKey;- await queryClient.cancelQueries({ queryKey });- const previous = queryClient.getQueryData<CrmCompanyResponse>(queryKey);- if (previous) {- queryClient.setQueryData<CrmCompanyResponse>(queryKey, {- ...previous,- name,- });- }- return { previous, optimisticName: name };- },- // Roll back only if the cache still holds this mutation's optimistic- // name — a stale failure must not clobber a newer rename's update.- onError: (_err, { companyId }, context) => {- if (context?.previous) {- queryClient.setQueryData<CrmCompanyResponse>(- crmKeys.company(companyId).queryKey,- (current) =>- current?.name === context.optimisticName- ? context.previous- : current- );- }- },- onSettled: (_data, _err, { companyId }) =>- Promise.all([- queryClient.invalidateQueries({- queryKey: crmKeys.company(companyId).queryKey,- }),- queryClient.invalidateQueries({ queryKey: soupKeys._def }),- ]),- }));+export function useSetCompanyNameMutation(deps: CrmRecordDependencies) {+ return useMutation(+ () => ({+ mutationFn: ({ companyId, name }: { companyId: string; name: string }) =>+ throwOnErr(() => deps.storage.setCompanyName({ companyId, name })),+ onMutate: async ({ companyId, name }) => {+ const queryKey = crmKeys.company(companyId).queryKey;+ await deps.client.cancelQueries({ queryKey });+ const previous = deps.client.getQueryData<CrmCompanyResponse>(queryKey);+ if (previous) {+ deps.client.setQueryData<CrmCompanyResponse>(queryKey, {+ ...previous,+ name,+ });+ }+ return { previous, optimisticName: name };+ },+ // Roll back only if the cache still holds this mutation's optimistic+ // name — a stale failure must not clobber a newer rename's update.+ onError: (_err, { companyId }, context) => {+ if (context?.previous) {+ deps.client.setQueryData<CrmCompanyResponse>(+ crmKeys.company(companyId).queryKey,+ (current) =>+ current?.name === context.optimisticName+ ? context.previous+ : current+ );+ }+ },+ onSettled: (_data, _err, { companyId }) =>+ Promise.all([+ deps.client.invalidateQueries({+ queryKey: crmKeys.company(companyId).queryKey,+ }),+ deps.client.invalidateQueries({ queryKey: soupKeys._def }),+ ]),+ }),+ () => deps.client+ );}/**@@ -231,28 +244,29 @@ export function useSetCompanyNameMutation() {* Invalidates soup (the company drops out of / returns to the listings) and the* company detail query so an open panel reflects the new hidden/email-sync state.*/-export function useSetCompanyHiddenMutation() {- return useMutation(() => ({- mutationFn: ({- companyId,- hidden,- }: {- companyId: string;- hidden: boolean;- }) =>- throwOnErr(() =>- storageServiceClient.setCompanyHidden({ companyId, hidden })- ),- onSuccess: (_data, { companyId }) => {- wipeCompanyEmailCache(companyId);- return Promise.all([- queryClient.invalidateQueries({ queryKey: soupKeys._def }),- queryClient.invalidateQueries({- queryKey: crmKeys.company(companyId).queryKey,- }),- ]);- },- }));+export function useSetCompanyHiddenMutation(deps: CrmRecordDependencies) {+ return useMutation(+ () => ({+ mutationFn: ({+ companyId,+ hidden,+ }: {+ companyId: string;+ hidden: boolean;+ }) =>+ throwOnErr(() => deps.storage.setCompanyHidden({ companyId, hidden })),+ onSuccess: (_data, { companyId }) => {+ wipeCompanyEmailCache(deps, companyId);+ return Promise.all([+ deps.client.invalidateQueries({ queryKey: soupKeys._def }),+ deps.client.invalidateQueries({+ queryKey: crmKeys.company(companyId).queryKey,+ }),+ ]);+ },+ }),+ () => deps.client+ );}/**@@ -261,32 +275,33 @@ export function useSetCompanyHiddenMutation() {* other's emails with this company — existing CRM data is never destroyed and* re-enabling needs no backfill.*/-export function useSetEmailSyncMutation() {- return useMutation(() => ({- mutationFn: ({- companyId,- emailSync,- }: {- companyId: string;- emailSync: boolean;- }) =>- throwOnErr(() =>- storageServiceClient.setEmailSync({ companyId, emailSync })- ),- // Wipe the cached email threads first so disabling sync can't leave stale- // rows on screen, then return the invalidation promise so the mutation stays- // pending until the refetches resolve — the company entity, empty-state- // message, and emails list flip in one beat. Soup carries the team-wide- // email visibility change; the company detail query backs the panel's- // `emailSync` empty-state text.- onSuccess: (_data, { companyId }) => {- wipeCompanyEmailCache(companyId);- return Promise.all([- queryClient.invalidateQueries({ queryKey: soupKeys._def }),- queryClient.invalidateQueries({- queryKey: crmKeys.company(companyId).queryKey,- }),- ]);- },- }));+export function useSetEmailSyncMutation(deps: CrmRecordDependencies) {+ return useMutation(+ () => ({+ mutationFn: ({+ companyId,+ emailSync,+ }: {+ companyId: string;+ emailSync: boolean;+ }) =>+ throwOnErr(() => deps.storage.setEmailSync({ companyId, emailSync })),+ // Wipe the cached email threads first so disabling sync can't leave stale+ // rows on screen, then return the invalidation promise so the mutation stays+ // pending until the refetches resolve — the company entity, empty-state+ // message, and emails list flip in one beat. Soup carries the team-wide+ // email visibility change; the company detail query backs the panel's+ // `emailSync` empty-state text.+ onSuccess: (_data, { companyId }) => {+ wipeCompanyEmailCache(deps, companyId);+ return Promise.all([+ deps.client.invalidateQueries({ queryKey: soupKeys._def }),+ deps.client.invalidateQueries({+ queryKey: crmKeys.company(companyId).queryKey,+ }),+ ]);+ },+ }),+ () => deps.client+ );}diff --git a/apps/web/src/features/companies/Company/use-company-emails-query.ts b/apps/web/src/features/crm/queries/company-emails.tssimilarity index 92%rename from apps/web/src/features/companies/Company/use-company-emails-query.tsrename to apps/web/src/features/crm/queries/company-emails.tsindex 3c728c911a..35b8d7a532 100644--- a/apps/web/src/features/companies/Company/use-company-emails-query.ts+++ b/apps/web/src/features/crm/queries/company-emails.ts@@ -1,11 +1,11 @@import { NIL_UUID } from '@app/features/next-soup/filters/filter-store';-import { useSoupAstItemsQuery } from '@queries/soup/items';+import type { useSoupAstItemsQuery } from '@queries/soup/items';import type { Accessor } from 'solid-js';import {andEmailFilters,emailFilterForDomains,emailFilterForSignal,-} from './emailFilter';+} from './email-filter';export type EmailView = 'team' | 'me';export type EmailSignalView = 'signal' | 'all';@@ -23,11 +23,12 @@ export type EmailSignalView = 'signal' | 'all';* `ef` with the CRM scope tree, so it composes with `ecd` too).*/export function useCompanyEmailsQuery(+ createQuery: typeof useSoupAstItemsQuery,domains: Accessor<string[]>,view: Accessor<EmailView>,signalView: Accessor<EmailSignalView>) {- return useSoupAstItemsQuery(+ return createQuery(() => {const base = {calf: { l: { id: NIL_UUID } },diff --git a/apps/web/src/lib/queries/soup/quick-access-crm-companies.ts b/apps/web/src/features/crm/queries/company-suggestions.tssimilarity index 75%rename from apps/web/src/lib/queries/soup/quick-access-crm-companies.tsrename to apps/web/src/features/crm/queries/company-suggestions.tsindex 43a0ebb300..aeb108d18d 100644--- a/apps/web/src/lib/queries/soup/quick-access-crm-companies.ts+++ b/apps/web/src/features/crm/queries/company-suggestions.ts@@ -1,9 +1,7 @@import { QUERY_FILTERS_BASE } from '@app/features/next-soup/filters/query-filters';-import { useFeatureFlag } from '@app/lib/analytics/posthog';-import { enableCrm } from '@core/constant/featureFlags';import { type CrmCompanyEntity, isCrmCompanyEntity } from '@entity';-import { useSoupItemsQuery } from '@queries/soup/items';-import { createMemo } from 'solid-js';+import type { useSoupItemsQuery } from '@queries/soup/items';+import { type Accessor, createMemo } from 'solid-js';const QUICK_ACCESS_COMPANIES_LIMIT = 500;const STALE_TIME = 5 * 60 * 1000;@@ -20,10 +18,11 @@ const STALE_TIME = 5 * 60 * 1000;** Every other entity type is filtered out by extending `QUERY_FILTERS_BASE`.*/-export function useQuickAccessCrmCompaniesQuery() {- const crmFlag = useFeatureFlag(enableCrm);-- const query = useSoupItemsQuery(+export function useQuickAccessCrmCompaniesQuery(+ useSource: typeof useSoupItemsQuery,+ enabled: Accessor<boolean>+) {+ const query = useSource(() => ({params: {limit: QUICK_ACCESS_COMPANIES_LIMIT,@@ -35,7 +34,7 @@ export function useQuickAccessCrmCompaniesQuery() {crm_company_filters: undefined,},}),- () => ({ staleTime: STALE_TIME, enabled: crmFlag().enabled })+ () => ({ staleTime: STALE_TIME, enabled: enabled() }));const companies = createMemo<CrmCompanyEntity[]>(() =>diff --git a/apps/web/src/features/contacts/Contact/use-contact-emails-query.ts b/apps/web/src/features/crm/queries/contact-emails.tssimilarity index 92%rename from apps/web/src/features/contacts/Contact/use-contact-emails-query.tsrename to apps/web/src/features/crm/queries/contact-emails.tsindex d71216ce9e..c384425a1a 100644--- a/apps/web/src/features/contacts/Contact/use-contact-emails-query.ts+++ b/apps/web/src/features/crm/queries/contact-emails.ts@@ -1,11 +1,11 @@import { NIL_UUID } from '@app/features/next-soup/filters/filter-store';+import type { useSoupAstItemsQuery } from '@queries/soup/items';+import type { Accessor } from 'solid-js';import {andEmailFilters,emailFilterForAddress,emailFilterForSignal,-} from '@companies/Company/emailFilter';-import { useSoupAstItemsQuery } from '@queries/soup/items';-import type { Accessor } from 'solid-js';+} from './email-filter';export type EmailView = 'team' | 'me';export type EmailSignalView = 'signal' | 'all';@@ -23,11 +23,12 @@ export type EmailSignalView = 'signal' | 'all';* `ef` with the CRM scope tree, so it composes with `eca` too).*/export function useContactEmailsQuery(+ createQuery: typeof useSoupAstItemsQuery,email: Accessor<string | undefined>,view: Accessor<EmailView>,signalView: Accessor<EmailSignalView>) {- return useSoupAstItemsQuery(+ return createQuery(() => {const addr = email();const base = {diff --git a/apps/web/src/features/crm/queries/contacts.ts b/apps/web/src/features/crm/queries/contacts.tsnew file mode 100644index 0000000000..1e04a67af6--- /dev/null+++ b/apps/web/src/features/crm/queries/contacts.ts@@ -0,0 +1,169 @@+import { throwOnErr } from '@core/util/result';+import { soupKeys } from '@queries/soup/keys';+import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';+import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import type { CrmRecordDependencies } from './dependencies';+import { crmKeys } from './keys';++const CONTACT_STALE_TIME = 60 * 1000;++function crmContactByEmailQueryOptions(+ deps: CrmRecordDependencies,+ teamId: string,+ email: string+) {+ const normalizedEmail = email.trim().toLowerCase();+ return queryOptions({+ queryKey: crmKeys.contactByEmail(teamId, normalizedEmail).queryKey,+ queryFn: async ({ signal }) => {+ const { contact } = await throwOnErr(() =>+ deps.storage.getContactByEmail({+ email: normalizedEmail,+ signal,+ })+ );+ if (contact) {+ deps.client.setQueryData(crmKeys.contact(contact.id).queryKey, contact);+ }+ return contact;+ },+ staleTime: CONTACT_STALE_TIME,+ });+}++/** Resolves a team CRM contact by email and primes its detail cache. */+export function useCrmContactByEmailQuery(+ deps: CrmRecordDependencies,+ teamId: Accessor<string>,+ email: Accessor<string>,+ enabled: Accessor<boolean>+) {+ return useQuery(+ () => ({+ ...crmContactByEmailQueryOptions(deps, teamId(), email()),+ enabled: enabled() && !!teamId() && !!email(),+ }),+ () => deps.client+ );+}++/**+ * Fetches a single CRM contact by id via `GET /crm/contacts/{id}`.+ * The endpoint is role-aware: admins/owners see hidden contacts too,+ * non-admins get 404 on hidden rows. The frontend doesn't branch — it+ * just calls the endpoint and trusts the response.+ */+export function useContactQuery(+ deps: CrmRecordDependencies,+ contactId: Accessor<string>+) {+ return useQuery(+ () => {+ const id = contactId();+ return {+ queryKey: crmKeys.contact(id).queryKey,+ queryFn: () => {+ if (!id) {+ throw new Error('contact id is required to fetch contact');+ }+ return throwOnErr(() => deps.storage.getContact({ contactId: id }));+ },+ staleTime: CONTACT_STALE_TIME,+ enabled: !!id,+ };+ },+ () => deps.client+ );+}++/**+ * Renames a contact via `PUT /crm/contacts/{id}/name`. Unlike company names+ * there is no global directory involved — `crm_contacts.name` is already+ * team-scoped, so the write is a plain overwrite. Optimistically updates the+ * contact detail cache (with rollback on error) so the title flips+ * immediately, then invalidates it plus the parent company (whose response+ * embeds the contact list) and soup so every listing picks up the new name.+ */+export function useSetContactNameMutation(deps: CrmRecordDependencies) {+ return useMutation(+ () => ({+ mutationFn: ({+ contactId,+ name,+ }: {+ contactId: string;+ companyId: string;+ name: string;+ }) => throwOnErr(() => deps.storage.setContactName({ contactId, name })),+ onMutate: async ({ contactId, name }) => {+ const queryKey = crmKeys.contact(contactId).queryKey;+ await deps.client.cancelQueries({ queryKey });+ const previous = deps.client.getQueryData<CrmContactResponse>(queryKey);+ if (previous) {+ deps.client.setQueryData<CrmContactResponse>(queryKey, {+ ...previous,+ name,+ });+ }+ return { previous, optimisticName: name };+ },+ // Roll back only if the cache still holds this mutation's optimistic+ // name — a stale failure must not clobber a newer rename's update.+ onError: (_err, { contactId }, context) => {+ if (context?.previous) {+ deps.client.setQueryData<CrmContactResponse>(+ crmKeys.contact(contactId).queryKey,+ (current) =>+ current?.name === context.optimisticName+ ? context.previous+ : current+ );+ }+ },+ onSettled: (_data, _err, { contactId, companyId }) =>+ Promise.all([+ deps.client.invalidateQueries({+ queryKey: crmKeys.contact(contactId).queryKey,+ }),+ deps.client.invalidateQueries({+ queryKey: crmKeys.company(companyId).queryKey,+ }),+ deps.client.invalidateQueries({ queryKey: soupKeys._def }),+ ]),+ }),+ () => deps.client+ );+}++/**+ * Toggles `crm_contacts.hidden` via `PUT /crm/contacts/{id}/hidden`.+ * Hidden contacts disappear from the parent company's contact list+ * (non-admin view) and from any soup surface that filters them.+ *+ * Returns the invalidation promise from `onSuccess` so the mutation+ * stays pending until both the contact query and the soup queries+ * refetch — the toggle state and any dependent UI all flip in one beat.+ */+export function useSetContactHiddenMutation(deps: CrmRecordDependencies) {+ return useMutation(+ () => ({+ mutationFn: ({+ contactId,+ hidden,+ }: {+ contactId: string;+ hidden: boolean;+ }) =>+ throwOnErr(() => deps.storage.setContactHidden({ contactId, hidden })),+ onSuccess: (_data, { contactId }) =>+ Promise.all([+ deps.client.invalidateQueries({ queryKey: soupKeys._def }),+ deps.client.invalidateQueries({+ queryKey: crmKeys.contact(contactId).queryKey,+ }),+ ]),+ }),+ () => deps.client+ );+}diff --git a/apps/web/src/features/companies/crm/deal-stages.test.tsx b/apps/web/src/features/crm/queries/deal-stages.test.tsxsimilarity index 93%rename from apps/web/src/features/companies/crm/deal-stages.test.tsxrename to apps/web/src/features/crm/queries/deal-stages.test.tsxindex 582cee18d9..7616eba678 100644--- a/apps/web/src/features/companies/crm/deal-stages.test.tsx+++ b/apps/web/src/features/crm/queries/deal-stages.test.tsx@@ -12,13 +12,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import { CRM_TEAM_STAGE_DEFINITION_NAME, useDealStages } from './deal-stages';const mocks = vi.hoisted(() => ({ definitions: vi.fn() }));-vi.mock('@queries/properties/definitions', () => ({- useListPropertiesQuery: () => mocks.definitions(),-}));-vi.mock('./team-crm-config', () => ({- useTeamCrmConfig: () => ({ config: () => ({}), isLoading: () => false }),-}));-const customized: PropertyDefinitionWithOptions = {definition: {id: 'team-stages',@@ -63,7 +56,12 @@ function mount(consumeStages: boolean, providerOwned = false) {})));function View() {- const stages = useDealStages();+ const stages = useDealStages(mocks.definitions(), {+ config: () => ({}),+ isLoading: () => false,+ isError: () => false,+ update: { isPending: false, mutate: vi.fn(), mutateAsync: vi.fn() },+ });return consumeStages ? (<div data-testid="stages">{stages.stageDefinitionId()}:@@ -79,7 +77,12 @@ function mount(consumeStages: boolean, providerOwned = false) {function ProviderOwnedView() {// SoupViewContextProvider creates its stage source and grouping memo// above the CRM child's boundary. SplitPanel wraps the provider itself.- const stages = useDealStages();+ const stages = useDealStages(mocks.definitions(), {+ config: () => ({}),+ isLoading: () => false,+ isError: () => false,+ update: { isPending: false, mutate: vi.fn(), mutateAsync: vi.fn() },+ });const group = createMemo(() => {if (!consumeStages) return 'Cached document';const stage = stages.resolveStage({diff --git a/apps/web/src/features/companies/crm/deal-stages.ts b/apps/web/src/features/crm/queries/deal-stages.tssimilarity index 72%rename from apps/web/src/features/companies/crm/deal-stages.tsrename to apps/web/src/features/crm/queries/deal-stages.tsindex 2ed98be6e8..e5d388ec79 100644--- a/apps/web/src/features/companies/crm/deal-stages.ts+++ b/apps/web/src/features/crm/queries/deal-stages.ts@@ -1,3 +1,4 @@+import { resolveCompanyStage } from '../core/stages';/*** Team-customizable deal stages for the CRM.*@@ -11,10 +12,8 @@* for which set is active.*/-// Imports come from the concrete @entity modules, not the barrel: this-// module loads inside soup-view-context's import chain, where the barrel-// can still be mid-initialization (circular import) and its re-exports-// undefined at module-eval time.+// Import concrete entity helpers to keep stage sources independent of+// the entity barrel's UI initialization.import { soupPropertyToProperty } from '@entity/extractors-property/property-helpers';import { getCompanyStageOptionId } from '@entity/utils/company-properties';import {@@ -27,56 +26,19 @@ import {SYSTEM_PROPERTY_IDS,} from '@property/constants';import type { Property } from '@property/types';-import { useListPropertiesQuery } from '@queries/properties/definitions';import type { PropertyDefinitionResponse } from '@service-properties/generated/schemas/propertyDefinitionResponse';import type { PropertyDefinitionWithOptions } from '@service-properties/generated/schemas/propertyDefinitionWithOptions';import type { PropertyOption } from '@service-properties/generated/schemas/propertyOption';import { createLazyMemo } from '@solid-primitives/memo';-import type { Accessor } from 'solid-js';-import { useTeamCrmConfig } from './team-crm-config';+import type { CrmQuery, TeamConfigSource } from '../context/crm-sources';// Canonical home is `@property/constants` (property pickers filter on it);// re-exported here for the CRM-side callers.export { CRM_TEAM_STAGE_DEFINITION_NAME } from '@property/constants';-export type DealStage = {- /** Property option id — the value stored on companies. */- id: string;- label: string;-};+import type { DealStage, DealStages } from '../context/crm-sources';-export type DealStages = {- /** Active stages, in display order (team set when customized). */- stages: Accessor<DealStage[]>;- /**- * Stages offered by stage *filters*: the active set plus, on the system- * default set, the retired legacy stages — companies may still carry- * those values and should stay reachable.- */- filterStages: Accessor<DealStage[]>;- /** True when the team has its own stage set. */- isCustomized: Accessor<boolean>;- /** Definition id stage values are read from / written to. */- stageDefinitionId: Accessor<string>;- /**- * `Property` stub for the active stage definition, for property editors- * and saves (mirrors `buildCompanyDefaultProperties` for the builtin).- */- stageProperty: Accessor<Property>;- /**- * The company's stage within the active set. When the team has custom- * stages, legacy values stored on the system Stage property are mapped- * onto the custom set (recorded map first, then label) so boards/lists- * don't blank out after customizing; moving a card writes the value to- * the team definition.- */- resolveStage: (entity: CompanyLike) => string | undefined;- /** 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>;-};+export type { DealStage, DealStages } from '../context/crm-sources';/** Minimal company shape needed to read stage values. */type CompanyLike = {@@ -214,18 +176,12 @@ function buildStagePropertyStub(* The active deal-stage set for the current team. See module docs for the* system-vs-team resolution rules.*/-export function useDealStages(): DealStages {- const teamDefinitionsQuery = useListPropertiesQuery(() => ({- scope: 'team',- includeOptions: true,- }));- const teamCrmConfig = useTeamCrmConfig();-- // Shared soup contexts also mount for documents and other non-CRM views.- // Only read the query when a stage consumer needs it; actual CRM consumers- // retain their Suspense behavior rather than treating pending data as defaults.- // Lazy memos keep their creation owner: SplitPanel wraps the soup provider- // itself in Suspense, covering provider-owned grouping as well as its children.+export function useDealStages(+ teamDefinitionsQuery: CrmQuery<PropertyDefinitionResponse[]>,+ teamCrmConfig: TeamConfigSource+): DealStages {+ // Read metadata when a stage consumer needs it. Keep pending metadata+ // within the existing Suspense boundary instead of showing default stages.const teamStageDefinition = createLazyMemo(() =>findTeamStageDefinition(teamDefinitionsQuery.data));@@ -278,17 +234,16 @@ export function useDealStages(): DealStages {const direct = getCompanySelectOptionId(entity, stageDefinitionId());if (direct && stageIds().has(direct)) return direct;if (stageDefinitionId() === SYSTEM_PROPERTY_IDS.STAGE) return direct;-- const legacy = getCompanyStageOptionId(- entity as Parameters<typeof getCompanyStageOptionId>[0]- );- if (!legacy) return undefined;- const mapped = teamCrmConfig.config().legacyStageIds?.[legacy];- if (mapped && stageIds().has(mapped)) return mapped;- const legacyLabel = getPropertyOptionLabel(legacy)?.toLowerCase();- if (!legacyLabel) return undefined;- return stages().find((stage) => stage.label.toLowerCase() === legacyLabel)- ?.id;+ return resolveCompanyStage({+ direct,+ customized: stageDefinitionId() !== SYSTEM_PROPERTY_IDS.STAGE,+ stages: stages(),+ legacy: getCompanyStageOptionId(+ entity as Parameters<typeof getCompanyStageOptionId>[0]+ ),+ legacyMapping: teamCrmConfig.config().legacyStageIds,+ legacyLabel: getPropertyOptionLabel,+ });};const stageLabel = (optionId: string): string | undefined =>diff --git a/apps/web/src/features/crm/queries/dependencies.ts b/apps/web/src/features/crm/queries/dependencies.tsnew file mode 100644index 0000000000..d158277efe--- /dev/null+++ b/apps/web/src/features/crm/queries/dependencies.ts@@ -0,0 +1,13 @@+import type { storageServiceClient } from '@service-storage/client';+import type { QueryClient } from '@tanstack/solid-query';+/** Concrete dependencies stay at the query adapter boundary. */+export type CrmQueryDependencies = {+ storage: typeof storageServiceClient;+ client: QueryClient;+ feedback: { success(message: string): void; failure(message: string): void };+};++export type CrmRecordDependencies = Pick<+ CrmQueryDependencies,+ 'storage' | 'client'+>;diff --git a/apps/web/src/features/companies/Company/emailFilter.ts b/apps/web/src/features/crm/queries/email-filter.tssimilarity index 100%rename from apps/web/src/features/companies/Company/emailFilter.tsrename to apps/web/src/features/crm/queries/email-filter.tsdiff --git a/apps/web/src/lib/queries/crm/export.ts b/apps/web/src/features/crm/queries/export.tssimilarity index 85%rename from apps/web/src/lib/queries/crm/export.tsrename to apps/web/src/features/crm/queries/export.tsindex 628049d967..21bf585da6 100644--- a/apps/web/src/lib/queries/crm/export.ts+++ b/apps/web/src/features/crm/queries/export.ts@@ -1,11 +1,12 @@import { QUERY_FILTERS_BASE } from '@app/features/next-soup/filters/query-filters';import { throwOnErr } from '@core/util/result';import { type CrmCompanyEntity, isCrmCompanyEntity } from '@entity';-import { storageServiceClient } from '@service-storage/client';-import { mapApiSoupItemToEntity } from '../soup/transform-utils';+import type { storageServiceClient } from '@service-storage/client';+import { mapApiSoupItemToEntity } from '../../../lib/queries/soup/transform-utils';/** Read every visible company, without changing the active CRM view. */export async function fetchCrmExportCompanies(+ storage: typeof storageServiceClient,signal: AbortSignal,onProgress: (count: number) => void) {@@ -15,7 +16,7 @@ export async function fetchCrmExportCompanies(do {signal.throwIfAborted();const page = await throwOnErr(() =>- storageServiceClient.getSoupItems({+ storage.getSoupItems({params: { cursor },body: {...QUERY_FILTERS_BASE,diff --git a/apps/web/src/lib/queries/crm/graphql.test.ts b/apps/web/src/features/crm/queries/graphql.test.tssimilarity index 100%rename from apps/web/src/lib/queries/crm/graphql.test.tsrename to apps/web/src/features/crm/queries/graphql.test.tsdiff --git a/apps/web/src/lib/queries/crm/graphql.ts b/apps/web/src/features/crm/queries/graphql.tssimilarity index 100%rename from apps/web/src/lib/queries/crm/graphql.tsrename to apps/web/src/features/crm/queries/graphql.tsdiff --git a/apps/web/src/lib/queries/crm/keys.ts b/apps/web/src/features/crm/queries/keys.tssimilarity index 100%rename from apps/web/src/lib/queries/crm/keys.tsrename to apps/web/src/features/crm/queries/keys.tsdiff --git a/apps/web/src/features/crm/queries/lists.ts b/apps/web/src/features/crm/queries/lists.tsnew file mode 100644index 0000000000..be438b5c15--- /dev/null+++ b/apps/web/src/features/crm/queries/lists.ts@@ -0,0 +1,111 @@+import { throwOnErr } from '@core/util/result';+import { useMutation, useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import { type CrmListConfig, isCrmListConfig } from '../core/navigation';+import type { CrmQueryDependencies } from './dependencies';+import { crmKeys } from './keys';++/** Personal collections use saved-view storage, with explicit membership and team scope. */+export function useCrmLists(+ deps: CrmQueryDependencies,+ teamId: Accessor<string | undefined>+) {+ const client = deps.client;+ const query = useQuery(+ () => ({+ queryKey: crmKeys.lists.queryKey,+ queryFn: () => throwOnErr(() => deps.storage.views.getSavedViews()),+ enabled: !!teamId(),+ }),+ () => deps.client+ );+ const lists = () =>+ query.isSuccess+ ? query.data.views.flatMap((view) =>+ isCrmListConfig(view.config) && view.config.teamId === teamId()+ ? [{ id: view.id, name: view.name, config: view.config }]+ : []+ )+ : [];+ const save = useMutation(+ () => ({+ mutationFn: async (input: {+ id?: string;+ name: string;+ companyIds: string[];+ }) => {+ const team = teamId();+ if (!team) throw new Error('Join a team to create a list');+ const config: CrmListConfig = {+ kind: 'crm-list',+ teamId: team,+ companyIds: [...new Set(input.companyIds)],+ };+ if (input.id) {+ await throwOnErr(() =>+ deps.storage.views.patchView({+ saved_view_id: input.id!,+ name: input.name,+ config,+ })+ );+ return input.id;+ }+ const created = await throwOnErr(() =>+ deps.storage.views.createSavedView({ name: input.name, config })+ );+ return created.id;+ },+ onSuccess: () =>+ client.invalidateQueries({ queryKey: crmKeys.lists.queryKey }),+ }),+ () => deps.client+ );+ const remove = useMutation(+ () => ({+ mutationFn: (id: string) =>+ throwOnErr(() => deps.storage.views.deleteView({ savedViewId: id })),+ onSuccess: () =>+ client.invalidateQueries({ queryKey: crmKeys.lists.queryKey }),+ }),+ () => deps.client+ );+ const setMembership = useMutation(+ () => ({+ mutationFn: async (input: {+ listId: string;+ companyId: string;+ included: boolean;+ }) => {+ const team = teamId();+ if (!team) throw new Error('A team is required');+ // Refresh before editing so another company's recently changed membership+ // isn't overwritten by an old detail-page snapshot.+ const latest = await throwOnErr(() =>+ deps.storage.views.getSavedViews()+ );+ const list = latest.views.find((entry) => entry.id === input.listId);+ if (+ !list ||+ !isCrmListConfig(list.config) ||+ list.config.teamId !== team+ )+ throw new Error('This list is no longer available');+ const config = list.config;+ const companyIds = new Set(config.companyIds);+ if (input.included) companyIds.add(input.companyId);+ else companyIds.delete(input.companyId);+ await throwOnErr(() =>+ deps.storage.views.patchView({+ saved_view_id: list.id,+ config: { ...config, companyIds: [...companyIds] },+ })+ );+ },+ onSuccess: () =>+ client.invalidateQueries({ queryKey: crmKeys.lists.queryKey }),+ }),+ () => deps.client+ );+ return { query, lists, save, remove, setMembership };+}diff --git a/apps/web/src/features/crm/queries/people.ts b/apps/web/src/features/crm/queries/people.tsnew file mode 100644index 0000000000..c5c6363b74--- /dev/null+++ b/apps/web/src/features/crm/queries/people.ts@@ -0,0 +1,91 @@+import { QUERY_FILTERS_BASE } from '@app/features/next-soup/filters/query-filters';+import { throwOnErr } from '@core/util/result';+import { useInfiniteQuery } from '@tanstack/solid-query';+import { type Accessor, createEffect } from 'solid-js';+import { soupKeys } from '../../../lib/queries/soup/keys';+import type { CrmPerson } from '../core/people';+import type { CrmQueryDependencies } from './dependencies';+import { crmKeys } from './keys';++/** Assemble one people directory from the existing company/contact endpoints.+ * Pages appear progressively; at most four company requests run at once.+ */+export function useCrmPeopleQuery(+ deps: CrmQueryDependencies,+ teamId: Accessor<string | undefined>+) {+ const client = deps.client;+ const query = useInfiniteQuery(+ () => ({+ queryKey: soupKeys.crmPeople(teamId() ?? '').queryKey,+ enabled: !!teamId(),+ staleTime: 60_000,+ initialPageParam: null as string | null,+ queryFn: async ({ pageParam, signal }) => {+ const page = await throwOnErr(() =>+ deps.storage.getSoupItems({+ params: { cursor: pageParam },+ body: {+ ...QUERY_FILTERS_BASE,+ crm_company_filters: { hidden: false },+ limit: 20,+ sort_method: 'updated_at',+ },+ })+ );+ const companies = page.items.flatMap((item) =>+ item.tag === 'crmCompany' ? [item.data] : []+ );+ const people: CrmPerson[] = [];+ for (let offset = 0; offset < companies.length; offset += 4) {+ signal.throwIfAborted();+ const batch = await Promise.all(+ companies.slice(offset, offset + 4).map(async (company) => {+ const detail = await client.fetchQuery({+ queryKey: crmKeys.company(company.id).queryKey,+ staleTime: 60_000,+ queryFn: () =>+ throwOnErr(() =>+ deps.storage.getCompany({ companyId: company.id })+ ),+ });+ return detail.hidden+ ? []+ : detail.contacts+ .filter((contact) => !contact.hidden)+ .map((contact) => ({+ ...contact,+ companyName:+ detail.name ||+ detail.domains[0]?.domain ||+ 'Unknown company',+ }));+ })+ );+ people.push(...batch.flat());+ }+ return { people, nextCursor: page.next_cursor };+ },+ getNextPageParam: (page) => page.nextCursor,+ }),+ () => deps.client+ );++ // Drive progressive network pagination while this directory is mounted.+ createEffect(() => {+ if (query.hasNextPage && !query.isFetching && !query.isError) {+ void query.fetchNextPage();+ }+ });+ const people = () =>+ !query.isPending+ ? [+ ...new Map(+ query.data?.pages+ .flatMap((page) => page.people)+ .map((person) => [person.id, person]) ?? []+ ).values(),+ ]+ : [];+ return { query, people };+}diff --git a/apps/web/src/features/crm/queries/previews.ts b/apps/web/src/features/crm/queries/previews.tsnew file mode 100644index 0000000000..978fda2060--- /dev/null+++ b/apps/web/src/features/crm/queries/previews.ts@@ -0,0 +1,50 @@+import type { PreviewItem } from '@queries/preview/types';+import type { storageServiceClient } from '@service-storage/client';++/**+ * Fetches CRM company previews via `GET /crm/companies/{id}`. Mirrors the+ * email preview fetcher's shape — N parallel REST calls rather than a+ * batch endpoint, since the CRM REST surface is per-id today and+ * companies are a smaller cardinality than mentions in flight.+ *+ * The backend already gates hidden visibility by role (admin/owner sees+ * hidden, non-admin 404s), so the fetcher doesn't need to repeat that+ * logic.+ */+export async function fetchCrmCompanyPreviews(+ getCompany: typeof storageServiceClient.getCompany,+ companyIds: string[]+): Promise<PreviewItem[]> {+ return await Promise.all(+ companyIds.map(async (id) => {+ const base = { id, type: 'crm_company' as const };+ const result = await getCompany({ companyId: id });++ if (result.isErr()) {+ // The backend returns 404 for every unreachable reason (wrong+ // team, hidden+member, doesn't exist) — deliberate, so existence+ // can't be probed across teams. Maps to "No Access" for parity+ // with the email fetcher's per-id convention; "Deleted" would be+ // misleading since we can't actually tell.+ return {+ ...base,+ access: 'no_access' as const,+ loading: false as const,+ };+ }++ const company = result.value;+ const displayName =+ company.name ?? company.domains[0]?.domain ?? 'Unknown Company';++ return {+ ...base,+ access: 'access' as const,+ loading: false as const,+ rawName: displayName,+ name: displayName,+ updatedAt: company.updatedAt,+ };+ })+ );+}diff --git a/apps/web/src/features/crm/queries/saved-view-codec.test.ts b/apps/web/src/features/crm/queries/saved-view-codec.test.tsnew file mode 100644index 0000000000..e5faee8438--- /dev/null+++ b/apps/web/src/features/crm/queries/saved-view-codec.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest';+import { decodeCrmViewParam, encodeCrmViewParam } from './saved-view-codec';+import { parseTeamViews } from './team-view-codec';++describe('CRM saved state boundary', () => {+ it('round trips Unicode and explicit ungrouped layouts', () => {+ const view = {+ kind: 'crm' as const,+ searchText: 'Zoë 日本',+ groupBy: null,+ stageFilter: ['qualified'],+ viewMode: 'board' as const,+ };+ expect(decodeCrmViewParam(encodeCrmViewParam(view))).toEqual(view);+ });+ it('accepts old snapshots and ignores unknown future fields', () => {+ expect(+ decodeCrmViewParam(btoa(JSON.stringify({ kind: 'crm', future: true })))+ ).toEqual({ kind: 'crm', future: true });+ });+ it.each([+ { stageFilter: 42 },+ { ownerFilter: [false] },+ { sort: 'updated_at' },+ { clientFilters: [] },+ { clientFilters: { and: 'company-stage' } },+ { viewMode: 'grid' },+ { searchText: { text: 'acme' } },+ ])('rejects malformed known state %j', (invalid) => {+ expect(+ decodeCrmViewParam(btoa(JSON.stringify({ kind: 'crm', ...invalid })))+ ).toBeUndefined();+ });+ it('rejects broken URLs and malformed saved records', () => {+ expect(decodeCrmViewParam('%invalid')).toBeUndefined();+ expect(+ parseTeamViews([+ null,+ { id: 1 },+ { id: 'saved', name: 'Pipeline', config: { kind: 'crm' } },+ ])+ ).toEqual([{ id: 'saved', name: 'Pipeline', config: { kind: 'crm' } }]);+ });+});diff --git a/apps/web/src/features/crm/queries/saved-view-codec.ts b/apps/web/src/features/crm/queries/saved-view-codec.tsnew file mode 100644index 0000000000..7aaeaec403--- /dev/null+++ b/apps/web/src/features/crm/queries/saved-view-codec.ts@@ -0,0 +1,20 @@+import { type CrmViewConfig, isCrmViewConfig } from '../core/saved-view';+export const CRM_VIEW_URL_PARAM = 'crmView';++/** Base64url-encode a view config for the share link. */+export function encodeCrmViewParam(config: CrmViewConfig): string {+ const json = JSON.stringify(config);+ const base64 = btoa(String.fromCharCode(...new TextEncoder().encode(json)));+ return base64.replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');+}++export function decodeCrmViewParam(param: string): CrmViewConfig | undefined {+ try {+ const base64 = param.replaceAll('-', '+').replaceAll('_', '/');+ const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));+ const parsed: unknown = JSON.parse(new TextDecoder().decode(bytes));+ return isCrmViewConfig(parsed) ? parsed : undefined;+ } catch {+ return undefined;+ }+}diff --git a/apps/web/src/features/crm/queries/saved-views.ts b/apps/web/src/features/crm/queries/saved-views.tsnew file mode 100644index 0000000000..c4f9c54d62--- /dev/null+++ b/apps/web/src/features/crm/queries/saved-views.ts@@ -0,0 +1,235 @@+import type { CrmQueryDependencies } from './dependencies';+/**+ * CRM saved views: named snapshots of the Customers view state.+ *+ * - Personal views persist per-user through the existing `/saved_views`+ * API (arbitrary JSON config, frontend-owned shape).+ * - Team views live in the shared team CRM config (see team-crm-config)+ * so every team member sees them.+ * - Any view can be shared as a link: the config is base64url-encoded in+ * the `crmView` search param of the Customers URL, so anyone on the+ * team can open it (the link carries only view state, never data).+ */++import { throwOnErr } from '@core/util/result';+import type { View } from '@service-storage/generated/schemas/view';+import { useMutation, useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import { createMemo } from 'solid-js';+import type { TeamConfigSource } from '../context/crm-sources';+import { type CrmViewConfig, isCrmViewConfig } from '../core/saved-view';+import type { TeamCrmSavedView } from '../core/team-config';++export { type CrmViewConfig, isCrmViewConfig } from '../core/saved-view';+export {+ CRM_VIEW_URL_PARAM,+ decodeCrmViewParam,+ encodeCrmViewParam,+} from './saved-view-codec';++const CRM_SAVED_VIEWS_QUERY_KEY = ['crm', 'saved-views'] as const;++export type PersonalCrmView = View & { config: CrmViewConfig };++/** Personal saved views (server-persisted via /saved_views). */+export function usePersonalCrmViews(deps: CrmQueryDependencies) {+ const queryClient = deps.client;++ const viewsQuery = useQuery(+ () => ({+ queryKey: CRM_SAVED_VIEWS_QUERY_KEY,+ queryFn: async () =>+ await throwOnErr(async () => await deps.storage.views.getSavedViews()),+ }),+ () => deps.client+ );++ const views = createMemo((): PersonalCrmView[] =>+ (viewsQuery.isSuccess ? viewsQuery.data.views : []).filter(+ (view): view is PersonalCrmView => isCrmViewConfig(view.config)+ )+ );++ const defaultView = () => views().find((view) => view.config.isDefault);++ const invalidate = () =>+ queryClient.invalidateQueries({ queryKey: CRM_SAVED_VIEWS_QUERY_KEY });++ const createMutation = useMutation(+ () => ({+ mutationFn: async (vars: { name: string; config: CrmViewConfig }) =>+ await throwOnErr(+ async () =>+ await deps.storage.views.createSavedView({+ name: vars.name,+ config: vars.config,+ })+ ),+ onSuccess: () => invalidate(),+ onError: (error: Error) => {+ console.error('Failed to save view', error);+ deps.feedback.failure('Failed to save view');+ },+ }),+ () => deps.client+ );++ const renameMutation = useMutation(+ () => ({+ mutationFn: async (vars: { id: string; name: string }) =>+ await throwOnErr(+ async () =>+ await deps.storage.views.patchView({+ saved_view_id: vars.id,+ name: vars.name,+ })+ ),+ onSuccess: () => invalidate(),+ onError: (error: Error) => {+ console.error('Failed to rename view', error);+ deps.feedback.failure('Failed to rename view');+ },+ }),+ () => deps.client+ );++ const deleteMutation = useMutation(+ () => ({+ mutationFn: async (vars: { id: string }) =>+ await throwOnErr(+ async () =>+ await deps.storage.views.deleteView({ savedViewId: vars.id })+ ),+ onSuccess: () => invalidate(),+ onError: (error: Error) => {+ console.error('Failed to delete view', error);+ deps.feedback.failure('Failed to delete view');+ },+ }),+ () => deps.client+ );++ // The backend PATCH shallow-merges into the stored config, so sending just+ // `{isDefault}` flips the flag without touching the rest of the snapshot.+ const setDefaultMutation = useMutation(+ () => ({+ mutationFn: async (vars: { id: string | undefined }) => {+ const { id } = vars;+ const previous = defaultView();+ if (previous && previous.id !== id) {+ await throwOnErr(+ async () =>+ await deps.storage.views.patchView({+ saved_view_id: previous.id,+ config: { isDefault: false },+ })+ );+ }+ if (id !== undefined) {+ await throwOnErr(+ async () =>+ await deps.storage.views.patchView({+ saved_view_id: id,+ config: { isDefault: true },+ })+ );+ }+ },+ onSuccess: () => invalidate(),+ onError: (error: Error) => {+ console.error('Failed to set default view', error);+ deps.feedback.failure('Failed to set default view');+ },+ }),+ () => deps.client+ );++ return {+ views,+ defaultView,+ isLoading: () => viewsQuery.isLoading,+ create: createMutation,+ rename: renameMutation,+ remove: deleteMutation,+ setDefault: setDefaultMutation,+ };+}++/** Team-shared saved views (stored in the shared team CRM config). */+export function useTeamCrmViews(+ deps: CrmQueryDependencies,+ userId: Accessor<string | undefined>,+ settings: TeamConfigSource+) {+ const { config, update, isLoading } = settings;++ const views = createMemo((): TeamCrmSavedView[] =>+ (config().teamViews ?? []).filter((view) => isCrmViewConfig(view.config))+ );++ const defaultViewId = () => config().defaultTeamViewId;++ const defaultView = () => views().find((view) => view.id === defaultViewId());++ const setDefault = (id: string | undefined) => {+ update.mutate(+ { defaultTeamViewId: id ?? null },+ {+ onError: (error: Error) => {+ console.error('Failed to set default team view', error);+ deps.feedback.failure('Failed to set default team view');+ },+ }+ );+ };++ const add = (name: string, viewConfig: CrmViewConfig) => {+ const view: TeamCrmSavedView = {+ id: crypto.randomUUID(),+ name,+ config: viewConfig,+ createdBy: userId(),+ createdAt: new Date().toISOString(),+ };+ update.mutate(+ // Updater form: derives from the latest cache when the (serialized)+ // mutation actually runs, so rapid saves don't drop each other.+ { teamViews: (current) => [...current, view] },+ {+ onError: (error: Error) => {+ console.error('Failed to save team view', error);+ deps.feedback.failure('Failed to save team view');+ },+ }+ );+ };++ const remove = (id: string) => {+ update.mutate(+ {+ teamViews: (current) => current.filter((view) => view.id !== id),+ // A deleted view can't stay the team default.+ ...(config().defaultTeamViewId === id+ ? { defaultTeamViewId: null }+ : {}),+ },+ {+ onError: (error: Error) => {+ console.error('Failed to delete team view', error);+ deps.feedback.failure('Failed to delete team view');+ },+ }+ );+ };++ return {+ views,+ defaultViewId,+ defaultView,+ add,+ remove,+ setDefault,+ isLoading,+ isSaving: () => update.isPending,+ };+}diff --git a/apps/web/src/features/crm/queries/settings-commands.ts b/apps/web/src/features/crm/queries/settings-commands.tsnew file mode 100644index 0000000000..b81a363af1--- /dev/null+++ b/apps/web/src/features/crm/queries/settings-commands.ts@@ -0,0 +1,28 @@+import { throwOnErr } from '@core/util/result';+import type { patchTeamCrmSettings } from '@service-auth/crm';+import type { PatchTeamCrmSettingsRequest } from '@service-auth/generated/schemas/patchTeamCrmSettingsRequest';+import type { PatchTeamCrmSettingsResponse } from '@service-auth/generated/schemas/patchTeamCrmSettingsResponse';+import { useMutation } from '@tanstack/solid-query';+import type { CrmQueryDependencies } from './dependencies';+export function usePatchTeamCrmSettingsMutation(+ deps: CrmQueryDependencies & {+ patch: typeof patchTeamCrmSettings;+ invalidateTeams(): void;+ }+) {+ return useMutation(+ () => ({+ mutationFn: async (req: PatchTeamCrmSettingsRequest) =>+ await throwOnErr(() => deps.patch(req)),+ onSuccess: (data: PatchTeamCrmSettingsResponse) => {+ deps.invalidateTeams();+ deps.feedback.success(data.enabled ? 'CRM enabled' : 'CRM disabled');+ },+ onError: (error: Error) => {+ console.error('Failed to update CRM settings', error);+ deps.feedback.failure('Failed to update CRM settings');+ },+ }),+ () => deps.client+ );+}diff --git a/apps/web/src/features/crm/queries/stages.ts b/apps/web/src/features/crm/queries/stages.tsnew file mode 100644index 0000000000..b60d647e41--- /dev/null+++ b/apps/web/src/features/crm/queries/stages.ts@@ -0,0 +1,46 @@+import { throwOnErr } from '@core/util/result';+import type { CrmStageInput } from '@service-storage/generated/schemas/crmStageInput';+import { useMutation } from '@tanstack/solid-query';+import { soupKeys } from '../../../lib/queries/soup/keys';+import type { CrmQueryDependencies } from './dependencies';+import { CRM_TEAM_SETTINGS_QUERY_KEY } from './team-config';++function invalidateStageReaders(deps: CrmQueryDependencies) {+ return Promise.all([+ deps.client.invalidateQueries({+ predicate: ({ queryKey }) =>+ queryKey.includes('properties') && queryKey.includes('definitions'),+ }),+ deps.client.invalidateQueries({ queryKey: soupKeys._def }),+ deps.client.invalidateQueries({ queryKey: CRM_TEAM_SETTINGS_QUERY_KEY }),+ ]);+}++export function useReplaceCrmStagesMutation(deps: CrmQueryDependencies) {+ return useMutation(+ () => ({+ mutationFn: (stages: CrmStageInput[]) =>+ throwOnErr(() => deps.storage.replaceCrmTeamStages({ stages })),+ onSuccess: () => invalidateStageReaders(deps),+ onError: (error: Error) => {+ console.error('Failed to update deal stages', error);+ deps.feedback.failure('Failed to update deal stages');+ },+ }),+ () => deps.client+ );+}++export function useResetCrmStagesMutation(deps: CrmQueryDependencies) {+ return useMutation(+ () => ({+ mutationFn: () => throwOnErr(() => deps.storage.resetCrmTeamStages()),+ onSuccess: () => invalidateStageReaders(deps),+ onError: (error: Error) => {+ console.error('Failed to reset deal stages', error);+ deps.feedback.failure('Failed to reset deal stages');+ },+ }),+ () => deps.client+ );+}diff --git a/apps/web/src/features/crm/queries/team-config.ts b/apps/web/src/features/crm/queries/team-config.tsnew file mode 100644index 0000000000..a01372f8d1--- /dev/null+++ b/apps/web/src/features/crm/queries/team-config.ts@@ -0,0 +1,112 @@+import type { TeamCrmConfig, TeamCrmConfigPatch } from '../core/team-config';+import type { CrmQueryDependencies } from './dependencies';+import { parseTeamViews } from './team-view-codec';++export type {+ CrmPermissionRole,+ CrmPermissions,+ TeamCrmConfig,+ TeamCrmConfigPatch,+ TeamCrmSavedView,+} from '../core/team-config';++/**+ * Team-shared CRM configuration (permissions, closed-stage set, 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).+ */++import { throwOnErr } from '@core/util/result';+import type { CrmTeamSettingsResponse } from '@service-storage/generated/schemas/crmTeamSettingsResponse';+import type { UpdateCrmTeamSettingsRequest } from '@service-storage/generated/schemas/updateCrmTeamSettingsRequest';+import { useMutation, useQuery } from '@tanstack/solid-query';+import { createMemo } from 'solid-js';++export const CRM_TEAM_SETTINGS_QUERY_KEY = ['crm', 'team-settings'] as const;++export function useTeamCrmConfig(deps: CrmQueryDependencies) {+ const queryClient = deps.client;++ const settingsQuery = useQuery(+ () => ({+ queryKey: CRM_TEAM_SETTINGS_QUERY_KEY,+ queryFn: async () =>+ await throwOnErr(() => deps.storage.getCrmTeamSettings()),+ }),+ () => deps.client+ );++ const config = createMemo((): TeamCrmConfig => {+ const data = settingsQuery.isSuccess ? settingsQuery.data : undefined;+ if (!data) return {};+ return {+ permissions: {+ editStages: data.edit_stages_role,+ 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,+ };+ });++ const updateMutation = useMutation(+ () => ({+ // Serialize updates: with whole-list team_views writes, concurrent+ // PUTs would clobber each other. Scoped mutations run one at a time,+ // and updater-style teamViews patches read the cache only once the+ // previous mutation's response has been written back.+ scope: { id: 'crm-team-settings' },+ mutationFn: async (patch: TeamCrmConfigPatch) => {+ const teamViews =+ typeof patch.teamViews === 'function'+ ? patch.teamViews(+ parseTeamViews(+ queryClient.getQueryData<CrmTeamSettingsResponse>(+ CRM_TEAM_SETTINGS_QUERY_KEY+ )?.team_views+ )+ )+ : patch.teamViews;+ const body: UpdateCrmTeamSettingsRequest = {+ 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 }+ : {}),+ };+ return await throwOnErr(() => deps.storage.updateCrmTeamSettings(body));+ },+ onSuccess: (settings) => {+ // The PUT returns the resulting row — seed the cache with it.+ queryClient.setQueryData(CRM_TEAM_SETTINGS_QUERY_KEY, settings);+ },+ onSettled: () =>+ queryClient.invalidateQueries({+ queryKey: CRM_TEAM_SETTINGS_QUERY_KEY,+ }),+ }),+ () => deps.client+ );++ return {+ config,+ isLoading: () => settingsQuery.isLoading,+ isError: () => settingsQuery.isError && settingsQuery.data === undefined,+ update: updateMutation,+ };+}diff --git a/apps/web/src/features/crm/queries/team-view-codec.ts b/apps/web/src/features/crm/queries/team-view-codec.tsnew file mode 100644index 0000000000..019afbe920--- /dev/null+++ b/apps/web/src/features/crm/queries/team-view-codec.ts@@ -0,0 +1,15 @@+import type { TeamCrmSavedView } from '../core/team-config';+/** Team settings are JSON; keep only records with the shape required by saved-view controls. */+export function parseTeamViews(value: unknown): TeamCrmSavedView[] {+ if (!Array.isArray(value)) return [];+ return value.filter(+ (item): item is TeamCrmSavedView =>+ typeof item === 'object' &&+ item !== null &&+ typeof item.id === 'string' &&+ typeof item.name === 'string' &&+ 'config' in item &&+ (item.createdBy === undefined || typeof item.createdBy === 'string') &&+ (item.createdAt === undefined || typeof item.createdAt === 'string')+ );+}diff --git a/apps/web/src/features/crm/record-adapter.ts b/apps/web/src/features/crm/record-adapter.tsnew file mode 100644index 0000000000..ba0b91102f--- /dev/null+++ b/apps/web/src/features/crm/record-adapter.ts@@ -0,0 +1,25 @@+import { storageServiceClient } from '@service-storage/client';+import { useQueryClient } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import { useSetCompanyHiddenMutation as createHiddenMutation } from './queries/companies';+import { useCrmContactByEmailQuery as createContactByEmailQuery } from './queries/contacts';++/** CRM record capabilities used by app-wide entity actions and user cards. */+export function useSetCompanyHiddenMutation() {+ return createHiddenMutation({+ storage: storageServiceClient,+ client: useQueryClient(),+ });+}+export function useCrmContactByEmailQuery(+ teamId: Accessor<string>,+ email: Accessor<string>,+ enabled: Accessor<boolean>+) {+ return createContactByEmailQuery(+ { storage: storageServiceClient, client: useQueryClient() },+ teamId,+ email,+ enabled+ );+}diff --git a/apps/web/src/features/companies/route.tsx b/apps/web/src/features/crm/route.tsxsimilarity index 57%rename from apps/web/src/features/companies/route.tsxrename to apps/web/src/features/crm/route.tsxindex c18f201aca..7f1b405147 100644--- a/apps/web/src/features/companies/route.tsx+++ b/apps/web/src/features/crm/route.tsx@@ -1,9 +1,4 @@-import { ViewTour } from '@app/features/tours/ViewTour';import { defineRoute } from '@app/lib/split-router';-import {- CRM_VIEW_URL_PARAM,- decodeCrmViewParam,-} from '@companies/crm/saved-views';import {RedirectSplit,usePageViewTracking,@@ -11,30 +6,24 @@ import {} from '@components/app/split-layout/split-router/app-route-shell';import { enableCrm, isFeatureEnabled } from '@core/constant/featureFlags';import { lazy } from 'solid-js';-import { getViewPreset } from '../next-soup/sidebar/soup-filter-presets';-import { companiesTour } from './tour';+import {+ CRM_VIEW_URL_PARAM,+ decodeCrmViewParam,+} from './queries/saved-view-codec';-const SoupView = lazy(async () => ({- default: (await import('../next-soup/soup-view/soup-view')).SoupView,+const Crm = lazy(async () => ({+ default: (await import('./crm')).Crm,}));export const CompaniesRouteView = withAuth(() => {if (!isFeatureEnabled(enableCrm))return <RedirectSplit to={{ type: 'component', id: 'home' }} />;usePageViewTracking('companies');- const preset = getViewPreset('companies');const crmView = new URLSearchParams(window.location.search).get(CRM_VIEW_URL_PARAM);return (- <SoupView- viewName="Customers"- initialFilters={preset?.filters}- initialClientFilters={preset?.clientFilters}- initialGroupBy={preset?.groupBy}- initialCrmView={crmView ? decodeCrmViewParam(crmView) : undefined}- tour={<ViewTour tour={companiesTour} />}- />+ <Crm initialView={crmView ? decodeCrmViewParam(crmView) : undefined} />);});diff --git a/apps/web/src/features/crm/stage-adapter.ts b/apps/web/src/features/crm/stage-adapter.tsnew file mode 100644index 0000000000..7bc74235d8--- /dev/null+++ b/apps/web/src/features/crm/stage-adapter.ts@@ -0,0 +1,17 @@+import { toast } from '@core/component/Toast/Toast';+import { useListPropertiesQuery } from '@queries/properties/definitions';+import { storageServiceClient } from '@service-storage/client';+import { useQueryClient } from '@tanstack/solid-query';+import { useDealStages } from './queries/deal-stages';+import { useTeamCrmConfig } from './queries/team-config';+export function createAppDealStages() {+ const settings = useTeamCrmConfig({+ client: useQueryClient(),+ storage: storageServiceClient,+ feedback: toast,+ });+ return useDealStages(+ useListPropertiesQuery(() => ({ scope: 'team', includeOptions: true })),+ settings+ );+}diff --git a/apps/web/src/features/companies/core/crm-export.test.ts b/apps/web/src/features/crm/tests/export.test.tssimilarity index 96%rename from apps/web/src/features/companies/core/crm-export.test.tsrename to apps/web/src/features/crm/tests/export.test.tsindex 4cbff3384f..d543f95bc1 100644--- a/apps/web/src/features/companies/core/crm-export.test.ts+++ b/apps/web/src/features/crm/tests/export.test.ts@@ -1,6 +1,6 @@import { parseCsv } from '@core/util/csv';import { describe, expect, it } from 'vitest';-import { createCrmCsv, personExportRecord } from './crm-export';+import { createCrmCsv, personExportRecord } from '../core/export';describe('CRM CSV export', () => {const columns = [diff --git a/apps/web/src/features/companies/tour.ts b/apps/web/src/features/crm/tour.tssimilarity index 100%rename from apps/web/src/features/companies/tour.tsrename to apps/web/src/features/crm/tour.tsdiff --git a/apps/web/src/features/crm/views/apply-view.ts b/apps/web/src/features/crm/views/apply-view.tsnew file mode 100644index 0000000000..f043e1e8c1--- /dev/null+++ b/apps/web/src/features/crm/views/apply-view.ts@@ -0,0 +1,29 @@+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import type { Query } from '../../next-soup/filters/filter-store';+import { useCrmWorkspace } from '../context/workspace-context';+import { createApplyCrmView } from '../primitives/apply-view';+export function useApplyCrmView() {+ const view = useCrmWorkspace();+ return createApplyCrmView({+ setActiveTab: view.setActiveTab,+ replaceFilters: (filters) =>+ view.queryFilters.replace((filters as Query | undefined) ?? null),+ replacePredicates: view.soup.predicates.set,+ setSearchText: view.setSearchText,+ setGroupBy: view.soup.grouping.setActiveGroupId,+ setSort: (ids) =>+ view.soup.sort.setAll(ids as Parameters<typeof view.soup.sort.setAll>[0]),+ setStageFilter(ids) {+ view.setStageFilter(ids);+ if (ids.length > 0 !== view.soup.predicates.isActive('company-stage'))+ view.soup.predicates.toggle({ and: ['company-stage'] });+ },+ setOwnerFilter(ids) {+ view.setOwnerFilter(ids);+ if (ids.length > 0 !== view.soup.predicates.isActive('company-owner'))+ view.soup.predicates.toggle({ and: ['company-owner'] });+ },+ setViewMode: view.setViewMode,+ defaultMode: () => (isTouchDevice() ? 'list' : 'board'),+ });+}diff --git a/apps/web/src/features/crm/views/companies.tsx b/apps/web/src/features/crm/views/companies.tsxnew file mode 100644index 0000000000..dad7dc10bd--- /dev/null+++ b/apps/web/src/features/crm/views/companies.tsx@@ -0,0 +1,101 @@+import { PillTabs } from '@components/app/mobile/PillTabs';+import { SplitHeaderLeft } from '@components/app/split-layout/components/SplitHeader';+import { ENABLE_UNIFIED_LIST_AI_INPUT } from '@core/constant/featureFlags';+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import { Show, Suspense } from 'solid-js';+import { SoupChatInput } from '../../chat/SoupChatInput';+import { MobileFilterDrawer } from '../../next-soup/soup-view/filters-bar/mobile-filter-drawer';+import { SoupFiltersBar } from '../../next-soup/soup-view/filters-bar/soup-filters-bar';+import { SoupViewList } from '../../next-soup/soup-view/soup-view';+import { MaybeSoupEntityActionDrawerManager } from '../../soup';+import { useCrmWorkspace } from '../context/workspace-context';+import { CompanyKanban } from './company-board';+import { CompanyGroupHeader } from './company-group-header';+import { ResponsiveCompanyListHeader } from './company-list-header';+import { CompanyListEntity } from './company-row';+import { CrmWorkspaceView } from './crm-workspace';+import { CrmEmptyState } from './empty-state';+import { useCrmUnavailable } from './use-crm';++export function Companies() {+ const view = useCrmWorkspace();+ const unavailable = useCrmUnavailable();+ return (+ <CrmWorkspaceView>+ {(options) => (+ <div+ class="size-full flex flex-col @container"+ data-list-view="companies"+ >+ <Show when={isTouchDevice()}>+ <div class="flex flex-col w-full">+ <SplitHeaderLeft>+ <div class="h-full flex gap-3 @max-[380px]/split-header:gap-2 items-center w-full flex-1 min-w-0">+ <PillTabs+ scrollable+ class="-ml-(--mobile-chrome-gutter) w-[100cqw] max-w-none flex-none"+ contentClass="px-(--mobile-chrome-gutter)"+ leading={+ <>+ {options.mobileHeaderLeading}+ <MobileFilterDrawer />+ </>+ }+ items={[+ { value: 'board', label: 'Board' },+ { value: 'list', label: 'List' },+ ]}+ value={view.viewMode()}+ onChange={(value) =>+ view.setViewMode(value as 'list' | 'board')+ }+ />+ </div>+ </SplitHeaderLeft>+ </div>+ <SoupFiltersBar />+ </Show>+ <div class="relative grow min-h-1 flex max-sm:flex-col flex-row size-full">+ <Suspense>+ <Show+ when={view.viewMode() !== 'board'}+ fallback={+ <MaybeSoupEntityActionDrawerManager>+ <CompanyKanban onOpenEntity={options.onOpenEntity} />+ </MaybeSoupEntityActionDrawerManager>+ }+ >+ <SoupViewList+ emptyContent={<CrmEmptyState />}+ onOpenEntity={options.onOpenEntity}+ rowEntry={{ component: CompanyListEntity, family: 'row' }}+ groupHeader={CompanyGroupHeader}+ listHeader={+ <Show when={!isTouchDevice()}>+ <ResponsiveCompanyListHeader class="shrink-0" />+ </Show>+ }+ />+ </Show>+ </Suspense>+ </div>+ <Suspense>+ <Show+ when={+ !isTouchDevice() &&+ ENABLE_UNIFIED_LIST_AI_INPUT &&+ (view.viewMode() !== 'board' || unavailable())+ }+ >+ <div class="absolute bottom-0 inset-x-px pb-2.5 px-2 flex justify-center pointer-events-none">+ <div class="pointer-events-auto w-full min-w-0 max-w-3xl">+ <SoupChatInput />+ </div>+ </div>+ </Show>+ </Suspense>+ </div>+ )}+ </CrmWorkspaceView>+ );+}diff --git a/apps/web/src/features/next-soup/soup-view/views/companies/CompanyKanban.tsx b/apps/web/src/features/crm/views/company-board.tsxsimilarity index 66%rename from apps/web/src/features/next-soup/soup-view/views/companies/CompanyKanban.tsxrename to apps/web/src/features/crm/views/company-board.tsxindex 43966dcf39..79e4f9ebdd 100644--- a/apps/web/src/features/next-soup/soup-view/views/companies/CompanyKanban.tsx+++ b/apps/web/src/features/crm/views/company-board.tsx@@ -2,22 +2,11 @@ import { resolveEntityActionViewContext } from '@app/features/next-soup/actions'import { NO_STAGE } from '@app/features/next-soup/filters/configs/';import { EmptyState } from '@app/features/next-soup/soup-view/empty-states';import { useFilterRefinements } from '@app/features/next-soup/soup-view/filters-bar/use-filter-refinements';-import { useSoupView } from '@app/features/next-soup/soup-view/soup-view-context';-import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';import { SoupEntityContextMenu } from '@app/features/soup';import { DEBUG_SETTING_KEYS, useDebugSetting } from '@app/lib/debugSettings';-import { useDealStages } from '@companies/crm/deal-stages';-import { CrmStageIcon } from '@companies/crm/StageIcon';-import {- useClosedStageIds,- useCrmPermissions,- useCrmUnavailable,-} from '@companies/crm/team-crm-config';-import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { CustomScrollbar } from '@core/component/CustomScrollbar';import { UserIcon } from '@core/component/UserIcon';import {- type CrmCompanyEntity,Entity,type EntityData,formatTimestamp,@@ -25,12 +14,21 @@ import {isCrmCompanyEntity,} from '@entity';import CircleDashed from '@phosphor/circle-dashed.svg';-import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';-import { getSoupEntityById } from '@queries/soup/normalized-cache';-import { EntityType } from '@service-properties/generated/schemas/entityType';import { createElementSize } from '@solid-primitives/resize-observer';import { cn, Layer } from '@ui';-import { createEffect, createMemo, createSignal, For, Show } from 'solid-js';+import { createMemo, createSignal, For, Show } from 'solid-js';+import { CrmStageIcon } from '../components/stage-icon';+import { useCrmContext } from '../context/crm-context';+import { useCrmWorkspace } from '../context/workspace-context';+import { createCompanyBoard } from '../primitives/company-board';+import { CrmEmptyState } from './empty-state';+import {+ useBulkSaveEntityPropertiesMutation,+ useClosedStageIds,+ useCrmPermissions,+ useCrmUnavailable,+ useDealStages,+} from './use-crm';/** Column key for companies without a Stage value. */const NO_STAGE_KEY = '';@@ -42,11 +40,6 @@ const COLUMN_GAP = 12;/** p-3 on each side of the column row. */const BOARD_PADDING_X = 24;-type StageColumn = {- key: string;- label: string;-};-/*** Kanban board for the Customers view: one column per active deal stage* (team-customized set when present, else the seeded system stages) plus@@ -59,49 +52,14 @@ type StageColumn = {export function CompanyKanban(props: {onOpenEntity?: (entity: EntityData) => boolean;}) {- const { source, soup, stageFilter, searchText, activeTab } = useSoupView();- const panel = useSplitPanelOrThrow();+ const { source, soup, stageFilter, searchText, activeTab, host } =+ useCrmWorkspace();const entityActionViewContext = () =>resolveEntityActionViewContext({- activeListView: panel.handle.content().id,+ activeListView: 'companies',activeTab: activeTab(),});- // Stage moves made while the board is fed by search results. Search rows- // bypass the normalized soup cache, so the mutation's optimistic update- // never reaches them — without this overlay a drop wouldn't move the card.- const [stageOverrides, setStageOverrides] = createSignal<- ReadonlyMap<string, string>- >(new Map());-- const setStageOverride = (entityId: string, stageKey: string) => {- setStageOverrides((prev) => new Map(prev).set(entityId, stageKey));- };-- // Drop an override, optionally only when it still points at `stageKey`- // (so a failed save doesn't undo a newer drag of the same card).- const clearStageOverride = (entityId: string, stageKey?: string) => {- setStageOverrides((prev) => {- if (stageKey !== undefined && prev.get(entityId) !== stageKey) {- return prev;- }- if (!prev.has(entityId)) return prev;- const next = new Map(prev);- next.delete(entityId);- return next;- });- };-- const saveMutation = useBulkSaveEntityPropertiesMutation({- onError: (_error, variables) => {- for (const item of variables.properties) {- if (item.apiValues.valueType !== 'SELECT_STRING') continue;- const stageKey = item.apiValues.values?.[0] ?? NO_STAGE_KEY;- clearStageOverride(item.entityId, stageKey);- }- },- });-const { stages, filterStages, stageProperty, resolveStage } = useDealStages();const { canEditCrm, canMoveClosedDeals } = useCrmPermissions();const closedStageIds = useClosedStageIds(stages);@@ -116,66 +74,14 @@ export function CompanyKanban(props: {DEBUG_SETTING_KEYS.FORCE_EMPTY_STATES);- const stageColumns = createMemo((): StageColumn[] => {- // Candidates in canonical pipeline order: the filterable set (active- // stages plus retired legacy stages on the system default), then- // "No stage" — checked columns always render in this fixed order.- const candidates: StageColumn[] = [- ...filterStages().map((stage) => ({ key: stage.id, label: stage.label })),- { key: NO_STAGE_KEY, label: 'No stage' },- ];- // An active stage filter removes the filtered-out columns entirely,- // not just their (already predicate-filtered) cards. With no filter,- // only the active stage set shows (legacy stages are opt-in).- const filter = stageFilter();- if (filter.length === 0) {- const active = new Set(stages().map((stage) => stage.id));- return candidates.filter(- (column) => column.key === NO_STAGE_KEY || active.has(column.key)- );- }- return candidates.filter((column) =>- filter.includes(column.key === NO_STAGE_KEY ? NO_STAGE : column.key)- );- });-// Search results don't carry properties, which would strand every match// in "No stage" (and skip closed-stage drag gating). Backfill from the// normalized soup cache, which still holds the full rows the search is// narrowing.const companies = createMemo(() =>- source- .data()- .filter(isCrmCompanyEntity)- .map((entity) => {- if (entity.properties) return entity;- const cached = getSoupEntityById(entity.id);- return cached?.tag === 'crmCompany'- ? { ...entity, properties: cached.data.properties }- : entity;- })+ source.data().filter(isCrmCompanyEntity).map(useCrmContext().hydrateCompany));- /** The stage column a company renders in: pending drag moves win. */- const effectiveStage = (company: CrmCompanyEntity) =>- stageOverrides().get(company.id) ?? resolveStage(company) ?? NO_STAGE_KEY;-- // Retire overrides the entity's own data has caught up with, so later- // remote stage changes aren't masked by a stale overlay.- createEffect(() => {- const overrides = stageOverrides();- if (overrides.size === 0) return;- for (const company of companies()) {- const override = overrides.get(company.id);- if (- override !== undefined &&- (resolveStage(company) ?? NO_STAGE_KEY) === override- ) {- clearStageOverride(company.id);- }- }- });-// Mirror the list view's empty states: beyond CRM-unavailable, an empty// board ("No customers yet" / no search or filter matches) shows the// panel instead of a row of empty columns. Fetches keep the board@@ -185,27 +91,35 @@ export function CompanyKanban(props: {(!source.isFetching() && companies().length === 0) ||forceEmptyState();- const columns = createMemo(() => {- const buckets = new Map<string, EntityData[]>(- stageColumns().map((column) => [column.key, []])- );- for (const company of companies()) {- const key = effectiveStage(company);- (buckets.get(buckets.has(key) ? key : NO_STAGE_KEY) ?? []).push(company);- }- return stageColumns().map((column) => ({- ...column,- entities: buckets.get(column.key) ?? [],- }));- });-- // A card can be dragged when the user can edit CRM data at all, and its- // current stage is either open or the user may move closed deals.- const canDragFrom = (stageKey: string) =>- canEditCrm() &&- (stageKey === NO_STAGE_KEY ||- !closedStageIds().has(stageKey) ||- canMoveClosedDeals());+ const saveMutation = useBulkSaveEntityPropertiesMutation();+ const { columns, stageColumns, canDragFrom, moveToStage } =+ createCompanyBoard<import('@entity').CrmCompanyEntity>({+ companies,+ stages,+ filterStages,+ selectedStages: stageFilter,+ noStageFilter: NO_STAGE,+ resolveStage,+ canEdit: canEditCrm,+ canMoveClosed: canMoveClosedDeals,+ closedStages: closedStageIds,+ saveStage: (entityId, stageKey, onError) =>+ void saveMutation+ .mutateAsync({+ properties: [+ {+ entityId,+ entityType: 'COMPANY',+ property: stageProperty(),+ apiValues: {+ valueType: 'SELECT_STRING',+ values: stageKey === NO_STAGE_KEY ? null : [stageKey],+ },+ },+ ],+ })+ .catch(onError),+ });const [draggedId, setDraggedId] = createSignal<string>();const [dropTarget, setDropTarget] = createSignal<string>();@@ -232,27 +146,6 @@ export function CompanyKanban(props: {return Math.floor((usable - (fit - 1) * COLUMN_GAP) / fit);});- const moveToStage = (entityId: string, stageKey: string) => {- const entity = companies().find((company) => company.id === entityId);- if (!entity) return;- if (effectiveStage(entity) === stageKey) return;-- setStageOverride(entityId, stageKey);- saveMutation.mutate({- properties: [- {- entityId,- entityType: EntityType.COMPANY,- property: stageProperty(),- apiValues: {- valueType: 'SELECT_STRING',- values: stageKey === NO_STAGE_KEY ? null : [stageKey],- },- },- ],- });- };-const openCompany = (entity: EntityData, event: MouseEvent) => {if (!event.metaKey &&@@ -264,11 +157,7 @@ export function CompanyKanban(props: {return;soup.focus.set(entity.id);- void openEntityInSplitFromUnifiedList(entity, {- openInNewSplit: event.shiftKey,- splitHandle: panel.handle,- referredFrom: 'companies',- });+ host.openCompany(entity, event.shiftKey);};return (@@ -276,7 +165,7 @@ export function CompanyKanban(props: {when={!showEmptyState()}fallback={<EmptyState- listView="companies"+ content={<CrmEmptyState />}search={!!searchText()}hasRefinementsFromBase={hasActiveRefinements()}hasHiddenItems={hasHiddenItems()}diff --git a/apps/web/src/features/companies/Company/CompanyContactsSection.tsx b/apps/web/src/features/crm/views/company-contacts-section.tsxsimilarity index 94%rename from apps/web/src/features/companies/Company/CompanyContactsSection.tsxrename to apps/web/src/features/crm/views/company-contacts-section.tsxindex 0774c99eeb..61f3c52773 100644--- a/apps/web/src/features/companies/Company/CompanyContactsSection.tsx+++ b/apps/web/src/features/crm/views/company-contacts-section.tsx@@ -1,7 +1,7 @@-import { useSplitLayout } from '@components/app/split-layout/layout';import type { CrmCompanyEntity } from '@entity';-import type { CompanyContact } from '@queries/crm/companies';import { createMemo, createSignal, For, Show } from 'solid-js';+import { useCrmContext } from '../context/crm-context';+import type { CrmContact as CompanyContact } from '../core/contact';export function CompanyContactsSection(props: {company?: CrmCompanyEntity;@@ -9,7 +9,7 @@ export function CompanyContactsSection(props: {onOpenContact?: (contact: CompanyContact) => void;}) {const contacts = () => props.contacts ?? [];- const { openWithSplit } = useSplitLayout();+ const { openWithSplit } = useCrmContext().createNavigation();const [search, setSearch] = createSignal('');const filtered = createMemo(() => {diff --git a/apps/web/src/features/companies/Company/Company.tsx b/apps/web/src/features/crm/views/company-detail.tsxsimilarity index 76%rename from apps/web/src/features/companies/Company/Company.tsxrename to apps/web/src/features/crm/views/company-detail.tsxindex 0e23258348..8d5ae4655d 100644--- a/apps/web/src/features/companies/Company/Company.tsx+++ b/apps/web/src/features/crm/views/company-detail.tsx@@ -1,19 +1,18 @@-import { openCreateContactModal } from '@app/features/companies/CreateContactModal';-import { useFeatureFlag } from '@app/lib/analytics/posthog';import { SidePanel } from '@components/app/side-panel';-import { enableCrmLists } from '@core/constant/featureFlags';import PlusIcon from '@phosphor/plus.svg';-import { type CompanyContact, useCompanyQuery } from '@queries/crm/companies';import { Button } from '@ui';import { Show, Suspense } from 'solid-js';-import { CompanyListsSection } from '../views/CompanyListsSection';-import { CompanyContactsSection } from './CompanyContactsSection';-import { CompanyDiscussionSection } from './CompanyDiscussionSection';-import { CompanyEmailsSection } from './CompanyEmailsSection';-import { CompanyHeader } from './CompanyHeader';-import { CompanyMetadataSection } from './CompanyMetadataSection';-import { CompanyPropertiesSection } from './CompanyPropertiesSection';-import { CompanySharingSection } from './CompanySharingSection';+import { useCrmContext } from '../context/crm-context';+import type { CrmContact as CompanyContact } from '../core/contact';+import { CompanyContactsSection } from './company-contacts-section';+import { CompanyDiscussionSection } from './company-discussion-section';+import { CompanyEmailsSection } from './company-emails-section';+import { CompanyHeader } from './company-header';+import { CompanyListsSection } from './company-list-membership';+import { CompanyMetadataSection } from './company-metadata-section';+import { CompanyPropertiesSection } from './company-properties-section';+import { CompanySharingSection } from './company-sharing-section';+import { useCompanyQuery } from './use-crm';/*** Root of the company detail view. Owns the company query and pushes the@@ -27,7 +26,8 @@ export function Company(props: {onHidden?: () => void;onOpenContact?: (contact: CompanyContact) => void;}) {- const listsFlag = useFeatureFlag(enableCrmLists);+ const openCreateContactModal = useCrmContext().openCreateContact;+ const listsEnabled = useCrmContext().listsEnabled();const { company, contacts } = useCompanyQuery(() => props.companyId);return (@@ -56,7 +56,7 @@ export function Company(props: {><CompanyPropertiesSection companyId={props.companyId} /></SidePanel.Section>- <Show when={listsFlag().enabled}>+ <Show when={listsEnabled()}><Suspense><CompanyListsSection companyId={props.companyId} /></Suspense>diff --git a/apps/web/src/features/companies/Company/CompanyDiscussionSection.tsx b/apps/web/src/features/crm/views/company-discussion-section.tsxsimilarity index 88%rename from apps/web/src/features/companies/Company/CompanyDiscussionSection.tsxrename to apps/web/src/features/crm/views/company-discussion-section.tsxindex 67aa85fb6c..90dc2a939d 100644--- a/apps/web/src/features/companies/Company/CompanyDiscussionSection.tsx+++ b/apps/web/src/features/crm/views/company-discussion-section.tsx@@ -1,5 +1,5 @@-import { useUserId } from '@core/context/user';import { EntityDiscussion } from '@core/messages/EntityDiscussion';+import { useCrmUserId as useUserId } from './use-crm';/** Discussion on a CRM company, on the shared message components. */export function CompanyDiscussionSection(props: { companyId: string }) {diff --git a/apps/web/src/features/companies/Company/CompanyEmailsSection.tsx b/apps/web/src/features/crm/views/company-emails-section.tsxsimilarity index 89%rename from apps/web/src/features/companies/Company/CompanyEmailsSection.tsxrename to apps/web/src/features/crm/views/company-emails-section.tsxindex c6ac99c836..cc29827cdf 100644--- a/apps/web/src/features/companies/Company/CompanyEmailsSection.tsx+++ b/apps/web/src/features/crm/views/company-emails-section.tsx@@ -1,4 +1,3 @@-import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';import { TabsInset } from '@core/component/TabsInset';import {type CrmCompanyEntity,@@ -7,14 +6,16 @@ import {ListLayoutProvider,} from '@entity';import { createMemo, createSignal, For, Show } from 'solid-js';-import {- type EmailSignalView,- type EmailView,- useCompanyEmailsQuery,-} from './use-company-emails-query';-import { useInfiniteScrollSentinel } from './use-infinite-scroll-sentinel';+import { useInfiniteScrollSentinel } from '../../../lib/primitives/infinite-scroll-sentinel';+import { useCrmContext } from '../context/crm-context';+import type {+ CrmEmailSignal as EmailSignalView,+ CrmEmailScope as EmailView,+} from '../context/crm-sources';+import { useCompanyEmailsQuery } from './use-crm';export function CompanyEmailsSection(props: { company?: CrmCompanyEntity }) {+ const { openEmail } = useCrmContext().createNavigation();const domains = createMemo(() => props.company?.domains.map((domain) => domain.domain) ?? []);@@ -88,9 +89,7 @@ export function CompanyEmailsSection(props: { company?: CrmCompanyEntity }) {<ListEntityentity={entity}timestamp={entity.updatedAt}- onClick={() =>- openEntityInSplitFromUnifiedList(entity, {})- }+ onClick={() => openEmail(entity)}/>)}</For>diff --git a/apps/web/src/features/next-soup/soup-view/views/companies/company-grid-layout.tsx b/apps/web/src/features/crm/views/company-grid-layout.tsxsimilarity index 93%rename from apps/web/src/features/next-soup/soup-view/views/companies/company-grid-layout.tsxrename to apps/web/src/features/crm/views/company-grid-layout.tsxindex 23069c3106..5c0797e4cc 100644--- a/apps/web/src/features/next-soup/soup-view/views/companies/company-grid-layout.tsx+++ b/apps/web/src/features/crm/views/company-grid-layout.tsx@@ -1,6 +1,3 @@-import { useDealStages } from '@companies/crm/deal-stages';-import { useCrmDisplayOptions } from '@companies/crm/display-options';-import { useCrmPermissions } from '@companies/crm/team-crm-config';import {Entity,type EntityData,@@ -20,16 +17,20 @@ import {type PropertySaveHandler,} from '@property/context/PropertiesContext';import type { Property, PropertyApiValues } from '@property/types';-import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';-import { EntityType } from '@service-properties/generated/schemas/entityType';import { cn } from '@ui/utils/classname';import { createMemo, For, Show, Suspense } from 'solid-js';-import { ListPropertyValue } from '../tasks/list-property-value';+import { ListPropertyValue } from '../../next-soup/soup-view/views/tasks/list-property-value';import {COMPANY_GRID_COLUMNS,companyGridTemplateAreas,companyGridTemplateColumns,-} from './company-grid-template';+} from '../components/company-grid-template';+import {+ useBulkSaveEntityPropertiesMutation,+ useCrmDisplayOptions,+ useCrmPermissions,+ useDealStages,+} from './use-crm';/*** Grid row layout for the Customers list: company name + editable CRM@@ -111,7 +112,7 @@ export function CompanyGridLayout(props: LayoutProps) {properties: [{entityId: props.entity.id,- entityType: EntityType.COMPANY,+ entityType: 'COMPANY',property,apiValues,},@@ -126,7 +127,7 @@ export function CompanyGridLayout(props: LayoutProps) {return (<PropertiesProvider- entityType={EntityType.COMPANY}+ entityType={'COMPANY'}canEdit={canEditCrm()}properties={properties}onRefresh={() => {}}diff --git a/apps/web/src/features/crm/views/company-group-header.tsx b/apps/web/src/features/crm/views/company-group-header.tsxnew file mode 100644index 0000000000..a9df3e2e18--- /dev/null+++ b/apps/web/src/features/crm/views/company-group-header.tsx@@ -0,0 +1,32 @@+import { Show } from 'solid-js';+import type { GroupHeaderProps } from '../../next-soup/create-soup-state';+import { DefaultGroupHeader } from '../../next-soup/soup-view/soup-view';+import { CrmStageIcon } from '../components/stage-icon';+import { useDealStages } from './use-crm';+export function CompanyGroupHeader(props: GroupHeaderProps) {+ const stages = useDealStages();+ const optionId = () => {+ const value = props.group.value ?? props.group.key;+ return typeof value === 'string' && value ? value : undefined;+ };+ const index = (id: string) => {+ const i = stages.stages().findIndex((stage) => stage.id === id);+ return i === -1 ? undefined : i;+ };+ return (+ <DefaultGroupHeader+ {...props}+ icon={+ <Show when={optionId()}>+ {(id) => (+ <CrmStageIcon+ optionId={id()}+ index={index(id())}+ class="size-3.5"+ />+ )}+ </Show>+ }+ />+ );+}diff --git a/apps/web/src/features/companies/Company/CompanyHeader.tsx b/apps/web/src/features/crm/views/company-header.tsxsimilarity index 97%rename from apps/web/src/features/companies/Company/CompanyHeader.tsxrename to apps/web/src/features/crm/views/company-header.tsxindex 1a31e26473..9908995ab5 100644--- a/apps/web/src/features/companies/Company/CompanyHeader.tsx+++ b/apps/web/src/features/crm/views/company-header.tsx@@ -1,8 +1,8 @@import { EntityIcon } from '@core/component/EntityIcon';import { InlineTitleEditor } from '@core/component/InlineTitleEditor';import type { CrmCompanyEntity } from '@entity';-import { useSetCompanyNameMutation } from '@queries/crm/companies';import { createEffect, createSignal, Show } from 'solid-js';+import { useSetCompanyNameMutation } from './use-crm';function Description(props: { text: string }) {const [expanded, setExpanded] = createSignal(false);diff --git a/apps/web/src/features/next-soup/soup-view/views/companies/CompanyListHeader.tsx b/apps/web/src/features/crm/views/company-list-header.tsxsimilarity index 93%rename from apps/web/src/features/next-soup/soup-view/views/companies/CompanyListHeader.tsxrename to apps/web/src/features/crm/views/company-list-header.tsxindex 99e7e6fd89..eb0abd2f74 100644--- a/apps/web/src/features/next-soup/soup-view/views/companies/CompanyListHeader.tsx+++ b/apps/web/src/features/crm/views/company-list-header.tsx@@ -1,16 +1,16 @@import type { SystemSortOption } from '@app/features/next-soup/soup-view/sort-options';-import { useSoupView } from '@app/features/next-soup/soup-view/soup-view-context';-import { useCrmDisplayOptions } from '@companies/crm/display-options';import { useListLayout } from '@entity/composed/list-entity/shared';import ArrowDownIcon from '@phosphor/arrow-down.svg';import { cn } from '@ui/utils/classname';import { createMemo, For, Show } from 'solid-js';-import '../tasks/list-property-value.css';+import { useCrmWorkspace } from '../context/workspace-context';+import { useCrmDisplayOptions } from './use-crm';+import '../../next-soup/soup-view/views/tasks/list-property-value.css';import {COMPANY_GRID_COLUMNS,companyGridTemplateAreas,companyGridTemplateColumns,-} from './company-grid-template';+} from '../components/company-grid-template';/*** Responsive wrapper that only shows the header when layout is wide.@@ -34,7 +34,7 @@ export function ResponsiveCompanyListHeader(props: { class?: string }) {* `updated_at`, which carries `crm_companies.last_interaction`).*/function CompanyListHeader(props: { class?: string }) {- const { soup } = useSoupView();+ const { soup } = useCrmWorkspace();const displayOptions = useCrmDisplayOptions();// Mirror the row grid: hidden display-option columns collapse here too sodiff --git a/apps/web/src/features/companies/views/CompanyListsSection.tsx b/apps/web/src/features/crm/views/company-list-membership.tsxsimilarity index 98%rename from apps/web/src/features/companies/views/CompanyListsSection.tsxrename to apps/web/src/features/crm/views/company-list-membership.tsxindex c3c6a3775e..c0700206ac 100644--- a/apps/web/src/features/companies/views/CompanyListsSection.tsx+++ b/apps/web/src/features/crm/views/company-list-membership.tsx@@ -1,9 +1,8 @@import { SidePanel } from '@components/app/side-panel';import ListIcon from '@phosphor/list-bullets.svg';-import { useCrmLists } from '@queries/crm/lists';-import { useCurrentTeamQuery } from '@queries/team/teams';import { Button } from '@ui';import { createSignal, For, Show } from 'solid-js';+import { useCrmLists, useCurrentTeamQuery } from './use-crm';export function CompanyListsSection(props: { companyId: string }) {const team = useCurrentTeamQuery();diff --git a/apps/web/src/features/companies/Company/CompanyMetadataSection.tsx b/apps/web/src/features/crm/views/company-metadata-section.tsxsimilarity index 100%rename from apps/web/src/features/companies/Company/CompanyMetadataSection.tsxrename to apps/web/src/features/crm/views/company-metadata-section.tsxdiff --git a/apps/web/src/features/companies/Company/CompanyPropertiesSection.tsx b/apps/web/src/features/crm/views/company-properties-section.tsxsimilarity index 93%rename from apps/web/src/features/companies/Company/CompanyPropertiesSection.tsxrename to apps/web/src/features/crm/views/company-properties-section.tsxindex 4e8f0680a7..9c155be702 100644--- a/apps/web/src/features/companies/Company/CompanyPropertiesSection.tsx+++ b/apps/web/src/features/crm/views/company-properties-section.tsx@@ -1,8 +1,7 @@import { EntityPropertiesSection } from '@app/features/property/side-panel/properties/EntityPropertiesSection';-import { useDealStages } from '@companies/crm/deal-stages';-import { useCrmPermissions } from '@companies/crm/team-crm-config';import { buildCompanyDefaultProperties } from '@entity/extractors-property';import { SYSTEM_PROPERTY_IDS } from '@property/constants';+import { useCrmPermissions, useDealStages } from './use-crm';/*** CRM properties for a company (Stage / Owner / Revenue + custom),diff --git a/apps/web/src/features/next-soup/soup-view/views/companies/CompanyListEntity.tsx b/apps/web/src/features/crm/views/company-row.tsxsimilarity index 97%rename from apps/web/src/features/next-soup/soup-view/views/companies/CompanyListEntity.tsxrename to apps/web/src/features/crm/views/company-row.tsxindex f3f8b83bed..429778726b 100644--- a/apps/web/src/features/next-soup/soup-view/views/companies/CompanyListEntity.tsx+++ b/apps/web/src/features/crm/views/company-row.tsx@@ -3,7 +3,6 @@ import {SwipableRow,SwipableRowContext,} from '@components/app/mobile/SwipableRow';-import { useSplitPanel } from '@components/app/split-layout/layoutUtils';import { isMobile } from '@core/mobile/isMobile';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { createEntityDraggable, Entity, unreadFilterFn } from '@entity';@@ -18,6 +17,7 @@ import type { EntityRowConfig } from '@entity/extractors-notification';import { mergeRefs } from '@solid-primitives/refs';import { cn } from '@ui/utils/classname';import { type JSX, Match, Show, Switch, useContext } from 'solid-js';+import { useCrmContext } from '../context/crm-context';import { CompanyGridLayout } from './company-grid-layout';function MaybeEntityRow(props: {@@ -66,7 +66,7 @@ export function CompanyListEntity(props: BaseListEntityProps) {const draggable = createEntityDraggable({entity: props.entity,- splitId: useSplitPanel()?.handle?.id,+ splitId: useCrmContext().createNavigation().splitId,deferUntilInteraction: () => props.deferInteractions === true,});diff --git a/apps/web/src/features/companies/Company/CompanySharingSection.tsx b/apps/web/src/features/crm/views/company-sharing-section.tsxsimilarity index 94%rename from apps/web/src/features/companies/Company/CompanySharingSection.tsxrename to apps/web/src/features/crm/views/company-sharing-section.tsxindex 0078b6f3f1..a070d4cf5a 100644--- a/apps/web/src/features/companies/Company/CompanySharingSection.tsx+++ b/apps/web/src/features/crm/views/company-sharing-section.tsx@@ -1,13 +1,13 @@-import { useSplitLayout } from '@components/app/split-layout/layout';import { toast } from '@core/component/Toast/Toast';import type { CrmCompanyEntity } from '@entity';+import { cn, InlineCheckbox } from '@ui';+import { Show } from 'solid-js';+import { useCrmContext } from '../context/crm-context';import {+ useIsTeamAdmin,useSetCompanyHiddenMutation,useSetEmailSyncMutation,-} from '@queries/crm/companies';-import { useIsTeamAdmin } from '@queries/team/teams';-import { cn, InlineCheckbox } from '@ui';-import { Show } from 'solid-js';+} from './use-crm';const TOGGLE_BUTTON_CLASS ='inline-flex items-center gap-2 rounded-md h-7 px-2.5 text-xs select-none w-fit border border-ink-muted/[0.08] bg-ink-muted/[0.025] text-ink hover:bg-ink-muted/[0.06]';@@ -18,7 +18,7 @@ export function CompanySharingSection(props: {}) {const hideMutation = useSetCompanyHiddenMutation();const emailSyncMutation = useSetEmailSyncMutation();- const { replaceOrInsertSplit } = useSplitLayout();+ const { showCompanies } = useCrmContext().createNavigation();const isTeamAdmin = useIsTeamAdmin();const handleToggleShare = async (@@ -36,7 +36,7 @@ export function CompanySharingSection(props: {if (willHide) {toast.success('Company hidden.');if (props.onHidden) props.onHidden();- else replaceOrInsertSplit({ type: 'component', id: 'companies' });+ else showCompanies();}} catch (error) {console.error('failed to update company sharing', error);diff --git a/apps/web/src/features/contacts/Contact/Contact.tsx b/apps/web/src/features/crm/views/contact-detail.tsxsimilarity index 81%rename from apps/web/src/features/contacts/Contact/Contact.tsxrename to apps/web/src/features/crm/views/contact-detail.tsxindex b20b75eab7..e87426d5d6 100644--- a/apps/web/src/features/contacts/Contact/Contact.tsx+++ b/apps/web/src/features/crm/views/contact-detail.tsx@@ -1,12 +1,11 @@import { SidePanel } from '@components/app/side-panel';-import { useContactQuery } from '@queries/crm/contacts';-import { useIsTeamAdmin } from '@queries/team/teams';import { Show } from 'solid-js';-import { ContactDiscussionSection } from './ContactDiscussionSection';-import { ContactEmailsSection } from './ContactEmailsSection';-import { ContactHeader } from './ContactHeader';-import { ContactMetadataSection } from './ContactMetadataSection';-import { ContactSharingSection } from './ContactSharingSection';+import { ContactDiscussionSection } from './contact-discussion-section';+import { ContactEmailsSection } from './contact-emails-section';+import { ContactHeader } from './contact-header';+import { ContactMetadataSection } from './contact-metadata-section';+import { ContactSharingSection } from './contact-sharing-section';+import { useContactQuery, useIsTeamAdmin } from './use-crm';/*** Root of the contact detail view. Owns the contact query and pushes thediff --git a/apps/web/src/features/contacts/Contact/ContactDiscussionSection.tsx b/apps/web/src/features/crm/views/contact-discussion-section.tsxsimilarity index 88%rename from apps/web/src/features/contacts/Contact/ContactDiscussionSection.tsxrename to apps/web/src/features/crm/views/contact-discussion-section.tsxindex 83d3cee6fd..cb5d82c796 100644--- a/apps/web/src/features/contacts/Contact/ContactDiscussionSection.tsx+++ b/apps/web/src/features/crm/views/contact-discussion-section.tsx@@ -1,5 +1,5 @@-import { useUserId } from '@core/context/user';import { EntityDiscussion } from '@core/messages/EntityDiscussion';+import { useCrmUserId as useUserId } from './use-crm';/** Discussion on a CRM contact, on the shared message components. */export function ContactDiscussionSection(props: { contactId: string }) {diff --git a/apps/web/src/features/contacts/Contact/ContactEmailsSection.tsx b/apps/web/src/features/crm/views/contact-emails-section.tsxsimilarity index 86%rename from apps/web/src/features/contacts/Contact/ContactEmailsSection.tsxrename to apps/web/src/features/crm/views/contact-emails-section.tsxindex cff613ad24..20768cd5eb 100644--- a/apps/web/src/features/contacts/Contact/ContactEmailsSection.tsx+++ b/apps/web/src/features/crm/views/contact-emails-section.tsx@@ -1,20 +1,21 @@-import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';-import { useInfiniteScrollSentinel } from '@companies/Company/use-infinite-scroll-sentinel';import { TabsInset } from '@core/component/TabsInset';import {ListEntity,ListEntityMetadataQueryProvider,ListLayoutProvider,} from '@entity';-import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';import { createSignal, For, Show } from 'solid-js';-import {- type EmailSignalView,- type EmailView,- useContactEmailsQuery,-} from './use-contact-emails-query';+import { useInfiniteScrollSentinel } from '../../../lib/primitives/infinite-scroll-sentinel';+import { useCrmContext } from '../context/crm-context';+import type {+ CrmEmailSignal as EmailSignalView,+ CrmEmailScope as EmailView,+} from '../context/crm-sources';+import type { CrmContact as CrmContactResponse } from '../core/contact';+import { useContactEmailsQuery } from './use-crm';export function ContactEmailsSection(props: { contact?: CrmContactResponse }) {+ const { openEmail } = useCrmContext().createNavigation();const email = () => props.contact?.email;const [view, setView] = createSignal<EmailView>('team');const [signalView, setSignalView] = createSignal<EmailSignalView>('all');@@ -77,9 +78,7 @@ export function ContactEmailsSection(props: { contact?: CrmContactResponse }) {<ListEntityentity={entity}timestamp={entity.updatedAt}- onClick={() =>- openEntityInSplitFromUnifiedList(entity, {})- }+ onClick={() => openEmail(entity)}/>)}</For>diff --git a/apps/web/src/features/contacts/Contact/ContactHeader.tsx b/apps/web/src/features/crm/views/contact-header.tsxsimilarity index 90%rename from apps/web/src/features/contacts/Contact/ContactHeader.tsxrename to apps/web/src/features/crm/views/contact-header.tsxindex 56add29fe4..fcd38d629f 100644--- a/apps/web/src/features/contacts/Contact/ContactHeader.tsx+++ b/apps/web/src/features/crm/views/contact-header.tsx@@ -1,10 +1,10 @@import { InlineTitleEditor } from '@core/component/InlineTitleEditor';-import { getInitialsFromName } from '@core/user';import ContactIcon from '@phosphor/address-book.svg';-import { useSetContactNameMutation } from '@queries/crm/contacts';-import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';import { Avatar } from '@ui';import { Show } from 'solid-js';+import { useCrmContext } from '../context/crm-context';+import type { CrmContact as CrmContactResponse } from '../core/contact';+import { useSetContactNameMutation } from './use-crm';// Renames overwrite `crm_contacts.name`, which is already team-scoped —// no global directory involved (unlike company renames).@@ -29,6 +29,7 @@ function TitleEditor(props: { contact: CrmContactResponse }) {}export function ContactHeader(props: { contact?: CrmContactResponse }) {+ const { contactInitials: getInitialsFromName } = useCrmContext();const showSubtitle = () =>props.contact?.name != null && props.contact.name !== props.contact.email;diff --git a/apps/web/src/features/contacts/Contact/ContactMetadataSection.tsx b/apps/web/src/features/crm/views/contact-metadata-section.tsxsimilarity index 86%rename from apps/web/src/features/contacts/Contact/ContactMetadataSection.tsxrename to apps/web/src/features/crm/views/contact-metadata-section.tsxindex c73753e308..1d378d9b69 100644--- a/apps/web/src/features/contacts/Contact/ContactMetadataSection.tsx+++ b/apps/web/src/features/crm/views/contact-metadata-section.tsx@@ -1,8 +1,9 @@import { NIL_UUID } from '@app/features/next-soup/filters/filter-store';-import { useSplitLayout } from '@components/app/split-layout/layout';-import { useCompanyQuery } from '@queries/crm/companies';-import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';import { type JSX, Show } from 'solid-js';+import { useCrmContext } from '../context/crm-context';++import type { CrmContact as CrmContactResponse } from '../core/contact';+import { useCompanyQuery } from './use-crm';function Field(props: { label: string; children: JSX.Element }) {return (@@ -17,7 +18,7 @@ export function ContactMetadataSection(props: {contact?: CrmContactResponse;onOpenCompany?: (companyId: string) => boolean;}) {- const { openWithSplit } = useSplitLayout();+ const { openWithSplit } = useCrmContext().createNavigation();// NIL while the contact is loading — useCompanyQuery's `enabled` gate// excludes it, so no doomed 404 fires before the real companyId arrives.const { company } = useCompanyQuery(diff --git a/apps/web/src/features/contacts/Contact/ContactSharingSection.tsx b/apps/web/src/features/crm/views/contact-sharing-section.tsxsimilarity index 92%rename from apps/web/src/features/contacts/Contact/ContactSharingSection.tsxrename to apps/web/src/features/crm/views/contact-sharing-section.tsxindex b980c137e5..0b9d44dd62 100644--- a/apps/web/src/features/contacts/Contact/ContactSharingSection.tsx+++ b/apps/web/src/features/crm/views/contact-sharing-section.tsx@@ -1,8 +1,8 @@import { toast } from '@core/component/Toast/Toast';-import { useSetContactHiddenMutation } from '@queries/crm/contacts';-import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';import { cn, InlineCheckbox } from '@ui';import { Show } from 'solid-js';+import type { CrmContact as CrmContactResponse } from '../core/contact';+import { useSetContactHiddenMutation } from './use-crm';const TOGGLE_BUTTON_CLASS ='inline-flex items-center gap-2 rounded-md h-7 px-2.5 text-xs select-none w-fit border border-ink-muted/[0.08] bg-ink-muted/[0.025] text-ink hover:bg-ink-muted/[0.06]';diff --git a/apps/web/src/features/companies/components/CrmCopyLinkButton.tsx b/apps/web/src/features/crm/views/copy-link-button.tsxsimilarity index 54%rename from apps/web/src/features/companies/components/CrmCopyLinkButton.tsxrename to apps/web/src/features/crm/views/copy-link-button.tsxindex a8492d9731..094550c90a 100644--- a/apps/web/src/features/companies/components/CrmCopyLinkButton.tsx+++ b/apps/web/src/features/crm/views/copy-link-button.tsx@@ -1,22 +1,13 @@-import { toast } from '@core/component/Toast/Toast';-import { buildSimpleEntityUrl } from '@core/util/url';import LinkIcon from '@phosphor/link.svg';import { Button } from '@ui';+import { useCrmContext } from '../context/crm-context';export function CrmCopyLinkButton(props: {id: string;type: 'company' | 'contact';}) {- const copyLink = async () => {- try {- await navigator.clipboard.writeText(- buildSimpleEntityUrl({ id: props.id, type: props.type })- );- toast.success('Link copied to clipboard');- } catch {- toast.failure('Could not copy link. Please try again.');- }- };+ const { copyRecordLink } = useCrmContext();+ const copyLink = () => copyRecordLink({ type: props.type, id: props.id });return (<Buttondiff --git a/apps/web/src/features/companies/CreateCompanyModal.tsx b/apps/web/src/features/crm/views/create-company.tsxsimilarity index 89%rename from apps/web/src/features/companies/CreateCompanyModal.tsxrename to apps/web/src/features/crm/views/create-company.tsxindex 2eec3d8a6f..fb2cca27f5 100644--- a/apps/web/src/features/companies/CreateCompanyModal.tsx+++ b/apps/web/src/features/crm/views/create-company.tsx@@ -1,20 +1,10 @@-import { useSplitLayout } from '@components/app/split-layout/layout';import { isMobile } from '@core/mobile/isMobile';-import { useFocusLock } from '@core/util/createControlledOpenSignal';import { ThrownResultError } from '@core/util/result';import BuildingsIcon from '@phosphor/buildings.svg';import XIcon from '@phosphor/x.svg';-import { useCreateCompanyMutation } from '@queries/crm/companies';import { Button, Dialog, Panel } from '@ui';import { createMemo, createSignal, Show } from 'solid-js';--const [createCompanyModalOpen, setCreateCompanyModalOpen] = createSignal(false);-const createCompanyModalFocusLock = useFocusLock('create-company');--export function openCreateCompanyModal() {- createCompanyModalFocusLock.acquire();- setCreateCompanyModalOpen(true);-}+import { useCreateCompanyMutation } from './use-crm';// Light client-side check for a bare domain like "acme.com"; the server// enforces the real rules (no scheme/path/@, not a generic email provider).@@ -32,8 +22,11 @@ function createErrorMessage(cause: unknown): string {return 'Failed to create company. Try again.';}-export function CreateCompanyModal() {- const { replaceOrInsertSplit } = useSplitLayout();+export function CreateCompanyModal(props: {+ open: boolean;+ onClose(): void;+ onCreated(id: string): void;+}) {const createCompanyMutation = useCreateCompanyMutation();const [name, setName] = createSignal('');const [domain, setDomain] = createSignal('');@@ -54,9 +47,8 @@ export function CreateCompanyModal() {}function resetAndClose() {- createCompanyModalFocusLock.release();reset();- setCreateCompanyModalOpen(false);+ props.onClose();}function close() {@@ -82,7 +74,7 @@ export function CreateCompanyModal() {domain: companyDomain(),});resetAndClose();- replaceOrInsertSplit({ type: 'company', id });+ props.onCreated(id);} catch (cause) {console.error('Failed to create company', cause);setError(createErrorMessage(cause));@@ -91,7 +83,7 @@ export function CreateCompanyModal() {return (<Dialog- open={createCompanyModalOpen()}+ open={props.open}onOpenChange={(open) => !open && close()}class="w-120">diff --git a/apps/web/src/features/companies/CreateContactModal.tsx b/apps/web/src/features/crm/views/create-contact.tsxsimilarity index 83%rename from apps/web/src/features/companies/CreateContactModal.tsxrename to apps/web/src/features/crm/views/create-contact.tsxindex 68c7a96524..63a873e753 100644--- a/apps/web/src/features/companies/CreateContactModal.tsx+++ b/apps/web/src/features/crm/views/create-contact.tsx@@ -1,28 +1,9 @@-import { useSplitLayout } from '@components/app/split-layout/layout';-import { useFocusLock } from '@core/util/createControlledOpenSignal';import { ThrownResultError } from '@core/util/result';import UserPlusIcon from '@phosphor/user-plus.svg';import XIcon from '@phosphor/x.svg';-import { useCreateContactMutation } from '@queries/crm/companies';import { Button, Dialog, Panel } from '@ui';import { createMemo, createSignal, Show } from 'solid-js';--// The company (and its domain, which fixes the email suffix) the modal-// creates a contact under; undefined = closed.-const [createContactTarget, setCreateContactTarget] = createSignal<- { companyId: string; domain: string } | undefined->();-const createContactModalFocusLock = useFocusLock('create-contact');--/**- * `domain` is the company domain contact emails are pinned to — the- * modal renders it as a fixed "@domain" suffix and the backend rejects- * any other domain.- */-export function openCreateContactModal(companyId: string, domain: string) {- createContactModalFocusLock.acquire();- setCreateContactTarget({ companyId, domain });-}+import { useCreateContactMutation } from './use-crm';// The part before the @: non-empty, no whitespace or a second @.const LOCAL_PART_PATTERN = /^[^\s@]+$/;@@ -39,8 +20,11 @@ function createErrorMessage(cause: unknown): string {return 'Failed to create contact. Try again.';}-export function CreateContactModal() {- const { replaceOrInsertSplit } = useSplitLayout();+export function CreateContactModal(props: {+ target?: { companyId: string; domain: string };+ onClose(): void;+ onCreated(id: string): void;+}) {const createContactMutation = useCreateContactMutation();const [name, setName] = createSignal('');const [localPart, setLocalPart] = createSignal('');@@ -61,9 +45,8 @@ export function CreateContactModal() {}function resetAndClose() {- createContactModalFocusLock.release();reset();- setCreateContactTarget(undefined);+ props.onClose();}function close() {@@ -74,7 +57,7 @@ export function CreateContactModal() {// Pasting a full address is common — strip our fixed suffix so// "[email protected]" collapses to "jane" instead of failing validation.function handleLocalPartInput(value: string) {- const domain = createContactTarget()?.domain;+ const domain = props.target?.domain;const suffix = domain ? `@${domain}` : undefined;setLocalPart(suffix && value.toLowerCase().endsWith(suffix)@@ -86,7 +69,7 @@ export function CreateContactModal() {async function handleSubmit(event: SubmitEvent) {event.preventDefault();- const target = createContactTarget();+ const target = props.target;if (!target) return;if (!contactName()) {setError('Enter a name');@@ -105,7 +88,7 @@ export function CreateContactModal() {email: `${emailLocalPart()}@${target.domain}`,});resetAndClose();- replaceOrInsertSplit({ type: 'contact', id });+ props.onCreated(id);} catch (cause) {console.error('Failed to create contact', cause);setError(createErrorMessage(cause));@@ -114,7 +97,7 @@ export function CreateContactModal() {return (<Dialog- open={createContactTarget() !== undefined}+ open={props.target !== undefined}onOpenChange={(open) => !open && close()}class="w-120">@@ -185,7 +168,7 @@ export function CreateContactModal() {class="h-full min-w-0 flex-1 border-none bg-transparent pl-3 text-sm text-ink outline-none placeholder:text-ink-placeholder focus:ring-0"/><span class="shrink-0 select-none pr-3 pl-0.5 text-sm text-ink-placeholder">- @{createContactTarget()?.domain}+ @{props.target?.domain}</span></div></div>diff --git a/apps/web/src/features/settings/Crm.tsx b/apps/web/src/features/crm/views/crm-settings.tsxsimilarity index 75%rename from apps/web/src/features/settings/Crm.tsxrename to apps/web/src/features/crm/views/crm-settings.tsxindex 822018eea3..cd5aa3137b 100644--- a/apps/web/src/features/settings/Crm.tsx+++ b/apps/web/src/features/crm/views/crm-settings.tsx@@ -1,15 +1,5 @@-/** 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 type { ItemDragOverlayData } from '@app/components/app/ItemDragAndDrop';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';@@ -18,21 +8,6 @@ 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,- useIsTeamAdmin,-} from '@queries/team/teams';-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 {createSortable,maybeTransformStyle,@@ -41,23 +16,27 @@ import {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 { createSignal, For, type JSX, Show, Suspense } from 'solid-js';import {SettingsCard,SettingsPage,SettingsRow,SettingsSection,-} from './primitives';--const authHost = SERVER_HOSTS['auth-service'];+} from '../../settings/primitives';+import { CrmStageDot as StageDot } from '../components/stage-icon';+import { useCrmContext } from '../context/crm-context';+import { createStageEditor } from '../primitives/stage-editor';+import {+ useClosedStageIds,+ useCrmPermissions,+ useCurrentTeamQuery,+ useDealStages,+ useIsTeamAdmin,+ usePatchTeamCrmSettingsMutation,+ useReplaceCrmStagesMutation,+ useResetCrmStagesMutation,+ useTeamCrmConfig,+} from './use-crm';/* ------------------------------------------------------------------ *//* Shared bits */@@ -115,31 +94,6 @@ function ConfirmDialog(props: {/* CRM enablement *//* ------------------------------------------------------------------ */-/**- * PATCH /team/crm on the auth service. The generated orval client- * (`patchTeamCrmSettings`) issues a bare relative `fetch` with no auth, so we- * go through `fetchWithAuth` against the auth host like `authServiceClient`.- */-function usePatchTeamCrmSettingsMutation() {- return useMutation(() => ({- mutationFn: async (req: PatchTeamCrmSettingsRequest) =>- await throwOnErr(() =>- fetchWithAuth<PatchTeamCrmSettingsResponse>(`${authHost}/team/crm`, {- method: 'PATCH',- body: JSON.stringify(req),- })- ),- onSuccess: (data: PatchTeamCrmSettingsResponse) => {- invalidateUserTeams();- toast.success(data.enabled ? 'CRM enabled' : 'CRM disabled');- },- onError: (error: Error) => {- console.error('Failed to update CRM settings', error);- toast.failure('Failed to update CRM settings');- },- }));-}-const DISABLE_CRM_PHRASE = 'Disable CRM';function CrmEnablementSection() {@@ -317,16 +271,11 @@ 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.+ * so entity drop consumers ignore stage drags. Supplies its own overlay icon.*/-export type StageDragData = {+export type StageDragData = ItemDragOverlayData & {dragType: 'stage';name: string;};@@ -392,6 +341,7 @@ function StageEditorRow(props: {reorderMode === 'drag'? createSortable(props.id, {dragType: 'stage',+ overlayIcon: StageDot,get name() {return props.label;},@@ -521,10 +471,6 @@ function StageEditorRow(props: {);}-function toStageInputs(stages: DealStage[]): CrmStageInput[] {- return stages.map((stage) => ({ id: stage.id, label: stage.label }));-}-function DealStagesSection() {const dealStages = useDealStages();const crmPermissions = useCrmPermissions();@@ -533,116 +479,41 @@ function DealStagesSection() {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 {+ newStageName,+ setNewStageName,+ stageToDelete,+ setStageToDelete,+ showResetModal,+ setShowResetModal,+ canEdit,+ pending,+ loading,+ failed,+ busy,+ blocked,+ drafts,+ setDrafts,+ orderedStages,+ stageIds,+ announcement,+ handleCustomize,+ handleRename,+ reorder,+ handleMove,+ handleAddStage,+ handleDeleteStage,+ handleReset,+ toggleClosedStage,+ } = createStageEditor({+ dealStages,+ crmPermissions,+ teamCrmConfig,+ closedStageIds,+ replaceMutation,+ resetMutation,+ onSuccess: useCrmContext().feedback.success,});- 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.@@ -658,43 +529,6 @@ function DealStagesSection() {);});- 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 (<SettingsSectiontitle="Deal stages"diff --git a/apps/web/src/features/companies/views/CrmWorkspace.tsx b/apps/web/src/features/crm/views/crm-workspace.tsxsimilarity index 77%rename from apps/web/src/features/companies/views/CrmWorkspace.tsxrename to apps/web/src/features/crm/views/crm-workspace.tsxindex e5ba691ea3..732ecece59 100644--- a/apps/web/src/features/companies/views/CrmWorkspace.tsx+++ b/apps/web/src/features/crm/views/crm-workspace.tsx@@ -13,40 +13,33 @@ import { SoupViewContextGroup } from '@app/features/next-soup/soup-view/filters-import { SoupViewContextSort } from '@app/features/next-soup/soup-view/filters-bar/soup-view-context-sort';import { UnifiedFilterDropdown } from '@app/features/next-soup/soup-view/filters-bar/unified-filter-dropdown';import { useFilterRefinements } from '@app/features/next-soup/soup-view/filters-bar/use-filter-refinements';-import { useSoupView } from '@app/features/next-soup/soup-view/soup-view-context';-import {- CompanyDisplayMenu,- CompanyViewsMenu,-} from '@app/features/next-soup/soup-view/views/companies/CompanyViewsMenu';-import { useApplyCrmView } from '@app/features/next-soup/soup-view/views/companies/use-apply-crm-view';-import { useFeatureFlag } from '@app/lib/analytics/posthog';import { usePreference } from '@app/preferences/use-preference';-import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';-import { enableCrmLists } from '@core/constant/featureFlags';-import { useSettingsState } from '@core/constant/SettingsState';-import { useUserId } from '@core/context/user';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { type EntityData, isCrmCompanyEntity } from '@entity';import ListIcon from '@phosphor/list.svg';-import { fetchCrmExportCompanies } from '@queries/crm/export';-import { useCrmLists } from '@queries/crm/lists';-import { useQuickAccessCrmCompaniesQuery } from '@queries/soup/quick-access-crm-companies';-import { useCurrentTeamQuery } from '@queries/team/teams';import { Button, Dropdown, Tooltip } from '@ui';import { tourTarget } from '@ui/components/Tour';import { createSignal, type JSX, onMount, Show, Suspense } from 'solid-js';-import { openCreateCompanyModal } from '../CreateCompanyModal';-import { CrmListDialog } from '../components/CrmListDialog';-import { CrmSidebar } from '../components/CrmSidebar';-import { CRM_VIEWS } from '../core/crm-navigation';+import { CrmListDialog } from '../components/company-list-dialog';+import { CrmSidebar } from '../components/crm-sidebar';+import { useCrmContext } from '../context/crm-context';+import { useCrmWorkspace } from '../context/workspace-context';+import { CRM_VIEWS } from '../core/navigation';+import type { CrmViewConfig } from '../core/saved-view';+import { createCrmExportLoader } from '../primitives/export-source';+import { useApplyCrmView } from './apply-view';+import { CrmExport } from './export-companies';+import { CrmImport } from './import-companies';+import { CrmCompanyDetail } from './record-detail';+import { CompanyDisplayMenu, CompanyViewsMenu } from './saved-views-menu';import {- type CrmViewConfig,+ useCrmLists,+ useCurrentTeamQuery,usePersonalCrmViews,+ useQuickAccessCrmCompaniesQuery,useTeamCrmViews,-} from '../crm/saved-views';-import { CrmCompanyDetail } from './CrmCompanyDetail';-import { CrmExport } from './CrmExport';-import { CrmImport } from './CrmImport';+ useCrmUserId as useUserId,+} from './use-crm';function NavigationToggle(props: {onExpand: () => void;@@ -108,12 +101,11 @@ function NavigationToggle(props: {}function CrmSearchBar() {- const view = useSoupView();- const panel = useSplitPanelOrThrow();+ const view = useCrmWorkspace();let input: HTMLInputElement | undefined;useViewControlHotkeys({- scopeId: panel.splitHotkeyScope,- enabled: panel.isPanelActive,+ scopeId: view.host.scopeId,+ enabled: view.host.isActive,search: {description: 'Search companies',run: () => {@@ -130,7 +122,7 @@ function CrmSearchBar() {placeholder="Search companies"value={view.searchText()}onValueChange={view.setSearchText}- onEscape={() => panel.panelRef()?.focus()}+ onEscape={view.host.focus}hotkey="cmd+f"class="max-w-md flex-1"/>@@ -139,7 +131,7 @@ function CrmSearchBar() {function CrmFilterChips(props: { onReset: () => void }) {const { consolidatedFiltersList } = useFilterRefinements();- const view = useSoupView();+ const view = useCrmWorkspace();const userId = useUserId();const filters = () =>consolidatedFiltersList().filter((filter) => {@@ -161,14 +153,17 @@ function CrmFilterChips(props: { onReset: () => void }) {);}-export function CrmWorkspace(props: {+export function CrmWorkspaceView(props: {children: (options: {onOpenEntity?: (entity: EntityData) => boolean;mobileHeaderLeading?: JSX.Element;}) => JSX.Element;}) {- const view = useSoupView();- const panel = useSplitPanelOrThrow();+ const {+ openCreateCompany: openCreateCompanyModal,+ exportCompanies: fetchCrmExportCompanies,+ } = useCrmContext();+ const view = useCrmWorkspace();const [selectedCompany, setSelectedCompany] = createSignal<{id: string;name: string;@@ -177,13 +172,12 @@ export function CrmWorkspace(props: {const openCompany = (entity: EntityData) => {if (!isCrmCompanyEntity(entity)) return false;view.soup.focus.set(entity.id);- panel.handle.captureEntryState();+ view.host.captureEntryState();setSelectedCompany({ id: entity.id, name: entity.name });return true;};const apply = useApplyCrmView();const userId = useUserId();- const { openSettings } = useSettingsState();const [collapsed, setCollapsed] = usePreference('macro:pref:crm:sidebar-collapsed',{ default: false }@@ -191,8 +185,8 @@ export function CrmWorkspace(props: {const teamQuery = useCurrentTeamQuery();const teamId = () =>teamQuery.isSuccess ? teamQuery.data?.team.id : undefined;- const listsFlag = useFeatureFlag(enableCrmLists);- const lists = useCrmLists(() => (listsFlag().enabled ? teamId() : undefined));+ const listsEnabled = useCrmContext().listsEnabled();+ const lists = useCrmLists(() => (listsEnabled() ? teamId() : undefined));const personal = usePersonalCrmViews();const team = useTeamCrmViews();const savedViews = () => [@@ -222,7 +216,7 @@ export function CrmWorkspace(props: {CRM_VIEWS.find((v) => v.id === active())?.label ??'Companies';const navigate = (id: string) => {- if (!listsFlag().enabled && id.startsWith('list:')) id = 'active';+ if (!listsEnabled() && id.startsWith('list:')) id = 'active';closeCompany();const saved = savedViews().find((v) => v.id === id);if (saved) {@@ -265,8 +259,7 @@ export function CrmWorkspace(props: {});};onMount(() => {- if (!listsFlag().enabled && active().startsWith('list:'))- navigate('active');+ if (!listsEnabled() && active().startsWith('list:')) navigate('active');});const sidebar = () => (<CrmSidebar@@ -282,7 +275,7 @@ export function CrmWorkspace(props: {count: list.config.companyIds.length,}))}savedViews={savedViews()}- listsEnabled={listsFlag().enabled}+ listsEnabled={listsEnabled()}listsLoading={lists.query.isLoading}listsError={lists.query.isError}canCreateList={!!teamId()}@@ -291,7 +284,7 @@ export function CrmWorkspace(props: {onNewList={() => setEditing({ name: '', companyIds: [] })}onImport={() => setImporting(true)}onExport={() => setExporting(true)}- onSettings={() => openSettings('CRM')}+ onSettings={view.host.openSettings}onCollapse={() => setCollapsed(true)}/>);@@ -305,10 +298,10 @@ export function CrmWorkspace(props: {</Suspense></ViewShell.Aside><ViewShell.Main>- <Show when={selectedCompany()}>+ <Show when={selectedCompany()} keyed>{(company) => (<CrmCompanyDetail- company={company()}+ company={company}viewName={title()}onClose={closeCompany}navigation={@@ -343,7 +336,7 @@ export function CrmWorkspace(props: {<Suspense><CompanyViewsMenu hideLabel /></Suspense>- <Show when={listsFlag().enabled && activeList()}>+ <Show when={listsEnabled() && activeList()}>{(list) => (<Buttonvariant="ghost"@@ -379,7 +372,7 @@ export function CrmWorkspace(props: {</div></Show></ViewShell.Main>- <Show when={listsFlag().enabled && editing()}>+ <Show when={listsEnabled() && editing()}>{(initial) => {const companies = useQuickAccessCrmCompaniesQuery();return (@@ -415,42 +408,11 @@ export function CrmWorkspace(props: {kind="companies"currentView={title()}onClose={() => setExporting(false)}- onLoad={async (scope, signal, progress) => {- const wait = async () => {- signal.throwIfAborted();- await new Promise((resolve) => setTimeout(resolve, 100));- };- if (scope === 'all')- return {- companies: await fetchCrmExportCompanies(signal, progress),- };- while (view.source.isFetching()) await wait();- if (view.source.error())- throw new Error('Could not load this view. Please retry.');- while (view.source.hasNextPage()) {- signal.throwIfAborted();- await view.source.fetchNextPage();- await wait();- if (view.source.error())- throw new Error(- 'Could not load the entire view. Please retry.'- );- progress(view.source.data().length);- }- signal.throwIfAborted();- let current = view.source.data().filter(isCrmCompanyEntity);- if (current.some((company) => !company.properties)) {- const full = new Map(- (await fetchCrmExportCompanies(signal, progress)).map(- (company) => [company.id, company]- )- );- current = current.map(- (company) => full.get(company.id) ?? company- );- }- return { companies: current };- }}+ onLoad={createCrmExportLoader(+ view.source,+ fetchCrmExportCompanies,+ isCrmCompanyEntity+ )}/></Show><Show when={importing()}>diff --git a/apps/web/src/features/next-soup/soup-view/views/companies/CrmDefaultView.tsx b/apps/web/src/features/crm/views/default-view.tsxsimilarity index 50%rename from apps/web/src/features/next-soup/soup-view/views/companies/CrmDefaultView.tsxrename to apps/web/src/features/crm/views/default-view.tsxindex 8135559900..fcb5d6b2fa 100644--- a/apps/web/src/features/next-soup/soup-view/views/companies/CrmDefaultView.tsx+++ b/apps/web/src/features/crm/views/default-view.tsx@@ -1,11 +1,8 @@-import { useApplyCrmView } from '@app/features/next-soup/soup-view/views/companies/use-apply-crm-view';-import {- type CrmViewConfig,- usePersonalCrmViews,- useTeamCrmViews,-} from '@companies/crm/saved-views';import { isTouchDevice } from '@core/mobile/isTouchDevice';-import { createEffect } from 'solid-js';+import type { CrmViewConfig } from '../core/saved-view';+import { createDefaultCrmView } from '../primitives/default-view';+import { useApplyCrmView } from './apply-view';+import { usePersonalCrmViews, useTeamCrmViews } from './use-crm';/*** Applies the default saved view (personal wins over team) once its queries@@ -19,16 +16,13 @@ export function CrmDefaultViewLoader() {const team = useTeamCrmViews();const applyView = useApplyCrmView();- let applied = false;- createEffect(() => {- if (applied || personal.isLoading() || team.isLoading()) return;- applied = true;- const config =- personal.defaultView()?.config ??- (team.defaultView()?.config as CrmViewConfig | undefined);- if (config) {- applyView(isTouchDevice() ? { ...config, viewMode: 'list' } : config);- }+ createDefaultCrmView({+ personalLoading: personal.isLoading,+ teamLoading: team.isLoading,+ personal: () => personal.defaultView()?.config,+ team: () => team.defaultView()?.config as CrmViewConfig | undefined,+ mobile: isTouchDevice,+ apply: applyView,});return null;diff --git a/apps/web/src/features/crm/views/empty-state.tsx b/apps/web/src/features/crm/views/empty-state.tsxnew file mode 100644index 0000000000..3a7ef328c5--- /dev/null+++ b/apps/web/src/features/crm/views/empty-state.tsx@@ -0,0 +1,72 @@+import EmptyStateCompaniesGraphic from '@design/empty-state-companies.svg';+import { EmptyStatePanel } from '@ui';+import { Match, Switch } from 'solid-js';+import { useCrmWorkspace } from '../context/workspace-context';+import { useCurrentTeamQuery, useIsTeamAdmin } from './use-crm';++export function CrmEmptyState() {+ const { host, activeTab } = useCrmWorkspace();+ const teamQuery = useCurrentTeamQuery();+ const isTeamAdmin = useIsTeamAdmin();+ const teamResolved = () => teamQuery.data !== undefined;+ const crmEnabled = () => teamQuery.data?.team.crm_enabled ?? false;+ const hasNoTeam = () => teamQuery.data === null;+ return (+ <Switch>+ {/* Render nothing until the team query resolves — showing a wrong+ panel for a moment is worse than a brief blank. */}+ <Match when={!teamResolved()}>{null}</Match>+ <Match when={hasNoTeam()}>+ <EmptyStatePanel+ centered+ graphic={EmptyStateCompaniesGraphic}+ title="Join a team to enable CRM"+ description="Create or join a team in Settings > Team."+ primaryAction={{+ label: 'Open team settings',+ onClick: () => host.openTeamSettings(),+ }}+ />+ </Match>+ <Match when={!crmEnabled()}>+ <EmptyStatePanel+ centered+ 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: () => host.openSettings(),+ }+ : undefined+ }+ />+ </Match>+ <Match when={true}>+ <EmptyStatePanel+ graphic={EmptyStateCompaniesGraphic}+ title={+ !activeTab() || activeTab() === 'active'+ ? 'No customers yet'+ : activeTab()?.startsWith('list:')+ ? 'No companies in this list'+ : 'No companies in this view'+ }+ description={+ !activeTab() || activeTab() === 'active'+ ? 'Customers your team emails will appear here.'+ : activeTab()?.startsWith('list:')+ ? 'Use Edit list to add companies to this collection.'+ : 'Companies that match this view will appear here.'+ }+ />+ </Match>+ </Switch>+ );+}diff --git a/apps/web/src/features/crm/views/export-companies.test.tsx b/apps/web/src/features/crm/views/export-companies.test.tsxnew file mode 100644index 0000000000..6898fa9282--- /dev/null+++ b/apps/web/src/features/crm/views/export-companies.test.tsx@@ -0,0 +1,85 @@+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@solidjs/testing-library';+import type { JSX, ParentProps } from 'solid-js';+import { afterEach, expect, it, vi } from 'vitest';+import { CrmExport } from './export-companies';++const downloadCsv = vi.hoisted(() =>+ vi.fn<(content: string, filename: string) => Promise<{ saved: boolean }>>()+);++vi.mock('@entity', () => ({ getCompanyOwnerId: () => undefined }));+vi.mock('@ui', () => {+ const Container = (props: ParentProps) => <>{props.children}</>;+ return {+ Button: (props: JSX.ButtonHTMLAttributes<HTMLButtonElement>) => (+ <button {...props} />+ ),+ Dialog: Object.assign(Container, {+ Title: Container,+ Description: Container,+ }),+ Panel: Object.assign(Container, { Body: Container }),+ };+});+vi.mock('../context/crm-context', () => ({+ useCrmContext: () => ({+ downloadCsv,+ userEmail: (id: string) => id,+ createExportDefinitions: () => ({+ isPending: false,+ isSuccess: true,+ isError: false,+ data: [],+ }),+ }),+}));+vi.mock('./use-crm', () => ({+ useDealStages: () => ({+ isLoading: () => false,+ isError: () => false,+ stageDefinitionId: () => 'stage',+ }),+}));++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++it.each([false, true])(+ 'waits for the platform save result and closes only when saved=%s',+ async (saved) => {+ let finishSave!: (result: { saved: boolean }) => void;+ downloadCsv.mockImplementation(+ () => new Promise((resolve) => (finishSave = resolve))+ );+ const close = vi.fn();+ render(() => (+ <CrmExport+ kind="companies"+ currentView="Pipeline"+ onClose={close}+ onLoad={async () => ({ companies: [] })}+ />+ ));+ fireEvent.click(screen.getByRole('button', { name: 'Prepare export' }));+ fireEvent.click(+ await screen.findByRole('button', { name: 'Download CSV' })+ );+ expect(downloadCsv).toHaveBeenCalledOnce();+ expect(close).not.toHaveBeenCalled();++ finishSave({ saved });+ await downloadCsv.mock.results[0].value;+ await waitFor(() => expect(close).toHaveBeenCalledTimes(saved ? 1 : 0));+ if (!saved) {+ expect(screen.getByRole('button', { name: 'Download CSV' })).toBeTruthy();+ }+ }+);diff --git a/apps/web/src/features/companies/views/CrmExport.tsx b/apps/web/src/features/crm/views/export-companies.tsxsimilarity index 69%rename from apps/web/src/features/companies/views/CrmExport.tsxrename to apps/web/src/features/crm/views/export-companies.tsxindex 3e4132ce96..86c3e2b04f 100644--- a/apps/web/src/features/companies/views/CrmExport.tsx+++ b/apps/web/src/features/crm/views/export-companies.tsx@@ -1,21 +1,13 @@-import { idToEmail } from '@core/user/util';import { type CrmCompanyEntity, getCompanyOwnerId } from '@entity';-import { downloadFile } from '@filesystem/download';import { SYSTEM_PROPERTY_IDS } from '@property/constants';-import { useListPropertiesQuery } from '@queries/properties/definitions';import { Button, Dialog, Panel } from '@ui';-import { createMemo, createSignal, For, onCleanup, Show } from 'solid-js';-import {- COMPANY_EXPORT_COLUMNS,- companyExportRecord,- createCrmCsv,- type ExportColumn,- type ExportRecord,- PEOPLE_EXPORT_COLUMNS,- personExportRecord,-} from '../core/crm-export';-import type { CrmPerson } from '../core/crm-people';-import { useDealStages } from '../crm/deal-stages';+import { For, Show } from 'solid-js';+import { COMPANY_EXPORT_COLUMNS } from '../components/export-columns';+import { useCrmContext } from '../context/crm-context';+import { createCrmCsv, PEOPLE_EXPORT_COLUMNS } from '../core/export';+import type { CrmPerson } from '../core/people';+import { createCrmExport } from '../primitives/export-companies';+import { useDealStages } from './use-crm';export function CrmExport(props: {kind: 'companies' | 'people';@@ -27,138 +19,47 @@ export function CrmExport(props: {progress: (count: number) => void) => Promise<{ companies?: CrmCompanyEntity[]; people?: CrmPerson[] }>;}) {+ const { userEmail: idToEmail, downloadCsv } = useCrmContext();const stages = useDealStages();- const definitions = useListPropertiesQuery(- () => ({- scope: 'all',- includeOptions: true,- forEntityType: 'COMPANY',- }),+ const definitions = useCrmContext().createExportDefinitions(() => props.kind === 'companies');- const baseColumns =- props.kind === 'people' ? PEOPLE_EXPORT_COLUMNS : COMPANY_EXPORT_COLUMNS;- const [scope, setScope] = createSignal<'current' | 'all'>('current');- const [selected, setSelected] = createSignal(- baseColumns.filter((column) => column.default).map((column) => column.id)- );- const [rows, setRows] = createSignal<ExportRecord[]>();- const [pending, setPending] = createSignal(false);- const [progress, setProgress] = createSignal(0);- const [error, setError] = createSignal('');- let controller: AbortController | undefined;- onCleanup(() => controller?.abort());- const propertyDefinitions = () =>- props.kind === 'companies' && definitions.isSuccess ? definitions.data : [];- const columns = createMemo<ExportColumn[]>(() => [- ...baseColumns,- ...propertyDefinitions().flatMap((entry) => {- const definition = 'definition' in entry ? entry.definition : entry;- if (- definition.is_metadata ||- baseColumns.some(- (column) => column.id === `property:${definition.id}`- ) ||- [- SYSTEM_PROPERTY_IDS.STAGE,- SYSTEM_PROPERTY_IDS.COMPANY_OWNER,- stages.stageDefinitionId(),- ].includes(definition.id)- )- return [];- return [- { id: `property:${definition.id}`, label: definition.display_name },- ];- }),- ]);- const selectedColumns = () =>- columns().filter((column) => selected().includes(column.id));- const options = createMemo(- () =>- new Map(- propertyDefinitions().flatMap((entry) =>- 'property_options' in entry- ? entry.property_options.map(- (option) => [option.id, String(option.value.value)] as const- )- : []- )- )- );- const formatProperty = (- property: NonNullable<CrmCompanyEntity['properties']>[number]- ) => {- const value = property.value;- if (!value) return '';- if (value.type === 'SelectOption')- return value.value.map((id) => options().get(id) ?? id).join('; ');- if (value.type === 'EntityReference')- return value.value- .map((ref) =>- ref.entity_id.startsWith('macro|')- ? idToEmail(ref.entity_id)- : ref.entity_id- )- .join('; ');- return Array.isArray(value.value) ? value.value.join('; ') : value.value;- };- const metadataLoading = () =>- props.kind === 'companies' && (definitions.isPending || stages.isLoading());- const metadataError = () =>- props.kind === 'companies' && (definitions.isError || stages.isError());- const filename = () =>- `macro-${- scope() === 'all'- ? `all-${props.kind}`- : props.currentView- .toLowerCase()- .replace(/[^a-z0-9]+/g, '-')- .replace(/^-|-$/g, '') || props.kind- }-${new Date().toISOString().slice(0, 10)}.csv`;- async function prepare() {- if (pending()) return;- controller = new AbortController();- const signal = controller.signal;- setPending(true);- setError('');- setProgress(0);- setRows(undefined);- try {- const result = await props.onLoad(scope(), signal, setProgress);- signal.throwIfAborted();- setRows(- result.people- ? result.people.map(personExportRecord)- : (result.companies ?? []).map((company) => {- const stageId = stages.resolveStage(company);- const owner = getCompanyOwnerId(company);- return companyExportRecord(- company,- stageId ? (stages.stageLabel(stageId) ?? stageId) : '',- owner ? idToEmail(owner) : '',- formatProperty- );- })- );- } catch (cause) {- if (!signal.aborted)- setError(- cause instanceof Error- ? cause.message- : 'Could not prepare the export. Please retry.'- );- } finally {- if (!signal.aborted) setPending(false);- }- }+ const {+ baseColumns,+ scope,+ setScope,+ selected,+ setSelected,+ rows,+ setRows,+ pending,+ progress,+ error,+ setError,+ columns,+ selectedColumns,+ metadataLoading,+ metadataError,+ filename,+ prepare,+ } = createCrmExport(props, {+ baseColumns:+ props.kind === 'people' ? PEOPLE_EXPORT_COLUMNS : COMPANY_EXPORT_COLUMNS,+ definitions,+ stages,+ userEmail: idToEmail,+ ownerId: getCompanyOwnerId,+ stageId: SYSTEM_PROPERTY_IDS.STAGE,+ ownerPropertyId: SYSTEM_PROPERTY_IDS.COMPANY_OWNER,+ });async function download() {const data = rows();if (!data || !selectedColumns().length) return;- const blob = new Blob([createCrmCsv(selectedColumns(), data)], {- type: 'text/csv;charset=utf-8',- });- // Keep the dialog open when the Android save dialog is canceled.- const { saved } = await downloadFile(blob, filename());+ const { saved } = await downloadCsv(+ createCrmCsv(selectedColumns(), data),+ filename()+ );+ // Keep the dialog open when the platform save flow is canceled or fails.if (saved) props.onClose();}return (diff --git a/apps/web/src/features/companies/views/CrmImport.tsx b/apps/web/src/features/crm/views/import-companies.tsxsimilarity index 53%rename from apps/web/src/features/companies/views/CrmImport.tsxrename to apps/web/src/features/crm/views/import-companies.tsxindex fb285b6ef4..11d7accddf 100644--- a/apps/web/src/features/companies/views/CrmImport.tsx+++ b/apps/web/src/features/crm/views/import-companies.tsx@@ -1,83 +1,13 @@-import { parseCsv } from '@core/util/csv';-import { useCreateCompanyMutation } from '@queries/crm/companies';import { Button, Dialog, Panel } from '@ui';-import { createSignal, For, Show } from 'solid-js';+import { For, Show } from 'solid-js';+import { createCompanyImport } from '../primitives/import-companies';+import { useCreateCompanyMutation } from './use-crm';export function CrmImport(props: { onClose: () => void }) {const create = useCreateCompanyMutation();- const [rows, setRows] = createSignal<{ name: string; domain: string }[]>([]);- const [error, setError] = createSignal('');- const [pending, setPending] = createSignal(false);- const [completed, setCompleted] = createSignal(0);- async function read(file?: File) {- setError('');- setRows([]);- setCompleted(0);- if (!file) return;- if (file.size > 1024 * 1024) {- setError('Choose a CSV smaller than 1 MB.');- return;- }- try {- const parsed = parseCsv((await file.text()).replace(/^\uFEFF/, ''));- if (!parsed.ok) {- setError(parsed.error);- return;- }- const normalized = parsed.records.map((row) =>- Object.fromEntries(- Object.entries(row).map(([key, value]) => [- key.toLowerCase(),- value.trim(),- ])- )- );- if (- !normalized.length ||- normalized.length > 100 ||- normalized.some(- (row) =>- !row.name ||- !/^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/i.test(- row.domain ?? ''- )- )- ) {- setError(- 'Use name and domain columns, with 1–100 companies and domains like acme.com.'- );- return;- }- setRows(- normalized.map((row) => ({- name: row.name,- domain: row.domain.toLowerCase(),- }))- );- } catch {- setError('Could not read that file. Please try again.');- }- }- async function run() {- if (pending() || !rows().length) return;- setPending(true);- setError('');- const failed: { name: string; domain: string }[] = [];- for (const row of rows()) {- try {- await create.mutateAsync(row);- setCompleted((n) => n + 1);- } catch {- failed.push(row);- }- }- setRows(failed);- setPending(false);- if (failed.length)- setError(- `${failed.length} could not be imported. They may already exist or use an unsupported domain. Successful rows will not be retried.`- );- }+ const { rows, error, pending, completed, read, run } = createCompanyImport(+ (input) => create.mutateAsync(input)+ );return (<Dialogopendiff --git a/apps/web/src/features/companies/views/CrmPeople.tsx b/apps/web/src/features/crm/views/people.tsxsimilarity index 97%rename from apps/web/src/features/companies/views/CrmPeople.tsxrename to apps/web/src/features/crm/views/people.tsxindex 1d67e42109..35b576ec40 100644--- a/apps/web/src/features/companies/views/CrmPeople.tsx+++ b/apps/web/src/features/crm/views/people.tsx@@ -1,12 +1,12 @@-import { useSplitLayout } from '@components/app/split-layout/layout';import BuildingsIcon from '@phosphor/buildings.svg';import CaretDownIcon from '@phosphor/caret-down.svg';import MagnifyingGlassIcon from '@phosphor/magnifying-glass.svg';import UsersIcon from '@phosphor/users.svg';-import type { useCrmPeopleQuery } from '@queries/crm/people';import { Button } from '@ui';import { createMemo, createSignal, For, Show } from 'solid-js';-import { filterAndSortPeople, type PeopleSort } from '../core/crm-people';+import { useCrmContext } from '../context/crm-context';+import type { PeopleSource } from '../context/crm-sources';+import { filterAndSortPeople, type PeopleSort } from '../core/people';const PAGE_SIZE = 50;const dateLabel = (value: string) => {@@ -28,7 +28,7 @@ const columns: { label: string; sort?: PeopleSort; class: string }[] = [];export function CrmPeople(props: {- directory: ReturnType<typeof useCrmPeopleQuery>;+ directory: PeopleSource;search: string;onSearch: (value: string) => void;sort: PeopleSort;@@ -37,7 +37,7 @@ export function CrmPeople(props: {onDescending: (value: boolean) => void;}) {const directory = props.directory;- const { openWithSplit } = useSplitLayout();+ const { openWithSplit } = useCrmContext().createNavigation();const search = () => props.search;const sort = () => props.sort;const descending = () => props.descending;diff --git a/apps/web/src/features/crm/views/record-detail.test.tsx b/apps/web/src/features/crm/views/record-detail.test.tsxnew file mode 100644index 0000000000..3e7a676143--- /dev/null+++ b/apps/web/src/features/crm/views/record-detail.test.tsx@@ -0,0 +1,106 @@+import {+ cleanup,+ fireEvent,+ render,+ screen,+ within,+} from '@solidjs/testing-library';+import {+ createSignal,+ ErrorBoundary,+ type JSX,+ type ParentProps,+ Show,+} from 'solid-js';+import { afterEach, expect, it, vi } from 'vitest';+import type { CrmContact } from '../core/contact';+import { CrmCompanyDetail } from './record-detail';++vi.mock('@ui', async () => ({+ ...(await import('../../../components/ui/utils/classname')),+ Tooltip: (props: ParentProps) => <>{props.children}</>,+ Button: (props: JSX.ButtonHTMLAttributes<HTMLButtonElement>) => (+ <button {...props} />+ ),+}));+vi.mock('@components/app/side-panel', () => ({+ SidePanel: {+ Root: (props: ParentProps) => <>{props.children}</>,+ Toggle: () => null,+ },+}));+vi.mock('@core/component/EntityIcon', () => ({ EntityIcon: () => null }));+vi.mock('./copy-link-button', () => ({ CrmCopyLinkButton: () => null }));+vi.mock('./use-crm', () => ({+ useCompanyQuery: () => ({+ query: { isError: false },+ company: () => undefined,+ }),+ useContactQuery: () => ({ isSuccess: false, isError: false }),+}));+vi.mock('./company-detail', () => ({+ Company: (props: { onOpenContact(contact: CrmContact): void }) => (+ <button+ onClick={() =>+ props.onOpenContact({+ id: 'contact-1',+ companyId: 'company-1',+ name: 'Maya',+ email: '[email protected]',+ hidden: false,+ firstInteraction: '',+ lastInteraction: '',+ createdAt: '',+ updatedAt: '',+ })+ }+ >+ Open Maya+ </button>+ ),+}));+vi.mock('./contact-detail', () => ({+ Contact: (props: { contactId: string }) => (+ <div>Contact content: {props.contactId}</div>+ ),+}));+afterEach(cleanup);++it('removes contact breadcrumbs safely when returning to the company and reopening details', () => {+ const failed = vi.fn(() => <div>Navigation failed</div>);+ const [selected, setSelected] = createSignal(true);+ render(() => (+ <ErrorBoundary fallback={failed}>+ <Show+ when={selected()}+ fallback={+ <button onClick={() => setSelected(true)}>Open company</button>+ }+ >+ <CrmCompanyDetail+ company={{ id: 'company-1', name: 'Northstar' }}+ viewName="Pipeline"+ onClose={() => setSelected(false)}+ navigation={null}+ />+ </Show>+ </ErrorBoundary>+ ));+ for (let round = 0; round < 2; round++) {+ fireEvent.click(screen.getByRole('button', { name: 'Open Maya' }));+ const breadcrumbs = () =>+ within(screen.getByRole('navigation', { name: 'CRM record location' }));+ expect(breadcrumbs().getAllByRole('button')).toHaveLength(3);+ expect(screen.getByText('Contact content: contact-1')).toBeTruthy();+ fireEvent.click(breadcrumbs().getByRole('button', { name: 'Northstar' }));+ expect(failed).not.toHaveBeenCalled();+ expect(breadcrumbs().getAllByRole('button')).toHaveLength(2);+ expect(screen.getByRole('button', { name: 'Open Maya' })).toBeTruthy();+ fireEvent.click(breadcrumbs().getByRole('button', { name: 'Pipeline' }));+ expect(+ screen.queryByRole('navigation', { name: 'CRM record location' })+ ).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Open company' }));+ }+ expect(failed).not.toHaveBeenCalled();+});diff --git a/apps/web/src/features/companies/views/CrmCompanyDetail.tsx b/apps/web/src/features/crm/views/record-detail.tsxsimilarity index 93%rename from apps/web/src/features/companies/views/CrmCompanyDetail.tsxrename to apps/web/src/features/crm/views/record-detail.tsxindex 02a5f7c4fd..1e1109ec28 100644--- a/apps/web/src/features/companies/views/CrmCompanyDetail.tsx+++ b/apps/web/src/features/crm/views/record-detail.tsx@@ -1,10 +1,7 @@import { ViewBreadcrumbs } from '@app/components/view-shell';-import { Contact } from '@app/features/contacts/Contact/Contact';import { SidePanel } from '@components/app/side-panel';import { EntityIcon } from '@core/component/EntityIcon';import SpinnerIcon from '@phosphor/spinner.svg';-import { type CompanyContact, useCompanyQuery } from '@queries/crm/companies';-import { useContactQuery } from '@queries/crm/contacts';import { Button, Tooltip } from '@ui';import {createSignal,@@ -14,8 +11,11 @@ import {Show,Suspense,} from 'solid-js';-import { Company } from '../Company/Company';-import { CrmCopyLinkButton } from '../components/CrmCopyLinkButton';+import type { CrmContact as CompanyContact } from '../core/contact';+import { Company } from './company-detail';+import { Contact } from './contact-detail';+import { CrmCopyLinkButton } from './copy-link-button';+import { useCompanyQuery, useContactQuery } from './use-crm';export function CrmCompanyDetail(props: {company: { id: string; name: string };@@ -86,11 +86,11 @@ export function CrmCompanyDetail(props: {</Tooltip>)}</ViewBreadcrumbs.Item>- <Show when={selectedContact()}>+ <Show when={selectedContact()} keyed>{(contact) => (<ViewBreadcrumbs.Item- value={`contact:${contact().id}`}- metadata={{ type: 'contact', id: contact().id }}+ value={`contact:${contact.id}`}+ metadata={{ type: 'contact', id: contact.id }}order={2}>{(item) => (@@ -169,6 +169,7 @@ export function CrmCompanyDetail(props: {><Showwhen={selectedContact()}+ keyedfallback={<CompanycompanyId={props.company.id}@@ -180,7 +181,7 @@ export function CrmCompanyDetail(props: {>{(contact) => (<Contact- contactId={contact().id}+ contactId={contact.id}headerToggle={false}onOpenCompany={(companyId) => {if (companyId !== props.company.id) return false;diff --git a/apps/web/src/features/next-soup/soup-view/views/companies/CompanyViewsMenu.tsx b/apps/web/src/features/crm/views/saved-views-menu.tsxsimilarity index 93%rename from apps/web/src/features/next-soup/soup-view/views/companies/CompanyViewsMenu.tsxrename to apps/web/src/features/crm/views/saved-views-menu.tsxindex 7796a502c6..164f9984a8 100644--- a/apps/web/src/features/next-soup/soup-view/views/companies/CompanyViewsMenu.tsx+++ b/apps/web/src/features/crm/views/saved-views-menu.tsx@@ -1,38 +1,30 @@-import { useSoupView } from '@app/features/next-soup/soup-view/soup-view-context';import { useApplyPreset } from '@app/features/next-soup/soup-view/soup-view-tabs';-import { useApplyCrmView } from '@app/features/next-soup/soup-view/views/companies/use-apply-crm-view';-import {- CRM_LIST_COLUMN_LABELS,- type CrmListColumnId,- useCrmDisplayOptions,-} from '@companies/crm/display-options';-import {- buildCrmViewShareUrl,- type CrmViewConfig,- usePersonalCrmViews,- useTeamCrmViews,-} from '@companies/crm/saved-views';-import { useCrmPermissions } from '@companies/crm/team-crm-config';import { toast } from '@core/component/Toast/Toast';-import { useUserId } from '@core/context/user';import FloppyDiskIcon from '@phosphor/floppy-disk.svg';import LinkIcon from '@phosphor/link.svg';import PushPinIcon from '@phosphor/push-pin.svg';import SlidersIcon from '@phosphor/sliders-horizontal.svg';import StackIcon from '@phosphor/stack.svg';import TrashIcon from '@phosphor/trash.svg';-import { useIsTeamAdmin } from '@queries/team/teams';import { Button, cn, Dropdown, SegmentedControl, Tooltip } from '@ui';import { createSignal, For, type JSX, Show } from 'solid-js';import { unwrap } from 'solid-js/store';--/** Copy a view's share link, with a toast either way. */-const copyShareLink = (config: CrmViewConfig) => {- navigator.clipboard- .writeText(buildCrmViewShareUrl(config))- .then(() => toast.success('Link copied to clipboard'))- .catch(() => toast.failure('Failed to copy link'));-};+import { useCrmContext } from '../context/crm-context';+import { useCrmWorkspace } from '../context/workspace-context';+import {+ CRM_LIST_COLUMN_LABELS,+ type CrmListColumnId,+} from '../core/display-options';+import type { CrmViewConfig } from '../core/saved-view';+import { useApplyCrmView } from './apply-view';+import {+ useCrmDisplayOptions,+ useCrmPermissions,+ useIsTeamAdmin,+ usePersonalCrmViews,+ useTeamCrmViews,+ useCrmUserId as useUserId,+} from './use-crm';/*** Saved-view row: the name applies the view; trailing hover actions pin it@@ -114,9 +106,10 @@ const EmptyViewsHint = (props: { children: JSX.Element }) => (* Saved-views dropdown for the Customers view: personal and team-shared* snapshots of the full view state (filters, search, grouping, sort,* list/board mode, stage/owner sub-filters, tab), plus share links that- * encode the same state into the URL (see `@companies/crm/saved-views`).+ * encode the same state into the URL (see `queries/saved-view-codec.ts`).*/export function CompanyViewsMenu(props: { hideLabel?: boolean } = {}) {+ const copyShareLink = useCrmContext().copyViewLink;const {soup,queryFilters,@@ -125,7 +118,7 @@ export function CompanyViewsMenu(props: { hideLabel?: boolean } = {}) {ownerFilter,activeTab,viewMode,- } = useSoupView();+ } = useCrmWorkspace();const personal = usePersonalCrmViews();const team = useTeamCrmViews();const { canEditCrm } = useCrmPermissions();@@ -330,7 +323,7 @@ export function CompanyViewsMenu(props: { hideLabel?: boolean } = {}) {*/export function CompanyDisplayMenu() {const { options, toggleListColumn } = useCrmDisplayOptions();- const { activeTab, viewMode } = useSoupView();+ const { activeTab, viewMode } = useCrmWorkspace();const { applyTabPreset } = useApplyPreset();const isTeamAdmin = useIsTeamAdmin();diff --git a/apps/web/src/features/crm/views/use-crm.ts b/apps/web/src/features/crm/views/use-crm.tsnew file mode 100644index 0000000000..607fe61149--- /dev/null+++ b/apps/web/src/features/crm/views/use-crm.ts@@ -0,0 +1,82 @@+import { type CrmContext, useCrmContext } from '../context/crm-context';+export const useCompanyQuery = (+ ...args: Parameters<CrmContext['createCompanySource']>+) => useCrmContext().createCompanySource(...args);+export const useContactQuery = (+ ...args: Parameters<CrmContext['createContactSource']>+) => useCrmContext().createContactSource(...args);+export const useCurrentTeamQuery = (+ ...args: Parameters<CrmContext['createTeamSource']>+) => useCrmContext().createTeamSource(...args);+export const useIsTeamAdmin = (+ ...args: Parameters<CrmContext['isTeamAdmin']>+) => useCrmContext().isTeamAdmin(...args);+export const useTeamCrmConfig = (+ ...args: Parameters<CrmContext['createTeamConfigSource']>+) => useCrmContext().createTeamConfigSource(...args);+export const useCrmPermissions = (+ ...args: Parameters<CrmContext['createCapabilities']>+) => useCrmContext().createCapabilities(...args);+export const useDealStages = (+ ...args: Parameters<CrmContext['createDealStages']>+) => useCrmContext().createDealStages(...args);+export const useCrmUnavailable = (+ ...args: Parameters<CrmContext['createUnavailable']>+) => useCrmContext().createUnavailable(...args);+export const useClosedStageIds = (+ ...args: Parameters<CrmContext['createClosedStageIds']>+) => useCrmContext().createClosedStageIds(...args);+export const usePersonalCrmViews = (+ ...args: Parameters<CrmContext['createPersonalViews']>+) => useCrmContext().createPersonalViews(...args);+export const useTeamCrmViews = (+ ...args: Parameters<CrmContext['createTeamViews']>+) => useCrmContext().createTeamViews(...args);+export const useCrmLists = (...args: Parameters<CrmContext['createLists']>) =>+ useCrmContext().createLists(...args);+export const useCreateCompanyMutation = (+ ...args: Parameters<CrmContext['createCompany']>+) => useCrmContext().createCompany(...args);+export const useCreateContactMutation = (+ ...args: Parameters<CrmContext['createContact']>+) => useCrmContext().createContact(...args);+export const useSetCompanyNameMutation = (+ ...args: Parameters<CrmContext['renameCompany']>+) => useCrmContext().renameCompany(...args);+export const useSetContactNameMutation = (+ ...args: Parameters<CrmContext['renameContact']>+) => useCrmContext().renameContact(...args);+export const useSetCompanyHiddenMutation = (+ ...args: Parameters<CrmContext['hideCompany']>+) => useCrmContext().hideCompany(...args);+export const useSetContactHiddenMutation = (+ ...args: Parameters<CrmContext['hideContact']>+) => useCrmContext().hideContact(...args);+export const useSetEmailSyncMutation = (+ ...args: Parameters<CrmContext['setEmailSync']>+) => useCrmContext().setEmailSync(...args);++export const useCrmDisplayOptions = () =>+ useCrmContext().createDisplayOptions();+export const useCrmUserId = () => useCrmContext().userId;+export const useCompanyEmailsQuery = (+ ...args: Parameters<CrmContext['createCompanyEmails']>+) => useCrmContext().createCompanyEmails(...args);+export const useContactEmailsQuery = (+ ...args: Parameters<CrmContext['createContactEmails']>+) => useCrmContext().createContactEmails(...args);+export const useBulkSaveEntityPropertiesMutation = (+ ...args: Parameters<CrmContext['createPropertyCommands']>+) => useCrmContext().createPropertyCommands(...args);+export const usePatchTeamCrmSettingsMutation = (+ ...args: Parameters<CrmContext['createSettingsCommands']>+) => useCrmContext().createSettingsCommands(...args);+export const useReplaceCrmStagesMutation = (+ ...args: Parameters<CrmContext['createReplaceStages']>+) => useCrmContext().createReplaceStages(...args);+export const useResetCrmStagesMutation = (+ ...args: Parameters<CrmContext['createResetStages']>+) => useCrmContext().createResetStages(...args);+export const useQuickAccessCrmCompaniesQuery = (+ ...args: Parameters<CrmContext['createCompanySuggestions']>+) => useCrmContext().createCompanySuggestions(...args);diff --git a/apps/web/src/features/crm/workspace-adapter.tsx b/apps/web/src/features/crm/workspace-adapter.tsxnew file mode 100644index 0000000000..18d71dd011--- /dev/null+++ b/apps/web/src/features/crm/workspace-adapter.tsx@@ -0,0 +1,208 @@+import { usePreference } from '@app/preferences/use-preference';+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { useSettingsState } from '@core/constant/SettingsState';+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import { idToDisplayName } from '@core/user/util';+import { isCrmCompanyEntity } from '@entity';+import { COMPANY_STAGE_OPTIONS } from '@entity/utils/task-properties';+import { SYSTEM_PROPERTY_IDS } from '@property/constants';+import { batch, createEffect, createRenderEffect, on } from 'solid-js';+import type { Query } from '../next-soup/filters/filter-store';+import type { SetPredicatesInput } from '../next-soup/filters/filter-store/predicates-store';+import {+ getViewPreset,+ VIEW_TAB_PRESETS,+} from '../next-soup/sidebar/soup-filter-presets';+import { useSoup } from '../next-soup/soup-context';+import { createSoupViewState } from '../next-soup/soup-view/soup-view-context';+import { useSoupFilterPersistence } from '../next-soup/use-soup-filter-persistence';+import { openEntityInSplitFromUnifiedList } from '../next-soup/utils';+import type { CrmContext } from './context/crm-context';+import type { CrmWorkspace } from './context/workspace-context';+import type { CrmViewConfig } from './core/saved-view';+import { createCrmCollectionFilters } from './filter-adapter';+import { COMPANY_GROUP_OPTIONS } from './group-options';++export function createCrmWorkspace(+ crm: CrmContext,+ sharedView?: CrmViewConfig+) {+ const soup = useSoup();+ const panel = useSplitPanelOrThrow();+ const stages = crm.createDealStages();+ const resolveStage = (entity: import('@entity').EntityData) =>+ isCrmCompanyEntity(entity) ? stages.resolveStage(entity) : undefined;+ const [persistFilters] = useSoupFilterPersistence();+ const filters = createCrmCollectionFilters(crm, soup, persistFilters, stages);+ const state = createSoupViewState({+ filterPersistence: persistFilters,+ soup,+ extensions: {+ propertyGrouping: {+ value: (entity, id) =>+ id === SYSTEM_PROPERTY_IDS.STAGE+ ? (resolveStage(entity) ?? '')+ : undefined,+ label: (value, id) =>+ id === SYSTEM_PROPERTY_IDS.STAGE+ ? stages.stageLabel(value)+ : id === SYSTEM_PROPERTY_IDS.COMPANY_OWNER+ ? idToDisplayName(value) || undefined+ : undefined,+ order: (id) =>+ id === SYSTEM_PROPERTY_IDS.STAGE+ ? stages.stages().map((stage) => stage.id)+ : COMPANY_STAGE_OPTIONS.map((option) => String(option.value)),+ },+ filterContext: () => ({+ resolveCompanyStage: resolveStage,+ companyStageLabel: stages.stageLabel,+ owners: filters.state.ownerFilter(),+ stages: filters.state.stageFilter(),+ }),+ selectFilters: filters.facets,+ groupOptions: {+ visible: () => filters.state.viewMode() === 'list',+ options: COMPANY_GROUP_OPTIONS,+ },+ },+ });+ const soupView = { ...state.context, ...filters.state };+ const preset = getViewPreset('companies');+ const entryState = panel.handle.currentEntryState();++ const persistedFilters = entryState?.['search.filters'] as Query | undefined;++ const persistedPredicates = entryState?.['search.predicates'] as+ | SetPredicatesInput<string>+ | undefined;++ const persistedSearchText = entryState?.['search.text'] as string | undefined;++ const persistedGroupBy = entryState?.['soup.groupBy'] as+ | string+ | null+ | undefined;++ const persistedActiveTab = entryState?.['soup.tab'] as string | undefined;++ const persistedCollapsedGroups = entryState?.['soup.collapsedGroups'] as+ | string[]+ | undefined;++ const [sortPref, setSortPref] = usePreference<string[]>(+ 'macro:pref:soup:companies:sort',+ { default: [] }+ );+ const initialCrmView = sharedView;++ // A default saved view only applies to a fresh Customers entry: restored+ // (back/forward) entries keep what the user was looking at, and share+ // links carry their own state.+ const applyDefaultCrmView =+ initialCrmView === undefined &&+ persistedFilters === undefined &&+ persistedPredicates === undefined;++ // Restore before child controls mount; shared links take precedence over storage.+ let init = false;+ createRenderEffect(() => {+ if (init) return;+ init = true;+ batch(() => {+ soupView.initialize({+ initialQuery: initialCrmView+ ? (initialCrmView.filters as Query | undefined)+ : (persistedFilters ?? preset?.filters),+ initialClientFilters: initialCrmView+ ? (initialCrmView.clientFilters ?? {})+ : (persistedPredicates ?? preset?.clientFilters),+ initialSearchText: initialCrmView+ ? (initialCrmView.searchText ?? '')+ : persistedSearchText,+ preferInitialFilters: initialCrmView !== undefined,+ });++ // `groupBy: null` in a shared view records an explicit "no grouping",+ // which the grouping store expresses as `undefined`.+ const initialGroupBy = initialCrmView+ ? (initialCrmView.groupBy ?? undefined)+ : (persistedGroupBy ?? preset?.groupBy);++ let initialSortIds = initialCrmView?.sort ?? sortPref();+ if (initialSortIds.length === 0) {+ initialSortIds = ['updated_at'];+ }++ const initialActiveTab =+ initialCrmView?.activeTab ??+ persistedActiveTab ??+ soupView.getPersistedActiveTab('companies') ??+ VIEW_TAB_PRESETS.companies.default;++ soup.grouping.setActiveGroupId(initialGroupBy);+ soup.grouping.collapseAll(persistedCollapsedGroups ?? []);++ soup.sort.setAll(+ initialSortIds as Parameters<typeof soup.sort.setAll>[0]+ );++ soupView.setActiveTab(initialActiveTab);++ if (initialCrmView) {+ // Stage/owner sub-filters ride separate signals plus a client+ // predicate that must be active iff the selection is non-empty+ // (same rule as handleStageChange/handleOwnerChange in+ // unified-filter-dropdown).+ const stages = initialCrmView.stageFilter ?? [];+ soupView.setStageFilter(stages);+ if (stages.length > 0 !== soup.predicates.isActive('company-stage')) {+ soup.predicates.toggle({ and: ['company-stage'] });+ }+ const owners = initialCrmView.ownerFilter ?? [];+ soupView.setOwnerFilter(owners);+ if (owners.length > 0 !== soup.predicates.isActive('company-owner')) {+ soup.predicates.toggle({ and: ['company-owner'] });+ }+ soupView.setViewMode(+ initialCrmView.viewMode ?? (isTouchDevice() ? 'list' : 'board')+ );+ }+ });+ });++ createEffect(() => {+ panel.handle.setDisplayName('Customers');+ });++ // Bridge live soup sort state back to preferences. `defer: true` skips the+ // initial run on mount, so we only write when the user actually changes it.+ createEffect(+ on(+ () => soup.sort.active().map((s) => s.id),+ (ids) => setSortPref(ids),+ { defer: true }+ )+ );++ const { openSettings } = useSettingsState();+ const context: CrmWorkspace = {+ ...soupView,+ host: {+ scopeId: panel.splitHotkeyScope,+ isActive: panel.isPanelActive,+ focus: () => panel.panelRef()?.focus(),+ captureEntryState: () => panel.handle.captureEntryState(),+ openCompany: (entity, newSplit) => {+ void openEntityInSplitFromUnifiedList(entity, {+ openInNewSplit: newSplit,+ splitHandle: panel.handle,+ referredFrom: 'companies',+ });+ },+ openSettings: () => openSettings('CRM'),+ openTeamSettings: () => openSettings('Team'),+ },+ };+ return { state, context, applyDefaultCrmView };+}diff --git a/apps/web/src/features/next-soup/actions/make-hide-company-action.ts b/apps/web/src/features/next-soup/actions/make-hide-company-action.tsindex 9143047dbe..c459db7a9b 100644--- a/apps/web/src/features/next-soup/actions/make-hide-company-action.ts+++ b/apps/web/src/features/next-soup/actions/make-hide-company-action.ts@@ -1,46 +1 @@-import { toast } from '@core/component/Toast/Toast';-import type { EntityData } from '@entity';-import { restoreSoupFocus } from '../utils';-import type { EntityActionListState } from './entity-action-context';--type MakeHideCompanyOptions = {- // Available to all team members; the backend enforces- // EditAccessLevel on PUT /crm/companies/{id}/hidden.- setHidden: (companyId: string, hidden: boolean) => Promise<unknown>;-};--export const makeHideCompanyAction = (options: MakeHideCompanyOptions) => {- const { setHidden } = options;-- const canExecute = (entity: EntityData): boolean =>- entity.type === 'crm_company';-- const executeWithSoup = async (- entities: EntityData[],- soup: EntityActionListState- ) => {- const entity = entities[0];- if (entity?.type !== 'crm_company') return;-- // The row leaves (Hide) or joins (Unhide) the active list once soup- // refetches, so move focus to a neighbour first — same as delete.- const currentIndex = soup.focus.index();- const nextRow =- soup.items.at(currentIndex + 1) ?? soup.items.at(currentIndex - 1);- const hidden = entity.hidden;-- soup.selection.clear();- if (nextRow) soup.focus.set(nextRow.id);-- try {- await setHidden(entity.id, !hidden);- toast.success(hidden ? 'Unhidden' : 'Hidden');- } catch {- toast.failure(hidden ? 'Failed to unhide' : 'Failed to hide');- }-- await restoreSoupFocus(nextRow?.id);- };-- return { canExecute, executeWithSoup };-};+export { makeHideCompanyAction } from '../../crm/crm-hide-action';diff --git a/apps/web/src/features/next-soup/actions/make-set-company-property-action.test.ts b/apps/web/src/features/next-soup/actions/make-set-company-property-action.test.tsindex 0830ef763c..f0d06c0d3f 100644--- a/apps/web/src/features/next-soup/actions/make-set-company-property-action.test.ts+++ b/apps/web/src/features/next-soup/actions/make-set-company-property-action.test.ts@@ -13,8 +13,8 @@ const mocks = vi.hoisted(() => ({vi.mock('@app/features/property/editor/state/propertyEditor', () => ({openPropertyEditor: mocks.open,}));-vi.mock('@companies/crm/deal-stages', () => ({- useDealStages: () => ({+vi.mock('@app/features/crm/stage-adapter', () => ({+ createAppDealStages: () => ({isLoading: () => mocks.loading,stageProperty: mocks.stageProperty,}),diff --git a/apps/web/src/features/next-soup/actions/make-set-company-property-action.ts b/apps/web/src/features/next-soup/actions/make-set-company-property-action.tsindex ccf3244dc2..da6ea2187a 100644--- a/apps/web/src/features/next-soup/actions/make-set-company-property-action.ts+++ b/apps/web/src/features/next-soup/actions/make-set-company-property-action.ts@@ -1,47 +1,4 @@-import { openPropertyEditor } from '@app/features/property/editor/state/propertyEditor';-import { useDealStages } from '@companies/crm/deal-stages';-import type { EntityData } from '@entity';-import { buildCompanyDefaultProperties } from '@entity/extractors-property';-import { SYSTEM_PROPERTY_IDS } from '@property/constants';-import type { Property } from '@property/types';--/** Builtin CRM company fields settable from entity action menus. */-export type CompanyCrmField = 'stage' | 'owner' | 'revenue';--/**- * "Set stage / owner / revenue" for CRM company rows: opens the global- * property editor (the same one task status/priority/assignee commands- * use) targeting the builtin CRM property, editing the whole selection.- * Available to all team members; the backend enforces write access on- * property saves.- */-export const makeSetCompanyPropertyAction = () => {- const dealStages = useDealStages();-- const canExecute = (entity: EntityData, field: CompanyCrmField): boolean =>- entity.type === 'crm_company' &&- (field !== 'stage' || !dealStages.isLoading());-- const propertyFor = (field: CompanyCrmField): Property | undefined => {- // Stage resolves through the active deal-stage set (the team's own- // definition when customized) so edits write to the active definition.- if (field === 'stage') return dealStages.stageProperty();- const definitionId =- field === 'owner'- ? SYSTEM_PROPERTY_IDS.COMPANY_OWNER- : SYSTEM_PROPERTY_IDS.REVENUE;- return buildCompanyDefaultProperties().find(- (property) => property.propertyDefinitionId === definitionId- );- };-- const execute = (entities: EntityData[], field: CompanyCrmField) => {- // Stages are lazy: don't open an editor against system defaults before- // the team's active definition has resolved.- if (field === 'stage' && dealStages.isLoading()) return;- const property = propertyFor(field);- if (property) openPropertyEditor(entities, 'direct', property);- };-- return { canExecute, execute };-};+export {+ type CompanyCrmField,+ makeSetCompanyPropertyAction,+} from '../../crm/crm-actions';diff --git a/apps/web/src/features/next-soup/filters/configs/company.ts b/apps/web/src/features/next-soup/filters/configs/company.tsindex 0184bba930..73946c08f7 100644--- a/apps/web/src/features/next-soup/filters/configs/company.ts+++ b/apps/web/src/features/next-soup/filters/configs/company.ts@@ -1,57 +1 @@-import {- matchesInteractionWindow,- needsCompanyFollowUp,-} from '@companies/core/crm-navigation';-import { getCompanyStageOptionId } from '@entity/utils/company-properties';-import { getPropertyOptionLabel } from '@entity/utils/task-properties';-import {- companyOwnedByUsersFilter,- companyStageFilter as companyStagePredicate,-} from '../predicates';-import { config } from './base';--// Companies are fetched via the dedicated CRM soup request (capped at 500-// per team) rather than the dynamic filter AST, which has no property-// support for the `ccf` target — so stage/owner filters are client-side-// predicates with a no-op server query.--/**- * Stage filter for the Customers view, driven by the view's stage- * selection (`ctx.stages`, option ids from the team's active deal-stage- * set plus the `NO_STAGE` sentinel). Mirrors `companyOwnerFilter`.- */-export const companyStageFilter = config({- id: 'company-stage',- predicate: (e, ctx) =>- companyStagePredicate(() => ctx.stages, ctx.resolveCompanyStage)(e),- query: {},-});--export const companyOwnerFilter = config({- id: 'company-owner',- predicate: (e, ctx) => companyOwnedByUsersFilter(() => ctx.owners)(e),- query: {},-});--export const companyNeedsFollowUpFilter = config({- id: 'company-needs-follow-up',- predicate: (entity, ctx) => {- if (entity.type !== 'crm_company') return false;- const stageId = ctx.resolveCompanyStage- ? ctx.resolveCompanyStage(entity)- : getCompanyStageOptionId(entity);- const label = stageId- ? (ctx.companyStageLabel ?? getPropertyOptionLabel)(stageId)- : undefined;- return needsCompanyFollowUp(entity.updatedAt, label);- },- query: {},-});--export const companyRecentlyActiveFilter = config({- id: 'company-recently-active',- predicate: (entity) =>- entity.type === 'crm_company' &&- matchesInteractionWindow(entity.updatedAt, 'recently-active'),- query: {},-});+export * from '../../../crm/collection-filters';diff --git a/apps/web/src/features/next-soup/filters/configs/entity.ts b/apps/web/src/features/next-soup/filters/configs/entity.tsindex 0ed88ed135..b0c7bb2df2 100644--- a/apps/web/src/features/next-soup/filters/configs/entity.ts+++ b/apps/web/src/features/next-soup/filters/configs/entity.ts@@ -1,3 +1,9 @@+export {+ crmCompanyActiveFilter,+ crmCompanyFilter,+ crmCompanyHiddenFilter,+} from '../../../crm/collection-filters';+import { getEntityProjectId } from '@entity';import { defineQueryFilters } from '../filter-store/compile';import {@@ -5,9 +11,6 @@ import {calendarEventFilter as calendarEventPredicate,callsFilter as callsPredicate,channelsFilter as channelsPredicate,- crmCompanyActiveFilter as crmCompanyActivePredicate,- crmCompanyHiddenFilter as crmCompanyHiddenPredicate,- crmCompanyFilter as crmCompanyPredicate,doneRemindersFilter as doneRemindersPredicate,filesAndFolderFilter as filesAndFolderPredicate,firedRemindersFilter as firedRemindersPredicate,@@ -82,12 +85,6 @@ export const calendarFilter = config({query: defineQueryFilters({}, { skipTargets: ['calf'] }),});-export const crmCompanyFilter = config({- id: 'crm-company',- predicate: crmCompanyPredicate,- query: defineQueryFilters({}, { skipTargets: ['ccf'] }),-});-// Reminders are opt-in server-side, so unlike the other entity filters these// queries name `includeReminders` rather than just skipping their own target —// there is no `remf` entry in ID_FIELD_NAMES to skip.@@ -147,24 +144,6 @@ export const doneRemindersFilter = config({}),});-export const crmCompanyActiveFilter = config({- id: 'crm-company-active',- predicate: crmCompanyActivePredicate,- query: defineQueryFilters(- { include: { crmCompanyHidden: false } },- { skipTargets: ['ccf'] }- ),-});--export const crmCompanyHiddenFilter = config({- id: 'crm-company-hidden',- predicate: crmCompanyHiddenPredicate,- query: defineQueryFilters(- { include: { crmCompanyHidden: true } },- { skipTargets: ['ccf'] }- ),-});-export const searchSupportedFilter = config({id: 'search-supported',predicate: searchSupportedPredicate,diff --git a/apps/web/src/features/next-soup/filters/predicates.ts b/apps/web/src/features/next-soup/filters/predicates.tsindex cdd482be20..b0da87eb6e 100644--- a/apps/web/src/features/next-soup/filters/predicates.ts+++ b/apps/web/src/features/next-soup/filters/predicates.ts@@ -1,7 +1,5 @@import {type EntityData,- getCompanyOwnerId,- getCompanyStageOptionId,getTaskAssigneeIds,getTaskStatusOptionId,isGithubPrEntity,@@ -13,7 +11,6 @@ import {import { getTaskPriorityOptionId } from '@entity/utils/task-properties';import { compositeEntity, type NotificationSource } from '@notifications';import { PROPERTY_OPTION_IDS } from '@property/constants';-import { NO_ASSIGNEE, NO_STAGE } from './configs/base';function getPredicateNotifications(entity: EntityData,@@ -141,10 +138,6 @@ export function calendarEventFilter(entity: EntityData): boolean {return entity.type === 'calendar_event';}-export function crmCompanyFilter(entity: EntityData): boolean {- return entity.type === 'crm_company';-}-export function remindersFilter(entity: EntityData): boolean {return entity.type === 'reminder';}@@ -204,57 +197,6 @@ export function searchSupportedFilter(entity: EntityData): boolean {);}-export function crmCompanyActiveFilter(entity: EntityData): boolean {- return entity.type === 'crm_company' && !entity.hidden;-}--export function crmCompanyHiddenFilter(entity: EntityData): boolean {- return entity.type === 'crm_company' && entity.hidden;-}--/**- * Stage filter for companies, driven by the view's stage selection- * (`ctx.stages`). `NO_STAGE` matches companies without a Stage set. Stage- * resolution goes through `resolveStage` (the team's active deal-stage- * set, from `ctx.resolveCompanyStage`) when supplied, so the filter- * buckets companies exactly like the kanban — legacy system-stage values- * included; otherwise it falls back to the raw system Stage value.- */-export function companyStageFilter(- stageIds: () => string[] | undefined,- resolveStage?: (entity: EntityData) => string | undefined-) {- return (entity: EntityData): boolean => {- const stages = stageIds();- if (!stages?.length) return true;- if (entity.type !== 'crm_company') return false;- const stageId = resolveStage- ? resolveStage(entity)- : getCompanyStageOptionId(entity);- return stages.some((id) =>- id === NO_STAGE ? stageId === undefined : stageId === id- );- };-}--/**- * Owner filter for companies, driven by the view's owner selection- * (`ctx.owners`). `NO_OWNER` matches companies without an Owner set.- */-export function companyOwnedByUsersFilter(- ownerIds: () => string[] | undefined-) {- return (entity: EntityData): boolean => {- const owners = ownerIds();- if (!owners?.length) return true;- if (entity.type !== 'crm_company') return false;- const ownerId = getCompanyOwnerId(entity);- return owners.some((id) =>- id === NO_ASSIGNEE ? ownerId === undefined : ownerId === id- );- };-}-export function filesAndFolderFilter(entity: EntityData): boolean {if (entity.type !== 'project' && entity.type !== 'document') return false;diff --git a/apps/web/src/features/next-soup/sidebar/soup-filter-presets.ts b/apps/web/src/features/next-soup/sidebar/soup-filter-presets.tsindex 211edd18c2..b3e0367531 100644--- a/apps/web/src/features/next-soup/sidebar/soup-filter-presets.ts+++ b/apps/web/src/features/next-soup/sidebar/soup-filter-presets.ts@@ -17,6 +17,7 @@ import {import { PROPERTY_OPTION_IDS, SYSTEM_PROPERTY_IDS } from '@property/constants';import type { Params } from '@service-storage/generated/schemas/params';import { startOfDay, subWeeks } from 'date-fns';+import { CRM_TAB_PRESETS } from '../../crm/collection-presets';type SoupFiltersPreset = {/** Filter data for server query */@@ -57,7 +58,7 @@ type TabPresetResolver = (ctx: PresetContext) => SoupFiltersPreset | undefined;type TabConfig = Record<string, TabPresetResolver>;-type ViewTabConfig = {+export type ViewTabConfig = {default: string;tabs: TabConfig;};@@ -529,33 +530,7 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {}),},},- companies: {- default: 'active',- tabs: {- active: () => ({- filters: defineQueryFilters(- { include: { crmCompanyHidden: false } },- { skipTargets: ['ccf'] }- ),- clientFilters: { and: ['crm-company-active'] },- groupBy: `property:${SYSTEM_PROPERTY_IDS.STAGE}`,- }),- // Admin/owner only — the BE rejects `hidden: true` requests from- // non-admins with 403. Returning `undefined` hides the tab for- // non-admins via the same pattern context-required views use.- hidden: (ctx) => {- if (!ctx.isTeamAdmin) return undefined;- return {- filters: defineQueryFilters(- { include: { crmCompanyHidden: true } },- { skipTargets: ['ccf'] }- ),- clientFilters: { and: ['crm-company-hidden'] },- groupBy: `property:${SYSTEM_PROPERTY_IDS.STAGE}`,- };- },- },- },+ companies: CRM_TAB_PRESETS,folders: {default: 'owned',tabs: {diff --git a/apps/web/src/features/next-soup/soup-view/collection-select-filter.ts b/apps/web/src/features/next-soup/soup-view/collection-select-filter.tsnew file mode 100644index 0000000000..3c7cf71188--- /dev/null+++ b/apps/web/src/features/next-soup/soup-view/collection-select-filter.ts@@ -0,0 +1,18 @@+import type { Accessor } from 'solid-js';+import type { FilterValue } from './filters-bar/consolidated-filter-chip';+import type { SearchableOption } from './filters-bar/searchable-multi-select';+export type CollectionSelectFilter = {+ id: string;+ label: string;+ placeholder: string;+ values: Accessor<string[]>;+ effectiveValues: Accessor<string[]>;+ options: Accessor<SearchableOption[]>;+ chipOptions: Accessor<SearchableOption[]>;+ chipValues: Accessor<FilterValue[]>;+ change(ids: string[]): void;+ changeChip(ids: string[]): void;+ clear(): void;+ active?: Accessor<boolean>;+ preserveOrder?: boolean;+};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.tsxindex 935a4315d7..aaa381de55 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@@ -6,13 +6,11 @@ import {useCreatableEnabled,} from '@app/features/command/Launcher';import { openNewChannelModal } from '@channel/CreateChannelModal';-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';import EmptyStateCallsGraphic from '@design/empty-state-calls.svg';import EmptyStateChannelsGraphic from '@design/empty-state-channels.svg';-import EmptyStateCompaniesGraphic from '@design/empty-state-companies.svg';import EmptyStateDocGraphic from '@design/empty-state-doc.svg';import EmptyStateEmailGraphic from '@design/empty-state-email.svg';import EmptyStateFolderGraphic from '@design/empty-state-folder.svg';@@ -22,7 +20,6 @@ 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 { FolderDropZone } from './FolderDropZone';@@ -96,6 +93,7 @@ const FALLBACK_CONTENT: Partial<Record<ListView, FallbackContent>> = {};export function EmptyState(props: {+ content?: JSXElement;listView?: ListView;search?: boolean;hasRefinementsFromBase?: boolean;@@ -105,19 +103,7 @@ export function EmptyState(props: {const emailActive = useEmailLinksStatus();const startAddInbox = useAddInboxFlow();const soup = useSoupView();- const teamQuery = useCurrentTeamQuery();const isCreatableEnabled = useCreatableEnabled();- 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. A user- // with no team at all (data resolves to null) is pointed to team settings- // instead, since CRM can only be enabled on a team. Branches wait for the- // query to resolve so enabled teams don't flash the disabled copy.- const teamResolved = () => teamQuery.data !== undefined;- const crmEnabled = () => teamQuery.data?.team.crm_enabled ?? false;- const hasNoTeam = () => teamQuery.data === null;const onConnectEmail = () => {void startAddInbox();@@ -155,6 +141,8 @@ export function EmptyState(props: {</EmptyStatePanel></Match>+ <Match when={props.content}>{props.content}</Match>+{/* The Reminders tab is not an email surface, so it sits above theconnect-email gate — its empty copy is the same with or without alinked inbox. */}@@ -323,65 +311,6 @@ export function EmptyState(props: {/></Match>- <Match when={props.listView === 'companies'}>- <Switch>- {/* Render nothing until the team query resolves — showing a wrong- panel for a moment is worse than a brief blank. */}- <Match when={!teamResolved()}>{null}</Match>- <Match when={hasNoTeam()}>- <EmptyStatePanel- centered- graphic={EmptyStateCompaniesGraphic}- title="Join a team to enable CRM"- description="Create or join a team in Settings > Team."- primaryAction={{- label: 'Open team settings',- onClick: () => openSettings('Team'),- }}- />- </Match>- <Match when={!crmEnabled()}>- <EmptyStatePanel- centered- 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- }- />- </Match>- <Match when={true}>- <EmptyStatePanel- graphic={EmptyStateCompaniesGraphic}- title={- !soup.activeTab() || soup.activeTab() === 'active'- ? 'No customers yet'- : soup.activeTab()?.startsWith('list:')- ? 'No companies in this list'- : 'No companies in this view'- }- description={- !soup.activeTab() || soup.activeTab() === 'active'- ? 'Customers your team emails will appear here.'- : soup.activeTab()?.startsWith('list:')- ? 'Use Edit list to add companies to this collection.'- : 'Companies that match this view will appear here.'- }- />- </Match>- </Switch>- </Match>-<Matchwhen={props.listView === 'folders' ||diff --git a/apps/web/src/features/next-soup/soup-view/filters-bar/soup-filters-bar.tsx b/apps/web/src/features/next-soup/soup-view/filters-bar/soup-filters-bar.tsxindex cfe8cff8f4..8b4ee3f951 100644--- a/apps/web/src/features/next-soup/soup-view/filters-bar/soup-filters-bar.tsx+++ b/apps/web/src/features/next-soup/soup-view/filters-bar/soup-filters-bar.tsx@@ -4,15 +4,8 @@ import { SoupViewContextGroup } from '@app/features/next-soup/soup-view/filters-import { SoupViewContextSort } from '@app/features/next-soup/soup-view/filters-bar/soup-view-context-sort';import { UnifiedFilterDropdown } from '@app/features/next-soup/soup-view/filters-bar/unified-filter-dropdown';import { useFilterRefinements } from '@app/features/next-soup/soup-view/filters-bar/use-filter-refinements';-import {- CompanyDisplayMenu,- CompanyViewsMenu,-} from '@app/features/next-soup/soup-view/views/companies/CompanyViewsMenu';import { CollapsibleToolbarItem } from '@components/app/split-layout/components/CollapsibleItem';-import {- SplitToolbarLeft,- SplitToolbarRight,-} from '@components/app/split-layout/components/SplitToolbar';+import { SplitToolbarLeft } from '@components/app/split-layout/components/SplitToolbar';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { createMemo, createSignal, Show } from 'solid-js';@@ -29,10 +22,6 @@ export function SoupFiltersBar(props: { variant?: 'default' | 'tag' }) {const content = panel.handle.content();return content.type === 'component' && content.id === 'search';});- const isCompaniesView = createMemo(() => {- const content = panel.handle.content();- return content.type === 'component' && content.id === 'companies';- });const isTagView = createMemo(() => props.variant === 'tag');// The inbox hides sort (it's fixed to updated_at for this view).@@ -78,18 +67,8 @@ export function SoupFiltersBar(props: { variant?: 'default' | 'tag' }) {</Show><CollapsibleGroup /><CollapsibleFilter />- <Show when={isCompaniesView()}>- <CompanyDisplayMenu />- </Show></Show></SplitToolbarLeft>- <SplitToolbarRight>- <Show when={isCompaniesView()}>- <CollapsibleToolbarItem id="soup-toolbar-views" priority={2}>- {(isCollapsed) => <CompanyViewsMenu hideLabel={isCollapsed()} />}- </CollapsibleToolbarItem>- </Show>- </SplitToolbarRight>{/* Active filters bar - shown below the toolbar when there are filters */}<Show when={!isSearchView() && !isTagView()}><SoupActiveFiltersBardiff --git a/apps/web/src/features/next-soup/soup-view/filters-bar/soup-view-context-group.tsx b/apps/web/src/features/next-soup/soup-view/filters-bar/soup-view-context-group.tsxindex 11f26b494b..36ce2aefbd 100644--- a/apps/web/src/features/next-soup/soup-view/filters-bar/soup-view-context-group.tsx+++ b/apps/web/src/features/next-soup/soup-view/filters-bar/soup-view-context-group.tsx@@ -1,7 +1,6 @@import type { ListView } from '@app/constants/list-views';import { GroupDropdown } from '@app/features/next-soup/soup-view/filters-bar/group-dropdown';import {- COMPANY_GROUP_OPTIONS,type GroupOptionId,TAG_VIEW_GROUP_OPTIONS,TASK_GROUP_OPTIONS,@@ -14,7 +13,7 @@ import { createMemo, createSignal, Show } from 'solid-js';export const SoupViewContextGroup = (props: { hideLabel?: boolean }) => {const panel = useSplitPanelOrThrow();- const { soup, viewMode } = useSoupView();+ const { soup, extensions } = useSoupView();const groupByEnabled = useFeatureFlag(enableSoupGroupBy);const [groupOpen, setGroupOpen] = createSignal(false);@@ -57,11 +56,11 @@ export const SoupViewContextGroup = (props: { hideLabel?: boolean }) => {</Show>{/* The board is inherently grouped by stage columns, so grouping onlyapplies to the list mode. */}- <Show when={isComponentListView('companies') && viewMode() === 'list'}>+ <Show when={extensions?.groupOptions?.visible()}><GroupDropdownvalue={value}onChange={onChange}- options={COMPANY_GROUP_OPTIONS}+ options={extensions?.groupOptions?.options ?? []}open={groupOpen()}onOpenChange={setGroupOpen}hideLabel={props.hideLabel}diff --git a/apps/web/src/features/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx b/apps/web/src/features/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsxindex 759bc6db8d..8c93cc4b10 100644--- a/apps/web/src/features/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx+++ b/apps/web/src/features/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx@@ -3,7 +3,6 @@ import { isListViewID, TAGGABLE_LIST_VIEWS } from '@app/constants/list-views';import {type FilterContext,NO_ASSIGNEE,- NO_STAGE,} from '@app/features/next-soup/filters/configs/';import {buildDocumentTypeQuery,@@ -21,22 +20,18 @@ import {type ReadFilter,useSoupView,} from '@app/features/next-soup/soup-view/soup-view-context';-import { useDealStages } from '@companies/crm/deal-stages';-import { CrmStageIcon } from '@companies/crm/StageIcon';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { EntityIcon } from '@core/component/EntityIcon';import { UserIcon } from '@core/component/UserIcon';import { useUserId } from '@core/context/user';import { registerHotkey } from '@core/hotkey/hotkeys';import { TOKENS } from '@core/hotkey/tokens';-import { idToDisplayName } from '@core/user/util';import CircleDashedIcon from '@phosphor/circle-dashed.svg';import FilterIcon from '@phosphor/funnel-simple.svg';import { PropertyValueIcon } from '@property/component/propertyValue/PropertyValueIcon';import { PROPERTY_OPTION_IDS, SYSTEM_PROPERTY_IDS } from '@property/constants';import { useGithubLinkStatusQuery } from '@queries/auth';import { useContacts } from '@queries/contacts/contacts';-import { useCurrentTeamQuery } from '@queries/team/teams';import { cn, Dropdown, Tooltip } from '@ui';import {type Accessor,@@ -431,18 +426,13 @@ export const UnifiedFilterDropdown = (queryFilters,assigneeFilter,setAssigneeFilter,- ownerFilter,- setOwnerFilter,- stageFilter,- setStageFilter,activeTab,readFilter,setReadFilter,} = useSoupView();const contacts = useContacts();- const teamQuery = useCurrentTeamQuery();const userId = useUserId();- const dealStages = useDealStages();+ const selectFilters = useSoupView().extensions?.selectFilters ?? [];const currentView = createMemo((): ListView | undefined => {const content = panel.handle.content();@@ -603,99 +593,6 @@ export const UnifiedFilterDropdown = (});};- // Owner options for the Customers view (team members, plus a "No owner"- // row) — company owners are always teammates, so the broader contacts- // list (anyone ever interacted with) would mostly be noise here.- const ownerOptions = createMemo((): SearchableOption[] => {- const currentUserId = userId();- const noOwnerOption: SearchableOption = {- id: NO_ASSIGNEE,- label: 'No owner',- icon: () => <CircleDashedIcon class="size-3.5 text-ink-muted" />,- };- let meOption: SearchableOption | undefined;- const memberOptions: SearchableOption[] = [];- for (const member of teamQuery.data?.members ?? []) {- const id = member.user_id;- const opt: SearchableOption = {- id,- label: buildContactLabel(- { id, name: idToDisplayName(id) },- currentUserId- ),- icon: () => (- <UserIcon id={id} size="sm" suppressClick showTooltip={false} />- ),- };- if (id === currentUserId) {- meOption = opt;- } else {- memberOptions.push(opt);- }- }- memberOptions.sort((a, b) => a.label.localeCompare(b.label));- return [...(meOption ? [meOption] : []), noOwnerOption, ...memberOptions];- });-- // Owner filtering is a client-side predicate (companies come back from a- // dedicated capped CRM request), so no query filters to maintain here.- const handleOwnerChange = (ids: string[]) => {- batch(() => {- setOwnerFilter(ids);- const shouldBeActive = ids.length > 0;- if (shouldBeActive !== soup.predicates.isActive('company-owner')) {- soup.predicates.toggle({ and: ['company-owner'] });- }- });- };-- // Stage options for the Customers view: the team's active deal-stage set- // (plus retired legacy stages on the default set) and a trailing- // "No stage" row.- const stageOptions = createMemo((): SearchableOption[] => [- ...dealStages.filterStages().map((stage, index) => ({- id: stage.id,- label: stage.label,- icon: () => (- <CrmStageIcon optionId={stage.id} index={index} class="size-3.5" />- ),- })),- {- id: NO_STAGE,- label: 'No stage',- icon: () => <CircleDashedIcon class="size-3.5 text-ink-muted" />,- },- ]);-- // The stage set shown when no filter is active: the active deal stages- // plus "No stage" — retired legacy stages only display when filtered in.- const defaultStageIds = createMemo(- () => new Set([...dealStages.stages().map((stage) => stage.id), NO_STAGE])- );-- // The stage submenu reflects what's on screen: an empty filter shows the- // default columns, so exactly those read as checked (legacy stages don't).- const effectiveStageFilter = () =>- stageFilter().length > 0 ? stageFilter() : [...defaultStageIds()];-- // Stage filtering is a client-side predicate, mirroring the owner filter.- const handleStageChange = (ids: string[]) => {- // Checking exactly the default set is the same as no filter — store it- // as empty so the predicate deactivates.- const next =- ids.length === defaultStageIds().size &&- ids.every((id) => defaultStageIds().has(id))- ? []- : ids;- batch(() => {- setStageFilter(next);- const shouldBeActive = next.length > 0;- if (shouldBeActive !== soup.predicates.isActive('company-stage')) {- soup.predicates.toggle({ and: ['company-stage'] });- }- });- };-const isTasksView = () => currentView() === 'tasks';const isDocumentsView = () => currentView() === 'documents';const isCreatedByFilterView = () => {@@ -704,7 +601,6 @@ export const UnifiedFilterDropdown = (};const showCreatedByFilter = () =>isCreatedByFilterView() && !(isDocumentsView() && activeTab() === 'owned');- const isCompaniesView = () => currentView() === 'companies';// The Files "Owned" tab has a creator constraint as part of its base// preset. Keep that constraint when a user clears an explicit Created by@@ -805,7 +701,7 @@ export const UnifiedFilterDropdown = (when={categories().length > 0 ||isTasksView() ||- isCompaniesView() ||+ selectFilters.length > 0 ||isHomeView() ||showTagsFilter()}@@ -848,7 +744,7 @@ export const UnifiedFilterDropdown = (categories().length === 1 &&!isDocumentsView() &&!isTasksView() &&- !isCompaniesView() &&+ selectFilters.length === 0 &&!isHomeView()}fallback={@@ -896,25 +792,19 @@ export const UnifiedFilterDropdown = (/></Show>- {/* Stage + Owner filters for the Customers view */}- <Show when={isCompaniesView()}>- <SearchableFilterSubmenu- label="Stage"- active={stageFilter().length > 0}- options={stageOptions}- activeIds={effectiveStageFilter}- onChange={handleStageChange}- placeholder="Filter stages..."- preserveOrder- />- <SearchableFilterSubmenu- label="Owner"- options={ownerOptions}- activeIds={ownerFilter}- onChange={handleOwnerChange}- placeholder="Search owners..."- />- </Show>+ <For each={selectFilters}>+ {(filter) => (+ <SearchableFilterSubmenu+ label={filter.label}+ active={filter.active?.()}+ options={filter.options}+ activeIds={filter.effectiveValues}+ onChange={filter.change}+ placeholder={filter.placeholder}+ preserveOrder={filter.preserveOrder}+ />+ )}+ </For></>}>diff --git a/apps/web/src/features/next-soup/soup-view/filters-bar/use-filter-refinements.tsx b/apps/web/src/features/next-soup/soup-view/filters-bar/use-filter-refinements.tsxindex 5753563d63..d02ee4caad 100644--- a/apps/web/src/features/next-soup/soup-view/filters-bar/use-filter-refinements.tsx+++ b/apps/web/src/features/next-soup/soup-view/filters-bar/use-filter-refinements.tsx@@ -4,7 +4,6 @@ import {type FilterContext,type FilterID,NO_ASSIGNEE,- NO_STAGE,} from '@app/features/next-soup/filters';import {buildDocumentTypeQuery,@@ -22,8 +21,6 @@ import {VIEW_TAB_PRESETS,} from '@app/features/next-soup/sidebar/soup-filter-presets';import { useSoupView } from '@app/features/next-soup/soup-view/soup-view-context';-import { useDealStages } from '@companies/crm/deal-stages';-import { CrmStageIcon } from '@companies/crm/StageIcon';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { UserIcon } from '@core/component/UserIcon';import { useUserContext, useUserId } from '@core/context/user';@@ -79,10 +76,6 @@ export function useFilterRefinements() {queryFilters,assigneeFilter,setAssigneeFilter,- ownerFilter,- setOwnerFilter,- stageFilter,- setStageFilter,activeTab,} = useSoupView();const filterData = () => queryFilters.state;@@ -91,7 +84,7 @@ export function useFilterRefinements() {const contacts = useContacts();const currentUserId = useUserId();const tagFilter = useTagFilter();- const dealStages = useDealStages();+ const selectFilters = useSoupView().extensions?.selectFilters ?? [];const getPresetContext = (): PresetContext => ({userId: user.userId(),@@ -146,8 +139,7 @@ export function useFilterRefinements() {const hasSubFilters =assigneeFilter().length > 0 ||- ownerFilter().length > 0 ||- stageFilter().length > 0;+ selectFilters.some((filter) => filter.values().length > 0);return hasClientFilterDiff || hasQueryFilterDiff || hasSubFilters;});@@ -222,72 +214,6 @@ export function useFilterRefinements() {];});- /**- * Owner options for the Customers view's owner sub-filter, keyed by id.- */- const ownerOptionsMap = createMemo(- (): Map<string, { label: string; icon?: () => JSX.Element }> => {- const uid = currentUserId();- const map = new Map<- string,- { label: string; icon?: () => JSX.Element }- >();- map.set(NO_ASSIGNEE, {- label: 'No owner',- icon: () => <CircleDashedIcon class="size-3 text-ink-muted" />,- });- for (const contact of contacts()) {- map.set(contact.id, {- label: buildContactLabel(contact, uid),- icon: () => (- <UserIcon- id={contact.id}- size="sm"- suppressClick- showTooltip={false}- />- ),- });- }- return map;- }- );-- const ownerSearchableOptions = createMemo((): SearchableOption[] => {- const uid = currentUserId();- const noOwnerOption: SearchableOption = {- id: NO_ASSIGNEE,- label: 'No owner',- icon: () => <CircleDashedIcon class="size-3.5 text-ink-muted" />,- };- let meOption: SearchableOption | undefined;- const otherContactOptions: SearchableOption[] = [];- for (const contact of contacts()) {- const opt: SearchableOption = {- id: contact.id,- label: buildContactLabel(contact, uid),- icon: () => (- <UserIcon- id={contact.id}- size="sm"- suppressClick- showTooltip={false}- />- ),- };- if (contact.id === uid) {- meOption = opt;- } else {- otherContactOptions.push(opt);- }- }- return [- ...(meOption ? [meOption] : []),- noOwnerOption,- ...otherContactOptions,- ];- });-/** Creator options for the Tasks and Files Created by filter. */const createdByOptionsMap = createMemo((): Map<string, { label: string; icon?: () => JSX.Element }> => {@@ -360,68 +286,6 @@ export function useFilterRefinements() {});};- /**- * Handler for owner filter changes (Customers view). Client-side- * predicate only — companies come back from a dedicated capped CRM- * request with no property filter support.- */- const handleOwnerChange = (ids: string[]) => {- batch(() => {- setOwnerFilter(ids);- const shouldBeActive = ids.length > 0;- if (shouldBeActive !== soup.predicates.isActive('company-owner')) {- soup.predicates.toggle({ and: ['company-owner'] });- }- });- };-- /**- * Stage options for the Customers view's stage sub-filter: the team's- * active deal-stage set (plus retired legacy stages on the default set)- * and a trailing "No stage" row.- */- const stageSearchableOptions = createMemo((): SearchableOption[] => [- ...dealStages.filterStages().map((stage, index) => ({- id: stage.id,- label: stage.label,- icon: () => (- <CrmStageIcon optionId={stage.id} index={index} class="size-3.5" />- ),- })),- {- id: NO_STAGE,- label: 'No stage',- icon: () => <CircleDashedIcon class="size-3.5 text-ink-muted" />,- },- ]);-- const stageOptionsMap = createMemo(- (): Map<string, { label: string; icon?: () => JSX.Element }> => {- const map = new Map<- string,- { label: string; icon?: () => JSX.Element }- >();- for (const option of stageSearchableOptions()) {- map.set(option.id, { label: option.label, icon: option.icon });- }- return map;- }- );-- /**- * Handler for stage filter changes (Customers view). Client-side- * predicate only, mirroring the owner filter.- */- const handleStageChange = (ids: string[]) => {- batch(() => {- setStageFilter(ids);- const shouldBeActive = ids.length > 0;- if (shouldBeActive !== soup.predicates.isActive('company-stage')) {- soup.predicates.toggle({ and: ['company-stage'] });- }- });- };-/*** Handler for assignee filter changes.*/@@ -872,109 +736,44 @@ export function useFilterRefinements() {);};- // Owner filter (consolidated) for the Customers view.- const pushOwnerConsolidatedChip = () => {- if (view !== 'companies') return;- const key = 'owner';- const popupOpen =- consolidatedChipCache.get(key)?.isPopupOpen?.() ?? false;- const ids = ownerFilter();- if (ids.length === 0 && !popupOpen) return;-- seenKeys.add(key);-- const getValues = (): FilterValue[] =>- ownerFilter().map((id) => {- const opt = ownerOptionsMap().get(id);- return {- id,- label: opt?.label ?? id,- icon: opt?.icon,- };- });-- filters.push(- getOrCreateConsolidatedChip(key, () => {- const [isPopupOpen, _setPopupOpen] = createSignal(false);- const setPopupOpen = (v: boolean) => {- if (!v) {- queueMicrotask(() =>- panel.panelRef()?.focus({ preventScroll: true })- );- }- _setPopupOpen(v);- };- return {- key,- categoryLabel: 'Owner',- values: getValues,- searchableOptions: ownerSearchableOptions,- activeSearchableIds: ownerFilter,- onSearchableChange: handleOwnerChange,- searchPlaceholder: 'Search owners...',- isPopupOpen,- setPopupOpen,- onRemoveAll: () => handleOwnerChange([]),- };- })- );- };-- // Stage filter (consolidated) for the Customers view.- const pushStageConsolidatedChip = () => {- if (view !== 'companies') return;- const key = 'stage';- const popupOpen =- consolidatedChipCache.get(key)?.isPopupOpen?.() ?? false;- const ids = stageFilter();- if (ids.length === 0 && !popupOpen) return;-- seenKeys.add(key);-- const getValues = (): FilterValue[] =>- stageFilter().map((id) => {- const opt = stageOptionsMap().get(id);- return {- id,- label: opt?.label ?? id,- icon: opt?.icon,- };- });-- filters.push(- getOrCreateConsolidatedChip(key, () => {- const [isPopupOpen, _setPopupOpen] = createSignal(false);- const setPopupOpen = (v: boolean) => {- if (!v) {- queueMicrotask(() =>- panel.panelRef()?.focus({ preventScroll: true })- );- }- _setPopupOpen(v);- };- return {- key,- categoryLabel: 'Stage',- values: getValues,- searchableOptions: stageSearchableOptions,- activeSearchableIds: stageFilter,- onSearchableChange: handleStageChange,- searchPlaceholder: 'Filter stages...',- // Stages read as a pipeline — keep canonical order, don't pin- // checked ones to the top.- preserveOptionOrder: true,- isPopupOpen,- setPopupOpen,- onRemoveAll: () => handleStageChange([]),- };- })- );+ const pushSelectFilterChips = () => {+ for (const filter of selectFilters) {+ const key = filter.id;+ const popupOpen =+ consolidatedChipCache.get(key)?.isPopupOpen?.() ?? false;+ if (filter.values().length === 0 && !popupOpen) continue;+ seenKeys.add(key);+ filters.push(+ getOrCreateConsolidatedChip(key, () => {+ const [isPopupOpen, _setPopupOpen] = createSignal(false);+ const setPopupOpen = (v: boolean) => {+ if (!v)+ queueMicrotask(() =>+ panel.panelRef()?.focus({ preventScroll: true })+ );+ _setPopupOpen(v);+ };+ return {+ key,+ categoryLabel: filter.label,+ values: filter.chipValues,+ searchableOptions: filter.chipOptions,+ activeSearchableIds: filter.values,+ onSearchableChange: filter.changeChip,+ searchPlaceholder: filter.placeholder,+ preserveOptionOrder: filter.preserveOrder,+ isPopupOpen,+ setPopupOpen,+ onRemoveAll: () => filter.changeChip([]),+ };+ })+ );+ }};pushAssigneeConsolidatedChip();pushCreatedByConsolidatedChip();- pushStageConsolidatedChip();- pushOwnerConsolidatedChip();+ pushSelectFilterChips();pushTagsConsolidatedChip();// Evict stale chips@@ -1090,8 +889,7 @@ export function useFilterRefinements() {soup.predicates.set(preset.clientFilters);queryFilters.replace(preset.filters ?? null);setAssigneeFilter([]);- setOwnerFilter([]);- setStageFilter([]);+ for (const filter of selectFilters) filter.clear();});};diff --git a/apps/web/src/features/next-soup/soup-view/group-options.ts b/apps/web/src/features/next-soup/soup-view/group-options.tsindex a945490545..329841d9e1 100644--- a/apps/web/src/features/next-soup/soup-view/group-options.ts+++ b/apps/web/src/features/next-soup/soup-view/group-options.ts@@ -55,12 +55,6 @@ export const TASK_GROUP_OPTIONS: GroupOption[] = [{ value: 'date', label: 'Date' },];-export const COMPANY_GROUP_OPTIONS: GroupOption[] = [- { value: 'none', label: 'None' },- { value: `property:${SYSTEM_PROPERTY_IDS.STAGE}`, label: 'Stage' },- { value: `property:${SYSTEM_PROPERTY_IDS.COMPANY_OWNER}`, label: 'Owner' },-];-export const TAG_VIEW_GROUP_OPTIONS: GroupOption[] = [{ value: 'none', label: 'None' },{ value: 'entity_type', label: 'Type' },diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsxindex 1dcb344581..423c1e9795 100644--- a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx+++ b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx@@ -44,7 +44,6 @@ import { deduplicateEntities } from '@app/features/next-soup/utils';import { withEntityNotifications } from '@app/features/soup/entity-notifications';import { useFeatureFlag } from '@app/lib/analytics/posthog';import { makeFlaggedPersisted } from '@app/preferences/make-flagged-persisted';-import { useDealStages } from '@companies/crm/deal-stages';import { useGlobalNotificationSource } from '@components/app/GlobalAppState';import { useEntryState } from '@components/app/split-layout/entry-state';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';@@ -61,15 +60,12 @@ import {NATIVE_OFFLINE_ERROR_MESSAGE,nativeNetworkStatus,} from '@core/mobile/native-network-status';-import { idToDisplayName } from '@core/user/util';import {- COMPANY_STAGE_OPTIONS,type EntityData,getPropertyOptionLabel,isWithNotification,unreadFilterFn,} from '@entity';-import { SYSTEM_PROPERTY_IDS } from '@property/constants';import { useQueryClient } from '@queries/client';import { invalidateUserNotifications } from '@queries/notification/user-notifications';import { createGroupedSoupQueries } from '@queries/soup/grouped/create-grouped-soup-queries';@@ -167,7 +163,8 @@ export type ReadFilter = 'all' | 'unread' | 'read';/** List/board display mode — currently only the Customers view offers a board. */export type SoupViewMode = 'list' | 'board';-interface SoupViewContextValues {+export interface SoupViewContextValues {+ extensions?: CollectionExtensions;soup: SoupState;initialize: (options?: SoupViewInitializeOptions) => void;source: DataSource<EntityData>;@@ -187,10 +184,6 @@ interface SoupViewContextValues {filterByTag: (optionId: string) => void;assigneeFilter: Accessor<string[]>;setAssigneeFilter: Setter<string[]>;- ownerFilter: Accessor<string[]>;- setOwnerFilter: Setter<string[]>;- stageFilter: Accessor<string[]>;- setStageFilter: Setter<string[]>;inboxFilter: Accessor<string[] | undefined>;setInboxFilter: Setter<string[] | undefined>;activeTab: Accessor<string | undefined>;@@ -199,8 +192,6 @@ interface SoupViewContextValues {* it has one the client can reproduce, else the sort state. */clientSort: Accessor<SortConfig<SoupEntity>[]>;getPersistedActiveTab: (view: ListView) => string | undefined;- viewMode: Accessor<SoupViewMode>;- setViewMode: Setter<SoupViewMode>;readFilter: Accessor<ReadFilter>;setReadFilter: Setter<ReadFilter>;groupByField: Accessor<GroupByField | undefined>;@@ -225,9 +216,27 @@ export const useSoupView = () => {export const useMaybeSoupView = () => useContext(SoupViewContext);-interface SoupViewContextProviderProps extends SoupViewInitializeOptions {+/** Optional policies supplied by the owning collection surface. */+export type CollectionExtensions = {+ propertyGrouping?: {+ value(entity: EntityData, definitionId: string): string | undefined;+ label(value: string, definitionId: string): string | undefined;+ order(definitionId: string): readonly string[];+ };+ filterContext?: () => Partial<FilterContext>;+ selectFilters?: import('./collection-select-filter').CollectionSelectFilter[];+ groupOptions?: {+ visible: Accessor<boolean>;+ options: import('./group-options').GroupOption[];+ };+};++export interface SoupViewContextProviderProps+ extends SoupViewInitializeOptions {+ extensions?: CollectionExtensions;soup?: SoupState;initialEnabled?: boolean;+ filterPersistence?: Accessor<boolean>;}type PersistedQueryFilters = Partial<@@ -316,9 +325,7 @@ function nativeOfflineLoadError(hasData: () => boolean): Error | null {: null;}-export const SoupViewContextProvider: FlowComponent<- SoupViewContextProviderProps-> = (props) => {+export const createSoupViewState = (props: SoupViewContextProviderProps) => {const soup = props.soup ?? createSoupState();const [enabled, setEnabled] = createSignal(props.initialEnabled ?? false);const [config, setConfig] = createSignal<SoupViewInitializeOptions>({@@ -334,7 +341,9 @@ export const SoupViewContextProvider: FlowComponent<});const queryClient = useQueryClient();- const [persistFilterPreference] = useSoupFilterPersistence();+ const [persistFilterPreference] = props.filterPersistence+ ? [props.filterPersistence]+ : useSoupFilterPersistence();const filterPersistenceEnabled = () =>config().persistFilters !== false && persistFilterPreference();@@ -501,20 +510,6 @@ export const SoupViewContextProvider: FlowComponent<name: soupViewPersistenceKey('soup-view-assignee-filter'),});- const [ownerFilter, setOwnerFilter] = makeFlaggedPersisted(- useEntryState<string[]>('soup.ownerFilter', { default: [] }),- {- enabled: filterPersistenceEnabled,- name: soupViewPersistenceKey('soup-view-owner-filter'),- }- );- const [stageFilter, setStageFilter] = makeFlaggedPersisted(- useEntryState<string[]>('soup.stageFilter', { default: [] }),- {- enabled: filterPersistenceEnabled,- name: soupViewPersistenceKey('soup-view-stage-filter'),- }- );const [inboxFilter, setInboxFilter] = makeFlaggedPersisted(useEntryState<string[] | undefined>(INBOX_FILTER_ENTRY_KEY, {default: undefined,@@ -614,11 +609,6 @@ export const SoupViewContextProvider: FlowComponent<}));- // List/board display mode — per-entry state so back/forward restores the- // mode the user left each entry with.- const [viewMode, setViewMode] = useEntryState<SoupViewMode>('soup.viewMode', {- default: isTouchDevice() ? 'list' : 'board',- });const [readFilter, setReadFilter] = makeFlaggedPersisted(useEntryState<ReadFilter>('soup.readFilter', { default: 'all' }),{@@ -659,17 +649,6 @@ export const SoupViewContextProvider: FlowComponent<}});- // Clear the owner/stage sub-filters when leaving the CRM company presets- createEffect(() => {- if (- !soup.predicates.isActive('crm-company-active') &&- !soup.predicates.isActive('crm-company-hidden')- ) {- setOwnerFilter([]);- setStageFilter([]);- }- });-const notificationSource = useGlobalNotificationSource();const userId = useUserId();const isTeamAdmin = useIsTeamAdmin();@@ -731,25 +710,10 @@ export const SoupViewContextProvider: FlowComponent<: soup.sort.active());- // Active deal-stage set (team-customized when present). Drives the- // Customers view's stage grouping, stage filter and group labels.- const dealStages = useDealStages();-- // `resolveStage` takes the minimal company shape; widen it to any soup- // entity (non-companies resolve to undefined since they carry no stage).- const resolveCompanyStage = (entity: EntityData): string | undefined =>- dealStages.resolveStage(- entity as Parameters<typeof dealStages.resolveStage>[0]- );-- // CRM companies come back from a dedicated soup request (not the dynamic- // query the server-side grouped path is built on), so property grouping on- // the Customers view buckets client-side over the flat list — same approach- // as date grouping. `groupByField` stays populated so group headers can- // resolve icons/labels for the grouping property.const isClientPropertyGroup = createMemo(() =>- activeListView() === 'companies' && groupByField()?.type === 'property'+ !!props.extensions?.propertyGrouping &&+ groupByField()?.type === 'property');// The group-by actually sent to the backend (drives the grouped queries).@@ -938,10 +902,7 @@ export const SoupViewContextProvider: FlowComponent<userId: userId(),notificationSource,assignees: assigneeFilter(),- owners: ownerFilter(),- stages: stageFilter(),- resolveCompanyStage,- companyStageLabel: dealStages.stageLabel,+ ...props.extensions?.filterContext?.(),});// This is temporary while we are experimenting/handling@@ -1227,38 +1188,16 @@ export const SoupViewContextProvider: FlowComponent<const hasNextGroupPage = (groupKey: string) =>groupQueryFor(groupKey)?.hasNextPage() ?? false;- // True when grouping by the canonical Stage id (the "group by Stage"- // presets always use the system definition id, even when the team's own- // stage set is active).- const isStageGrouping = () => {- const field = groupByField();- return (- field?.type === 'property' &&- field.propertyDefinitionId === SYSTEM_PROPERTY_IDS.STAGE- );- };-- const isOwnerGrouping = () => {+ const resolveGroupLabel = (key: string): string | undefined => {const field = groupByField();+ const definitionId =+ field?.type === 'property' ? field.propertyDefinitionId : '';return (- field?.type === 'property' &&- field.propertyDefinitionId === SYSTEM_PROPERTY_IDS.COMPANY_OWNER+ props.extensions?.propertyGrouping?.label(key, definitionId) ??+ getPropertyOptionLabel(key));};- // Group-key → label, preferring the active deal-stage set for stage- // groupings (custom option ids are unknown to the static option table).- const resolveGroupLabel = (key: string): string | undefined => {- if (isStageGrouping()) {- return dealStages.stageLabel(key) ?? getPropertyOptionLabel(key);- }- // Owner group keys are user ids — resolve to the display name.- if (isOwnerGrouping()) {- return idToDisplayName(key) || undefined;- }- return getPropertyOptionLabel(key);- };-const buildGroupMeta = (group: ApiGroupMeta): GroupMeta => {const resolvedLabel = resolveGroupLabel(group.key) ?? group.label;return {@@ -1308,12 +1247,11 @@ export const SoupViewContextProvider: FlowComponent<field?.type === 'property' ? field.propertyDefinitionId : '';// Stage grouping resolves through the active deal-stage set so legacy// system-stage values land in the matching custom-stage bucket.- const isStage = definitionId === SYSTEM_PROPERTY_IDS.STAGE;const buckets = new Map<string, SoupEntity[]>();for (const entity of entities()) {- const key = isStage- ? (resolveCompanyStage(entity) ?? '')- : clientPropertyGroupKey(entity, definitionId);+ const key =+ props.extensions?.propertyGrouping?.value(entity, definitionId) ??+ clientPropertyGroupKey(entity, definitionId);const bucket = buckets.get(key);if (bucket) {bucket.push(entity);@@ -1322,9 +1260,8 @@ export const SoupViewContextProvider: FlowComponent<}}- const stageOrder = isStage- ? dealStages.stages().map((stage) => stage.id)- : COMPANY_STAGE_OPTIONS.map((o) => o.value as string);+ const stageOrder =+ props.extensions?.propertyGrouping?.order(definitionId) ?? [];const order = [...buckets.keys()].sort((a, b) => {if (a === '') return 1;if (b === '') return -1;@@ -1516,6 +1453,7 @@ export const SoupViewContextProvider: FlowComponent<nativeOfflineLoadError(searchSourceHasData);const context = {+ extensions: props.extensions,soup,initialize,source: {@@ -1606,18 +1544,12 @@ export const SoupViewContextProvider: FlowComponent<filterByTag,assigneeFilter,setAssigneeFilter,- ownerFilter,- setOwnerFilter,- stageFilter,- setStageFilter,inboxFilter,setInboxFilter,activeTab,setActiveTab,clientSort,getPersistedActiveTab,- viewMode,- setViewMode,readFilter,setReadFilter,groupByField,@@ -1626,13 +1558,28 @@ export const SoupViewContextProvider: FlowComponent<hasNextGroupPage,};+ return { context, rows: builtRows };+};++export const SoupViewStateProvider: FlowComponent<{+ state: ReturnType<typeof createSoupViewState>;+}> = (props) => (+ <SoupViewContext.Provider value={props.state.context}>+ {props.children}+ <Suspense>+ <SyncWithSoup soup={props.state.context.soup} rows={props.state.rows()} />+ </Suspense>+ </SoupViewContext.Provider>+);++export const SoupViewContextProvider: FlowComponent<+ SoupViewContextProviderProps+> = (props) => {+ const state = createSoupViewState(props);return (- <SoupViewContext.Provider value={context}>+ <SoupViewStateProvider state={state}>{props.children}- <Suspense>- <SyncWithSoup soup={soup} rows={builtRows()} />- </Suspense>- </SoupViewContext.Provider>+ </SoupViewStateProvider>);};diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsx b/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsxindex 177711e059..182efd4af0 100644--- a/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsx+++ b/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsx@@ -5,7 +5,7 @@ import {runCreateAction,useCreatableEnabled,} from '@app/features/command/Launcher';-import { openCreateCompanyModal } from '@app/features/companies/CreateCompanyModal';+import { openCreateCompanyModal } from '@app/features/crm/crm-create';import { useHandleFileUpload } from '@app/util/handleFileUpload';import { openNewChannelModal } from '@channel/CreateChannelModal';import { CollapsibleHeaderItem } from '@components/app/split-layout/components/CollapsibleItem';diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-tabs.tsx b/apps/web/src/features/next-soup/soup-view/soup-view-tabs.tsxindex 6975083fd2..104080c7f5 100644--- a/apps/web/src/features/next-soup/soup-view/soup-view-tabs.tsx+++ b/apps/web/src/features/next-soup/soup-view/soup-view-tabs.tsx@@ -14,10 +14,7 @@ import {import { useSoup } from '@app/features/next-soup/soup-context';import { MobileFilterDrawer } from '@app/features/next-soup/soup-view/filters-bar/mobile-filter-drawer';import { MobileSearchFilterDrawer } from '@app/features/next-soup/soup-view/filters-bar/search/mobile-search-filter-drawer';-import {- type SoupViewMode,- useSoupView,-} from '@app/features/next-soup/soup-view/soup-view-context';+import { useSoupView } from '@app/features/next-soup/soup-view/soup-view-context';import {type TabbedListView,VIEW_TAB_LISTS,@@ -31,15 +28,7 @@ import { TabsInsetDropdown } from '@core/component/TabsInsetDropdown';import { enableReminders } from '@core/constant/featureFlags';import { useUserContext } from '@core/context/user';import { useIsTeamAdmin } from '@queries/team/teams';-import {- batch,- createMemo,- For,- type JSX,- Match,- Show,- Switch,-} from 'solid-js';+import { batch, createMemo, For, Match, Switch } from 'solid-js';const useCurrentListView = () => {const panel = useSplitPanelOrThrow();@@ -212,9 +201,6 @@ export const SoupViewTabs = () => {return (<Switch>- <Match when={listView() === 'companies'}>- <CompanyModeTabs />- </Match><For each={Object.keys(VIEW_TAB_LISTS) as TabbedListView[]}>{(v) => (<Match when={listView() === v}>@@ -226,25 +212,6 @@ export const SoupViewTabs = () => {);};-/** The Customers view swaps filter tabs for a board/list mode switch. */-const COMPANY_MODE_TABS: TabItem[] = [- { value: 'board', label: 'Board' },- { value: 'list', label: 'List' },-];--const CompanyModeTabs = () => {- const { viewMode, setViewMode } = useSoupView();-- return (- <TabsInset- list={COMPANY_MODE_TABS}- value={viewMode()}- defaultValue="board"- onChange={(value) => setViewMode(value as SoupViewMode)}- />- );-};-const ViewTabs = (props: { view: TabbedListView }) => {const { applyTabPreset } = useApplyPreset();const { activeTab } = useSoupView();@@ -264,7 +231,7 @@ const ViewTabs = (props: { view: TabbedListView }) => {export const CollapsedSoupViewTabs = () => {const listView = useCurrentListView();const { applyTabPreset } = useApplyPreset();- const { activeTab, viewMode, setViewMode } = useSoupView();+ const { activeTab } = useSoupView();const visibleViewTabs = useVisibleViewTabs();const view = createMemo(() => {@@ -283,29 +250,17 @@ export const CollapsedSoupViewTabs = () => {});return (- <Show- when={listView() !== 'companies'}- fallback={- <TabsInsetDropdown- list={COMPANY_MODE_TABS}- value={viewMode()}- defaultValue="board"- onChange={(value) => setViewMode(value as SoupViewMode)}- />- }- >- <TabsInsetDropdown- list={list()}- value={activeTab()}- defaultValue={defaultValue()}- onChange={(value) => {- const v = view();- if (v) {- applyTabPreset(v, value);- }- }}- />- </Show>+ <TabsInsetDropdown+ list={list()}+ value={activeTab()}+ defaultValue={defaultValue()}+ onChange={(value) => {+ const v = view();+ if (v) {+ applyTabPreset(v, value);+ }+ }}+ />);};@@ -316,7 +271,7 @@ export const CollapsedSoupViewTabs = () => {* the scroll content. The drawer button leads the strip and scrolls along* with the pills.*/-export const MobileSoupViewTabs = (props: { leading?: JSX.Element } = {}) => {+export const MobileSoupViewTabs = () => {const listView = useCurrentListView();return (@@ -327,9 +282,6 @@ export const MobileSoupViewTabs = (props: { leading?: JSX.Element } = {}) => {mobile counterpart). */}<MobileSearchFilterDrawer /></Match>- <Match when={listView() === 'companies'}>- <MobileCompanyModeTabs leading={props.leading} />- </Match><Foreach={Object.keys(VIEW_TAB_LISTS) as (keyof typeof VIEW_TAB_LISTS)[]}>@@ -354,27 +306,6 @@ const MOBILE_TAB_STRIP_CLASS ='-ml-(--mobile-chrome-gutter) w-[100cqw] max-w-none flex-none';const MOBILE_TAB_CONTENT_CLASS = 'px-(--mobile-chrome-gutter)';-const MobileCompanyModeTabs = (props: { leading?: JSX.Element }) => {- const { viewMode, setViewMode } = useSoupView();-- return (- <PillTabs- scrollable- class={MOBILE_TAB_STRIP_CLASS}- contentClass={MOBILE_TAB_CONTENT_CLASS}- leading={- <>- {props.leading}- <MobileFilterDrawer />- </>- }- items={COMPANY_MODE_TABS}- value={viewMode()}- onChange={(value) => setViewMode(value as SoupViewMode)}- />- );-};-const MobileViewTabs = (props: { view: TabbedListView }) => {const { applyTabPreset } = useApplyPreset();const { activeTab } = useSoupView();diff --git a/apps/web/src/features/next-soup/soup-view/soup-view.tsx b/apps/web/src/features/next-soup/soup-view/soup-view.tsxindex 95fa292046..775d122ff4 100644--- a/apps/web/src/features/next-soup/soup-view/soup-view.tsx+++ b/apps/web/src/features/next-soup/soup-view/soup-view.tsx@@ -39,10 +39,6 @@ import {useApplyPreset,} from '@app/features/next-soup/soup-view/soup-view-tabs';import { useIsHomeView } from '@app/features/next-soup/soup-view/use-is-home-view';-import { CompanyKanban } from '@app/features/next-soup/soup-view/views/companies/CompanyKanban';-import { CompanyListEntity } from '@app/features/next-soup/soup-view/views/companies/CompanyListEntity';-import { ResponsiveCompanyListHeader } from '@app/features/next-soup/soup-view/views/companies/CompanyListHeader';-import { CrmDefaultViewLoader } from '@app/features/next-soup/soup-view/views/companies/CrmDefaultView';import { InboxListEntity } from '@app/features/next-soup/soup-view/views/inbox/InboxListEntity';import { TaskListEntity } from '@app/features/next-soup/soup-view/views/tasks/TaskListEntity';import { ResponsiveTaskListHeader } from '@app/features/next-soup/soup-view/views/tasks/TaskListHeader';@@ -60,11 +56,6 @@ import {} from '@app/features/soup';import { DEBUG_SETTING_KEYS, useDebugSetting } from '@app/lib/debugSettings';import { usePreference } from '@app/preferences/use-preference';-import { useDealStages } from '@companies/crm/deal-stages';-import { CrmStageIcon } from '@companies/crm/StageIcon';-import type { CrmViewConfig } from '@companies/crm/saved-views';-import { useCrmUnavailable } from '@companies/crm/team-crm-config';-import { CrmWorkspace } from '@companies/views/CrmWorkspace';import { useGlobalNotificationSource } from '@components/app/GlobalAppState';import { PullToRefresh } from '@components/app/mobile/PullToRefresh';import { SwipableRowProvider } from '@components/app/mobile/SwipableRow';@@ -135,33 +126,8 @@ import { useSoupNavigationHotkeys } from './use-soup-navigation-hotkeys';import { useSoupViewHotkeys } from './use-soup-view-hotkeys';export const DefaultGroupHeader = (- props: GroupHeaderProps & { highlighted?: boolean }+ props: GroupHeaderProps & { highlighted?: boolean; icon?: JSX.Element }) => {- const panel = useSplitPanelOrThrow();- const dealStages = useDealStages();-- // The Customers view groups by option ids from the team's deal-stage set- // (or other custom select options) that the static PropertyValueIcon- // table doesn't know — render those through CrmStageIcon instead.- const isCompaniesView = () => {- const content = panel.handle.content();- return content.type === 'component' && content.id === 'companies';- };-- // Index into the active stage set so header dots match kanban columns.- const stageIndex = (optionId: string): number | undefined => {- const index = dealStages- .stages()- .findIndex((stage) => stage.id === optionId);- return index === -1 ? undefined : index;- };-- const stageOptionId = () => {- if (!isCompaniesView()) return undefined;- const value = props.group.value ?? props.group.key;- return typeof value === 'string' && value ? value : undefined;- };-return (<SoupSectionHeaderonClick={() => props.group.toggle()}@@ -177,15 +143,7 @@ export const DefaultGroupHeader = (</div></Layer>- <Show when={stageOptionId()}>- {(value) => (- <CrmStageIcon- optionId={value()}- index={stageIndex(value())}- class="size-3.5"- />- )}- </Show>+ {props.icon}<span class="truncate">{props.group.label}</span><spanclass={cn(@@ -216,10 +174,9 @@ const SOUP_LIST_STATE_ENTRY_KEY = 'soup.listState';type SoupRowComponent =| typeof ListEntity| typeof InboxListEntity- | typeof TaskListEntity- | typeof CompanyListEntity;+ | typeof TaskListEntity;-type SoupRowEntry = {+export type SoupRowEntry = {component: SoupRowComponent;/*** The --soup-row-* geometry the component renders with (ListEntity.css).@@ -272,11 +229,6 @@ interface SoupViewProps {* preset whose `clientFilters` include a predicate that matches them.*/additionalEntities?: Accessor<EntityData[]>;- /**- * Shared CRM view opened via a `?crmView=` link (Customers view only).- * When set, its pieces win over persisted/preset state during init.- */- initialCrmView?: CrmViewConfig;/** The view's tour, e.g. `<ViewTour tour={callsTour} />`. */tour?: JSX.Element;}@@ -312,20 +264,6 @@ export const SoupView = (props: SoupViewProps) => {`macro:pref:soup:${contentId}:sort`,{ default: [] });- // Shared CRM view opened via a `?crmView=` link — only honored on the- // Customers view; its pieces win over persisted/preset values in init.- const initialCrmView =- contentId === 'companies' ? props.initialCrmView : undefined;-- // A default saved view only applies to a fresh Customers entry: restored- // (back/forward) entries keep what the user was looking at, and share- // links carry their own state.- const applyDefaultCrmView =- contentId === 'companies' &&- initialCrmView === undefined &&- persistedFilters === undefined &&- persistedPredicates === undefined;-// We handle the restore of the persistence here instead of within the context// because the context is no longer recreated for each soup view because we// moved it within the `SplitPanel`.@@ -341,25 +279,14 @@ export const SoupView = (props: SoupViewProps) => {init = true;batch(() => {soupView.initialize({- initialQuery: initialCrmView- ? (initialCrmView.filters as Query | undefined)- : (persistedFilters ?? props.initialFilters),- initialClientFilters: initialCrmView- ? (initialCrmView.clientFilters ?? {})- : (persistedPredicates ?? props.initialClientFilters),- initialSearchText: initialCrmView- ? (initialCrmView.searchText ?? '')- : (persistedSearchText ?? props.initialSearchText),- preferInitialFilters: initialCrmView !== undefined,+ initialQuery: persistedFilters ?? props.initialFilters,+ initialClientFilters: persistedPredicates ?? props.initialClientFilters,+ initialSearchText: persistedSearchText ?? props.initialSearchText,disableLocalSearch: props.disableLocalSearch,additionalEntities: props.additionalEntities,});- // `groupBy: null` in a shared view records an explicit "no grouping",- // which the grouping store expresses as `undefined`.- const initialGroupBy = initialCrmView- ? (initialCrmView.groupBy ?? undefined)- : (persistedGroupBy ?? props.initialGroupBy);+ const initialGroupBy = persistedGroupBy ?? props.initialGroupBy;// The inbox exposes no sort control on either desktop (the toolbar// hides SoupViewContextSort) or mobile, so its order is fixed: update@@ -367,10 +294,7 @@ export const SoupView = (props: SoupViewProps) => {// notified order they serve (see `clientSort`). Ignore any sort// persisted back when the control was reachable: honoring it would pin// the list to an order the user can no longer change.- let initialSortIds =- contentId === 'home'- ? ['updated_at']- : (initialCrmView?.sort ?? sortPref());+ let initialSortIds = contentId === 'home' ? ['updated_at'] : sortPref();if (initialSortIds.length === 0) {initialSortIds = props.initialClientSort ?? ['updated_at'];}@@ -378,10 +302,7 @@ export const SoupView = (props: SoupViewProps) => {const persistedViewActiveTab = isListViewID(contentId)? soupView.getPersistedActiveTab(contentId): undefined;- let initialActiveTab =- initialCrmView?.activeTab ??- persistedActiveTab ??- persistedViewActiveTab;+ let initialActiveTab = persistedActiveTab ?? persistedViewActiveTab;if (initialActiveTab === undefined && isListViewID(contentId)) {initialActiveTab = VIEW_TAB_PRESETS[contentId].default;@@ -395,26 +316,6 @@ export const SoupView = (props: SoupViewProps) => {);soupView.setActiveTab(initialActiveTab);-- if (initialCrmView) {- // Stage/owner sub-filters ride separate signals plus a client- // predicate that must be active iff the selection is non-empty- // (same rule as handleStageChange/handleOwnerChange in- // unified-filter-dropdown).- const stages = initialCrmView.stageFilter ?? [];- soupView.setStageFilter(stages);- if (stages.length > 0 !== soup.predicates.isActive('company-stage')) {- soup.predicates.toggle({ and: ['company-stage'] });- }- const owners = initialCrmView.ownerFilter ?? [];- soupView.setOwnerFilter(owners);- if (owners.length > 0 !== soup.predicates.isActive('company-owner')) {- soup.predicates.toggle({ and: ['company-owner'] });- }- soupView.setViewMode(- initialCrmView.viewMode ?? (isTouchDevice() ? 'list' : 'board')- );- }});});@@ -454,16 +355,6 @@ export const SoupView = (props: SoupViewProps) => {return view ? LIST_VIEW_DOCS_URL[view] : undefined;});- const isBoardMode = createMemo(- () => activeListView() === 'companies' && soupView.viewMode() === 'board'- );-- // When CRM is unavailable (no team / disabled) the board renders the- // empty state instead of columns, so board-only chrome tweaks (like- // hiding the AI bar) shouldn't apply.- const crmUnavailable = useCrmUnavailable();- const isBoardRendered = createMemo(() => isBoardMode() && !crmUnavailable());-const [narrowSearchExpanded, setNarrowSearchExpanded] = createSignal(false);const [searchIsCollapsed, setSearchIsCollapsed] = createSignal(false);@@ -480,15 +371,12 @@ export const SoupView = (props: SoupViewProps) => {},});- const content = (- onOpenEntity?: (entity: EntityData) => boolean,- mobileHeaderLeading?: JSX.Element- ) => (+ const content = () => (<divclass="size-full flex flex-col @container"data-list-view={activeListView()}>- <Show when={!isComponentListView('companies') || isTouchDevice()}>+ <Show when={true}><div class="flex flex-col w-full"><SplitHeaderLeft><div@@ -505,7 +393,7 @@ export const SoupView = (props: SoupViewProps) => {the view title (the bottom accessory region now belongs to theglobal views row). */}<Show when={isTouchDevice()}>- <MobileSoupViewTabs leading={mobileHeaderLeading} />+ <MobileSoupViewTabs /></Show><Show when={!isTouchDevice() && !narrowSearchExpanded()}><div class="flex items-center gap-1">@@ -651,27 +539,15 @@ export const SoupView = (props: SoupViewProps) => {</Show><div class="relative grow min-h-1 flex max-sm:flex-col flex-row size-full"><Suspense>- <Show- when={!isBoardMode()}- fallback={- <MaybeSoupEntityActionDrawerManager>- <CompanyKanban onOpenEntity={onOpenEntity} />- </MaybeSoupEntityActionDrawerManager>- }- >- <SoupViewList onOpenEntity={onOpenEntity} />- </Show>+ <SoupViewList /></Suspense></div><Suspense>- {/* The board hides the AI bar: it floats over- content that is already constrained in both layouts. */}<Showwhen={!isTouchDevice() &&ENABLE_UNIFIED_LIST_AI_INPUT &&!isHomeView() &&- !isBoardRendered() &&!isComponentListView('search')}>@@ -684,24 +560,17 @@ export const SoupView = (props: SoupViewProps) => {</Suspense></div>);- return (- <>- <Show when={applyDefaultCrmView}>- <CrmDefaultViewLoader />- </Show>- <Show when={isComponentListView('companies')} fallback={content()}>- <CrmWorkspace>- {(options) =>- content(options.onOpenEntity, options.mobileHeaderLeading)- }- </CrmWorkspace>- </Show>- </>- );+ return content();};interface SoupViewListProps {+ rowEntry?: SoupRowEntry;+ listHeader?: JSX.Element;+ groupHeader?: import('solid-js').Component<+ GroupHeaderProps & { highlighted?: boolean }+ >;emptyState?: () => JSX.Element;+ emptyContent?: JSX.Element;timestamp?: (entity: EntityData) => DateValue | null | undefined;navigationKey?: string;/** Composed folder browsers keep ordinary folder activation in their pane. */@@ -724,6 +593,9 @@ interface SoupViewListProps {export const SoupViewList = (props: SoupViewListProps) => (<SoupRowMetadataProvider><SoupViewListContent+ rowEntry={props.rowEntry}+ listHeader={props.listHeader}+ groupHeader={props.groupHeader}customScrollbarHidden={props.customScrollbarHidden}scopeId={props.scopeId}onOpenProject={props.onOpenProject}@@ -733,6 +605,7 @@ export const SoupViewList = (props: SoupViewListProps) => (timestamp={props.timestamp}navigationKey={props.navigationKey}emptyState={props.emptyState}+ emptyContent={props.emptyContent}/></SoupRowMetadataProvider>);@@ -898,18 +771,17 @@ const SoupViewListContent = (props: SoupViewListProps) => {const rowsByView: Partial<Record<ListView, SoupRowEntry>> = {home: { component: InboxListEntity, family: 'card' },tasks: { component: TaskListEntity, family: 'row' },- companies: { component: CompanyListEntity, family: 'row' },};const defaultRow: SoupRowEntry = { component: ListEntity, family: 'row' };const rowEntry = (): SoupRowEntry => {const view = currentView();- return (view && rowsByView[view]) ?? defaultRow;+ return props.rowEntry ?? (view && rowsByView[view]) ?? defaultRow;};const groupHeaderComponent = () => {if (currentView() === 'tasks') return TaskGroupHeader;if (soup.grouping.activeGroupId() === 'date') return DateGroupHeader;- return DefaultGroupHeader;+ return props.groupHeader ?? DefaultGroupHeader;};useSoupViewHotkeys({@@ -1309,6 +1181,7 @@ const SoupViewListContent = (props: SoupViewListProps) => {when={!searchText() && props.emptyState}fallback={<EmptyState+ content={props.emptyContent}listView={currentView()}search={!!searchText()}hasRefinementsFromBase={hasActiveRefinements()}@@ -1329,11 +1202,7 @@ const SoupViewListContent = (props: SoupViewListProps) => {<Show when={currentView() === 'tasks' && !isTouchDevice()}><ResponsiveTaskListHeader class="shrink-0" /></Show>- <Show- when={currentView() === 'companies' && !isTouchDevice()}- >- <ResponsiveCompanyListHeader class="shrink-0" />- </Show>+ {props.listHeader}<SwipableRowProvidercontainer={localEntityListRef}canSwipeLeft={(entityId) => {diff --git a/apps/web/src/features/next-soup/soup-view/views/companies/CrmDefaultView.test.tsx b/apps/web/src/features/next-soup/soup-view/views/companies/CrmDefaultView.test.tsxdeleted file mode 100644index df58230e68..0000000000--- a/apps/web/src/features/next-soup/soup-view/views/companies/CrmDefaultView.test.tsx+++ /dev/null@@ -1,55 +0,0 @@-import type { CrmViewConfig } from '@companies/crm/saved-views';-import { cleanup, render } from '@solidjs/testing-library';-import { afterEach, describe, expect, it, vi } from 'vitest';--const mocks = vi.hoisted(() => ({- mobile: true,- apply: vi.fn(),- config: {- kind: 'crm',- viewMode: 'board',- searchText: 'Acme',- } as CrmViewConfig,-}));-vi.mock('@core/mobile/isTouchDevice', () => ({- isTouchDevice: () => mocks.mobile,-}));-vi.mock('@companies/crm/saved-views', () => ({- usePersonalCrmViews: () => ({- isLoading: () => false,- defaultView: () => ({ config: mocks.config }),- }),- useTeamCrmViews: () => ({- isLoading: () => false,- defaultView: () => undefined,- }),-}));-vi.mock(- '@app/features/next-soup/soup-view/views/companies/use-apply-crm-view',- () => ({- useApplyCrmView: () => mocks.apply,- })-);--import { CrmDefaultViewLoader } from './CrmDefaultView';--afterEach(() => {- cleanup();- vi.clearAllMocks();-});-describe('CRM default saved layout', () => {- it('uses a list on mobile while retaining the saved filters', () => {- mocks.mobile = true;- render(() => <CrmDefaultViewLoader />);- expect(mocks.apply).toHaveBeenCalledWith({- ...mocks.config,- viewMode: 'list',- });- expect(mocks.config.viewMode).toBe('board');- });- it('retains the saved desktop layout', () => {- mocks.mobile = false;- render(() => <CrmDefaultViewLoader />);- expect(mocks.apply).toHaveBeenCalledWith(mocks.config);- });-});diff --git a/apps/web/src/features/next-soup/soup-view/views/companies/use-apply-crm-view.ts b/apps/web/src/features/next-soup/soup-view/views/companies/use-apply-crm-view.tsdeleted file mode 100644index 5c78392370..0000000000--- a/apps/web/src/features/next-soup/soup-view/views/companies/use-apply-crm-view.ts+++ /dev/null@@ -1,52 +0,0 @@-import type { Query } from '@app/features/next-soup/filters/filter-store';-import { useSoupView } from '@app/features/next-soup/soup-view/soup-view-context';-import type { CrmViewConfig } from '@companies/crm/saved-views';-import { isTouchDevice } from '@core/mobile/isTouchDevice';-import { batch } from 'solid-js';--/**- * Applies a saved CRM view config to the current Customers view. Mirrors the- * init/applyTabPreset path: replace filters + predicates atomically, then- * re-derive the stage/owner predicate active state from the saved sub-filter- * selections (same rule as handleStageChange / handleOwnerChange in- * unified-filter-dropdown).- */-export function useApplyCrmView() {- const {- soup,- queryFilters,- setSearchText,- setStageFilter,- setOwnerFilter,- setActiveTab,- setViewMode,- } = useSoupView();-- return (config: CrmViewConfig) => {- batch(() => {- if (config.activeTab !== undefined) setActiveTab(config.activeTab);- queryFilters.replace((config.filters as Query | undefined) ?? null);- soup.predicates.set(config.clientFilters ?? {});- setSearchText(config.searchText ?? '');- // `groupBy: null` records an explicit "no grouping"; the grouping- // store expresses that as `undefined` (same as the init path).- soup.grouping.setActiveGroupId(config.groupBy ?? undefined);- soup.sort.setAll(- (config.sort?.length ? config.sort : ['updated_at']) as Parameters<- typeof soup.sort.setAll- >[0]- );- const stages = config.stageFilter ?? [];- setStageFilter(stages);- if (stages.length > 0 !== soup.predicates.isActive('company-stage')) {- soup.predicates.toggle({ and: ['company-stage'] });- }- const owners = config.ownerFilter ?? [];- setOwnerFilter(owners);- if (owners.length > 0 !== soup.predicates.isActive('company-owner')) {- soup.predicates.toggle({ and: ['company-owner'] });- }- setViewMode(config.viewMode ?? (isTouchDevice() ? 'list' : 'board'));- });- };-}diff --git a/apps/web/src/features/reviews-view/components/ReviewsList.tsx b/apps/web/src/features/reviews-view/components/ReviewsList.tsxindex 9a9b287850..f65963da5d 100644--- a/apps/web/src/features/reviews-view/components/ReviewsList.tsx+++ b/apps/web/src/features/reviews-view/components/ReviewsList.tsx@@ -5,8 +5,8 @@ import {toEntityActionListState,useEntityActionHotkeys,} from '@app/features/next-soup/actions';+import { useInfiniteScrollSentinel } from '@app/lib/primitives/infinite-scroll-sentinel';import { globalSplitManager } from '@app/signal/splitLayout';-import { useInfiniteScrollSentinel } from '@companies/Company/use-infinite-scroll-sentinel';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { ContextMenuContent, MenuItem } from '@core/component/ContextMenu';import {diff --git a/apps/web/src/features/settings/SettingsTabContent.tsx b/apps/web/src/features/settings/SettingsTabContent.tsxindex 344d92aca7..d05e1b97f1 100644--- a/apps/web/src/features/settings/SettingsTabContent.tsx+++ b/apps/web/src/features/settings/SettingsTabContent.tsx@@ -1,6 +1,7 @@import type { SettingsTab } from '@core/constant/SettingsState';import { useSettingsTabAvailable } from '@core/constant/settingsTabsConfig';import { Show, Suspense } from 'solid-js';+import { CrmSettings as Crm } from '../crm/crm-settings';import { Account } from './Account';import { Admin } from './Admin';import { Agent } from './Agent';@@ -10,7 +11,6 @@ import { Appearance } from './Appearance';import { Billing } from './Billing';import { Bots } from './Bots';import { ConnectedAccounts } from './ConnectedAccounts';-import { Crm } from './Crm';import { MobileApp } from './MobileApp';import { Notifications } from './Notifications';import { Shortcuts } from './Shortcuts';diff --git a/apps/web/src/features/soup/createSoupEntityActions.ts b/apps/web/src/features/soup/createSoupEntityActions.tsindex 44cbdaf1da..0fbdea6f51 100644--- a/apps/web/src/features/soup/createSoupEntityActions.ts+++ b/apps/web/src/features/soup/createSoupEntityActions.ts@@ -1,3 +1,4 @@+import { createCrmEntityActionItems } from '@app/features/crm/crm-action-items';import {type EntityActionListState,type EntityActionNavigationHandler,@@ -11,7 +12,6 @@ import {makeDeleteAction,makeEditReminderAction,makeFavoriteAction,- makeHideCompanyAction,makeMarkDoneAction,makeMarkNotDoneAction,makeMarkNotificationsReadAction,@@ -23,7 +23,6 @@ import {makeMuteAction,makeRemoveFromProjectAction,makeRenameAction,- makeSetCompanyPropertyAction,makeShareAction,markReminderTargetDone,} from '@app/features/next-soup/actions';@@ -43,7 +42,6 @@ import { type HotkeyToken, TOKENS } from '@core/hotkey/tokens';import { isMobile } from '@core/mobile/isMobile';import type { EntityData } from '@entity';import { isEmailEntity, isTaskEntity } from '@entity';-import { useSetCompanyHiddenMutation } from '@queries/crm/companies';import type { Component, JSX } from 'solid-js';type SoupEntityActionItem = {@@ -101,7 +99,7 @@ export function createSoupEntityActions(): {const projectsFlag = useFeatureFlag(enableProjects);const userId = useUserId();const notificationSource = useGlobalNotificationSource();- const hiddenMutation = useSetCompanyHiddenMutation();+ const crmActions = createCrmEntityActionItems();const markDone = makeMarkDoneAction({userId: () => userId(),@@ -146,11 +144,6 @@ export function createSoupEntityActions(): {const blockSenderAction = makeBlockSenderAction();const markSenderSignalAction = makeMarkSenderSignalAction();const markSenderNoiseAction = makeMarkSenderNoiseAction();- const hideCompanyAction = makeHideCompanyAction({- setHidden: (companyId, hidden) =>- hiddenMutation.mutateAsync({ companyId, hidden }),- });- const setCompanyPropertyAction = makeSetCompanyPropertyAction();const buildActionGroups: BuildActionGroups = (soup,@@ -486,39 +479,7 @@ export function createSoupEntityActions(): {});}- // CRM group: Set stage/owner/revenue on the whole company- // selection, Hide / Unhide for a single company.- const crmItems: SoupEntityActionItem[] = [];-- for (const [field, label] of [- ['stage', 'Set stage'],- ['owner', 'Set owner'],- ['revenue', 'Set revenue'],- ] as const) {- if (- !canExecuteAll((entity) =>- setCompanyPropertyAction.canExecute(entity, field)- )- )- continue;- crmItems.push({- id: `set-${field}`,- label,- onClick: () => setCompanyPropertyAction.execute(entities, field),- });- }-- const singleEntity = entities.length === 1 ? entities[0] : undefined;- if (- singleEntity?.type === 'crm_company' &&- hideCompanyAction.canExecute(singleEntity)- ) {- crmItems.push({- id: 'hide-company',- label: singleEntity.hidden ? 'Unhide' : 'Hide',- onClick: handle(hideCompanyAction.executeWithSoup),- });- }+ const crmItems = crmActions(entities, soup);// Delete groupconst deleteItems: SoupEntityActionItem[] = [];diff --git a/apps/web/src/lib/core/component/AI/component/tool/Crm.tsx b/apps/web/src/lib/core/component/AI/component/tool/Crm.tsxdeleted file mode 100644index 378f473e2e..0000000000--- a/apps/web/src/lib/core/component/AI/component/tool/Crm.tsx+++ /dev/null@@ -1,191 +0,0 @@-import Buildings from '@phosphor-icons/core/regular/buildings.svg';-import type { NamedTool } from '@service-cognition/generated/tools/tool';-import { For, Show } from 'solid-js';-import { BaseTool } from './BaseTool';-import { Tool } from './Tool';-import { createToolRenderer } from './ToolRenderer';--type ListCompaniesResponse = NamedTool<'ListCompanies', 'response'>['data'];-type CompanyListItem = ListCompaniesResponse['companies'][number];-type GetCompanyResponse = NamedTool<'GetCompany', 'response'>['data'];--const pluralize = (count: number, singular: string, plural = `${singular}s`) =>- `${count} ${count === 1 ? singular : plural}`;--function companySubtitle(company: CompanyListItem) {- const parts: string[] = [];- const domain = company.domains[0];- if (domain) parts.push(domain);- if (company.stage) parts.push(company.stage.label);- return parts.join(' · ');-}--function CompanyRow(props: { company: CompanyListItem }) {- return (- <Tool.ListItem icon={<Buildings class="size-4" />}>- <div class="min-w-0 flex-1">- <div class="truncate text-xs text-ink">- {props.company.name ?? props.company.domains[0] ?? props.company.id}- </div>- <Show when={companySubtitle(props.company)}>- {(subtitle) => (- <div class="truncate text-xs text-ink-placeholder">- {subtitle()}- </div>- )}- </Show>- </div>- </Tool.ListItem>- );-}--function ListCompaniesToolResponse(props: ListCompaniesResponse) {- return (- <Tool.List>- <Show- when={props.companies.length > 0}- fallback={<Tool.ListItem>No matching CRM companies.</Tool.ListItem>}- >- <For each={props.companies}>- {(company) => <CompanyRow company={company} />}- </For>- </Show>- </Tool.List>- );-}--const listCompaniesHandler = createToolRenderer({- name: 'ListCompanies',- render: (ctx) => {- const companies = () => ctx.response?.data.companies ?? [];- const statusText = () => {- if (!ctx.response) return undefined;- if (companies().length === 0) return 'No results';- return pluralize(companies().length, 'company', 'companies');- };-- return (- <BaseTool- icon={Buildings}- renderContext={ctx.renderContext}- type="call"- response={- ctx.response ? (- <ListCompaniesToolResponse {...ctx.response.data} />- ) : undefined- }- >- <div class="flex min-w-0 flex-1 items-center justify-between gap-3 overflow-hidden">- <span class="min-w-0 truncate">- List CRM companies- <Show when={ctx.tool.data.search}>- {(search) => <> matching "{search()}"</>}- </Show>- <Show when={ctx.tool.data.stage}>- {(stage) => <> in stage {stage()}</>}- </Show>- </span>- <Show when={statusText()}>- {(text) => (- <span class="shrink-0 whitespace-nowrap text-xs text-ink-extra-muted">- {text()}- </span>- )}- </Show>- </div>- </BaseTool>- );- },-});--function GetCompanyToolResponse(props: GetCompanyResponse) {- const details = () => {- const rows: { label: string; value: string }[] = [];- if (props.domains.length > 0) {- rows.push({ label: 'Domains', value: props.domains.join(', ') });- }- if (props.stage) rows.push({ label: 'Stage', value: props.stage.label });- if (props.ownerUserId) {- rows.push({ label: 'Owner', value: props.ownerUserId });- }- if (props.revenue !== undefined && props.revenue !== null) {- rows.push({ label: 'Revenue', value: `$${props.revenue}` });- }- rows.push({- label: 'Contacts',- value: pluralize(props.contacts.length, 'contact'),- });- return rows;- };-- return (- <Tool.List>- <Tool.ListItem icon={<Buildings class="size-4" />}>- <div class="min-w-0 flex-1">- <div class="truncate text-xs text-ink">- {props.name ?? props.domains[0] ?? props.id}- </div>- <Show when={props.description}>- {(description) => (- <div class="truncate text-xs text-ink-placeholder">- {description()}- </div>- )}- </Show>- </div>- </Tool.ListItem>- <For each={details()}>- {(row) => (- <Tool.ListItem>- <div class="flex min-w-0 flex-1 gap-2 text-xs">- <span class="shrink-0 text-ink-placeholder">{row.label}</span>- <span class="min-w-0 truncate text-ink">{row.value}</span>- </div>- </Tool.ListItem>- )}- </For>- </Tool.List>- );-}--const getCompanyHandler = createToolRenderer({- name: 'GetCompany',- render: (ctx) => {- const statusText = () => {- if (!ctx.response) return undefined;- const data = ctx.response.data;- return data.stage?.label ?? data.domains[0];- };-- return (- <BaseTool- icon={Buildings}- renderContext={ctx.renderContext}- type="call"- response={- ctx.response ? (- <GetCompanyToolResponse {...ctx.response.data} />- ) : undefined- }- >- <div class="flex min-w-0 flex-1 items-center justify-between gap-3 overflow-hidden">- <span class="min-w-0 truncate">- Read CRM company- <Show when={ctx.response?.data.name}>- {(name) => <> {name()}</>}- </Show>- </span>- <Show when={statusText()}>- {(text) => (- <span class="shrink-0 whitespace-nowrap text-xs text-ink-extra-muted">- {text()}- </span>- )}- </Show>- </div>- </BaseTool>- );- },-});--export { getCompanyHandler, listCompaniesHandler };diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsxindex 65475b6d31..7a99b85933 100644--- a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx@@ -1,3 +1,7 @@+import {+ getCompanyHandler,+ listCompaniesHandler,+} from '@app/features/crm/crm-tool-renderers';import {deserializeToolCall,deserializeToolResponse,@@ -30,7 +34,6 @@ import {import { createDocumentHandler } from './CreateDocument';import { createProjectHandler } from './CreateProject';import { createTagHandler } from './CreateTag';-import { getCompanyHandler, listCompaniesHandler } from './Crm';import { deleteTagHandler } from './DeleteTag';import { displayResultsHandler } from './DisplayResults';import {diff --git a/apps/web/src/lib/core/component/UserCardDrawer.test.tsx b/apps/web/src/lib/core/component/UserCardDrawer.test.tsxindex 40d7d88834..533e39df72 100644--- a/apps/web/src/lib/core/component/UserCardDrawer.test.tsx+++ b/apps/web/src/lib/core/component/UserCardDrawer.test.tsx@@ -49,7 +49,7 @@ vi.mock('@queries/channel/get-or-create-dm', () => ({}),}));-vi.mock('@queries/crm/contacts', () => ({+vi.mock('@app/features/crm/record-adapter', () => ({useCrmContactByEmailQuery: () => ({ isSuccess: false, data: undefined }),}));diff --git a/apps/web/src/lib/core/component/UserTooltip.test.tsx b/apps/web/src/lib/core/component/UserTooltip.test.tsxindex 8e11e67f81..631ac154cf 100644--- a/apps/web/src/lib/core/component/UserTooltip.test.tsx+++ b/apps/web/src/lib/core/component/UserTooltip.test.tsx@@ -48,7 +48,7 @@ vi.mock('@queries/channel/get-or-create-dm', () => ({useGetOrCreateDirectMessageMutation: () => ({ mutateAsync: vi.fn() }),}));-vi.mock('@queries/crm/contacts', () => ({+vi.mock('@app/features/crm/record-adapter', () => ({useCrmContactByEmailQuery: () => ({// Pending lookups report no data yet, exactly as solid-query does.get isSuccess() {diff --git a/apps/web/src/lib/core/component/userCardActions.tsx b/apps/web/src/lib/core/component/userCardActions.tsxindex feda3c7c1d..fdfe1aa5ec 100644--- a/apps/web/src/lib/core/component/userCardActions.tsx+++ b/apps/web/src/lib/core/component/userCardActions.tsx@@ -1,17 +1,13 @@-import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { createCrmUserCardAction } from '@app/features/crm/crm-user-action';import { useSplitLayout } from '@components/app/split-layout/layout';import { toast } from '@core/component/Toast/Toast';-import { enableCrm } from '@core/constant/featureFlags';import { isBotPrincipalId } from '@core/constant/macroAgent';import { useUserId } from '@core/context/user';import { useIsConnectedSecondaryInbox } from '@core/user';-import WideContact from '@phosphor/address-book.svg';import WideChat from '@phosphor/chat.svg';import CopyIcon from '@phosphor/copy.svg';import WideTask from '@phosphor/list-checks.svg';import { useGetOrCreateDirectMessageMutation } from '@queries/channel/get-or-create-dm';-import { useCrmContactByEmailQuery } from '@queries/crm/contacts';-import { useCurrentTeamQuery } from '@queries/team/teams';import {type Accessor,type Component,@@ -72,7 +68,6 @@ export function useUserCardActions(const currentUserId = useUserId();const isConnectedSecondaryInbox = useIsConnectedSecondaryInbox();const { openWithSplit, popoverSplit } = useSplitLayout();- const crmFlag = useFeatureFlag(enableCrm);const getOrCreateDmMutation = useGetOrCreateDirectMessageMutation({onError: () => toast.failure('Failed to open direct message'),});@@ -87,21 +82,7 @@ export function useUserCardActions(const canDirectMessage = () =>canTreatAsUser() && !isBotPrincipalId(userId());- // Only the CRM contact lookup needs the team, so a card on a workspace- // without CRM never fetches one.- const currentTeamQuery = useCurrentTeamQuery(() => crmFlag().enabled);- // Guarded reads: an unguarded `data` suspends whoever renders the card, and- // a card that suspends takes its hover surface or sheet down with it.- const team = () =>- currentTeamQuery.isSuccess ? currentTeamQuery.data?.team : undefined;- const crmEnabled = () => crmFlag().enabled && team()?.crm_enabled === true;- const contactQuery = useCrmContactByEmailQuery(- () => team()?.id ?? '',- () => target().email ?? '',- crmEnabled- );- const crmContact = () =>- crmEnabled() && contactQuery.isSuccess ? contactQuery.data : undefined;+ const contactAction = createCrmUserCardAction(() => target().email);const copyAction = (id: UserCardActionId,@@ -125,15 +106,6 @@ export function useUserCardActions(},});- const openContact = (event: MouseEvent, contactId: string) => {- event.preventDefault();- event.stopPropagation();- openWithSplit(- { type: 'contact', id: contactId },- { preferNewSplit: event.shiftKey, reopen: 'latest' }- );- };-const openDirectMessage = async (event: MouseEvent) => {event.preventDefault();event.stopPropagation();@@ -177,15 +149,8 @@ export function useUserCardActions(actions.push(copyAction('copy-name', 'Copy name', name, 'Name copied'));}- const contact = crmContact();- if (contact) {- actions.push({- id: 'open-contact',- label: 'Open contact',- icon: WideContact,- onSelect: (event) => openContact(event, contact.id),- });- }+ const contact = contactAction();+ if (contact) actions.push(contact);if (canDirectMessage() && userId() !== currentUserId()) {actions.push({diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.tsindex bcf61274ae..a1a042d5d1 100644--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts@@ -130,7 +130,8 @@ vi.mock('@queries/history/graphql', () => ({vi.mock('@queries/soup/quick-access-agent-sessions', () => ({useQuickAccessAgentSessionsQuery: () => ({ query: {}, sessions: () => [] }),}));-vi.mock('@queries/soup/quick-access-crm-companies', () => ({+vi.mock('@app/features/crm/crm-search', async () => ({+ ...(await import('@app/features/crm/queries/graphql')),useQuickAccessCrmCompaniesQuery: () => ({query: {},companies: () => mocks.companies,diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsxindex 38a487aa42..d2295f30e1 100644--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx@@ -1,3 +1,7 @@+import {+ materializeCachedGraphqlCrmCompanies,+ useQuickAccessCrmCompaniesQuery,+} from '@app/features/crm/crm-search';import { useFeatureFlag } from '@app/lib/analytics/posthog';import { itemToSafeName } from '@core/constant/allBlocks';import { enableCrm } from '@core/constant/featureFlags';@@ -22,12 +26,10 @@ import {type CachedGraphqlChannel,materializeCachedGraphqlChannels,} from '@queries/channel/graphql';-import { materializeCachedGraphqlCrmCompanies } from '@queries/crm/graphql';import { queryReadyGate } from '@queries/gate';import { materializeCachedGraphqlHistoryItems } from '@queries/history/graphql';import { type HistoryItem, useHistoryQuery } from '@queries/history/history';import { useQuickAccessAgentSessionsQuery } from '@queries/soup/quick-access-agent-sessions';-import { useQuickAccessCrmCompaniesQuery } from '@queries/soup/quick-access-crm-companies';import { useQuickAccessSkillsQuery } from '@queries/soup/quick-access-skills';import { useQuickAccessSnippetsQuery } from '@queries/soup/quick-access-snippets';import { useRecentlyViewedSoupQuery } from '@queries/soup/recently-viewed';diff --git a/apps/web/src/features/companies/Company/use-infinite-scroll-sentinel.ts b/apps/web/src/lib/primitives/infinite-scroll-sentinel.tssimilarity index 100%rename from apps/web/src/features/companies/Company/use-infinite-scroll-sentinel.tsrename to apps/web/src/lib/primitives/infinite-scroll-sentinel.tsdiff --git a/apps/web/src/lib/queries/crm/contacts.ts b/apps/web/src/lib/queries/crm/contacts.tsdeleted file mode 100644index 1937be5306..0000000000--- a/apps/web/src/lib/queries/crm/contacts.ts+++ /dev/null@@ -1,157 +0,0 @@-import { throwOnErr } from '@core/util/result';-import { storageServiceClient } from '@service-storage/client';-import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';-import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';-import type { Accessor } from 'solid-js';-import { queryClient } from '../client';-import { soupKeys } from '../soup/keys';-import { crmKeys } from './keys';--const CONTACT_STALE_TIME = 60 * 1000;--function crmContactByEmailQueryOptions(teamId: string, email: string) {- const normalizedEmail = email.trim().toLowerCase();- return queryOptions({- queryKey: crmKeys.contactByEmail(teamId, normalizedEmail).queryKey,- queryFn: async ({ signal }) => {- const { contact } = await throwOnErr(() =>- storageServiceClient.getContactByEmail({- email: normalizedEmail,- signal,- })- );- if (contact) {- queryClient.setQueryData(crmKeys.contact(contact.id).queryKey, contact);- }- return contact;- },- staleTime: CONTACT_STALE_TIME,- });-}--/** Resolves a team CRM contact by email and primes its detail cache. */-export function useCrmContactByEmailQuery(- teamId: Accessor<string>,- email: Accessor<string>,- enabled: Accessor<boolean>-) {- return useQuery(() => ({- ...crmContactByEmailQueryOptions(teamId(), email()),- enabled: enabled() && !!teamId() && !!email(),- }));-}--/**- * Fetches a single CRM contact by id via `GET /crm/contacts/{id}`.- * The endpoint is role-aware: admins/owners see hidden contacts too,- * non-admins get 404 on hidden rows. The frontend doesn't branch — it- * just calls the endpoint and trusts the response.- */-export function useContactQuery(contactId: Accessor<string>) {- return useQuery(() => {- const id = contactId();- return {- queryKey: crmKeys.contact(id).queryKey,- queryFn: () => {- if (!id) {- throw new Error('contact id is required to fetch contact');- }- return throwOnErr(() =>- storageServiceClient.getContact({ contactId: id })- );- },- staleTime: CONTACT_STALE_TIME,- enabled: !!id,- };- });-}--/**- * Renames a contact via `PUT /crm/contacts/{id}/name`. Unlike company names- * there is no global directory involved — `crm_contacts.name` is already- * team-scoped, so the write is a plain overwrite. Optimistically updates the- * contact detail cache (with rollback on error) so the title flips- * immediately, then invalidates it plus the parent company (whose response- * embeds the contact list) and soup so every listing picks up the new name.- */-export function useSetContactNameMutation() {- return useMutation(() => ({- mutationFn: ({- contactId,- name,- }: {- contactId: string;- companyId: string;- name: string;- }) =>- throwOnErr(() =>- storageServiceClient.setContactName({ contactId, name })- ),- onMutate: async ({ contactId, name }) => {- const queryKey = crmKeys.contact(contactId).queryKey;- await queryClient.cancelQueries({ queryKey });- const previous = queryClient.getQueryData<CrmContactResponse>(queryKey);- if (previous) {- queryClient.setQueryData<CrmContactResponse>(queryKey, {- ...previous,- name,- });- }- return { previous, optimisticName: name };- },- // Roll back only if the cache still holds this mutation's optimistic- // name — a stale failure must not clobber a newer rename's update.- onError: (_err, { contactId }, context) => {- if (context?.previous) {- queryClient.setQueryData<CrmContactResponse>(- crmKeys.contact(contactId).queryKey,- (current) =>- current?.name === context.optimisticName- ? context.previous- : current- );- }- },- onSettled: (_data, _err, { contactId, companyId }) =>- Promise.all([- queryClient.invalidateQueries({- queryKey: crmKeys.contact(contactId).queryKey,- }),- queryClient.invalidateQueries({- queryKey: crmKeys.company(companyId).queryKey,- }),- queryClient.invalidateQueries({ queryKey: soupKeys._def }),- ]),- }));-}--/**- * Toggles `crm_contacts.hidden` via `PUT /crm/contacts/{id}/hidden`.- * Hidden contacts disappear from the parent company's contact list- * (non-admin view) and from any soup surface that filters them.- *- * Returns the invalidation promise from `onSuccess` so the mutation- * stays pending until both the contact query and the soup queries- * refetch — the toggle state and any dependent UI all flip in one beat.- */-export function useSetContactHiddenMutation() {- return useMutation(() => ({- mutationFn: ({- contactId,- hidden,- }: {- contactId: string;- hidden: boolean;- }) =>- throwOnErr(() =>- storageServiceClient.setContactHidden({ contactId, hidden })- ),- onSuccess: (_data, { contactId }) =>- Promise.all([- queryClient.invalidateQueries({ queryKey: soupKeys._def }),- queryClient.invalidateQueries({- queryKey: crmKeys.contact(contactId).queryKey,- }),- ]),- }));-}diff --git a/apps/web/src/lib/queries/crm/lists.ts b/apps/web/src/lib/queries/crm/lists.tsdeleted file mode 100644index 871c168900..0000000000--- a/apps/web/src/lib/queries/crm/lists.ts+++ /dev/null@@ -1,97 +0,0 @@-import {- type CrmListConfig,- isCrmListConfig,-} from '@companies/core/crm-navigation';-import { throwOnErr } from '@core/util/result';-import { storageServiceClient } from '@service-storage/client';-import { useMutation, useQuery, useQueryClient } from '@tanstack/solid-query';-import type { Accessor } from 'solid-js';-import { crmKeys } from './keys';--/** Personal collections use saved-view storage, with explicit membership and team scope. */-export function useCrmLists(teamId: Accessor<string | undefined>) {- const client = useQueryClient();- const query = useQuery(() => ({- queryKey: crmKeys.lists.queryKey,- queryFn: () => throwOnErr(() => storageServiceClient.views.getSavedViews()),- enabled: !!teamId(),- }));- const lists = () =>- query.isSuccess- ? query.data.views.flatMap((view) =>- isCrmListConfig(view.config) && view.config.teamId === teamId()- ? [{ id: view.id, name: view.name, config: view.config }]- : []- )- : [];- const save = useMutation(() => ({- mutationFn: async (input: {- id?: string;- name: string;- companyIds: string[];- }) => {- const team = teamId();- if (!team) throw new Error('Join a team to create a list');- const config: CrmListConfig = {- kind: 'crm-list',- teamId: team,- companyIds: [...new Set(input.companyIds)],- };- if (input.id) {- await throwOnErr(() =>- storageServiceClient.views.patchView({- saved_view_id: input.id!,- name: input.name,- config,- })- );- return input.id;- }- const created = await throwOnErr(() =>- storageServiceClient.views.createSavedView({ name: input.name, config })- );- return created.id;- },- onSuccess: () =>- client.invalidateQueries({ queryKey: crmKeys.lists.queryKey }),- }));- const remove = useMutation(() => ({- mutationFn: (id: string) =>- throwOnErr(() =>- storageServiceClient.views.deleteView({ savedViewId: id })- ),- onSuccess: () =>- client.invalidateQueries({ queryKey: crmKeys.lists.queryKey }),- }));- const setMembership = useMutation(() => ({- mutationFn: async (input: {- listId: string;- companyId: string;- included: boolean;- }) => {- const team = teamId();- if (!team) throw new Error('A team is required');- // Refresh before editing so another company's recently changed membership- // isn't overwritten by an old detail-page snapshot.- const latest = await throwOnErr(() =>- storageServiceClient.views.getSavedViews()- );- const list = latest.views.find((entry) => entry.id === input.listId);- if (!list || !isCrmListConfig(list.config) || list.config.teamId !== team)- throw new Error('This list is no longer available');- const config = list.config;- const companyIds = new Set(config.companyIds);- if (input.included) companyIds.add(input.companyId);- else companyIds.delete(input.companyId);- await throwOnErr(() =>- storageServiceClient.views.patchView({- saved_view_id: list.id,- config: { ...config, companyIds: [...companyIds] },- })- );- },- onSuccess: () =>- client.invalidateQueries({ queryKey: crmKeys.lists.queryKey }),- }));- return { query, lists, save, remove, setMembership };-}diff --git a/apps/web/src/lib/queries/crm/people.ts b/apps/web/src/lib/queries/crm/people.tsdeleted file mode 100644index 48b2aecd0f..0000000000--- a/apps/web/src/lib/queries/crm/people.ts+++ /dev/null@@ -1,85 +0,0 @@-import { QUERY_FILTERS_BASE } from '@app/features/next-soup/filters/query-filters';-import type { CrmPerson } from '@companies/core/crm-people';-import { throwOnErr } from '@core/util/result';-import { storageServiceClient } from '@service-storage/client';-import { useInfiniteQuery, useQueryClient } from '@tanstack/solid-query';-import { type Accessor, createEffect } from 'solid-js';-import { soupKeys } from '../soup/keys';-import { crmKeys } from './keys';--/** Assemble one people directory from the existing company/contact endpoints.- * Pages appear progressively; at most four company requests run at once.- */-export function useCrmPeopleQuery(teamId: Accessor<string | undefined>) {- const client = useQueryClient();- const query = useInfiniteQuery(() => ({- queryKey: soupKeys.crmPeople(teamId() ?? '').queryKey,- enabled: !!teamId(),- staleTime: 60_000,- initialPageParam: null as string | null,- queryFn: async ({ pageParam, signal }) => {- const page = await throwOnErr(() =>- storageServiceClient.getSoupItems({- params: { cursor: pageParam },- body: {- ...QUERY_FILTERS_BASE,- crm_company_filters: { hidden: false },- limit: 20,- sort_method: 'updated_at',- },- })- );- const companies = page.items.flatMap((item) =>- item.tag === 'crmCompany' ? [item.data] : []- );- const people: CrmPerson[] = [];- for (let offset = 0; offset < companies.length; offset += 4) {- signal.throwIfAborted();- const batch = await Promise.all(- companies.slice(offset, offset + 4).map(async (company) => {- const detail = await client.fetchQuery({- queryKey: crmKeys.company(company.id).queryKey,- staleTime: 60_000,- queryFn: () =>- throwOnErr(() =>- storageServiceClient.getCompany({ companyId: company.id })- ),- });- return detail.hidden- ? []- : detail.contacts- .filter((contact) => !contact.hidden)- .map((contact) => ({- ...contact,- companyName:- detail.name ||- detail.domains[0]?.domain ||- 'Unknown company',- }));- })- );- people.push(...batch.flat());- }- return { people, nextCursor: page.next_cursor };- },- getNextPageParam: (page) => page.nextCursor,- }));-- // Drive progressive network pagination while this directory is mounted.- createEffect(() => {- if (query.hasNextPage && !query.isFetching && !query.isError) {- void query.fetchNextPage();- }- });- const people = () =>- !query.isPending- ? [- ...new Map(- query.data?.pages- .flatMap((page) => page.people)- .map((person) => [person.id, person]) ?? []- ).values(),- ]- : [];- return { query, people };-}diff --git a/apps/web/src/lib/queries/crm/stages.ts b/apps/web/src/lib/queries/crm/stages.tsdeleted file mode 100644index c66ade3741..0000000000--- a/apps/web/src/lib/queries/crm/stages.ts+++ /dev/null@@ -1,43 +0,0 @@-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/queries/preview/fetchers.ts b/apps/web/src/lib/queries/preview/fetchers.tsindex 9e71562be5..dcc59d9768 100644--- a/apps/web/src/lib/queries/preview/fetchers.ts+++ b/apps/web/src/lib/queries/preview/fetchers.ts@@ -1,3 +1,4 @@+import { fetchCrmCompanyPreviews } from '@app/features/crm/preview-adapter';import { itemToSafeName } from '@core/constant/allBlocks';import {enableGraphqlSoup,@@ -251,53 +252,6 @@ async function fetchProjectPreviews(});}-/**- * Fetches CRM company previews via `GET /crm/companies/{id}`. Mirrors the- * email preview fetcher's shape — N parallel REST calls rather than a- * batch endpoint, since the CRM REST surface is per-id today and- * companies are a smaller cardinality than mentions in flight.- *- * The backend already gates hidden visibility by role (admin/owner sees- * hidden, non-admin 404s), so the fetcher doesn't need to repeat that- * logic.- */-async function fetchCrmCompanyPreviews(- companyIds: string[]-): Promise<PreviewItem[]> {- return await Promise.all(- companyIds.map(async (id) => {- const base = { id, type: 'crm_company' as const };- const result = await storageServiceClient.getCompany({ companyId: id });-- if (result.isErr()) {- // The backend returns 404 for every unreachable reason (wrong- // team, hidden+member, doesn't exist) — deliberate, so existence- // can't be probed across teams. Maps to "No Access" for parity- // with the email fetcher's per-id convention; "Deleted" would be- // misleading since we can't actually tell.- return {- ...base,- access: 'no_access' as const,- loading: false as const,- };- }-- const company = result.value;- const displayName =- company.name ?? company.domains[0]?.domain ?? 'Unknown Company';-- return {- ...base,- access: 'access' as const,- loading: false as const,- rawName: displayName,- name: displayName,- updatedAt: company.updatedAt,- };- })- );-}-/*** Reuse the thread-messages query the email block fetches on open: returns* cached data (any staleness — previews tolerate 24h), or joins an in-flightdiff --git a/apps/web/src/lib/service-clients/service-auth/crm.ts b/apps/web/src/lib/service-clients/service-auth/crm.tsnew file mode 100644index 0000000000..858f6c8825--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/crm.ts@@ -0,0 +1,12 @@+import { SERVER_HOSTS } from '@core/constant/servers';+import { fetchWithAuth } from './fetch';+import type { PatchTeamCrmSettingsRequest } from './generated/schemas/patchTeamCrmSettingsRequest';+import type { PatchTeamCrmSettingsResponse } from './generated/schemas/patchTeamCrmSettingsResponse';++/** Authenticated counterpart of the generated relative-URL endpoint. */+export function patchTeamCrmSettings(body: PatchTeamCrmSettingsRequest) {+ return fetchWithAuth<PatchTeamCrmSettingsResponse>(+ `${SERVER_HOSTS['auth-service']}/team/crm`,+ { method: 'PATCH', body: JSON.stringify(body) }+ );+}diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.jsonindex 0e9eb21f2b..3c35ff81d8 100644--- a/apps/web/tsconfig.json+++ b/apps/web/tsconfig.json@@ -158,15 +158,9 @@"@channel/*": ["./src/features/channel/*"],- "@companies/*": [- "./src/features/companies/*"- ],"@block-company/*": ["./src/features/block-company/*"],- "@contacts/*": [- "./src/features/contacts/*"- ],"@block-contact/*": ["./src/features/block-contact/*"],diff --git a/rules/ast-grep/ts-crm-public-boundary.yml b/rules/ast-grep/ts-crm-public-boundary.ymlnew file mode 100644index 0000000000..ab3541cbde--- /dev/null+++ b/rules/ast-grep/ts-crm-public-boundary.yml@@ -0,0 +1,18 @@+id: ts-crm-public-boundary+language: typescript+severity: error+message: Import a CRM entry point or host adapter; CRM implementation layers are private.+files:+ - apps/web/src/**+ignores:+ - apps/web/src/features/crm/**+rule:+ kind: string+ regex: "[/]crm[/](core|context|queries|primitives|components|views)[/]"+ any:+ - inside:+ kind: import_statement+ field: source+ - inside:+ kind: export_statement+ field: sourcediff --git a/rules/ast-grep/ts-feature-components-presentational.yml b/rules/ast-grep/ts-feature-components-presentational.ymlindex 25990f79cf..63b506130d 100644--- a/rules/ast-grep/ts-feature-components-presentational.yml+++ b/rules/ast-grep/ts-feature-components-presentational.yml@@ -13,6 +13,7 @@ note: |-untyped wire JSON for property-changed rows. In block-agent, `ui/` isthe presentation layer and `component/` is the composition layer.files:+ - apps/web/src/features/crm/components/**- apps/web/src/features/channels-view/components/ChannelDetailView*- apps/web/src/features/channel/components/channel-invite*- apps/web/src/features/projects/components/**diff --git a/rules/ast-grep/ts-feature-core-pure.yml b/rules/ast-grep/ts-feature-core-pure.ymlindex ca42574218..ad8f378a6f 100644--- a/rules/ast-grep/ts-feature-core-pure.yml+++ b/rules/ast-grep/ts-feature-core-pure.yml@@ -15,6 +15,7 @@ note: |-The shared @core/util/base64 codec is also pure and may be reused by email.Block-agent names its rendering layers `ui/` and `component/`.files:+ - apps/web/src/features/crm/core/**- apps/web/src/features/channel/core/channel-invite*- apps/web/src/features/projects/core/**- apps/web/src/features/block-agent/core/**diff --git a/rules/ast-grep/ts-feature-data-no-ui.yml b/rules/ast-grep/ts-feature-data-no-ui.ymlindex 6c958efcc4..489580abcc 100644--- a/rules/ast-grep/ts-feature-data-no-ui.yml+++ b/rules/ast-grep/ts-feature-data-no-ui.yml@@ -11,6 +11,8 @@ note: |-with fake clients and controllers with fake capabilities; neither importsrendering code, including block-agent’s `ui/` and `component/` layers.files:+ - apps/web/src/features/crm/queries/**+ - apps/web/src/features/crm/primitives/**- apps/web/src/features/channels-view/queries/channel-detail-source*- apps/web/src/features/channels-view/primitives/create-channel-detail*- apps/web/src/features/channel/queries/channel-invite*diff --git a/rules/ast-grep/ts-feature-layers-use-context.yml b/rules/ast-grep/ts-feature-layers-use-context.ymlindex b6e4cbf91e..37424f6dba 100644--- a/rules/ast-grep/ts-feature-layers-use-context.yml+++ b/rules/ast-grep/ts-feature-layers-use-context.yml@@ -15,6 +15,11 @@ note: |-`files` in each ts-/tsx-feature-* rule. Block-agent uses `ui/` forpresentation and `component/` for composition.files:+ - apps/web/src/features/crm/queries/**+ - apps/web/src/features/crm/primitives/**+ - apps/web/src/features/crm/components/**+ - apps/web/src/features/crm/views/**+ - apps/web/src/features/crm/context/**- apps/web/src/features/channels-view/queries/channel-detail-source*- apps/web/src/features/channels-view/primitives/create-channel-detail*- apps/web/src/features/channels-view/context/channel-detail-source*diff --git a/rules/ast-grep/ts-no-service-client-outside-queries.yml b/rules/ast-grep/ts-no-service-client-outside-queries.ymlindex 5efb7da0e7..d8ac27e105 100644--- a/rules/ast-grep/ts-no-service-client-outside-queries.yml+++ b/rules/ast-grep/ts-no-service-client-outside-queries.yml@@ -16,6 +16,11 @@ note: |-files:- apps/web/src/**ignores:+ # FE-33 composition roots pass the client to CRM query adapters.+ - apps/web/src/features/crm/crm-adapter.ts+ - apps/web/src/features/crm/preview-adapter.ts+ - apps/web/src/features/crm/record-adapter.ts+ - apps/web/src/features/crm/stage-adapter.ts- '**/queries/**'- '**/queries.ts'- '**/service-clients/**'diff --git a/rules/ast-grep/tsx-crm-public-boundary.yml b/rules/ast-grep/tsx-crm-public-boundary.ymlnew file mode 100644index 0000000000..1173f65107--- /dev/null+++ b/rules/ast-grep/tsx-crm-public-boundary.yml@@ -0,0 +1,18 @@+id: tsx-crm-public-boundary+language: tsx+severity: error+message: Import a CRM entry point or host adapter; CRM implementation layers are private.+files:+ - apps/web/src/**+ignores:+ - apps/web/src/features/crm/**+rule:+ kind: string+ regex: "[/]crm[/](core|context|queries|primitives|components|views)[/]"+ any:+ - inside:+ kind: import_statement+ field: source+ - inside:+ kind: export_statement+ field: sourcediff --git a/rules/ast-grep/tsx-feature-components-presentational.yml b/rules/ast-grep/tsx-feature-components-presentational.ymlindex 68d7e62cb3..28c96c20de 100644--- a/rules/ast-grep/tsx-feature-components-presentational.yml+++ b/rules/ast-grep/tsx-feature-components-presentational.yml@@ -13,6 +13,7 @@ note: |-untyped wire JSON for property-changed rows. In block-agent, `ui/` isthe presentation layer and `component/` is the composition layer.files:+ - apps/web/src/features/crm/components/**- apps/web/src/features/channels-view/components/ChannelDetailView*- apps/web/src/features/channel/components/channel-invite*- apps/web/src/features/projects/components/**diff --git a/rules/ast-grep/tsx-feature-core-pure.yml b/rules/ast-grep/tsx-feature-core-pure.ymlindex 8db2170b88..13d50c2127 100644--- a/rules/ast-grep/tsx-feature-core-pure.yml+++ b/rules/ast-grep/tsx-feature-core-pure.yml@@ -15,6 +15,7 @@ note: |-The shared @core/util/base64 codec is also pure and may be reused by email.Block-agent names its rendering layers `ui/` and `component/`.files:+ - apps/web/src/features/crm/core/**- apps/web/src/features/channel/core/channel-invite*- apps/web/src/features/projects/core/**- apps/web/src/features/block-agent/core/**diff --git a/rules/ast-grep/tsx-feature-data-no-ui.yml b/rules/ast-grep/tsx-feature-data-no-ui.ymlindex b8ec642459..4e58e2ebc3 100644--- a/rules/ast-grep/tsx-feature-data-no-ui.yml+++ b/rules/ast-grep/tsx-feature-data-no-ui.yml@@ -11,6 +11,8 @@ note: |-with fake clients and controllers with fake capabilities; neither importsrendering code, including block-agent’s `ui/` and `component/` layers.files:+ - apps/web/src/features/crm/queries/**+ - apps/web/src/features/crm/primitives/**- apps/web/src/features/channels-view/queries/channel-detail-source*- apps/web/src/features/channels-view/primitives/create-channel-detail*- apps/web/src/features/channel/queries/channel-invite*diff --git a/rules/ast-grep/tsx-feature-layers-use-context.yml b/rules/ast-grep/tsx-feature-layers-use-context.ymlindex 0414d5a09a..13220a9e8f 100644--- a/rules/ast-grep/tsx-feature-layers-use-context.yml+++ b/rules/ast-grep/tsx-feature-layers-use-context.yml@@ -15,6 +15,11 @@ note: |-`files` in each ts-/tsx-feature-* rule. Block-agent uses `ui/` forpresentation and `component/` for composition.files:+ - apps/web/src/features/crm/queries/**+ - apps/web/src/features/crm/primitives/**+ - apps/web/src/features/crm/components/**+ - apps/web/src/features/crm/views/**+ - apps/web/src/features/crm/context/**- apps/web/src/features/channels-view/queries/channel-detail-source*- apps/web/src/features/channels-view/primitives/create-channel-detail*- apps/web/src/features/channels-view/context/channel-detail-source*diff --git a/rules/ast-grep/tsx-no-service-client-outside-queries.yml b/rules/ast-grep/tsx-no-service-client-outside-queries.ymlindex 6c41ea7419..bcb246d7cc 100644--- a/rules/ast-grep/tsx-no-service-client-outside-queries.yml+++ b/rules/ast-grep/tsx-no-service-client-outside-queries.yml@@ -16,6 +16,11 @@ note: |-files:- apps/web/src/**ignores:+ # FE-33 composition roots pass the client to CRM query adapters.+ - apps/web/src/features/crm/crm-adapter.ts+ - apps/web/src/features/crm/preview-adapter.ts+ - apps/web/src/features/crm/record-adapter.ts+ - apps/web/src/features/crm/stage-adapter.ts- '**/queries/**'- '**/queries.ts'- '**/service-clients/**'