Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(crm): add left bar and navigation breadcrumb stack (#6509)

Jacob Beckermanfcc28fbafe45
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsx
index 8d766b22b2..59f2e245ba 100644
--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx
+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx
@@ -592,7 +592,8 @@ registerComponent(
initialCrmView={initialCrmView}
/>
);
- })
+ }),
+ { splitPanelLayout: 'composable' }
);
registerComponent(
diff --git a/apps/web/src/components/ui/components/NavRow.tsx b/apps/web/src/components/ui/components/NavRow.tsx
index 22b2ae528c..2dada75429 100644
--- a/apps/web/src/components/ui/components/NavRow.tsx
+++ b/apps/web/src/components/ui/components/NavRow.tsx
@@ -11,10 +11,6 @@ import { Button, type ButtonProps } from './Button';
* padding, slim-mode `justify-center`, etc. — are passed through via `class`,
* which is merged last so callers can extend without leaking layout concerns in.
*/
-const NAV_ROW_BASE =
- 'flex items-center justify-start text-sm gap-2 cursor-default w-full rounded-md py-1 px-2 text-ink-extra-muted not-disabled:hover:bg-ink/3';
-const NAV_ROW_ACTIVE = 'bg-ink/6 not-disabled:hover:bg-ink/6 text-ink';
-
export type NavRowProps = ButtonProps & { active?: boolean };
export const NavRow = (props: NavRowProps) => {
@@ -23,7 +19,15 @@ export const NavRow = (props: NavRowProps) => {
<Button
variant="ghost"
{...rest}
- class={cn(NAV_ROW_BASE, local.active && NAV_ROW_ACTIVE, local.class)}
+ // Rows paint a single background, like Home items. Suppress Button's
+ // additional hover/press scrim so hover never doubles up to selection.
+ class={cn(
+ 'flex items-center justify-start text-sm gap-2 cursor-default w-full rounded-md py-1 px-2 text-ink-extra-muted bg-none!',
+ local.active
+ ? 'bg-active text-ink not-disabled:hover:bg-active'
+ : 'not-disabled:hover:bg-hover not-disabled:hover:text-ink',
+ local.class
+ )}
/>
);
};
diff --git a/apps/web/src/components/view-shell/ViewSidebar.tsx b/apps/web/src/components/view-shell/ViewSidebar.tsx
index e21f48ac6b..9987a6b074 100644
--- a/apps/web/src/components/view-shell/ViewSidebar.tsx
+++ b/apps/web/src/components/view-shell/ViewSidebar.tsx
@@ -90,8 +90,8 @@ function Item(props: NavRowProps) {
active={local.active}
aria-current={ariaCurrent()}
class={cn(
- 'h-8 gap-2 rounded-xl border-0 px-2.5 py-0 text-sm font-normal text-ink-muted transition-none not-disabled:hover:bg-hover not-disabled:hover:text-ink touch:h-11',
- local.active && 'bg-active text-ink not-disabled:hover:bg-active',
+ 'h-8 gap-2 rounded-xl border-0 px-2.5 py-0 text-sm font-normal transition-none touch:h-11',
+ !local.active && 'text-ink-muted',
local.class
)}
/>
diff --git a/apps/web/src/features/block-company/component/CompanyBlockAdapter.tsx b/apps/web/src/features/block-company/component/CompanyBlockAdapter.tsx
index 364c899b62..54bcda7f35 100644
--- a/apps/web/src/features/block-company/component/CompanyBlockAdapter.tsx
+++ b/apps/web/src/features/block-company/component/CompanyBlockAdapter.tsx
@@ -1,4 +1,7 @@
import { Company } from '@companies/Company/Company';
+import { CrmCopyLinkButton } from '@companies/components/CrmCopyLinkButton';
+import { HeaderIsland } from '@components/app/split-layout/components/HeaderIsland';
+import { SplitHeaderRight } from '@components/app/split-layout/components/SplitHeader';
import { useBlockId } from '@core/block';
/**
@@ -8,5 +11,14 @@ import { useBlockId } from '@core/block';
*/
export function CompanyBlockAdapter() {
const companyId = useBlockId();
- return <Company companyId={companyId} />;
+ return (
+ <>
+ <SplitHeaderRight>
+ <HeaderIsland>
+ <CrmCopyLinkButton type="company" id={companyId} />
+ </HeaderIsland>
+ </SplitHeaderRight>
+ <Company companyId={companyId} />
+ </>
+ );
}
diff --git a/apps/web/src/features/block-contact/component/ContactBlockAdapter.tsx b/apps/web/src/features/block-contact/component/ContactBlockAdapter.tsx
index 1541ff3905..b346bf673b 100644
--- a/apps/web/src/features/block-contact/component/ContactBlockAdapter.tsx
+++ b/apps/web/src/features/block-contact/component/ContactBlockAdapter.tsx
@@ -1,3 +1,6 @@
+import { CrmCopyLinkButton } from '@companies/components/CrmCopyLinkButton';
+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';
@@ -8,5 +11,14 @@ import { useBlockId } from '@core/block';
*/
export function ContactBlockAdapter() {
const contactId = useBlockId();
- return <Contact contactId={contactId} />;
+ return (
+ <>
+ <SplitHeaderRight>
+ <HeaderIsland>
+ <CrmCopyLinkButton type="contact" id={contactId} />
+ </HeaderIsland>
+ </SplitHeaderRight>
+ <Contact contactId={contactId} />
+ </>
+ );
}
diff --git a/apps/web/src/features/companies/Company/Company.tsx b/apps/web/src/features/companies/Company/Company.tsx
index 387298f939..0e23258348 100644
--- a/apps/web/src/features/companies/Company/Company.tsx
+++ b/apps/web/src/features/companies/Company/Company.tsx
@@ -1,8 +1,12 @@
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 { useCompanyQuery } from '@queries/crm/companies';
+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';
@@ -17,11 +21,17 @@ import { CompanySharingSection } from './CompanySharingSection';
* page: middle content constrained to a centered column, additional info in
* the right-hand SidePanel.
*/
-export function Company(props: { companyId: string }) {
+export function Company(props: {
+ companyId: string;
+ headerToggle?: boolean;
+ onHidden?: () => void;
+ onOpenContact?: (contact: CompanyContact) => void;
+}) {
+ const listsFlag = useFeatureFlag(enableCrmLists);
const { company, contacts } = useCompanyQuery(() => props.companyId);
return (
- <SidePanel.Layout>
+ <SidePanel.Layout headerToggle={props.headerToggle}>
<div class="flex h-full flex-col overflow-y-auto scrollbar-hidden">
<div class="mx-auto flex w-full max-w-3xl min-w-0 grow flex-col gap-6 px-6 pt-12 pb-12">
<CompanyHeader company={company()} />
@@ -46,6 +56,11 @@ export function Company(props: { companyId: string }) {
>
<CompanyPropertiesSection companyId={props.companyId} />
</SidePanel.Section>
+ <Show when={listsFlag().enabled}>
+ <Suspense>
+ <CompanyListsSection companyId={props.companyId} />
+ </Suspense>
+ </Show>
<SidePanel.Section
id="company-contacts"
title="Contacts"
@@ -69,10 +84,14 @@ export function Company(props: { companyId: string }) {
</Button>
}
>
- <CompanyContactsSection company={company()} contacts={contacts()} />
+ <CompanyContactsSection
+ company={company()}
+ contacts={contacts()}
+ onOpenContact={props.onOpenContact}
+ />
</SidePanel.Section>
<SidePanel.Section id="company-sharing" title="Sharing" order={25}>
- <CompanySharingSection company={company()} />
+ <CompanySharingSection company={company()} onHidden={props.onHidden} />
</SidePanel.Section>
{/* TODO: add a References section (inbound channel messages + documents)
once the references backend supports the crm_company entity type. */}
diff --git a/apps/web/src/features/companies/Company/CompanyContactsSection.tsx b/apps/web/src/features/companies/Company/CompanyContactsSection.tsx
index 9e66f651f1..0774c99eeb 100644
--- a/apps/web/src/features/companies/Company/CompanyContactsSection.tsx
+++ b/apps/web/src/features/companies/Company/CompanyContactsSection.tsx
@@ -6,6 +6,7 @@ import { createMemo, createSignal, For, Show } from 'solid-js';
export function CompanyContactsSection(props: {
company?: CrmCompanyEntity;
contacts?: CompanyContact[];
+ onOpenContact?: (contact: CompanyContact) => void;
}) {
const contacts = () => props.contacts ?? [];
const { openWithSplit } = useSplitLayout();
@@ -56,15 +57,19 @@ export function CompanyContactsSection(props: {
{(contact) => (
<button
type="button"
- onClick={(event) =>
+ onClick={(event) => {
+ if (props.onOpenContact && !event.shiftKey) {
+ props.onOpenContact(contact);
+ return;
+ }
openWithSplit(
{
type: 'contact',
id: contact.id,
},
{ activate: true, preferNewSplit: event.shiftKey }
- )
- }
+ );
+ }}
class="flex min-w-0 flex-col gap-0.5 rounded-md px-1 py-0.5 text-left hover:bg-ink-muted/[0.06]"
>
<span class="truncate text-sm">
diff --git a/apps/web/src/features/companies/Company/CompanySharingSection.tsx b/apps/web/src/features/companies/Company/CompanySharingSection.tsx
index 40ab0ad0b4..0078b6f3f1 100644
--- a/apps/web/src/features/companies/Company/CompanySharingSection.tsx
+++ b/apps/web/src/features/companies/Company/CompanySharingSection.tsx
@@ -12,7 +12,10 @@ import { Show } from 'solid-js';
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]';
-export function CompanySharingSection(props: { company?: CrmCompanyEntity }) {
+export function CompanySharingSection(props: {
+ company?: CrmCompanyEntity;
+ onHidden?: () => void;
+}) {
const hideMutation = useSetCompanyHiddenMutation();
const emailSyncMutation = useSetEmailSyncMutation();
const { replaceOrInsertSplit } = useSplitLayout();
@@ -32,7 +35,8 @@ export function CompanySharingSection(props: { company?: CrmCompanyEntity }) {
// Un-hide leaves them on the block.
if (willHide) {
toast.success('Company hidden.');
- replaceOrInsertSplit({ type: 'component', id: 'companies' });
+ if (props.onHidden) props.onHidden();
+ else replaceOrInsertSplit({ type: 'component', id: 'companies' });
}
} catch (error) {
console.error('failed to update company sharing', error);
diff --git a/apps/web/src/features/companies/components/CrmCopyLinkButton.tsx b/apps/web/src/features/companies/components/CrmCopyLinkButton.tsx
new file mode 100644
index 0000000000..a8492d9731
--- /dev/null
+++ b/apps/web/src/features/companies/components/CrmCopyLinkButton.tsx
@@ -0,0 +1,35 @@
+import { toast } from '@core/component/Toast/Toast';
+import { buildSimpleEntityUrl } from '@core/util/url';
+import LinkIcon from '@phosphor/link.svg';
+import { Button } from '@ui';
+
+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.');
+ }
+ };
+
+ return (
+ <Button
+ variant="outline"
+ size="sm"
+ depth={2}
+ class="shrink-0 bg-surface"
+ label={`Copy ${props.type} link`}
+ tooltip={`Copy ${props.type} link`}
+ onClick={() => void copyLink()}
+ >
+ <LinkIcon class="size-3.5" />
+ Copy link
+ </Button>
+ );
+}
diff --git a/apps/web/src/features/companies/components/CrmListDialog.tsx b/apps/web/src/features/companies/components/CrmListDialog.tsx
new file mode 100644
index 0000000000..f4364544ea
--- /dev/null
+++ b/apps/web/src/features/companies/components/CrmListDialog.tsx
@@ -0,0 +1,149 @@
+import { Button, Dialog, Panel } from '@ui';
+import { createMemo, createSignal, For, Show } from 'solid-js';
+
+/** Mounted for one editing session so cancel never changes the stored collection. */
+export function CrmListDialog(props: {
+ initial?: { id: string; name: string; companyIds: string[] };
+ companies: { id: string; name: string }[];
+ loading: boolean;
+ onSave: (name: string, ids: string[]) => Promise<void>;
+ onDelete?: () => Promise<void>;
+ onClose: () => void;
+}) {
+ const [name, setName] = createSignal(props.initial?.name ?? '');
+ const [search, setSearch] = createSignal('');
+ const [ids, setIds] = createSignal(props.initial?.companyIds ?? []);
+ const [pending, setPending] = createSignal(false);
+ const [error, setError] = createSignal('');
+ const filtered = createMemo(() =>
+ props.companies.filter((c) =>
+ c.name.toLowerCase().includes(search().toLowerCase())
+ )
+ );
+ async function save(event: SubmitEvent) {
+ event.preventDefault();
+ if (pending() || !name().trim()) return;
+ setPending(true);
+ try {
+ await props.onSave(name().trim(), ids());
+ props.onClose();
+ } catch {
+ setError('Could not save this list. Please try again.');
+ } finally {
+ setPending(false);
+ }
+ }
+ async function remove() {
+ if (pending() || !props.onDelete) return;
+ setPending(true);
+ try {
+ await props.onDelete();
+ props.onClose();
+ } catch {
+ setError('Could not delete this list. Please try again.');
+ } finally {
+ setPending(false);
+ }
+ }
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => !open && !pending() && props.onClose()}
+ class="w-112 max-w-[calc(100vw-2rem)]"
+ >
+ <Panel>
+ <Panel.Body>
+ <form class="flex flex-col gap-4 p-5" onSubmit={save}>
+ <Dialog.Title class="text-base font-semibold">
+ {props.initial ? 'Edit list' : 'New list'}
+ </Dialog.Title>
+ <Dialog.Description class="text-sm text-ink-muted">
+ A personal collection. Add companies without changing their stage
+ or owner.
+ </Dialog.Description>
+ <label class="flex flex-col gap-1.5 text-sm">
+ List name
+ <input
+ required
+ maxlength={100}
+ value={name()}
+ onInput={(e) => setName(e.currentTarget.value)}
+ placeholder="e.g. Design partners"
+ class="rounded-lg border border-edge-muted bg-input px-3 py-2 outline-none focus:border-accent"
+ />
+ </label>
+ <input
+ aria-label="Find companies for list"
+ placeholder="Find companies…"
+ value={search()}
+ onInput={(e) => setSearch(e.currentTarget.value)}
+ class="rounded-lg border border-edge-muted bg-input px-3 py-2 text-sm outline-none focus:border-accent"
+ />
+ <div class="max-h-64 overflow-auto">
+ <For each={filtered()}>
+ {(company) => (
+ <label class="flex items-center gap-3 rounded-lg px-2 py-2 text-sm hover:bg-hover">
+ <input
+ type="checkbox"
+ checked={ids().includes(company.id)}
+ disabled={pending()}
+ onChange={(e) =>
+ setIds((current) =>
+ e.currentTarget.checked
+ ? [...current, company.id]
+ : current.filter((id) => id !== company.id)
+ )
+ }
+ />
+ <span class="truncate">{company.name}</span>
+ </label>
+ )}
+ </For>
+ <Show when={!filtered().length}>
+ <p class="py-3 text-sm text-ink-muted">
+ {props.loading
+ ? 'Loading companies…'
+ : 'No matching companies'}
+ </p>
+ </Show>
+ </div>
+ <p class="text-xs text-ink-muted">
+ {ids().length} selected · Browse up to 500 recent companies
+ </p>
+ <Show when={error()}>
+ <p role="alert" class="text-sm text-failure">
+ {error()}
+ </p>
+ </Show>
+ <div class="flex items-center gap-2">
+ <Show when={props.onDelete}>
+ <Button
+ variant="ghost"
+ disabled={pending()}
+ onClick={() => void remove()}
+ >
+ Delete list
+ </Button>
+ </Show>
+ <Button
+ variant="ghost"
+ class="ml-auto"
+ disabled={pending()}
+ onClick={props.onClose}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ variant="accent"
+ disabled={pending() || !name().trim()}
+ >
+ {pending() ? 'Saving…' : 'Save list'}
+ </Button>
+ </div>
+ </form>
+ </Panel.Body>
+ </Panel>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/features/companies/components/CrmSidebar.tsx b/apps/web/src/features/companies/components/CrmSidebar.tsx
new file mode 100644
index 0000000000..e17a1cec0b
--- /dev/null
+++ b/apps/web/src/features/companies/components/CrmSidebar.tsx
@@ -0,0 +1,188 @@
+import { CollapsibleSection, ViewSidebar } from '@app/components/view-shell';
+import { SidebarCreateHeader } from '@app/components/view-shell/SidebarCreateButton';
+import { TabsInset } from '@core/component/TabsInset';
+import ExportIcon from '@phosphor/download-simple.svg';
+import GearIcon from '@phosphor/gear-six.svg';
+import ListIcon from '@phosphor/list-bullets.svg';
+import PlusIcon from '@phosphor/plus.svg';
+import SidebarIcon from '@phosphor/sidebar-simple.svg';
+import StackIcon from '@phosphor/stack.svg';
+import ImportIcon from '@phosphor/upload-simple.svg';
+import { Button, Tooltip } from '@ui';
+import { createSignal, For, Show } from 'solid-js';
+import { CRM_VIEWS } from '../core/crm-navigation';
+
+export function CrmSidebar(props: {
+ active: string;
+ viewMode: 'board' | 'list';
+ onViewModeChange: (mode: 'board' | 'list') => void;
+ lists: { id: string; name: string; count: number }[];
+ savedViews: { id: string; name: string }[];
+ listsEnabled: boolean;
+ listsLoading: boolean;
+ listsError: boolean;
+ canCreateList: boolean;
+ onNavigate: (id: string) => void;
+ onCreate: () => void;
+ onNewList: () => void;
+ onImport: () => void;
+ onExport: () => void;
+ onSettings: () => void;
+ onCollapse: () => void;
+}) {
+ const [viewsOpen, setViewsOpen] = createSignal(true);
+ const [listsOpen, setListsOpen] = createSignal(true);
+ return (
+ <ViewSidebar.Root aria-label="CRM navigation" class="gap-4 bg-panel">
+ <SidebarCreateHeader
+ title="Customers"
+ label="New company"
+ onCreate={props.onCreate}
+ actions={
+ <Tooltip label="Collapse CRM sidebar">
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ label="Collapse CRM sidebar"
+ onClick={props.onCollapse}
+ >
+ <SidebarIcon class="size-4" />
+ </Button>
+ </Tooltip>
+ }
+ />
+ <ViewSidebar.Content class="flex flex-col gap-6">
+ <div class="px-1.5">
+ <TabsInset
+ aria-label="Company layout"
+ fullWidth
+ class="h-auto"
+ labelClass="py-1.5"
+ list={[
+ { value: 'board', label: 'Board' },
+ { value: 'list', label: 'List' },
+ ]}
+ value={props.viewMode}
+ onChange={(mode) =>
+ props.onViewModeChange(mode === 'board' ? 'board' : 'list')
+ }
+ />
+ </div>
+ <CollapsibleSection.Root open={viewsOpen()} onOpenChange={setViewsOpen}>
+ <CollapsibleSection.Trigger class="text-xs">
+ <span>Views</span>
+ <CollapsibleSection.Indicator />
+ </CollapsibleSection.Trigger>
+ <CollapsibleSection.Content>
+ <ViewSidebar.Nav aria-label="Company views">
+ <For each={CRM_VIEWS}>
+ {(view) => (
+ <Tooltip label={view.description} placement="right">
+ <ViewSidebar.Item
+ active={props.active === view.id}
+ onClick={() => props.onNavigate(view.id)}
+ >
+ <span class="ml-7 truncate">{view.label}</span>
+ </ViewSidebar.Item>
+ </Tooltip>
+ )}
+ </For>
+ <For each={props.savedViews}>
+ {(view) => (
+ <ViewSidebar.Item
+ active={props.active === view.id}
+ title={view.name}
+ onClick={() => props.onNavigate(view.id)}
+ >
+ <ViewSidebar.Icon>
+ <StackIcon class="size-4" />
+ </ViewSidebar.Icon>
+ <span class="truncate">{view.name}</span>
+ </ViewSidebar.Item>
+ )}
+ </For>
+ </ViewSidebar.Nav>
+ </CollapsibleSection.Content>
+ </CollapsibleSection.Root>
+ <Show when={props.listsEnabled}>
+ <CollapsibleSection.Root
+ open={listsOpen()}
+ onOpenChange={setListsOpen}
+ >
+ <CollapsibleSection.Trigger class="text-xs">
+ <span>Lists</span>
+ <CollapsibleSection.Indicator />
+ </CollapsibleSection.Trigger>
+ <CollapsibleSection.Content>
+ <ViewSidebar.Nav aria-label="Company lists">
+ <For each={props.lists}>
+ {(list) => (
+ <ViewSidebar.Item
+ active={props.active === `list:${list.id}`}
+ title={list.name}
+ onClick={() => props.onNavigate(`list:${list.id}`)}
+ >
+ <ViewSidebar.Icon>
+ <ListIcon class="size-4" />
+ </ViewSidebar.Icon>
+ <span class="min-w-0 flex-1 truncate">{list.name}</span>
+ <span class="text-xs tabular-nums text-ink-extra-muted">
+ {list.count}
+ </span>
+ </ViewSidebar.Item>
+ )}
+ </For>
+ <Show when={!props.lists.length}>
+ <p class="px-3 pb-2 text-xs leading-5 text-ink-extra-muted">
+ {props.listsLoading
+ ? 'Loading lists…'
+ : props.listsError
+ ? 'Could not load lists.'
+ : 'Your own collections of companies.'}
+ </p>
+ </Show>
+ <ViewSidebar.Item
+ onClick={props.onNewList}
+ disabled={!props.canCreateList}
+ >
+ <ViewSidebar.Icon>
+ <PlusIcon class="size-4" />
+ </ViewSidebar.Icon>
+ <span>New list</span>
+ </ViewSidebar.Item>
+ </ViewSidebar.Nav>
+ </CollapsibleSection.Content>
+ </CollapsibleSection.Root>
+ </Show>
+ </ViewSidebar.Content>
+ <div class="shrink-0 border-t border-edge-muted p-1.5 py-3">
+ <ViewSidebar.Nav aria-label="CRM tools">
+ <ViewSidebar.Item
+ onClick={props.onImport}
+ disabled={!props.canCreateList}
+ >
+ <ViewSidebar.Icon>
+ <ImportIcon class="size-4" />
+ </ViewSidebar.Icon>
+ Import
+ </ViewSidebar.Item>
+ <ViewSidebar.Item
+ onClick={props.onExport}
+ disabled={!props.canCreateList}
+ >
+ <ViewSidebar.Icon>
+ <ExportIcon class="size-4" />
+ </ViewSidebar.Icon>
+ Export
+ </ViewSidebar.Item>
+ <ViewSidebar.Item onClick={props.onSettings}>
+ <ViewSidebar.Icon>
+ <GearIcon class="size-4" />
+ </ViewSidebar.Icon>
+ CRM settings
+ </ViewSidebar.Item>
+ </ViewSidebar.Nav>
+ </div>
+ </ViewSidebar.Root>
+ );
+}
diff --git a/apps/web/src/features/companies/core/crm-export.test.ts b/apps/web/src/features/companies/core/crm-export.test.ts
new file mode 100644
index 0000000000..4cbff3384f
--- /dev/null
+++ b/apps/web/src/features/companies/core/crm-export.test.ts
@@ -0,0 +1,49 @@
+import { parseCsv } from '@core/util/csv';
+import { describe, expect, it } from 'vitest';
+import { createCrmCsv, personExportRecord } from './crm-export';
+
+describe('CRM CSV export', () => {
+ const columns = [
+ { id: 'name', label: 'Name' },
+ { id: 'value', label: 'Value' },
+ ];
+ it('round trips quotes, commas, newlines and unicode with a UTF-8 BOM', () => {
+ const rows = [{ name: 'Zoë, "Founder"', value: 'first\nsecond' }];
+ const csv = createCrmCsv(columns, rows);
+ expect(csv.startsWith('\uFEFF')).toBe(true);
+ const result = parseCsv(csv.slice(1));
+ expect(result.ok && result.records).toEqual([
+ { Name: rows[0].name, Value: rows[0].value },
+ ]);
+ });
+ it('exports only selected columns, keeping zero and false', () => {
+ expect(
+ createCrmCsv(columns, [{ name: false, value: 0, hidden: 'private' }])
+ ).toBe('\uFEFF"Name","Value"\r\n"false","0"\r\n');
+ });
+ it('neutralizes spreadsheet formulas in text without altering numeric values', () => {
+ const csv = createCrmCsv(columns, [
+ { name: ' =HYPERLINK("x")', value: -42 },
+ ]);
+ expect(csv).toContain('"\' =HYPERLINK(""x"")"');
+ expect(csv).toContain('"-42"');
+ });
+ it('can export a deliberately empty view as headers only', () => {
+ expect(createCrmCsv(columns, [])).toBe('\uFEFF"Name","Value"\r\n');
+ });
+ it('uses contact interaction dates rather than record modification dates', () => {
+ const row = personExportRecord({
+ id: 'p',
+ companyId: 'c',
+ companyName: 'Acme',
+ email: '[email protected]',
+ hidden: false,
+ createdAt: '2026-01-01',
+ updatedAt: '2026-09-01',
+ firstInteraction: '2025-01-01',
+ lastInteraction: '2026-08-01',
+ });
+ expect(row.lastInteraction).toBe('2026-08-01');
+ expect(row.firstInteraction).toBe('2025-01-01');
+ });
+});
diff --git a/apps/web/src/features/companies/core/crm-export.ts b/apps/web/src/features/companies/core/crm-export.ts
new file mode 100644
index 0000000000..322268b3f4
--- /dev/null
+++ b/apps/web/src/features/companies/core/crm-export.ts
@@ -0,0 +1,94 @@
+import type { CrmCompanyEntity } from '@entity';
+import { SYSTEM_PROPERTY_IDS } from '@property/constants';
+import type { CrmPerson } from './crm-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 },
+ { id: 'companyName', label: 'Company', default: true },
+ { id: 'lastInteraction', label: 'Last contacted', default: true },
+ { id: 'firstInteraction', label: 'First contact', default: true },
+ { id: 'createdAt', label: 'Date added' },
+ { id: 'id', label: 'Contact ID' },
+ { id: 'companyId', label: 'Company ID' },
+];
+export type ExportRecord = Record<
+ string,
+ string | number | boolean | null | undefined
+>;
+
+/** Quote RFC 4180 fields and neutralize spreadsheet formulas in text values. */
+export function createCrmCsv(columns: ExportColumn[], rows: ExportRecord[]) {
+ const cell = (value: ExportRecord[string]) => {
+ let text = value == null ? '' : String(value);
+ if (typeof value === 'string' && /^[\s]*[=+\-@]/.test(text))
+ text = `'${text}`;
+ return `"${text.replaceAll('"', '""')}"`;
+ };
+ return (
+ '\uFEFF' +
+ [
+ columns.map((column) => cell(column.label)).join(','),
+ ...rows.map((row) =>
+ columns.map((column) => cell(row[column.id])).join(',')
+ ),
+ ].join('\r\n') +
+ '\r\n'
+ );
+}
+
+export function companyExportRecord(
+ company: CrmCompanyEntity,
+ stage: string,
+ owner: string,
+ propertyValue: (
+ property: NonNullable<CrmCompanyEntity['properties']>[number]
+ ) => string | number | boolean
+): ExportRecord {
+ return {
+ id: company.id,
+ name: company.name,
+ domains: company.domains.map((domain) => domain.domain).join('; '),
+ stage,
+ owner,
+ lastInteraction: String(company.updatedAt ?? ''),
+ firstInteraction: String(company.createdAt ?? ''),
+ description: company.description,
+ emailSync: company.emailSync,
+ ...Object.fromEntries(
+ (company.properties ?? []).map((property) => [
+ `property:${property.definition.id}`,
+ propertyValue(property),
+ ])
+ ),
+ };
+}
+export function personExportRecord(person: CrmPerson): ExportRecord {
+ return {
+ id: person.id,
+ name: person.name,
+ email: person.email,
+ companyName: person.companyName,
+ companyId: person.companyId,
+ firstInteraction: person.firstInteraction,
+ lastInteraction: person.lastInteraction,
+ createdAt: person.createdAt,
+ };
+}
diff --git a/apps/web/src/features/companies/core/crm-navigation.test.ts b/apps/web/src/features/companies/core/crm-navigation.test.ts
new file mode 100644
index 0000000000..8eeab0243c
--- /dev/null
+++ b/apps/web/src/features/companies/core/crm-navigation.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from 'vitest';
+import {
+ isCrmListConfig,
+ matchesInteractionWindow,
+ needsCompanyFollowUp,
+} from './crm-navigation';
+
+const now = Date.parse('2026-09-16T12:00:00Z');
+const daysAgo = (days: number) => new Date(now - days * 86400000).toISOString();
+describe('CRM interaction views', () => {
+ it('follow-up requires a non-churned stage as well as inactivity', () => {
+ for (const stage of [undefined, '', 'Churned', ' churned ']) {
+ expect(needsCompanyFollowUp(daysAgo(30), stage, now)).toBe(false);
+ }
+ for (const stage of ['Lead', 'Demo', 'Customer', 'Custom evaluation']) {
+ expect(needsCompanyFollowUp(daysAgo(14), stage, now)).toBe(true);
+ expect(needsCompanyFollowUp(daysAgo(13), stage, now)).toBe(false);
+ expect(needsCompanyFollowUp(null, stage, now)).toBe(true);
+ }
+ });
+ it('includes the follow-up boundary and excludes recent interactions', () => {
+ expect(matchesInteractionWindow(daysAgo(14), 'needs-follow-up', now)).toBe(
+ true
+ );
+ expect(matchesInteractionWindow(daysAgo(13), 'needs-follow-up', now)).toBe(
+ false
+ );
+ expect(matchesInteractionWindow(null, 'needs-follow-up', now)).toBe(true);
+ });
+ it('recent activity excludes missing, invalid, future and older timestamps', () => {
+ for (const value of [null, 'invalid', daysAgo(-1), daysAgo(8)]) {
+ expect(matchesInteractionWindow(value, 'recently-active', now)).toBe(
+ false
+ );
+ }
+ expect(matchesInteractionWindow(daysAgo(7), 'recently-active', now)).toBe(
+ true
+ );
+ });
+});
+describe('CRM collection storage', () => {
+ it('accepts empty collections without mistaking saved filters for lists', () => {
+ expect(
+ isCrmListConfig({ kind: 'crm-list', teamId: 'team', companyIds: [] })
+ ).toBe(true);
+ expect(isCrmListConfig({ kind: 'crm', filters: {} })).toBe(false);
+ });
+ it('rejects malformed membership and missing team scope', () => {
+ expect(
+ isCrmListConfig({
+ kind: 'crm-list',
+ teamId: 'team',
+ companyIds: ['id', 2],
+ })
+ ).toBe(false);
+ expect(isCrmListConfig({ kind: 'crm-list', companyIds: ['id'] })).toBe(
+ false
+ );
+ });
+});
diff --git a/apps/web/src/features/companies/core/crm-navigation.ts b/apps/web/src/features/companies/core/crm-navigation.ts
new file mode 100644
index 0000000000..69f52bf4a2
--- /dev/null
+++ b/apps/web/src/features/companies/core/crm-navigation.ts
@@ -0,0 +1,75 @@
+export const CRM_VIEWS = [
+ {
+ id: 'active',
+ label: 'All companies',
+ description: 'Every visible company in your CRM',
+ },
+ {
+ id: 'my-companies',
+ label: 'My companies',
+ description: 'Companies assigned to you',
+ },
+ {
+ id: 'needs-follow-up',
+ label: 'Needs follow-up',
+ description:
+ 'Has a stage other than Churned, with no interaction in the last 14 days',
+ },
+ {
+ id: 'recently-active',
+ label: 'Recently active',
+ description:
+ 'Team email activity in the last 7 days. Newly added companies may also appear.',
+ },
+ {
+ id: 'unassigned',
+ label: 'Unassigned',
+ description: 'Companies without an owner',
+ },
+] as const;
+
+export type CrmListConfig = {
+ kind: 'crm-list';
+ teamId: string;
+ companyIds: string[];
+};
+
+export function isCrmListConfig(value: unknown): value is CrmListConfig {
+ if (typeof value !== 'object' || value === null) return false;
+ return (
+ 'kind' in value &&
+ value.kind === 'crm-list' &&
+ 'teamId' in value &&
+ typeof value.teamId === 'string' &&
+ 'companyIds' in value &&
+ Array.isArray(value.companyIds) &&
+ value.companyIds.every((id: unknown) => typeof id === 'string')
+ );
+}
+
+export function matchesInteractionWindow(
+ updatedAt: string | Date | null | undefined,
+ view: 'needs-follow-up' | 'recently-active',
+ now = Date.now()
+) {
+ if (!updatedAt) return view === 'needs-follow-up';
+ const timestamp = new Date(updatedAt).getTime();
+ if (!Number.isFinite(timestamp)) return false;
+ const age = now - timestamp;
+ return view === 'needs-follow-up'
+ ? age >= 14 * 86400000
+ : age >= 0 && age <= 7 * 86400000;
+}
+
+export function needsCompanyFollowUp(
+ updatedAt: string | Date | null | undefined,
+ stageLabel: string | undefined,
+ now = Date.now()
+) {
+ const stage = stageLabel?.trim().toLowerCase();
+ return (
+ !!stage &&
+ stage !== 'churned' &&
+ matchesInteractionWindow(updatedAt, 'needs-follow-up', now)
+ );
+}
diff --git a/apps/web/src/features/companies/core/crm-people.test.ts b/apps/web/src/features/companies/core/crm-people.test.ts
new file mode 100644
index 0000000000..ca26d35b2e
--- /dev/null
+++ b/apps/web/src/features/companies/core/crm-people.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from 'vitest';
+import { type CrmPerson, filterAndSortPeople } from './crm-people';
+
+const person = (id: string, overrides: Partial<CrmPerson> = {}): CrmPerson => ({
+ id,
+ name: id,
+ email: `${id}@example.com`,
+ companyId: 'company',
+ companyName: 'Example',
+ hidden: false,
+ createdAt: '2025-01-01',
+ updatedAt: '2026-01-01',
+ firstInteraction: '2025-01-01',
+ lastInteraction: '2026-01-01',
+ ...overrides,
+});
+
+describe('people directory', () => {
+ it('searches contact names, emails and companies without exposing hidden contacts', () => {
+ const rows = [
+ person('Ada'),
+ person('B', { companyName: 'Ada Labs' }),
+ person('C', { email: '[email protected]' }),
+ person('D', { name: 'Ada', hidden: true }),
+ ];
+ expect(
+ filterAndSortPeople(rows, ' ADA ', 'name', false).map((row) => row.id)
+ ).toEqual(['Ada', 'B', 'C']);
+ expect(rows).toHaveLength(4);
+ });
+ it('orders actual interaction dates across companies and places missing dates last', () => {
+ const rows = [
+ person('old', { lastInteraction: '2024-09-16' }),
+ person('unknown', { lastInteraction: '' }),
+ person('new', { lastInteraction: '2026-09-16' }),
+ ];
+ expect(
+ filterAndSortPeople(rows, '', 'lastInteraction', true).map(
+ (row) => row.id
+ )
+ ).toEqual(['new', 'old', 'unknown']);
+ });
+ it('sorts unnamed contacts by email and leaves the input order unchanged', () => {
+ const rows = [person('z', { name: null }), person('a')];
+ expect(
+ filterAndSortPeople(rows, '', 'name', false).map((row) => row.id)
+ ).toEqual(['a', 'z']);
+ expect(rows.map((row) => row.id)).toEqual(['z', 'a']);
+ });
+});
diff --git a/apps/web/src/features/companies/core/crm-people.ts b/apps/web/src/features/companies/core/crm-people.ts
new file mode 100644
index 0000000000..51010e6c6d
--- /dev/null
+++ b/apps/web/src/features/companies/core/crm-people.ts
@@ -0,0 +1,34 @@
+import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';
+
+export type CrmPerson = CrmContactResponse & { companyName: string };
+export type PeopleSort =
+ | 'name'
+ | 'companyName'
+ | 'lastInteraction'
+ | 'firstInteraction';
+
+export function filterAndSortPeople(
+ people: CrmPerson[],
+ search: string,
+ sort: PeopleSort,
+ descending: boolean
+) {
+ const term = search.trim().toLowerCase();
+ return people
+ .filter(
+ (person) =>
+ !person.hidden &&
+ [person.name, person.email, person.companyName].some((value) =>
+ value?.toLowerCase().includes(term)
+ )
+ )
+ .sort((a, b) => {
+ const left = sort === 'name' ? a.name || a.email : a[sort];
+ const right = sort === 'name' ? b.name || b.email : b[sort];
+ const order =
+ sort === 'lastInteraction' || sort === 'firstInteraction'
+ ? (Date.parse(left) || 0) - (Date.parse(right) || 0)
+ : left.localeCompare(right, undefined, { sensitivity: 'base' });
+ return (descending ? -order : order) || a.id.localeCompare(b.id);
+ });
+}
diff --git a/apps/web/src/features/companies/crm/saved-views.ts b/apps/web/src/features/companies/crm/saved-views.ts
index ff56ee4f1b..e9d73bdc29 100644
--- a/apps/web/src/features/companies/crm/saved-views.ts
+++ b/apps/web/src/features/companies/crm/saved-views.ts
@@ -95,8 +95,8 @@ export function usePersonalCrmViews() {
}));
const views = createMemo((): PersonalCrmView[] =>
- (viewsQuery.data?.views ?? []).filter((view): view is PersonalCrmView =>
- isCrmViewConfig(view.config)
+ (viewsQuery.isSuccess ? viewsQuery.data.views : []).filter(
+ (view): view is PersonalCrmView => isCrmViewConfig(view.config)
)
);
diff --git a/apps/web/src/features/companies/crm/team-crm-config.ts b/apps/web/src/features/companies/crm/team-crm-config.ts
index 8cd93436ab..7bb537f1c9 100644
--- a/apps/web/src/features/companies/crm/team-crm-config.ts
+++ b/apps/web/src/features/companies/crm/team-crm-config.ts
@@ -101,7 +101,7 @@ export function useTeamCrmConfig() {
}));
const config = createMemo((): TeamCrmConfig => {
- const data = settingsQuery.data;
+ const data = settingsQuery.isSuccess ? settingsQuery.data : undefined;
if (!data) return {};
return {
permissions: {
diff --git a/apps/web/src/features/companies/views/CompanyListsSection.tsx b/apps/web/src/features/companies/views/CompanyListsSection.tsx
new file mode 100644
index 0000000000..c3c6a3775e
--- /dev/null
+++ b/apps/web/src/features/companies/views/CompanyListsSection.tsx
@@ -0,0 +1,167 @@
+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';
+
+export function CompanyListsSection(props: { companyId: string }) {
+ const team = useCurrentTeamQuery();
+ const teamId = () => (team.isSuccess ? team.data?.team.id : undefined);
+ const lists = useCrmLists(teamId);
+ const [editing, setEditing] = createSignal(false);
+ const [search, setSearch] = createSignal('');
+ const [error, setError] = createSignal('');
+ const memberships = () =>
+ lists
+ .lists()
+ .filter((list) => list.config.companyIds.includes(props.companyId));
+ const filtered = () =>
+ lists
+ .lists()
+ .filter((list) =>
+ list.name.toLowerCase().includes(search().trim().toLowerCase())
+ );
+ async function setMembership(listId: string, included: boolean) {
+ if (lists.setMembership.isPending) return;
+ setError('');
+ try {
+ await lists.setMembership.mutateAsync({
+ listId,
+ companyId: props.companyId,
+ included,
+ });
+ } catch {
+ setError('Could not update list membership. Please try again.');
+ }
+ }
+ return (
+ <SidePanel.Section id="company-lists" title="Lists" order={18} defaultOpen>
+ <div class="flex flex-col gap-3">
+ <Show when={team.isError || lists.query.isError}>
+ <div
+ role="alert"
+ class="flex items-center justify-between gap-2 text-xs text-ink-muted"
+ >
+ <span>Could not load lists.</span>
+ <Button
+ variant="ghost"
+ size="xs"
+ onClick={() => {
+ void team.refetch();
+ void lists.query.refetch();
+ }}
+ >
+ Retry
+ </Button>
+ </div>
+ </Show>
+ <Show when={team.isLoading || (!!teamId() && lists.query.isLoading)}>
+ <p class="text-xs text-ink-muted">Loading lists…</p>
+ </Show>
+ <Show when={lists.query.isSuccess && teamId()}>
+ <Show
+ when={memberships().length}
+ fallback={
+ <p class="text-xs text-ink-muted">Not in any lists yet.</p>
+ }
+ >
+ <div
+ class="flex flex-wrap gap-1.5"
+ aria-label="Company list memberships"
+ >
+ <For each={memberships()}>
+ {(list) => (
+ <span
+ class="inline-flex max-w-full items-center gap-1.5 rounded-lg bg-active px-2 py-1 text-xs"
+ title={list.name}
+ >
+ <ListIcon class="size-3.5 shrink-0" />
+ <span class="truncate">{list.name}</span>
+ </span>
+ )}
+ </For>
+ </div>
+ </Show>
+ <Button
+ variant="ghost"
+ size="sm"
+ class="self-start"
+ aria-expanded={editing()}
+ onClick={() => setEditing(!editing())}
+ >
+ {editing() ? 'Done' : 'Manage lists'}
+ </Button>
+ <Show when={editing()}>
+ <p class="text-xs text-ink-muted">
+ Your personal company lists. Changes save immediately.
+ </p>
+ <Show
+ when={lists.lists().length}
+ fallback={
+ <p class="text-xs text-ink-muted">
+ Create a list in the CRM sidebar to get started.
+ </p>
+ }
+ >
+ <input
+ aria-label="Find company lists"
+ placeholder="Find a list…"
+ value={search()}
+ onInput={(event) => setSearch(event.currentTarget.value)}
+ class="w-full rounded-lg border border-edge-muted bg-input px-2.5 py-1.5 text-sm outline-none focus:border-accent"
+ />
+ <div
+ class="max-h-56 overflow-y-auto"
+ aria-busy={lists.setMembership.isPending}
+ >
+ <For each={filtered()}>
+ {(list) => (
+ <label class="flex items-center gap-2 rounded-lg px-2 py-2 text-sm hover:bg-hover">
+ <input
+ type="checkbox"
+ checked={list.config.companyIds.includes(
+ props.companyId
+ )}
+ disabled={lists.setMembership.isPending}
+ onChange={(event) => {
+ const included = event.currentTarget.checked;
+ event.currentTarget.checked =
+ list.config.companyIds.includes(props.companyId);
+ void setMembership(list.id, included);
+ }}
+ />
+ <span class="min-w-0 truncate" title={list.name}>
+ {list.name}
+ </span>
+ </label>
+ )}
+ </For>
+ <Show when={!filtered().length}>
+ <p class="px-2 py-2 text-xs text-ink-muted">
+ No matching lists.
+ </p>
+ </Show>
+ </div>
+ </Show>
+ </Show>
+ </Show>
+ <Show when={lists.setMembership.isPending}>
+ <p role="status" class="text-xs text-ink-muted">
+ Saving…
+ </p>
+ </Show>
+ <Show when={error()}>
+ <p role="alert" class="text-xs text-failure">
+ {error()}
+ </p>
+ </Show>
+ <Show when={team.isSuccess && !teamId()}>
+ <p class="text-xs text-ink-muted">
+ Join a team to use company lists.
+ </p>
+ </Show>
+ </div>
+ </SidePanel.Section>
+ );
+}
diff --git a/apps/web/src/features/companies/views/CrmCompanyDetail.tsx b/apps/web/src/features/companies/views/CrmCompanyDetail.tsx
new file mode 100644
index 0000000000..02a5f7c4fd
--- /dev/null
+++ b/apps/web/src/features/companies/views/CrmCompanyDetail.tsx
@@ -0,0 +1,223 @@
+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,
+ ErrorBoundary,
+ type JSX,
+ onMount,
+ Show,
+ Suspense,
+} from 'solid-js';
+import { Company } from '../Company/Company';
+import { CrmCopyLinkButton } from '../components/CrmCopyLinkButton';
+
+export function CrmCompanyDetail(props: {
+ company: { id: string; name: string };
+ viewName: string;
+ onClose: () => void;
+ navigation: JSX.Element;
+}) {
+ const { query, company } = useCompanyQuery(() => props.company.id);
+ const companyName = () => company()?.name ?? props.company.name;
+ const [selectedContact, setSelectedContact] = createSignal<CompanyContact>();
+ const contactQuery = useContactQuery(() => selectedContact()?.id ?? '');
+ const contactName = () => {
+ const contact = contactQuery.isSuccess
+ ? contactQuery.data
+ : selectedContact();
+ return contact?.name ?? contact?.email ?? 'Contact';
+ };
+ const closeContact = () => setSelectedContact(undefined);
+ const activeQuery = () => (selectedContact() ? contactQuery : query);
+ const closeDetail = () =>
+ selectedContact() ? closeContact() : props.onClose();
+ let container: HTMLDivElement | undefined;
+ onMount(() => container?.focus());
+
+ return (
+ <ViewBreadcrumbs.Root
+ value={
+ selectedContact()
+ ? `contact:${selectedContact()!.id}`
+ : `company:${props.company.id}`
+ }
+ onChange={(value) => {
+ if (value === 'crm-view') props.onClose();
+ if (value === `company:${props.company.id}`) closeContact();
+ }}
+ >
+ <ViewBreadcrumbs.Item
+ value="crm-view"
+ metadata={{ type: 'companies' }}
+ order={0}
+ >
+ {(item) => (
+ <Tooltip label={`Back to ${props.viewName}`} class="min-w-0">
+ <ViewBreadcrumbs.Button
+ isActive={item.isActive()}
+ onClick={item.onSelect}
+ >
+ <span class="truncate">{props.viewName}</span>
+ </ViewBreadcrumbs.Button>
+ </Tooltip>
+ )}
+ </ViewBreadcrumbs.Item>
+ <ViewBreadcrumbs.Item
+ value={`company:${props.company.id}`}
+ metadata={{ type: 'company', id: props.company.id }}
+ order={1}
+ >
+ {(item) => (
+ <Tooltip label={companyName()} class="min-w-0">
+ <ViewBreadcrumbs.Button
+ isActive={item.isActive()}
+ onClick={item.onSelect}
+ class="gap-1.5"
+ >
+ <EntityIcon targetType="crm_company" size="xs" class="shrink-0" />
+ <span class="truncate">{companyName()}</span>
+ </ViewBreadcrumbs.Button>
+ </Tooltip>
+ )}
+ </ViewBreadcrumbs.Item>
+ <Show when={selectedContact()}>
+ {(contact) => (
+ <ViewBreadcrumbs.Item
+ value={`contact:${contact().id}`}
+ metadata={{ type: 'contact', id: contact().id }}
+ order={2}
+ >
+ {(item) => (
+ <Tooltip label={contactName()} class="min-w-0">
+ <ViewBreadcrumbs.Button
+ isActive={item.isActive()}
+ onClick={item.onSelect}
+ class="gap-1.5"
+ >
+ <EntityIcon targetType="contact" size="xs" class="shrink-0" />
+ <span class="truncate">{contactName()}</span>
+ </ViewBreadcrumbs.Button>
+ </Tooltip>
+ )}
+ </ViewBreadcrumbs.Item>
+ )}
+ </Show>
+ <SidePanel.Root persistKey="crm-company">
+ <div
+ ref={container}
+ tabindex={-1}
+ class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden outline-none"
+ >
+ <div class="flex h-12 min-w-0 shrink-0 items-center gap-3 border-b border-edge-muted px-4">
+ {props.navigation}
+ <ViewBreadcrumbs.Outlet
+ aria-label="CRM record location"
+ class="flex-1"
+ />
+ <div class="ml-auto flex shrink-0 items-center gap-2">
+ <CrmCopyLinkButton
+ type={selectedContact() ? 'contact' : 'company'}
+ id={selectedContact()?.id ?? props.company.id}
+ />
+ <SidePanel.Toggle />
+ </div>
+ </div>
+ <div class="relative min-h-0 min-w-0 flex-1">
+ <Show when={selectedContact()?.id ?? props.company.id} keyed>
+ {(_recordId) => (
+ <ErrorBoundary
+ fallback={(error, reset) => {
+ console.error('Failed to render CRM record', error);
+ return (
+ <DetailError
+ onRetry={reset}
+ onClose={closeDetail}
+ isContact={!!selectedContact()}
+ />
+ );
+ }}
+ >
+ <Show
+ when={!activeQuery().isError}
+ fallback={
+ <DetailError
+ onRetry={() => void activeQuery().refetch()}
+ onClose={closeDetail}
+ isContact={!!selectedContact()}
+ />
+ }
+ >
+ <Suspense
+ fallback={
+ <div class="grid size-full place-items-center text-ink-muted">
+ <SpinnerIcon
+ aria-label={
+ selectedContact()
+ ? 'Loading contact'
+ : 'Loading company'
+ }
+ class="size-5 animate-spin"
+ />
+ </div>
+ }
+ >
+ <Show
+ when={selectedContact()}
+ fallback={
+ <Company
+ companyId={props.company.id}
+ headerToggle={false}
+ onHidden={props.onClose}
+ onOpenContact={setSelectedContact}
+ />
+ }
+ >
+ {(contact) => (
+ <Contact
+ contactId={contact().id}
+ headerToggle={false}
+ onOpenCompany={(companyId) => {
+ if (companyId !== props.company.id) return false;
+ closeContact();
+ return true;
+ }}
+ />
+ )}
+ </Show>
+ </Suspense>
+ </Show>
+ </ErrorBoundary>
+ )}
+ </Show>
+ </div>
+ </div>
+ </SidePanel.Root>
+ </ViewBreadcrumbs.Root>
+ );
+}
+
+function DetailError(props: {
+ onRetry: () => void;
+ onClose: () => void;
+ isContact: boolean;
+}) {
+ return (
+ <div class="flex size-full flex-col items-center justify-center gap-3 text-sm text-ink-muted">
+ <p>This {props.isContact ? 'contact' : 'company'} couldn’t be loaded.</p>
+ <div class="flex gap-2">
+ <Button variant="outline" size="sm" onClick={props.onRetry}>
+ Try again
+ </Button>
+ <Button variant="ghost" size="sm" onClick={props.onClose}>
+ {props.isContact ? 'Back to company' : 'Back to view'}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/companies/views/CrmExport.tsx b/apps/web/src/features/companies/views/CrmExport.tsx
new file mode 100644
index 0000000000..9a219f2f16
--- /dev/null
+++ b/apps/web/src/features/companies/views/CrmExport.tsx
@@ -0,0 +1,418 @@
+import { idToEmail } from '@core/user/util';
+import { type CrmCompanyEntity, getCompanyOwnerId } from '@entity';
+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';
+
+export function CrmExport(props: {
+ kind: 'companies' | 'people';
+ currentView: string;
+ onClose: () => void;
+ onLoad: (
+ scope: 'current' | 'all',
+ signal: AbortSignal,
+ progress: (count: number) => void
+ ) => Promise<{ companies?: CrmCompanyEntity[]; people?: CrmPerson[] }>;
+}) {
+ const stages = useDealStages();
+ const definitions = useListPropertiesQuery(
+ () => ({
+ scope: 'all',
+ includeOptions: true,
+ forEntityType: 'COMPANY',
+ }),
+ () => 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);
+ }
+ }
+ function download() {
+ const data = rows();
+ if (!data || !selectedColumns().length) return;
+ const blob = new Blob([createCrmCsv(selectedColumns(), data)], {
+ type: 'text/csv;charset=utf-8',
+ });
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+ link.href = url;
+ link.download = filename();
+ document.body.append(link);
+ link.click();
+ link.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+ props.onClose();
+ }
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => !open && props.onClose()}
+ class="w-[560px] max-w-[calc(100vw-2rem)]"
+ >
+ <Panel>
+ <Panel.Body>
+ <div class="flex max-h-[85vh] flex-col">
+ <div class="px-5 pt-5 pb-4">
+ <Dialog.Title class="text-base font-semibold">
+ Export {props.kind}
+ </Dialog.Title>
+ <Dialog.Description class="mt-1 text-sm text-ink-muted">
+ Choose the records and columns for your CSV. Review the export
+ before downloading.
+ </Dialog.Description>
+ </div>
+ <div class="min-h-0 overflow-auto px-5 pb-4 flex flex-col gap-5">
+ <fieldset disabled={pending()} class="flex flex-col gap-2">
+ <legend class="mb-2 text-xs font-medium text-ink-muted">
+ Records
+ </legend>
+ <For each={['current', 'all'] as const}>
+ {(value) => (
+ <label class="flex items-start gap-3 rounded-lg bg-hover/50 p-3 text-sm">
+ <input
+ type="radio"
+ name="crm-export-scope"
+ value={value}
+ checked={scope() === value}
+ onChange={() => {
+ setScope(value);
+ setRows(undefined);
+ setError('');
+ }}
+ class="mt-0.5 accent-accent"
+ />
+ <span>
+ <span class="block font-medium">
+ {value === 'current'
+ ? `Current view · ${props.currentView}`
+ : `All ${props.kind} across views`}
+ </span>
+ <span class="mt-1 block text-xs text-ink-muted">
+ {value === 'current'
+ ? 'Includes all matching records, with the current filters and search.'
+ : 'All visible records, once each. Ignores the current filters and search.'}
+ </span>
+ </span>
+ </label>
+ )}
+ </For>
+ </fieldset>
+ <fieldset disabled={pending()} aria-label="Export columns">
+ <div class="mb-2 flex items-center justify-between gap-3">
+ <span class="text-xs font-medium text-ink-muted">
+ Columns · {selectedColumns().length} selected
+ </span>
+ <div class="flex gap-2 text-xs">
+ <button
+ type="button"
+ class="text-ink-muted hover:text-ink"
+ onClick={() =>
+ setSelected(columns().map((column) => column.id))
+ }
+ >
+ Select all
+ </button>
+ <span class="text-ink-extra-muted">/</span>
+ <button
+ type="button"
+ class="text-ink-muted hover:text-ink"
+ onClick={() => setSelected([])}
+ >
+ Clear
+ </button>
+ </div>
+ </div>
+ <div class="grid grid-cols-2 gap-x-3 gap-y-1">
+ <For each={baseColumns}>
+ {(column) => (
+ <label class="flex min-w-0 items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-hover">
+ <input
+ type="checkbox"
+ class="accent-accent"
+ checked={selected().includes(column.id)}
+ onChange={(event) =>
+ setSelected((current) =>
+ event.currentTarget.checked
+ ? [...current, column.id]
+ : current.filter((id) => id !== column.id)
+ )
+ }
+ />
+ <span class="truncate" title={column.label}>
+ {column.label}
+ </span>
+ </label>
+ )}
+ </For>
+ </div>
+ <Show when={columns().length > baseColumns.length}>
+ <details class="mt-3 rounded-lg bg-hover/40 px-3 py-2">
+ <summary class="text-xs font-medium text-ink-muted">
+ Additional properties ·{' '}
+ {columns().length - baseColumns.length}
+ </summary>
+ <div class="mt-2 grid grid-cols-2 gap-x-3 gap-y-1">
+ <For each={columns().slice(baseColumns.length)}>
+ {(column) => (
+ <label class="flex min-w-0 items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-hover">
+ <input
+ type="checkbox"
+ class="accent-accent"
+ checked={selected().includes(column.id)}
+ onChange={(event) =>
+ setSelected((current) =>
+ event.currentTarget.checked
+ ? [...current, column.id]
+ : current.filter((id) => id !== column.id)
+ )
+ }
+ />
+ <span class="truncate" title={column.label}>
+ {column.label}
+ </span>
+ </label>
+ )}
+ </For>
+ </div>
+ </details>
+ </Show>
+ <Show when={metadataLoading()}>
+ <p class="mt-2 text-xs text-ink-muted">
+ Loading property columns…
+ </p>
+ </Show>
+ <Show when={metadataError()}>
+ <p role="alert" class="mt-2 text-sm text-failure">
+ Could not load CRM properties. Close and reopen Export to
+ retry.
+ </p>
+ </Show>
+ </fieldset>
+ <Show when={rows()}>
+ {(data) => (
+ <div class="flex flex-col gap-2">
+ <p role="status" class="text-sm font-medium">
+ {data().length.toLocaleString()} {props.kind} ·{' '}
+ {selectedColumns().length} columns
+ </p>
+ <Show
+ when={data().length}
+ fallback={
+ <p class="text-xs text-ink-muted">
+ No records match. The CSV will contain column headers
+ only.
+ </p>
+ }
+ >
+ <div class="overflow-x-auto rounded-lg bg-hover/40 p-2">
+ <table
+ class="w-full text-left text-xs"
+ aria-label="Export preview"
+ >
+ <thead>
+ <tr>
+ <For each={selectedColumns()}>
+ {(column) => (
+ <th class="whitespace-nowrap px-2 py-2 font-medium text-ink-muted">
+ {column.label}
+ </th>
+ )}
+ </For>
+ </tr>
+ </thead>
+ <tbody>
+ <For each={data().slice(0, 3)}>
+ {(record) => (
+ <tr>
+ <For each={selectedColumns()}>
+ {(column) => (
+ <td
+ class="max-w-40 truncate px-2 py-1.5"
+ title={String(record[column.id] ?? '')}
+ >
+ {String(record[column.id] ?? '')}
+ </td>
+ )}
+ </For>
+ </tr>
+ )}
+ </For>
+ </tbody>
+ </table>
+ </div>
+ <p class="text-xs text-ink-muted">
+ Preview of the first {Math.min(3, data().length)}{' '}
+ records. Dates retain their original timestamps.
+ </p>
+ </Show>
+ </div>
+ )}
+ </Show>
+ <Show when={pending()}>
+ <p role="status" class="text-sm text-ink-muted">
+ Preparing all records…{' '}
+ {progress() ? `${progress().toLocaleString()} loaded` : ''}
+ </p>
+ </Show>
+ <Show when={error()}>
+ <p role="alert" class="text-sm text-failure">
+ {error()}
+ </p>
+ </Show>
+ </div>
+ <div class="flex items-center gap-3 border-t border-edge-muted px-5 py-4">
+ <span
+ class="mr-auto min-w-0 truncate text-xs text-ink-muted"
+ title={filename()}
+ >
+ {filename()}
+ </span>
+ <Button variant="ghost" onClick={props.onClose}>
+ Cancel
+ </Button>
+ <Button
+ variant="accent"
+ disabled={
+ pending() ||
+ !selectedColumns().length ||
+ metadataLoading() ||
+ metadataError()
+ }
+ onClick={() => (rows() ? download() : void prepare())}
+ >
+ {pending()
+ ? 'Preparing…'
+ : rows()
+ ? 'Download CSV'
+ : 'Prepare export'}
+ </Button>
+ </div>
+ </div>
+ </Panel.Body>
+ </Panel>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/features/companies/views/CrmImport.tsx b/apps/web/src/features/companies/views/CrmImport.tsx
new file mode 100644
index 0000000000..03231550d8
--- /dev/null
+++ b/apps/web/src/features/companies/views/CrmImport.tsx
@@ -0,0 +1,150 @@
+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';
+
+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.`
+ );
+ }
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => !open && !pending() && props.onClose()}
+ class="w-112 max-w-[calc(100vw-2rem)]"
+ >
+ <Panel>
+ <Panel.Body>
+ <div class="flex flex-col gap-4 p-5">
+ <Dialog.Title class="text-base font-semibold">
+ Import companies
+ </Dialog.Title>
+ <Dialog.Description class="text-sm text-ink-muted">
+ Upload a CSV with name and domain columns. Review the companies
+ before importing them into your team CRM.
+ </Dialog.Description>
+ <input
+ aria-label="Companies CSV"
+ type="file"
+ accept=".csv,text/csv"
+ disabled={pending()}
+ onChange={(e) => void read(e.currentTarget.files?.[0])}
+ class="text-sm"
+ />
+ <Show when={rows().length}>
+ <div class="max-h-64 overflow-auto rounded-lg border border-edge-muted">
+ <For each={rows()}>
+ {(row) => (
+ <div class="flex justify-between gap-3 border-b border-edge-muted px-3 py-2 text-sm last:border-0">
+ <span class="truncate">{row.name}</span>
+ <span class="text-ink-muted">{row.domain}</span>
+ </div>
+ )}
+ </For>
+ </div>
+ </Show>
+ <Show when={completed()}>
+ <p role="status" class="text-sm">
+ {completed()} companies imported.
+ </p>
+ </Show>
+ <Show when={error()}>
+ <p role="alert" class="text-sm text-failure">
+ {error()}
+ </p>
+ </Show>
+ <div class="flex justify-end gap-2">
+ <Button
+ variant="ghost"
+ disabled={pending()}
+ onClick={props.onClose}
+ >
+ Close
+ </Button>
+ <Button
+ variant="accent"
+ disabled={pending() || !rows().length}
+ onClick={() => void run()}
+ >
+ {pending()
+ ? 'Importing…'
+ : `Import ${rows().length || ''} companies`}
+ </Button>
+ </div>
+ </div>
+ </Panel.Body>
+ </Panel>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/features/companies/views/CrmPeople.tsx b/apps/web/src/features/companies/views/CrmPeople.tsx
new file mode 100644
index 0000000000..1d67e42109
--- /dev/null
+++ b/apps/web/src/features/companies/views/CrmPeople.tsx
@@ -0,0 +1,275 @@
+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';
+
+const PAGE_SIZE = 50;
+const dateLabel = (value: string) => {
+ const date = new Date(value);
+ return Number.isNaN(date.getTime())
+ ? '—'
+ : date.toLocaleDateString(undefined, {
+ month: 'short',
+ day: 'numeric',
+ year: 'numeric',
+ });
+};
+const columns: { label: string; sort?: PeopleSort; class: string }[] = [
+ { label: 'Name', sort: 'name', class: 'w-[25%]' },
+ { label: 'Email', class: 'w-[26%]' },
+ { label: 'Company', sort: 'companyName', class: 'w-[23%]' },
+ { label: 'Last contacted', sort: 'lastInteraction', class: 'w-40' },
+ { label: 'First contact', sort: 'firstInteraction', class: 'w-40' },
+];
+
+export function CrmPeople(props: {
+ directory: ReturnType<typeof useCrmPeopleQuery>;
+ search: string;
+ onSearch: (value: string) => void;
+ sort: PeopleSort;
+ onSort: (value: PeopleSort) => void;
+ descending: boolean;
+ onDescending: (value: boolean) => void;
+}) {
+ const directory = props.directory;
+ const { openWithSplit } = useSplitLayout();
+ const search = () => props.search;
+ const sort = () => props.sort;
+ const descending = () => props.descending;
+ const [page, setPage] = createSignal(0);
+ const people = createMemo(() =>
+ filterAndSortPeople(directory.people(), search(), sort(), descending())
+ );
+ const currentPage = () =>
+ Math.min(page(), Math.max(0, Math.ceil(people().length / PAGE_SIZE) - 1));
+ const rows = () =>
+ people().slice(currentPage() * PAGE_SIZE, (currentPage() + 1) * PAGE_SIZE);
+ const loading = () =>
+ !directory.query.isError &&
+ (directory.query.isFetching || directory.query.hasNextPage);
+ const changeSort = (value: PeopleSort) => {
+ props.onDescending(
+ sort() === value
+ ? !descending()
+ : value === 'lastInteraction' || value === 'firstInteraction'
+ );
+ props.onSort(value);
+ setPage(0);
+ };
+ return (
+ <div class="flex min-h-0 min-w-0 flex-1 flex-col">
+ <div class="flex flex-wrap items-center gap-3 border-b border-edge-muted px-4 py-3">
+ <div class="flex min-w-40 max-w-sm flex-1 items-center gap-2 rounded-md border border-edge-muted bg-input px-3 py-1.5 focus-within:border-accent">
+ <MagnifyingGlassIcon class="size-4 shrink-0 text-ink-muted" />
+ <input
+ type="search"
+ aria-label="Search people"
+ value={search()}
+ onInput={(event) => {
+ props.onSearch(event.currentTarget.value);
+ setPage(0);
+ }}
+ placeholder="Search people, emails, companies…"
+ class="min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-ink-placeholder"
+ />
+ </div>
+ <span class="ml-auto text-xs tabular-nums text-ink-muted" role="status">
+ {people().length.toLocaleString()}{' '}
+ {people().length === 1 ? 'person' : 'people'}
+ <Show when={loading()}> · Loading contacts…</Show>
+ </span>
+ </div>
+ <Show when={directory.query.isError}>
+ <div
+ class="flex items-center justify-between gap-3 border-b border-edge-muted px-4 py-3 text-sm text-ink-muted"
+ role="alert"
+ >
+ <span>
+ Some contacts could not be loaded. The people already loaded are
+ still available.
+ </span>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() =>
+ directory.query.isFetchNextPageError
+ ? void directory.query.fetchNextPage()
+ : void directory.query.refetch()
+ }
+ >
+ Retry
+ </Button>
+ </div>
+ </Show>
+ <div class="min-h-0 flex-1 overflow-auto">
+ <table
+ class="w-full min-w-[960px] table-fixed border-collapse text-left text-sm"
+ aria-label="People"
+ >
+ <thead class="sticky top-0 z-1 bg-panel text-xs text-ink-muted">
+ <tr>
+ <For each={columns}>
+ {(column) => (
+ <th
+ scope="col"
+ class={`border-b border-edge-muted px-4 py-3 font-medium ${column.class}`}
+ aria-sort={
+ column.sort === sort()
+ ? descending()
+ ? 'descending'
+ : 'ascending'
+ : undefined
+ }
+ >
+ <Show when={column.sort} fallback={column.label}>
+ {(field) => (
+ <button
+ type="button"
+ class="flex items-center gap-2 hover:text-ink"
+ onClick={() => changeSort(field())}
+ title={
+ field() === 'lastInteraction'
+ ? 'Most recent email interaction, incoming or outgoing'
+ : undefined
+ }
+ >
+ {column.label}
+ <Show when={sort() === field()}>
+ <CaretDownIcon
+ class="size-3"
+ classList={{ 'rotate-180': !descending() }}
+ />
+ </Show>
+ </button>
+ )}
+ </Show>
+ </th>
+ )}
+ </For>
+ </tr>
+ </thead>
+ <tbody>
+ <For each={rows()}>
+ {(person) => (
+ <tr class="group border-b border-edge-muted/60 hover:bg-hover">
+ <td class="px-4 py-2.5">
+ <button
+ type="button"
+ class="flex w-full min-w-0 items-center gap-3 text-left"
+ onClick={(event) =>
+ openWithSplit(
+ { type: 'contact', id: person.id },
+ { activate: true, preferNewSplit: event.shiftKey }
+ )
+ }
+ >
+ <span
+ class="flex size-7 shrink-0 items-center justify-center rounded-full bg-accent/10 text-xs font-medium text-accent"
+ aria-hidden="true"
+ >
+ {(person.name || person.email)
+ .slice(0, 1)
+ .toUpperCase()}
+ </span>
+ <span
+ class="truncate font-medium"
+ title={person.name || person.email}
+ >
+ {person.name || person.email}
+ </span>
+ </button>
+ </td>
+ <td
+ class="truncate px-4 py-2.5 text-ink-muted"
+ title={person.email}
+ >
+ {person.email}
+ </td>
+ <td class="px-4 py-2.5">
+ <button
+ type="button"
+ class="flex max-w-full items-center gap-2 text-ink-muted hover:text-ink"
+ onClick={(event) =>
+ openWithSplit(
+ { type: 'company', id: person.companyId },
+ { activate: true, preferNewSplit: event.shiftKey }
+ )
+ }
+ >
+ <BuildingsIcon class="size-4 shrink-0 text-ink-extra-muted" />
+ <span class="truncate" title={person.companyName}>
+ {person.companyName}
+ </span>
+ </button>
+ </td>
+ <td
+ class="px-4 py-2.5 text-ink-muted"
+ title={new Date(person.lastInteraction).toLocaleString()}
+ >
+ {dateLabel(person.lastInteraction)}
+ </td>
+ <td
+ class="px-4 py-2.5 text-ink-muted"
+ title={new Date(person.firstInteraction).toLocaleString()}
+ >
+ {dateLabel(person.firstInteraction)}
+ </td>
+ </tr>
+ )}
+ </For>
+ </tbody>
+ </table>
+ <Show when={!rows().length}>
+ <div
+ class="flex flex-col items-center gap-3 px-6 py-20 text-center"
+ role="status"
+ >
+ <UsersIcon class="size-8 text-ink-extra-muted" />
+ <p class="text-sm font-medium">
+ {loading()
+ ? 'Loading people…'
+ : search()
+ ? 'No matching people'
+ : 'No people yet'}
+ </p>
+ <p class="max-w-sm text-sm text-ink-muted">
+ {loading()
+ ? 'Your contacts will appear here as they load.'
+ : search()
+ ? 'Try a name, email address, or company.'
+ : 'People connected to your CRM companies will appear here.'}
+ </p>
+ </div>
+ </Show>
+ </div>
+ <div class="flex shrink-0 items-center gap-3 border-t border-edge-muted px-4 py-2 text-xs text-ink-muted">
+ <span class="mr-auto">
+ {people().length
+ ? `${currentPage() * PAGE_SIZE + 1}–${Math.min((currentPage() + 1) * PAGE_SIZE, people().length)} of ${people().length.toLocaleString()}`
+ : '0 people'}
+ </span>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={currentPage() === 0}
+ onClick={() => setPage(currentPage() - 1)}
+ >
+ Previous
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={(currentPage() + 1) * PAGE_SIZE >= people().length}
+ onClick={() => setPage(currentPage() + 1)}
+ >
+ Next
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/companies/views/CrmWorkspace.tsx b/apps/web/src/features/companies/views/CrmWorkspace.tsx
new file mode 100644
index 0000000000..e59ad88135
--- /dev/null
+++ b/apps/web/src/features/companies/views/CrmWorkspace.tsx
@@ -0,0 +1,444 @@
+import {
+ SearchBar,
+ useViewControlHotkeys,
+ useViewShell,
+ ViewShell,
+} from '@app/components/view-shell';
+import { NO_ASSIGNEE } from '@app/features/next-soup/filters/configs';
+import { NIL_UUID } from '@app/features/next-soup/filters/filter-store';
+import { getViewPreset } from '@app/features/next-soup/sidebar/soup-filter-presets';
+import { SoupActiveFiltersBar } from '@app/features/next-soup/soup-view/filters-bar/soup-active-filters-bar';
+import { SoupViewContextGroup } from '@app/features/next-soup/soup-view/filters-bar/soup-view-context-group';
+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 { type EntityData, isCrmCompanyEntity } from '@entity';
+import SidebarIcon from '@phosphor/sidebar-simple.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 { 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 {
+ type CrmViewConfig,
+ usePersonalCrmViews,
+ useTeamCrmViews,
+} from '../crm/saved-views';
+import { CrmCompanyDetail } from './CrmCompanyDetail';
+import { CrmExport } from './CrmExport';
+import { CrmImport } from './CrmImport';
+
+function NavigationToggle(props: {
+ onExpand: () => void;
+ children: import('solid-js').JSX.Element;
+}) {
+ const shell = useViewShell();
+ const [open, setOpen] = createSignal(false);
+ return (
+ <Show when={shell.aside.isCollapsed()}>
+ <Show
+ when={shell.breakpoints.narrow?.()}
+ fallback={
+ <Tooltip label="Expand CRM sidebar">
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ label="Expand CRM sidebar"
+ onClick={props.onExpand}
+ >
+ <SidebarIcon class="size-4" />
+ </Button>
+ </Tooltip>
+ }
+ >
+ <Dropdown open={open()} onOpenChange={setOpen} placement="bottom-start">
+ <Tooltip label="Show CRM navigation">
+ <Dropdown.Trigger
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Show CRM navigation"
+ >
+ <SidebarIcon class="size-4" />
+ </Dropdown.Trigger>
+ </Tooltip>
+ <Dropdown.Content class="w-55 max-h-[80vh] overflow-auto p-0">
+ <div
+ onClick={(event) => {
+ if (
+ (event.target as HTMLElement).closest(
+ 'nav button, [role="radiogroup"]'
+ )
+ )
+ setOpen(false);
+ }}
+ >
+ {props.children}
+ </div>
+ </Dropdown.Content>
+ </Dropdown>
+ </Show>
+ </Show>
+ );
+}
+
+function CrmSearchBar() {
+ const view = useSoupView();
+ const panel = useSplitPanelOrThrow();
+ let input: HTMLInputElement | undefined;
+ useViewControlHotkeys({
+ scopeId: panel.splitHotkeyScope,
+ enabled: panel.isPanelActive,
+ search: {
+ description: 'Search companies',
+ run: () => {
+ input?.focus();
+ input?.select();
+ return true;
+ },
+ },
+ });
+ return (
+ <SearchBar
+ ref={(element) => (input = element)}
+ label="Search companies"
+ placeholder="Search companies"
+ value={view.searchText()}
+ onValueChange={view.setSearchText}
+ onEscape={() => panel.panelRef()?.focus()}
+ hotkey="cmd+f"
+ class="max-w-md flex-1"
+ />
+ );
+}
+
+function CrmFilterChips(props: { onReset: () => void }) {
+ const { consolidatedFiltersList } = useFilterRefinements();
+ const view = useSoupView();
+ const userId = useUserId();
+ const filters = () =>
+ consolidatedFiltersList().filter((filter) => {
+ const defaultOwner =
+ view.activeTab() === 'my-companies'
+ ? userId()
+ : view.activeTab() === 'unassigned'
+ ? NO_ASSIGNEE
+ : undefined;
+ return !(
+ filter.key === 'owner' &&
+ defaultOwner &&
+ filter.values().length === 1 &&
+ filter.values()[0].id === defaultOwner
+ );
+ });
+ return (
+ <SoupActiveFiltersBar filters={filters()} onClearAll={props.onReset} />
+ );
+}
+
+export function CrmWorkspace(props: {
+ children: (onOpenEntity: (entity: EntityData) => boolean) => JSX.Element;
+}) {
+ const view = useSoupView();
+ const panel = useSplitPanelOrThrow();
+ const [selectedCompany, setSelectedCompany] = createSignal<{
+ id: string;
+ name: string;
+ }>();
+ const closeCompany = () => setSelectedCompany(undefined);
+ const openCompany = (entity: EntityData) => {
+ if (!isCrmCompanyEntity(entity)) return false;
+ view.soup.focus.set(entity.id);
+ panel.handle.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 }
+ );
+ const teamQuery = useCurrentTeamQuery();
+ const teamId = () =>
+ teamQuery.isSuccess ? teamQuery.data?.team.id : undefined;
+ const listsFlag = useFeatureFlag(enableCrmLists);
+ const lists = useCrmLists(() => (listsFlag().enabled ? teamId() : undefined));
+ const personal = usePersonalCrmViews();
+ const team = useTeamCrmViews();
+ const savedViews = () => [
+ ...personal
+ .views()
+ .map((v) => ({ id: `personal:${v.id}`, name: v.name, config: v.config })),
+ ...team.views().map((v) => ({
+ id: `team:${v.id}`,
+ name: v.name,
+ config: v.config as CrmViewConfig,
+ })),
+ ];
+ const [editing, setEditing] = createSignal<{
+ id?: string;
+ name: string;
+ companyIds: string[];
+ }>();
+ const [importing, setImporting] = createSignal(false);
+ const active = () =>
+ view.activeTab() === 'people' ? 'active' : (view.activeTab() ?? 'active');
+ const [exporting, setExporting] = createSignal(false);
+ const activeList = () =>
+ lists.lists().find((list) => `list:${list.id}` === active());
+ const title = () =>
+ activeList()?.name ??
+ savedViews().find((v) => v.id === active())?.name ??
+ CRM_VIEWS.find((v) => v.id === active())?.label ??
+ 'Companies';
+ const navigate = (id: string) => {
+ if (!listsFlag().enabled && id.startsWith('list:')) id = 'active';
+ closeCompany();
+ const saved = savedViews().find((v) => v.id === id);
+ if (saved) {
+ apply({ ...saved.config, viewMode: view.viewMode() });
+ view.setActiveTab(id);
+ return;
+ }
+ const preset = getViewPreset('companies');
+ const list = lists.lists().find((list) => `list:${list.id}` === id);
+ const filters = structuredClone(preset?.filters ?? {});
+ if (list)
+ filters.include = {
+ ...filters.include,
+ crmCompanyId: list.config.companyIds.length
+ ? list.config.companyIds
+ : [NIL_UUID],
+ };
+ apply({
+ kind: 'crm',
+ activeTab: id,
+ filters,
+ clientFilters: {
+ and: [
+ 'crm-company-active',
+ ...(id === 'needs-follow-up'
+ ? ['company-needs-follow-up']
+ : id === 'recently-active'
+ ? ['company-recently-active']
+ : []),
+ ],
+ },
+ ownerFilter:
+ id === 'my-companies'
+ ? [userId() ?? NIL_UUID]
+ : id === 'unassigned'
+ ? [NO_ASSIGNEE]
+ : [],
+ groupBy: preset?.groupBy,
+ viewMode: view.viewMode(),
+ });
+ };
+ onMount(() => {
+ if (!listsFlag().enabled && active().startsWith('list:'))
+ navigate('active');
+ });
+ const sidebar = () => (
+ <CrmSidebar
+ active={active()}
+ viewMode={view.viewMode()}
+ onViewModeChange={(mode) => {
+ closeCompany();
+ view.setViewMode(mode);
+ }}
+ lists={lists.lists().map((list) => ({
+ id: list.id,
+ name: list.name,
+ count: list.config.companyIds.length,
+ }))}
+ savedViews={savedViews()}
+ listsEnabled={listsFlag().enabled}
+ listsLoading={lists.query.isLoading}
+ listsError={lists.query.isError}
+ canCreateList={!!teamId()}
+ onNavigate={navigate}
+ onCreate={openCreateCompanyModal}
+ onNewList={() => setEditing({ name: '', companyIds: [] })}
+ onImport={() => setImporting(true)}
+ onExport={() => setExporting(true)}
+ onSettings={() => openSettings('CRM')}
+ onCollapse={() => setCollapsed(true)}
+ />
+ );
+ return (
+ <ViewShell.Root
+ class="touch:pt-(--safe-top) touch:pb-(--mobile-content-inset-bottom)"
+ aside={collapsed() ? false : { width: 216, min: 216, max: 216 }}
+ main={{ min: 320 }}
+ >
+ <ViewShell.Aside>
+ <Suspense
+ fallback={<div class="p-4 text-sm text-ink-muted">Loading CRM…</div>}
+ >
+ {sidebar()}
+ </Suspense>
+ </ViewShell.Aside>
+ <ViewShell.Main>
+ <Show when={selectedCompany()}>
+ {(company) => (
+ <CrmCompanyDetail
+ company={company()}
+ viewName={title()}
+ onClose={closeCompany}
+ navigation={
+ <NavigationToggle onExpand={() => setCollapsed(false)}>
+ <Suspense>{sidebar()}</Suspense>
+ </NavigationToggle>
+ }
+ />
+ )}
+ </Show>
+ <Show when={!selectedCompany()}>
+ <div class="flex h-12 shrink-0 items-center gap-3 border-b border-edge-muted px-4">
+ <NavigationToggle onExpand={() => setCollapsed(false)}>
+ <Suspense>{sidebar()}</Suspense>
+ </NavigationToggle>
+ <h1
+ class="flex h-7 min-w-0 flex-1 items-center px-1 text-sm font-semibold tracking-[-0.03em]"
+ title={title()}
+ >
+ <span class="truncate">{title()}</span>
+ </h1>
+ </div>
+ <ViewShell.Header>
+ <div class="flex min-w-0 items-center justify-between gap-3">
+ <CrmSearchBar />
+ <div class="ml-auto flex shrink-0 items-center gap-2 [&_button]:h-8 [&_button]:min-w-8 [&_button]:rounded-lg [&_button>svg]:size-4!">
+ <SoupViewContextSort />
+ <SoupViewContextGroup hideLabel />
+ <UnifiedFilterDropdown hideLabel />
+ <CompanyDisplayMenu />
+ <Suspense>
+ <CompanyViewsMenu hideLabel />
+ </Suspense>
+ <Show when={listsFlag().enabled && activeList()}>
+ {(list) => (
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() =>
+ setEditing({
+ id: list().id,
+ name: list().name,
+ companyIds: [...list().config.companyIds],
+ })
+ }
+ >
+ Edit list
+ </Button>
+ )}
+ </Show>
+ </div>
+ </div>
+ </ViewShell.Header>
+ <Suspense>
+ <CrmFilterChips onReset={() => navigate(active())} />
+ </Suspense>
+ <div class="min-h-0 min-w-0 flex-1">
+ {props.children(openCompany)}
+ </div>
+ </Show>
+ </ViewShell.Main>
+ <Show when={listsFlag().enabled && editing()}>
+ {(initial) => {
+ const companies = useQuickAccessCrmCompaniesQuery();
+ return (
+ <CrmListDialog
+ initial={
+ initial().id ? { ...initial(), id: initial().id! } : undefined
+ }
+ companies={companies.companies()}
+ loading={companies.query.isLoading}
+ onClose={() => setEditing(undefined)}
+ onSave={async (name, companyIds) => {
+ const id = await lists.save.mutateAsync({
+ id: initial().id,
+ name,
+ companyIds,
+ });
+ navigate(`list:${id}`);
+ }}
+ onDelete={
+ initial().id
+ ? async () => {
+ await lists.remove.mutateAsync(initial().id!);
+ navigate('active');
+ }
+ : undefined
+ }
+ />
+ );
+ }}
+ </Show>
+ <Show when={exporting()}>
+ <CrmExport
+ 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 };
+ }}
+ />
+ </Show>
+ <Show when={importing()}>
+ <CrmImport onClose={() => setImporting(false)} />
+ </Show>
+ </ViewShell.Root>
+ );
+}
diff --git a/apps/web/src/features/contacts/Contact/Contact.tsx b/apps/web/src/features/contacts/Contact/Contact.tsx
index 1cf07f8983..b20b75eab7 100644
--- a/apps/web/src/features/contacts/Contact/Contact.tsx
+++ b/apps/web/src/features/contacts/Contact/Contact.tsx
@@ -14,13 +14,17 @@ import { ContactSharingSection } from './ContactSharingSection';
* company block: middle content constrained to a centered column, with
* additional info in the right-hand SidePanel.
*/
-export function Contact(props: { contactId: string }) {
+export function Contact(props: {
+ contactId: string;
+ headerToggle?: boolean;
+ onOpenCompany?: (companyId: string) => boolean;
+}) {
const contactQuery = useContactQuery(() => props.contactId);
const contact = () => contactQuery.data;
const isTeamAdmin = useIsTeamAdmin();
return (
- <SidePanel.Layout>
+ <SidePanel.Layout headerToggle={props.headerToggle}>
<div class="flex h-full flex-col overflow-y-auto scrollbar-hidden">
<div class="mx-auto flex w-full max-w-3xl min-w-0 grow flex-col gap-6 px-6 pt-12 pb-12">
<ContactHeader contact={contact()} />
@@ -35,7 +39,10 @@ export function Contact(props: { contactId: string }) {
order={10}
defaultOpen
>
- <ContactMetadataSection contact={contact()} />
+ <ContactMetadataSection
+ contact={contact()}
+ onOpenCompany={props.onOpenCompany}
+ />
</SidePanel.Section>
{/* Sharing is admin-only; hide the whole section for non-admins
rather than rendering it empty. */}
diff --git a/apps/web/src/features/contacts/Contact/ContactMetadataSection.tsx b/apps/web/src/features/contacts/Contact/ContactMetadataSection.tsx
index 8fd26203a1..c73753e308 100644
--- a/apps/web/src/features/contacts/Contact/ContactMetadataSection.tsx
+++ b/apps/web/src/features/contacts/Contact/ContactMetadataSection.tsx
@@ -15,6 +15,7 @@ function Field(props: { label: string; children: JSX.Element }) {
export function ContactMetadataSection(props: {
contact?: CrmContactResponse;
+ onOpenCompany?: (companyId: string) => boolean;
}) {
const { openWithSplit } = useSplitLayout();
// NIL while the contact is loading — useCompanyQuery's `enabled` gate
@@ -24,6 +25,7 @@ export function ContactMetadataSection(props: {
);
const openCompany = (companyId: string, event: MouseEvent) => {
+ if (!event.shiftKey && props.onOpenCompany?.(companyId)) return;
openWithSplit(
{ type: 'company', id: companyId },
{ activate: true, preferNewSplit: event.shiftKey }
diff --git a/apps/web/src/features/next-soup/filters/configs/base.ts b/apps/web/src/features/next-soup/filters/configs/base.ts
index b1b843fc3d..50eaa4c781 100644
--- a/apps/web/src/features/next-soup/filters/configs/base.ts
+++ b/apps/web/src/features/next-soup/filters/configs/base.ts
@@ -61,6 +61,7 @@ export type FilterContext = {
* functions bucket companies exactly like the kanban does.
*/
resolveCompanyStage?: (entity: EntityData) => string | undefined;
+ companyStageLabel?: (optionId: string) => string | undefined;
};
export type Predicate = (entity: EntityData, ctx: FilterContext) => boolean;
diff --git a/apps/web/src/features/next-soup/filters/configs/company.ts b/apps/web/src/features/next-soup/filters/configs/company.ts
index 47faa8abf6..0184bba930 100644
--- a/apps/web/src/features/next-soup/filters/configs/company.ts
+++ b/apps/web/src/features/next-soup/filters/configs/company.ts
@@ -1,3 +1,9 @@
+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,
@@ -26,3 +32,26 @@ export const companyOwnerFilter = config({
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: {},
+});
diff --git a/apps/web/src/features/next-soup/filters/configs/index.ts b/apps/web/src/features/next-soup/filters/configs/index.ts
index 75c5ec9e89..6963ce714b 100644
--- a/apps/web/src/features/next-soup/filters/configs/index.ts
+++ b/apps/web/src/features/next-soup/filters/configs/index.ts
@@ -10,7 +10,12 @@ export * from './general';
export * from './task';
import type { FilterGroupConfig } from './base';
-import { companyOwnerFilter, companyStageFilter } from './company';
+import {
+ companyNeedsFollowUpFilter,
+ companyOwnerFilter,
+ companyRecentlyActiveFilter,
+ companyStageFilter,
+} from './company';
import {
DOCUMENT_CONTEXTUAL_FILTERS,
emailAttachmentsFilter,
@@ -99,6 +104,8 @@ export const SOUP_FILTERS = [
crmCompanyActiveFilter,
crmCompanyHiddenFilter,
companyOwnerFilter,
+ companyNeedsFollowUpFilter,
+ companyRecentlyActiveFilter,
companyStageFilter,
emailAttachmentsFilter,
inFolderFilter,
diff --git a/apps/web/src/features/next-soup/soup-view/create-search-state.ts b/apps/web/src/features/next-soup/soup-view/create-search-state.ts
index 920e27f8c9..18547ef7c7 100644
--- a/apps/web/src/features/next-soup/soup-view/create-search-state.ts
+++ b/apps/web/src/features/next-soup/soup-view/create-search-state.ts
@@ -282,7 +282,10 @@ export const createSearchState = ({
include_crm: true,
filters: {
...baseFilters,
- crm_company_filters: { hidden: state.include.crmCompanyHidden },
+ crm_company_filters: {
+ company_ids: state.include.crmCompanyId,
+ hidden: state.include.crmCompanyHidden,
+ },
},
}
: {
diff --git a/apps/web/src/features/next-soup/soup-view/empty-states.tsx b/apps/web/src/features/next-soup/soup-view/empty-states.tsx
index 1f1a6f07af..4daaec92a0 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
@@ -363,8 +363,20 @@ export function EmptyState(props: {
<Match when={true}>
<EmptyStatePanel
graphic={EmptyStateCompaniesGraphic}
- title="No customers yet"
- description="Customers your team emails will appear here."
+ 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>
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.tsx
index 584386e658..b3188bce11 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
@@ -962,6 +962,7 @@ export const SoupViewContextProvider: FlowComponent<
owners: ownerFilter(),
stages: stageFilter(),
resolveCompanyStage,
+ companyStageLabel: dealStages.stageLabel,
});
// This is temporary while we are experimenting/handling
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.tsx
index 635725c09b..c104dc622f 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
@@ -67,6 +67,7 @@ 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';
@@ -583,186 +584,188 @@ export const SoupView = (props: SoupViewProps) => {
},
});
- return (
+ const content = (onOpenEntity?: (entity: EntityData) => boolean) => (
<div
class="size-full flex flex-col @container"
data-list-view={activeListView()}
>
- <div class="flex flex-col w-full">
- <SplitHeaderLeft>
- <div
- class={cn(
- 'h-full flex gap-3 @max-[380px]/split-header:gap-2 items-center',
- {
- 'shrink-0': !isTouchDevice() && !narrowSearchExpanded(),
- 'flex-1 min-w-0': !isTouchDevice() && narrowSearchExpanded(),
- 'w-full flex-1 min-w-0': isTouchDevice(),
- }
- )}
- >
- {/* On mobile/tablet the header strip hosts the filter pills instead of
+ <Show when={!isComponentListView('companies')}>
+ <div class="flex flex-col w-full">
+ <SplitHeaderLeft>
+ <div
+ class={cn(
+ 'h-full flex gap-3 @max-[380px]/split-header:gap-2 items-center',
+ {
+ 'shrink-0': !isTouchDevice() && !narrowSearchExpanded(),
+ 'flex-1 min-w-0': !isTouchDevice() && narrowSearchExpanded(),
+ 'w-full flex-1 min-w-0': isTouchDevice(),
+ }
+ )}
+ >
+ {/* On mobile/tablet the header strip hosts the filter pills instead of
the view title (the bottom accessory region now belongs to the
global views row). */}
- <Show when={isTouchDevice()}>
- <MobileSoupViewTabs />
- </Show>
- <Show when={!isTouchDevice() && !narrowSearchExpanded()}>
- <div class="flex items-center gap-1">
- <span class="text-sm font-semibold">{props.viewName}</span>
- <Show when={docsUrl()}>
- {(url) => (
- <Button
- variant="ghost"
- class="p-0.5 rounded-sm text-ink-extra-muted hover:text-ink-muted @max-[380px]/split-header:hidden"
- label="View documentation"
- onClick={() => openExternalUrl(url())}
- >
- <InfoIcon class="size-3.5" />
- </Button>
- )}
- </Show>
- </div>
- </Show>
- <Show
- when={!narrowSearchExpanded() && !isComponentListView('search')}
- >
- <Show when={!isTouchDevice()}>
- <CollapsibleHeaderItem
- id="tabs"
- priority={1}
- containerClass="h-full"
- >
- {(isCollapsed) => (
- <Show
- when={!isCollapsed()}
- fallback={props.customTabs ?? <CollapsedSoupViewTabs />}
- >
- {props.customTabs ?? <SoupViewTabs />}
- </Show>
- )}
- </CollapsibleHeaderItem>
+ <Show when={isTouchDevice()}>
+ <MobileSoupViewTabs />
</Show>
- </Show>
- <Show
- when={
- !isTouchDevice() &&
- !narrowSearchExpanded() &&
- isComponentListView('mail')
- }
- >
- <InboxSelector />
- </Show>
- </div>
- </SplitHeaderLeft>
- <Show when={!isTouchDevice()}>
- <SplitHeaderRight>
- <Show
- when={
- !narrowSearchExpanded() &&
- !isComponentListView('search') &&
- props.showCreateButton !== false
- }
- >
- <SoupViewCreateButton />
- </Show>
- <Show when={narrowSearchExpanded()}>
- <Layer depth={2}>
- <div class="flex-1 min-w-0">
- <SoupSearchbar
- variant="secondary"
- autoFocus
- initialValue={props.initialSearchText}
- onDismiss={() => setNarrowSearchExpanded(false)}
- />
+ <Show when={!isTouchDevice() && !narrowSearchExpanded()}>
+ <div class="flex items-center gap-1">
+ <span class="text-sm font-semibold">{props.viewName}</span>
+ <Show when={docsUrl()}>
+ {(url) => (
+ <Button
+ variant="ghost"
+ class="p-0.5 rounded-sm text-ink-extra-muted hover:text-ink-muted @max-[380px]/split-header:hidden"
+ label="View documentation"
+ onClick={() => openExternalUrl(url())}
+ >
+ <InfoIcon class="size-3.5" />
+ </Button>
+ )}
+ </Show>
</div>
- </Layer>
- </Show>
- <Show
- when={!isComponentListView('search')}
- fallback={
- <>
- <Layer depth={2}>
- <div class="grow ml-2 min-w-0 [contain:inline-size]">
- <SoupSearchbar
- variant="secondary"
- placeholder="Search, @mention contacts"
- initialValue={props.initialSearchText}
- />
- </div>
- </Layer>
- <SearchAskAiButton />
- </>
- }
- >
- <Show when={!narrowSearchExpanded()}>
- <CollapsibleHeaderItem
- id="search"
- priority={0}
- onCollapsedChange={(isCollapsed) => {
- setSearchIsCollapsed(isCollapsed);
- if (!isCollapsed) setNarrowSearchExpanded(false);
- }}
- >
- {(isCollapsed) => (
- <Show
- when={!isCollapsed()}
- fallback={
- <Tooltip label="Search" hotkey={TOKENS.soup.openSearch}>
- <Button
- variant="outline"
- class="p-1 size-7 rounded-lg ml-2 bg-surface"
- onClick={() => setNarrowSearchExpanded(true)}
- depth={2}
+ </Show>
+ <Show
+ when={!narrowSearchExpanded() && !isComponentListView('search')}
+ >
+ <Show when={!isTouchDevice()}>
+ <CollapsibleHeaderItem
+ id="tabs"
+ priority={1}
+ containerClass="h-full"
+ >
+ {(isCollapsed) => (
+ <Show
+ when={!isCollapsed()}
+ fallback={props.customTabs ?? <CollapsedSoupViewTabs />}
+ >
+ {props.customTabs ?? <SoupViewTabs />}
+ </Show>
+ )}
+ </CollapsibleHeaderItem>
+ </Show>
+ </Show>
+ <Show
+ when={
+ !isTouchDevice() &&
+ !narrowSearchExpanded() &&
+ isComponentListView('mail')
+ }
+ >
+ <InboxSelector />
+ </Show>
+ </div>
+ </SplitHeaderLeft>
+ <Show when={!isTouchDevice()}>
+ <SplitHeaderRight>
+ <Show
+ when={
+ !narrowSearchExpanded() &&
+ !isComponentListView('search') &&
+ props.showCreateButton !== false
+ }
+ >
+ <SoupViewCreateButton />
+ </Show>
+ <Show when={narrowSearchExpanded()}>
+ <Layer depth={2}>
+ <div class="flex-1 min-w-0">
+ <SoupSearchbar
+ variant="secondary"
+ autoFocus
+ initialValue={props.initialSearchText}
+ onDismiss={() => setNarrowSearchExpanded(false)}
+ />
+ </div>
+ </Layer>
+ </Show>
+ <Show
+ when={!isComponentListView('search')}
+ fallback={
+ <>
+ <Layer depth={2}>
+ <div class="grow ml-2 min-w-0 [contain:inline-size]">
+ <SoupSearchbar
+ variant="secondary"
+ placeholder="Search, @mention contacts"
+ initialValue={props.initialSearchText}
+ />
+ </div>
+ </Layer>
+ <SearchAskAiButton />
+ </>
+ }
+ >
+ <Show when={!narrowSearchExpanded()}>
+ <CollapsibleHeaderItem
+ id="search"
+ priority={0}
+ onCollapsedChange={(isCollapsed) => {
+ setSearchIsCollapsed(isCollapsed);
+ if (!isCollapsed) setNarrowSearchExpanded(false);
+ }}
+ >
+ {(isCollapsed) => (
+ <Show
+ when={!isCollapsed()}
+ fallback={
+ <Tooltip
+ label="Search"
+ hotkey={TOKENS.soup.openSearch}
>
- <SearchIcon class="size-4 touch:size-6" />
- </Button>
- </Tooltip>
- }
- >
- <Layer depth={2}>
- <div class="w-60 ml-2">
- <SoupSearchbar
- variant="secondary"
- initialValue={props.initialSearchText}
- />
- </div>
- </Layer>
- </Show>
- )}
- </CollapsibleHeaderItem>
+ <Button
+ variant="outline"
+ class="p-1 size-7 rounded-lg ml-2 bg-surface"
+ onClick={() => setNarrowSearchExpanded(true)}
+ depth={2}
+ >
+ <SearchIcon class="size-4 touch:size-6" />
+ </Button>
+ </Tooltip>
+ }
+ >
+ <Layer depth={2}>
+ <div class="w-60 ml-2">
+ <SoupSearchbar
+ variant="secondary"
+ initialValue={props.initialSearchText}
+ />
+ </div>
+ </Layer>
+ </Show>
+ )}
+ </CollapsibleHeaderItem>
+ </Show>
</Show>
- </Show>
- </SplitHeaderRight>
- </Show>
- </div>
- <SoupFiltersBar
- variant={props.filterBarVariant}
- hasPreviewItems={hasPreviewItems()}
- onPreviewEngage={openFocusedEntityInPreview}
- onPreviewOpenChange={(open) => {
- if (DEFAULT_PREVIEW_VIEWS.has(contentId))
- setPreviewOpenPreference(open);
- }}
- />
+ </SplitHeaderRight>
+ </Show>
+ </div>
+ <SoupFiltersBar
+ variant={props.filterBarVariant}
+ hasPreviewItems={hasPreviewItems()}
+ onPreviewEngage={openFocusedEntityInPreview}
+ onPreviewOpenChange={(open) => {
+ if (DEFAULT_PREVIEW_VIEWS.has(contentId))
+ setPreviewOpenPreference(open);
+ }}
+ />
+ </Show>
<Show when={soupView.source.cachedMail?.()}>
<p role="status" class="px-4 py-1 text-xs text-ink-muted">
Showing cached mail. Only synchronized messages are available.
</p>
</Show>
- <Show when={applyDefaultCrmView}>
- <CrmDefaultViewLoader />
- </Show>
<div class="relative grow min-h-1 flex max-sm:flex-col flex-row size-full">
<Suspense>
<Show
when={!isBoardMode()}
fallback={
<MaybeSoupEntityActionDrawerManager>
- <CompanyKanban />
+ <CompanyKanban onOpenEntity={onOpenEntity} />
</MaybeSoupEntityActionDrawerManager>
}
>
- <SoupViewList />
+ <SoupViewList onOpenEntity={onOpenEntity} />
</Show>
</Suspense>
</div>
@@ -788,9 +791,21 @@ export const SoupView = (props: SoupViewProps) => {
</Suspense>
</div>
);
+ return (
+ <>
+ <Show when={applyDefaultCrmView}>
+ <CrmDefaultViewLoader />
+ </Show>
+ <Show when={isComponentListView('companies')} fallback={content()}>
+ <CrmWorkspace>{(onOpenEntity) => content(onOpenEntity)}</CrmWorkspace>
+ </Show>
+ </>
+ );
};
interface SoupViewListProps {
+ /** Return true when the host handles ordinary activation in its own detail view. */
+ onOpenEntity?: (entity: EntityData) => boolean;
emptyState?: () => JSX.Element;
timestamp?: (entity: EntityData) => DateValue | null | undefined;
navigationKey?: string;
@@ -812,6 +827,7 @@ export const SoupViewList = (props: SoupViewListProps) => (
customScrollbarHidden={props.customScrollbarHidden}
scopeId={props.scopeId}
onOpenProject={props.onOpenProject}
+ onOpenEntity={props.onOpenEntity}
uploadProjectId={props.uploadProjectId}
disableTabHotkeys={props.disableTabHotkeys}
timestamp={props.timestamp}
@@ -1003,6 +1019,7 @@ const SoupViewListContent = (props: SoupViewListProps) => {
applyTabPreset,
fetchNextGroupPage,
onOpenProject: props.onOpenProject,
+ onOpenEntity: props.onOpenEntity,
disableTabHotkeys: props.disableTabHotkeys,
});
@@ -1056,6 +1073,15 @@ const SoupViewListContent = (props: SoupViewListProps) => {
markReminderSeenOnOpen(entity, notificationSource);
+ if (
+ !event.metaKey &&
+ !event.ctrlKey &&
+ !event.shiftKey &&
+ !event.altKey &&
+ props.onOpenEntity?.(entity)
+ )
+ return;
+
// FIXME: this never gets called because we have overrides
if (event.metaKey || event.ctrlKey) {
// Channels the viewer hasn't joined can't be opened; the row's inline
diff --git a/apps/web/src/features/next-soup/soup-view/use-soup-view-hotkeys.ts b/apps/web/src/features/next-soup/soup-view/use-soup-view-hotkeys.ts
index 694a2e9a9d..933a8f4eb5 100644
--- a/apps/web/src/features/next-soup/soup-view/use-soup-view-hotkeys.ts
+++ b/apps/web/src/features/next-soup/soup-view/use-soup-view-hotkeys.ts
@@ -15,6 +15,7 @@ import { createHotkeyGroup, registerHotkey } from '@core/hotkey/hotkeys';
import { TOKENS } from '@core/hotkey/tokens';
import { isScopeInActiveBranch } from '@core/hotkey/utils';
import {
+ type EntityData,
filterNotDoneNotifications,
filterValidNotifications,
isSearchEntity,
@@ -31,6 +32,7 @@ import {
} from './soup-view-tabs';
type UseSoupViewHotkeysOptions = {
+ onOpenEntity?: (entity: EntityData) => boolean;
onOpenProject?: (id: string) => void;
disableTabHotkeys?: boolean;
scopeId: string;
@@ -187,6 +189,8 @@ export const useSoupViewHotkeys = (options: UseSoupViewHotkeysOptions) => {
return true;
}
+ if (options.onOpenEntity?.(entity)) return true;
+
const contentHitData = isSearchEntity(entity)
? entity.search.contentHitData
: undefined;
diff --git a/apps/web/src/features/next-soup/soup-view/views/companies/CompanyKanban.tsx b/apps/web/src/features/next-soup/soup-view/views/companies/CompanyKanban.tsx
index 5c8ae0131d..780892a030 100644
--- a/apps/web/src/features/next-soup/soup-view/views/companies/CompanyKanban.tsx
+++ b/apps/web/src/features/next-soup/soup-view/views/companies/CompanyKanban.tsx
@@ -59,7 +59,9 @@ type StageColumn = {
* closed stage additionally requires the move-closed-deals permission).
*
*/
-export function CompanyKanban() {
+export function CompanyKanban(props: {
+ onOpenEntity?: (entity: EntityData) => boolean;
+}) {
const { source, soup, stageFilter, searchText, activeTab } = useSoupView();
const panel = useSplitPanelOrThrow();
const entityActionViewContext = () =>
@@ -255,6 +257,14 @@ export function CompanyKanban() {
};
const openCompany = (entity: EntityData, event: MouseEvent) => {
+ if (
+ !event.metaKey &&
+ !event.ctrlKey &&
+ !event.shiftKey &&
+ !event.altKey &&
+ props.onOpenEntity?.(entity)
+ )
+ return;
// Shift+click always opens a fresh split; opt+click replaces the whole
// Preview Pair; a plain click while engaged as a Controller previews into
// the Viewer and shouldn't re-open an entity already shown elsewhere.
@@ -304,10 +314,8 @@ export function CompanyKanban() {
class={cn(
// Fallback sizing until the board is measured; after
// that the snapping columnWidth() takes over.
- 'flex h-full min-w-56 flex-1 flex-col rounded-lg border border-edge-muted bg-surface',
- dropTarget() === column.key &&
- draggedId() &&
- 'border-accent/50 bg-accent/5'
+ 'flex h-full min-w-56 flex-1 flex-col rounded-xl bg-surface-2/30 transition-colors',
+ dropTarget() === column.key && draggedId() && 'bg-accent/10'
)}
style={
columnWidth() !== undefined
@@ -434,8 +442,8 @@ function CompanyKanbanCard(props: {
onDragEnd={props.onDragEnd}
onClick={props.onClick}
class={cn(
- 'flex flex-col gap-1.5 rounded-lg border border-edge-muted bg-panel p-2.5 text-sm',
- 'hover:border-edge hover:bg-active transition-colors',
+ 'flex flex-col gap-1.5 rounded-lg bg-surface p-2.5 text-sm shadow-sm',
+ 'hover:bg-hover hover:shadow-md transition-[background-color,box-shadow]',
props.dragging && 'opacity-40'
)}
>
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index d14b46ed7a..28a00a110b 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -423,6 +423,13 @@ export const enableCrm = defineFlag({
default: onInDev,
});
+// Company collections are paused until ready; preserve stored lists while off.
+export const enableCrmLists = defineFlag({
+ key: 'enable-crm-lists',
+ env: 'ENABLE_CRM_LISTS',
+ default: false,
+});
+
// Reminders: the "Remind me" entry in the command menu, the soup
// context menu and the block ⋯ menu, its 'h' shortcut, and the composer modal.
// Every surface routes through `makeCreateReminderAction().canExecute`, so this
diff --git a/apps/web/src/lib/queries/crm/companies.ts b/apps/web/src/lib/queries/crm/companies.ts
index 3ae167a533..74e384b56a 100644
--- a/apps/web/src/lib/queries/crm/companies.ts
+++ b/apps/web/src/lib/queries/crm/companies.ts
@@ -45,13 +45,13 @@ export function useCompanyQuery(companyId: Accessor<string>) {
});
const company = createMemo<CrmCompanyEntity | undefined>(() => {
- const data = query.data;
+ const data = query.isSuccess ? query.data : undefined;
if (!data) return undefined;
return responseToEntity(data);
});
- const contacts = createMemo<CompanyContact[]>(
- () => query.data?.contacts ?? []
+ const contacts = createMemo<CompanyContact[]>(() =>
+ query.isSuccess ? (query.data?.contacts ?? []) : []
);
return { query, company, contacts };
diff --git a/apps/web/src/lib/queries/crm/export.ts b/apps/web/src/lib/queries/crm/export.ts
new file mode 100644
index 0000000000..628049d967
--- /dev/null
+++ b/apps/web/src/lib/queries/crm/export.ts
@@ -0,0 +1,40 @@
+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';
+
+/** Read every visible company, without changing the active CRM view. */
+export async function fetchCrmExportCompanies(
+ signal: AbortSignal,
+ onProgress: (count: number) => void
+) {
+ const companies = new Map<string, CrmCompanyEntity>();
+ let cursor: string | null = null;
+ const cursors = new Set<string>();
+ do {
+ signal.throwIfAborted();
+ const page = await throwOnErr(() =>
+ storageServiceClient.getSoupItems({
+ params: { cursor },
+ body: {
+ ...QUERY_FILTERS_BASE,
+ crm_company_filters: { hidden: false },
+ limit: 500,
+ sort_method: 'updated_at',
+ },
+ })
+ );
+ signal.throwIfAborted();
+ for (const item of page.items) {
+ const entity = mapApiSoupItemToEntity(item);
+ if (isCrmCompanyEntity(entity)) companies.set(entity.id, entity);
+ }
+ onProgress(companies.size);
+ cursor = page.next_cursor ?? null;
+ if (cursor && cursors.has(cursor))
+ throw new Error('Export pagination did not advance. Please retry.');
+ if (cursor) cursors.add(cursor);
+ } while (cursor);
+ return [...companies.values()];
+}
diff --git a/apps/web/src/lib/queries/crm/keys.ts b/apps/web/src/lib/queries/crm/keys.ts
index 85beed977d..bfbed8f47a 100644
--- a/apps/web/src/lib/queries/crm/keys.ts
+++ b/apps/web/src/lib/queries/crm/keys.ts
@@ -2,6 +2,7 @@ import { createQueryKeys } from '@lukemorales/query-key-factory';
import type { CrmCommentEntityType } from '@service-storage/generated/schemas/crmCommentEntityType';
export const crmKeys = createQueryKeys('crm', {
+ lists: null,
company: (companyId: string) => [companyId],
contact: (contactId: string) => [contactId],
contactByEmail: (teamId: string, email: string) => [teamId, email],
diff --git a/apps/web/src/lib/queries/crm/lists.ts b/apps/web/src/lib/queries/crm/lists.ts
new file mode 100644
index 0000000000..871c168900
--- /dev/null
+++ b/apps/web/src/lib/queries/crm/lists.ts
@@ -0,0 +1,97 @@
+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.ts
new file mode 100644
index 0000000000..48b2aecd0f
--- /dev/null
+++ b/apps/web/src/lib/queries/crm/people.ts
@@ -0,0 +1,85 @@
+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/soup/keys.ts b/apps/web/src/lib/queries/soup/keys.ts
index fc2d16f983..e5b5fd2e0b 100644
--- a/apps/web/src/lib/queries/soup/keys.ts
+++ b/apps/web/src/lib/queries/soup/keys.ts
@@ -4,6 +4,7 @@ import type { SoupAstItemsQueryArgs, SoupItemsQueryArgs } from './items';
import type { SearchSoupQueryArgs } from './search';
export const soupKeys = createQueryKeys('soup', {
+ crmPeople: (teamId: string) => [teamId],
items: (args: SoupItemsQueryArgs) => ({
queryKey: [args.params, args.body],
}),
diff --git a/apps/web/src/lib/queries/soup/quick-access-crm-companies.ts b/apps/web/src/lib/queries/soup/quick-access-crm-companies.ts
index 96046aa997..43a0ebb300 100644
--- a/apps/web/src/lib/queries/soup/quick-access-crm-companies.ts
+++ b/apps/web/src/lib/queries/soup/quick-access-crm-companies.ts
@@ -38,8 +38,8 @@ export function useQuickAccessCrmCompaniesQuery() {
() => ({ staleTime: STALE_TIME, enabled: crmFlag().enabled })
);
- const companies = createMemo<CrmCompanyEntity[]>(
- () => query.data?.filter(isCrmCompanyEntity) ?? []
+ const companies = createMemo<CrmCompanyEntity[]>(() =>
+ query.isSuccess ? (query.data?.filter(isCrmCompanyEntity) ?? []) : []
);
return { query, companies };
diff --git a/bun.lock b/bun.lock
index 9d8c307d59..f0f7012326 100644
--- a/bun.lock
+++ b/bun.lock
@@ -969,7 +969,7 @@
"@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],
- "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#6ddd660", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-6ddd660", "sha512-7+0ebEOYqedkOY67Clwu65Np3qJ3aJc/H/NjNxmjgA/7HIu0C+DSoKAArG7HTdTVpdcAtHyhrqsJujdEAyJf6Q=="],
+ "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#6ddd660", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-6ddd660"],
"@inquirer/ansi": ["@inquirer/[email protected]", "", {}, "sha512-3eTuUO1vH2cZm2ZKHeQxnOqlTi9EfZDGgIe3BL3I4u+rJHocr9Fz86M4fjYABPvFnQG/gGK551HqDiIcETwU6Q=="],
@@ -2933,7 +2933,7 @@
"pathval": ["[email protected]", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="],
- "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6", "sha512-HDFaPbCxLG2GHpf1smUG97nku5aPGBGaCcIbK05dGdp07TBLUlDcXsM4WcE82mO5W4RBPIBVYobX5N/6M6NFrA=="],
+ "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6"],
"pend": ["[email protected]", "", {}, "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg=="],
diff --git a/crates/channels/fixtures/channel_shared_content.sql b/crates/channels/fixtures/channel_shared_content.sql
new file mode 100644
index 0000000000..750be512ba
--- /dev/null
+++ b/crates/channels/fixtures/channel_shared_content.sql
@@ -0,0 +1,8 @@
+-- References include a duplicate attachment, an agent in a reply, and scoped exclusions.
+INSERT INTO comms_entity_mentions (id, source_entity_type, source_entity_id, entity_type, entity_id, created_at) VALUES
+ ('019a0000-0000-7000-8000-000000000001', 'message', '00000000-0000-0000-0000-000000000001', 'document', 'doc-1', '2024-01-01 10:00:00+00'),
+ ('019a0000-0000-7000-8000-000000000002', 'message', '00000000-0000-0000-0000-000000000003', 'document', 'mentioned-doc', '2024-01-01 12:00:00+00'),
+ ('019a0000-0000-7000-8000-000000000003', 'message', '00000000-0000-0000-0000-00000000b001', 'agent_session', 'shared-agent', '2024-01-01 12:00:00+00'),
+ ('019a0000-0000-7000-8000-000000000004', 'message', '00000000-0000-0000-0000-000000000002', 'document', 'deleted-reference', '2024-01-01 12:00:00+00'),
+ ('019a0000-0000-7000-8000-000000000005', 'message', '00000000-0000-0000-0000-000000000005', 'document', 'other-channel-reference', '2024-01-01 12:00:00+00'),
+ ('019a0000-0000-7000-8000-000000000006', 'message', '00000000-0000-0000-0000-000000000003', 'user', 'macro|[email protected]', '2024-01-01 12:00:00+00');
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index f883bd0c93..75783682ea 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -484,8 +484,73 @@ On phones, recorded call headers omit the **Call Again** action.
## Customers (CRM) — `/app/component/companies`
-Board/List views, `Company` create button. Requires a team ("Join a team to enable CRM" →
-`Open team settings`).
+The 216px local sidebar uses the same navigation primitives as Email and Tasks.
+Board and List share a horizontal segmented toggle at the top of the sidebar; the
+main header has no layout toggle. People is not available. Views include All companies, My companies
+(Owner = current user), Needs follow-up (has a stage other than Churned and last
+interaction at least 14 days ago),
+Recently active (team email activity within 7 days), and Unassigned (no Owner). Existing personal/team
+saved views also appear under Views. Stages remain board columns or list properties.
+Board/List switches the representation without changing the selected set.
+Recently active uses the CRM last-interaction timestamp, advanced by sent and received
+email. It does not count company @mentions or chat discussions. Manually created
+companies initialize that timestamp to creation time, so newly added companies may
+also appear before any email; the sidebar hover tooltip discloses this limitation.
+View descriptions appear in sidebar tooltips, not above the main board or list.
+The `Search companies` field uses the shared Email/Tasks search bar. Command-F
+focuses it, `Clear search` resets it, and Escape leaves the field.
+
+Clicking a company in Board or List (or pressing Enter on a focused list row)
+opens its details inside the CRM workspace, keeping the left navigation visible.
+The top breadcrumb reads `<current view or list> > <company>`; click the first
+segment to return with the same filters, layout, and list scroll position. Selecting
+another sidebar view or switching Board/List closes the company details.
+Shift-click still opens the company in a separate split. Direct company links use
+the standalone company page.
+Clicking a contact in an embedded company's Contacts section appends a third
+breadcrumb: `<current view or list> > <company> > <contact>`. The CRM sidebar stays
+visible. Click the company breadcrumb or the contact's Company link to return to
+the company; click the first breadcrumb to return directly to the originating
+view. Shift-click still opens a contact in a separate split. Direct contact links
+use the standalone contact page.
+Company and contact headers have `Copy link` beside the side-panel toggle.
+It copies the record's direct URL and shows a confirmation toast; this is also
+available in the embedded company and contact breadcrumb header.
+
+`Collapse CRM sidebar` persists across visits; `Expand CRM sidebar` restores it.
+At narrow widths, `Show CRM navigation` opens the same navigation in a menu.
+The sidebar's Views and Lists sections can also collapse independently.
+
+CRM lists are currently disabled by `enableCrmLists` (default `false`). The sidebar
+Lists section, list editor, and company membership controls only mount when enabled.
+Existing list data is preserved; a restored list view returns to All companies while
+disabled. Board/List layout and saved filter views remain available.
+
+When enabled, lists are personal, team-scoped collections of explicit company IDs, persisted through
+saved-view storage separately from saved filter views. `New list` opens a name and
+company picker; `Edit list` changes membership or deletes the collection. An empty list
+must not show every company. The picker browses up to 500 recent companies. Canceling
+never saves the draft. Saving only closes the dialog after the server succeeds.
+
+Company detail pages show a **Lists** section in the right panel, with current
+personal list memberships as chips. **Manage lists** expands a searchable checkbox
+picker. Checking or unchecking saves immediately and refreshes the CRM sidebar's
+membership counts. Changes are disabled while saving; failures show an inline retry
+message and keep the last saved membership. With no lists, create one in the CRM sidebar.
+
+`New company` uses the existing creation dialog. `Import` previews a CSV with `name`
+and `domain` columns (1–100 rows, at most 1 MB). The explicit Import button writes the
+previewed companies. Partial failures retain only failed rows for retry. Use preview
+and cancel for browser checks against hosted dev data. `CRM settings` opens the existing
+settings panel. Requires a team with CRM enabled.
+
+`Export` opens options for companies. Choose Current view
+(respects filters/search) or All records across views (each visible record once), then
+select CSV columns. Company exports include Stage, Owner, Revenue and optional custom
+properties. `Prepare export` fetches every page and shows a count and three-row preview;
+it does not download. `Download CSV` saves the prepared snapshot using the selected
+columns. Changing scope requires preparing again. Cancel stops preparation. CSV uses UTF-8,
+quoted fields, original date timestamps and spreadsheet formula escaping.
## Activity — `/app/component/activity`