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): project-style company record with section tabs (#7280)

teo7cdd6e4775f9
diff --git a/apps/web/src/features/block-company/component/CompanyBlockAdapter.tsx b/apps/web/src/features/block-company/component/CompanyBlockAdapter.tsx
index 9509adfa02..9dccf49e8d 100644
--- a/apps/web/src/features/block-company/component/CompanyBlockAdapter.tsx
+++ b/apps/web/src/features/block-company/component/CompanyBlockAdapter.tsx
@@ -1,7 +1,15 @@
-import { Company } from '@app/features/crm/crm-company';
+import {
+ Company,
+ type CompanySection,
+ CompanyTabs,
+} from '@app/features/crm/crm-company';
import { CrmCopyLinkButton } from '@app/features/crm/crm-link';
+import { CollapsibleHeaderItem } from '@components/app/split-layout/components/CollapsibleItem';
import { HeaderIsland } from '@components/app/split-layout/components/HeaderIsland';
-import { SplitHeaderRight } from '@components/app/split-layout/components/SplitHeader';
+import {
+ SplitHeaderLeft,
+ SplitHeaderRight,
+} from '@components/app/split-layout/components/SplitHeader';
import { useBlockId } from '@core/block';
import {
createParamsState,
@@ -9,6 +17,7 @@ import {
} from '@core/component/ParamsProvider';
import { createMethodRegistration } from '@core/orchestrator';
import { blockHandleSignal } from '@core/signal/load';
+import { createSignal } from 'solid-js';
/**
* Legacy adapter: bridges the block/split-layout system to the standalone
@@ -18,18 +27,44 @@ import { blockHandleSignal } from '@core/signal/load';
export function CompanyBlockAdapter() {
const companyId = useBlockId();
const params = createParamsState();
+ const [section, setSection] = createSignal<CompanySection>('overview');
createMethodRegistration(blockHandleSignal.get, {
goToLocationFromParams: params.navigate,
});
return (
<>
+ <SplitHeaderLeft>
+ <CollapsibleHeaderItem
+ id="company-tabs"
+ priority={1}
+ containerClass="ph-no-capture min-w-0 h-full mx-2"
+ >
+ {(isCollapsed) => (
+ // Labels keep their width so the header collapses them to
+ // icons; the icons scroll once even they no longer fit.
+ <div
+ class={
+ isCollapsed()
+ ? 'min-w-0 overflow-x-auto scrollbar-hidden'
+ : 'shrink-0'
+ }
+ >
+ <CompanyTabs
+ value={section()}
+ onChange={setSection}
+ compact={isCollapsed()}
+ />
+ </div>
+ )}
+ </CollapsibleHeaderItem>
+ </SplitHeaderLeft>
<SplitHeaderRight>
<HeaderIsland>
<CrmCopyLinkButton type="company" id={companyId} />
</HeaderIsland>
</SplitHeaderRight>
<ParamsProvider state={params}>
- <Company companyId={companyId} />
+ <Company companyId={companyId} section={section()} />
</ParamsProvider>
</>
);
diff --git a/apps/web/src/features/crm/components/record-section.tsx b/apps/web/src/features/crm/components/record-section.tsx
new file mode 100644
index 0000000000..9385eaf083
--- /dev/null
+++ b/apps/web/src/features/crm/components/record-section.tsx
@@ -0,0 +1,23 @@
+import type { JSX, ParentProps } from 'solid-js';
+import { Show } from 'solid-js';
+
+/** A full-height record tab: a title row with actions above scrolling content. */
+export function RecordSection(
+ props: ParentProps<{ title: string; actions?: JSX.Element }>
+) {
+ return (
+ <div class="flex size-full min-h-0 flex-col">
+ <div class="flex min-w-0 flex-wrap items-center gap-3 px-4 py-3">
+ <h2 class="text-sm font-medium text-ink-muted">{props.title}</h2>
+ <Show when={props.actions}>
+ <div class="ml-auto flex shrink-0 items-center gap-2.5">
+ {props.actions}
+ </div>
+ </Show>
+ </div>
+ <div class="min-h-0 flex-1 overflow-y-auto px-2 pb-6">
+ {props.children}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/crm/components/record-tabs.tsx b/apps/web/src/features/crm/components/record-tabs.tsx
new file mode 100644
index 0000000000..bd5dfe51e8
--- /dev/null
+++ b/apps/web/src/features/crm/components/record-tabs.tsx
@@ -0,0 +1,59 @@
+import { TabsInset } from '@core/component/TabsInset';
+import CheckSquareIcon from '@phosphor/check-square.svg';
+import EnvelopeIcon from '@phosphor/envelope.svg';
+import FilesIcon from '@phosphor/files.svg';
+import PhoneIcon from '@phosphor/phone.svg';
+import SquaresFourIcon from '@phosphor/squares-four.svg';
+import UsersIcon from '@phosphor/users.svg';
+import type { Component, JSX } from 'solid-js';
+import {
+ CRM_RECORD_SECTION_LABELS,
+ type CrmRecordSection,
+} from '../core/record';
+
+const SECTION_ICONS: Record<
+ CrmRecordSection,
+ Component<JSX.SvgSVGAttributes<SVGSVGElement>>
+> = {
+ overview: SquaresFourIcon,
+ team: UsersIcon,
+ emails: EnvelopeIcon,
+ files: FilesIcon,
+ tasks: CheckSquareIcon,
+ calls: PhoneIcon,
+};
+
+/**
+ * A CRM record's section tabs for its top bar, like a project's Overview /
+ * Tasks tabs. `compact` swaps labels for icons when the bar runs out of room.
+ */
+export function RecordTabs<S extends CrmRecordSection>(props: {
+ sections: readonly S[];
+ value: S;
+ onChange: (section: S) => void;
+ compact?: boolean;
+}) {
+ const list = () =>
+ props.sections.map((section) => {
+ const label = CRM_RECORD_SECTION_LABELS[section];
+ if (!props.compact) return { value: section, label };
+ const Icon = SECTION_ICONS[section];
+ return {
+ value: section,
+ label: (
+ <span class="flex items-center" title={label}>
+ <Icon class="size-4" />
+ </span>
+ ),
+ };
+ });
+ return (
+ <TabsInset
+ list={list()}
+ value={props.value}
+ onChange={(value) => props.onChange(value as S)}
+ aria-label="Record sections"
+ class="shrink-0 whitespace-nowrap"
+ />
+ );
+}
diff --git a/apps/web/src/features/crm/context/crm-context.tsx b/apps/web/src/features/crm/context/crm-context.tsx
index ace031b908..8ab8aad0a3 100644
--- a/apps/web/src/features/crm/context/crm-context.tsx
+++ b/apps/web/src/features/crm/context/crm-context.tsx
@@ -1,9 +1,15 @@
import type { CrmCompanyEntity } from '@entity';
-import { type Accessor, createContext, useContext } from 'solid-js';
+import {
+ type Accessor,
+ type Component,
+ createContext,
+ useContext,
+} from 'solid-js';
import type {
CrmDisplayOptions,
CrmListColumnId,
} from '../core/display-options';
+import type { CrmRecordScope } from '../core/record';
import type {
CompanySource,
ContactSource,
@@ -14,8 +20,8 @@ import type {
CrmStageInput,
CrmStagesResult,
DealStages,
- EmailSource,
ExportDefinitionsSource,
+ ItemListSource,
ListsSource,
PersonalViewsSource,
PropertyCommands,
@@ -40,7 +46,8 @@ export type CrmContext = {
options?: { activate?: boolean; preferNewSplit?: boolean }
): void;
showCompanies(): void;
- openEmail(entity: import('@entity').EntityData): void;
+ /** Open any soup row (email, file, call, ...) in a split. */
+ openEntity(entity: import('@entity').EntityData): void;
};
listsEnabled(): Accessor<boolean>;
@@ -49,12 +56,22 @@ export type CrmContext = {
domains: Accessor<string[]>,
scope: Accessor<CrmEmailScope>,
signal: Accessor<CrmEmailSignal>
- ): EmailSource;
+ ): ItemListSource;
createContactEmails(
email: Accessor<string | undefined>,
scope: Accessor<CrmEmailScope>,
signal: Accessor<CrmEmailSignal>
- ): EmailSource;
+ ): ItemListSource;
+ /** Files associated with the record or attached to its emails. */
+ createRecordFiles(
+ scope: Accessor<CrmRecordScope | undefined>
+ ): ItemListSource;
+ /** Calls associated with the record. */
+ createRecordCalls(
+ scope: Accessor<CrmRecordScope | undefined>
+ ): ItemListSource;
+ /** The record's Tasks tab, scoped to tasks associated with it. */
+ RecordTasks: Component<{ scope: CrmRecordScope }>;
createPropertyCommands(): PropertyCommands;
hydrateCompany(company: CrmCompanyEntity): CrmCompanyEntity;
createSettingsCommands(): CrmMutation<
diff --git a/apps/web/src/features/crm/context/crm-sources.ts b/apps/web/src/features/crm/context/crm-sources.ts
index a84225cb31..3ee4d11939 100644
--- a/apps/web/src/features/crm/context/crm-sources.ts
+++ b/apps/web/src/features/crm/context/crm-sources.ts
@@ -116,7 +116,12 @@ export type ListsSource = {
export type CrmEmailScope = 'team' | 'me';
export type CrmEmailSignal = 'signal' | 'all';
-export type EmailSource = {
+/** A paged soup list: email threads, files or calls of a CRM record. */
+export type ItemListSource = {
+ /** True until the first page is readable (including disabled queries). */
+ readonly isPending: boolean;
+ /** False while the query is disabled, e.g. a company without domains. */
+ readonly isEnabled: boolean;
readonly isLoading: boolean;
readonly data: { entities: import('@entity').EntityData[] } | undefined;
readonly hasNextPage: boolean;
diff --git a/apps/web/src/features/crm/core/record.test.ts b/apps/web/src/features/crm/core/record.test.ts
new file mode 100644
index 0000000000..759bf416dd
--- /dev/null
+++ b/apps/web/src/features/crm/core/record.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest';
+import { sameRecordScope } from './record';
+
+describe('sameRecordScope', () => {
+ const acme = { type: 'company' as const, id: 'c1', domains: ['acme.com'] };
+
+ it('treats a rebuilt scope with the same record as the same', () => {
+ expect(sameRecordScope(acme, { ...acme, domains: ['acme.com'] })).toBe(
+ true
+ );
+ expect(sameRecordScope(undefined, undefined)).toBe(true);
+ });
+
+ it('tells apart other records, domains and emails', () => {
+ expect(sameRecordScope(acme, { ...acme, id: 'c2' })).toBe(false);
+ expect(sameRecordScope(acme, { ...acme, domains: ['acme.io'] })).toBe(
+ false
+ );
+ expect(sameRecordScope(acme, undefined)).toBe(false);
+ const ada = { type: 'contact' as const, id: 'p1', email: '[email protected]' };
+ expect(sameRecordScope(ada, { ...ada, email: '[email protected]' })).toBe(false);
+ expect(sameRecordScope(ada, { ...acme, id: 'p1' })).toBe(false);
+ });
+});
diff --git a/apps/web/src/features/crm/core/record.ts b/apps/web/src/features/crm/core/record.ts
new file mode 100644
index 0000000000..884fbd1a9d
--- /dev/null
+++ b/apps/web/src/features/crm/core/record.ts
@@ -0,0 +1,52 @@
+/** A CRM record whose associated files, tasks and calls a record tab lists. */
+export type CrmRecordScope =
+ | { type: 'company'; id: string; domains: string[] }
+ | { type: 'contact'; id: string; email: string };
+
+/**
+ * Whether two scopes describe the same record. Record views keep their
+ * scope while a refetch changes nothing, so tabs keyed on it stay mounted.
+ */
+export function sameRecordScope(
+ a: CrmRecordScope | undefined,
+ b: CrmRecordScope | undefined
+): boolean {
+ if (!a || !b) return a === b;
+ if (a.type === 'company' && b.type === 'company') {
+ return a.id === b.id && a.domains.join('\n') === b.domains.join('\n');
+ }
+ if (a.type === 'contact' && b.type === 'contact') {
+ return a.id === b.id && a.email === b.email;
+ }
+ return false;
+}
+
+/** Tabs of a CRM record, in display order per record type. */
+export const COMPANY_SECTIONS = [
+ 'overview',
+ 'team',
+ 'emails',
+ 'files',
+ 'tasks',
+ 'calls',
+] as const;
+export const CONTACT_SECTIONS = [
+ 'overview',
+ 'emails',
+ 'files',
+ 'tasks',
+ 'calls',
+] as const;
+
+export type CompanySection = (typeof COMPANY_SECTIONS)[number];
+export type ContactSection = (typeof CONTACT_SECTIONS)[number];
+export type CrmRecordSection = CompanySection | ContactSection;
+
+export const CRM_RECORD_SECTION_LABELS: Record<CrmRecordSection, string> = {
+ overview: 'Overview',
+ team: 'Team',
+ emails: 'Emails',
+ files: 'Files',
+ tasks: 'Tasks',
+ calls: 'Calls',
+};
diff --git a/apps/web/src/features/crm/crm-adapter.ts b/apps/web/src/features/crm/crm-adapter.ts
index bb83b62048..e1d2530306 100644
--- a/apps/web/src/features/crm/crm-adapter.ts
+++ b/apps/web/src/features/crm/crm-adapter.ts
@@ -1,10 +1,13 @@
import { useQuickAccessCrmCompaniesQuery } from '@app/features/crm/crm-search';
+import { withEntityNotifications } from '@app/features/soup/entity-notifications';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
import { toast } from '@core/component/Toast/Toast';
import { enableCrmLists } from '@core/constant/featureFlags';
import { useUserId } from '@core/context/user';
import { getInitialsFromName } from '@core/user';
import { idToEmail } from '@core/user/util';
+import { queryReadyGate } from '@queries/gate';
import { useListPropertiesQuery } from '@queries/properties/definitions';
import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';
import { useSoupAstItemsQuery } from '@queries/soup/items';
@@ -17,7 +20,9 @@ import {
import { patchTeamCrmSettings } from '@service-auth/crm';
import { storageServiceClient } from '@service-storage/client';
import { useQueryClient } from '@tanstack/solid-query';
+import { createMemo, lazy } from 'solid-js';
import type { CrmContext } from './context/crm-context';
+import type { ItemListSource } from './context/crm-sources';
import {
openCreateCompanyModal,
openCreateContactModal,
@@ -51,6 +56,10 @@ import {
} from './queries/contacts';
import { fetchCrmExportCompanies } from './queries/export';
import { useCrmLists } from './queries/lists';
+import {
+ useRecordCallsQuery,
+ useRecordFilesQuery,
+} from './queries/record-items';
import { usePersonalCrmViews, useTeamCrmViews } from './queries/saved-views';
import { usePatchTeamCrmSettingsMutation } from './queries/settings-commands';
import {
@@ -60,6 +69,50 @@ import {
import { useTeamCrmConfig } from './queries/team-config';
import { createAppDealStages } from './stage-adapter';
+// Loaded on demand: the Tasks list imports soup, which imports CRM entry points.
+const CrmRecordTasks = lazy(async () => ({
+ default: (await import('./record-tasks-adapter')).CrmRecordTasks,
+}));
+
+/**
+ * Soup rows carry raw notification arrays; `ListEntity` reads them through
+ * an accessor bound to the app's notification source, as other lists do.
+ */
+function withRowNotifications(source: ItemListSource): ItemListSource {
+ const notificationSource = useGlobalNotificationSource();
+ // Reading `data` before the first page resolves would suspend the tab.
+ const data = createMemo(() =>
+ queryReadyGate(source)
+ ? {
+ entities: source.data.entities.map((entity) =>
+ withEntityNotifications(entity, notificationSource)
+ ),
+ }
+ : undefined
+ );
+ return {
+ get isPending() {
+ return source.isPending;
+ },
+ get isEnabled() {
+ return source.isEnabled;
+ },
+ get isLoading() {
+ return source.isLoading;
+ },
+ get data() {
+ return data();
+ },
+ get hasNextPage() {
+ return source.hasNextPage;
+ },
+ get isFetchingNextPage() {
+ return source.isFetchingNextPage;
+ },
+ fetchNextPage: () => source.fetchNextPage(),
+ };
+}
+
/** Only this app-facing adapter constructs production capabilities. */
export function createAppCrmContext(): CrmContext {
const deps = {
@@ -82,9 +135,18 @@ export function createAppCrmContext(): CrmContext {
return () => flag().enabled;
},
createCompanyEmails: (...args) =>
- useCompanyEmailsQuery(useSoupAstItemsQuery, ...args),
+ withRowNotifications(
+ useCompanyEmailsQuery(useSoupAstItemsQuery, ...args)
+ ),
createContactEmails: (...args) =>
- useContactEmailsQuery(useSoupAstItemsQuery, ...args),
+ withRowNotifications(
+ useContactEmailsQuery(useSoupAstItemsQuery, ...args)
+ ),
+ createRecordFiles: (scope) =>
+ withRowNotifications(useRecordFilesQuery(useSoupAstItemsQuery, scope)),
+ createRecordCalls: (scope) =>
+ withRowNotifications(useRecordCallsQuery(useSoupAstItemsQuery, scope)),
+ RecordTasks: CrmRecordTasks,
createPropertyCommands: useBulkSaveEntityPropertiesMutation,
createSettingsCommands: () =>
usePatchTeamCrmSettingsMutation({
diff --git a/apps/web/src/features/crm/crm-company.tsx b/apps/web/src/features/crm/crm-company.tsx
index 11ce99059e..b3e69fb65a 100644
--- a/apps/web/src/features/crm/crm-company.tsx
+++ b/apps/web/src/features/crm/crm-company.tsx
@@ -1,7 +1,12 @@
import type { ComponentProps } from 'solid-js';
+import { RecordTabs } from './components/record-tabs';
import { CrmProvider } from './context/crm-context';
+import { COMPANY_SECTIONS, type CompanySection } from './core/record';
import { createAppCrmContext } from './crm-adapter';
import { Company as View } from './views/company-detail';
+
+export type { CompanySection } from './core/record';
+
export function Company(props: ComponentProps<typeof View>) {
return (
<CrmProvider value={createAppCrmContext()}>
@@ -9,3 +14,12 @@ export function Company(props: ComponentProps<typeof View>) {
</CrmProvider>
);
}
+
+/** The company's section tabs, for a host's top bar. */
+export function CompanyTabs(props: {
+ value: CompanySection;
+ onChange: (section: CompanySection) => void;
+ compact?: boolean;
+}) {
+ return <RecordTabs sections={COMPANY_SECTIONS} {...props} />;
+}
diff --git a/apps/web/src/features/crm/navigation-adapter.ts b/apps/web/src/features/crm/navigation-adapter.ts
index d4958bc7ca..978bdb26b9 100644
--- a/apps/web/src/features/crm/navigation-adapter.ts
+++ b/apps/web/src/features/crm/navigation-adapter.ts
@@ -45,7 +45,7 @@ export function createAppCrmNavigation(): ReturnType<
showCompanies: () => {
layout.replaceOrInsertSplit({ type: 'component', id: 'companies' });
},
- openEmail: (entity) => {
+ openEntity: (entity) => {
void openEntityInSplitFromUnifiedList(entity, {});
},
};
diff --git a/apps/web/src/features/crm/queries/record-items.test.ts b/apps/web/src/features/crm/queries/record-items.test.ts
new file mode 100644
index 0000000000..22864ae534
--- /dev/null
+++ b/apps/web/src/features/crm/queries/record-items.test.ts
@@ -0,0 +1,65 @@
+import { NIL_UUID } from '@app/features/next-soup/filters/filter-store';
+import { describe, expect, it } from 'vitest';
+import { recordCallsBody, recordFilesBody } from './record-items';
+
+const COMPANIES = '00000001-0000-0000-0000-00000000000c';
+const CONTACTS = '00000001-0000-0000-0000-000000000013';
+
+describe('CRM record item queries', () => {
+ it('lists non-task files associated with a company or attached to emails with its domains', () => {
+ const body = recordFilesBody({
+ type: 'company',
+ id: 'company-1',
+ domains: ['acme.com', 'acme.io'],
+ });
+
+ expect(body.df).toEqual({
+ '&': [
+ { '!': { l: { dst: 'task' } } },
+ {
+ '|': [
+ {
+ '|': [
+ { l: { prop: { pd: COMPANIES, v: { er: 'company-1' } } } },
+ { l: { eap: { Domain: 'acme.com' } } },
+ ],
+ },
+ { l: { eap: { Domain: 'acme.io' } } },
+ ],
+ },
+ ],
+ });
+ expect(body.callf).toEqual({ l: { CallId: NIL_UUID } });
+ expect(body.ef).toEqual({ l: { ThreadId: NIL_UUID } });
+ });
+
+ it('matches a contact by its exact address', () => {
+ const body = recordFilesBody({
+ type: 'contact',
+ id: 'contact-1',
+ email: '[email protected]',
+ });
+
+ expect(body.df['&'][1]).toEqual({
+ '|': [
+ { l: { prop: { pd: CONTACTS, v: { er: 'contact-1' } } } },
+ { l: { eap: { Complete: '[email protected]' } } },
+ ],
+ });
+ });
+
+ it('lists only calls, through the record property', () => {
+ const body = recordCallsBody({
+ type: 'company',
+ id: 'company-1',
+ domains: ['acme.com'],
+ });
+
+ expect(body).not.toHaveProperty('callf');
+ expect(body.propf).toEqual({
+ l: { pd: COMPANIES, v: { er: 'company-1' } },
+ });
+ expect(body.df).toEqual({ l: { id: NIL_UUID } });
+ expect(body.ef).toEqual({ l: { ThreadId: NIL_UUID } });
+ });
+});
diff --git a/apps/web/src/features/crm/queries/record-items.ts b/apps/web/src/features/crm/queries/record-items.ts
new file mode 100644
index 0000000000..a1daa52710
--- /dev/null
+++ b/apps/web/src/features/crm/queries/record-items.ts
@@ -0,0 +1,122 @@
+import { NIL_UUID } from '@app/features/next-soup/filters/filter-store';
+import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
+import type { useSoupAstItemsQuery } from '@queries/soup/items';
+import type { Accessor } from 'solid-js';
+import { match } from 'ts-pattern';
+import type { CrmRecordScope } from '../core/record';
+
+/** The system property that associates entities with this kind of record. */
+export function crmRecordPropertyId(scope: CrmRecordScope): string {
+ return match(scope.type)
+ .with('company', () => SYSTEM_PROPERTY_IDS.COMPANIES)
+ .with('contact', () => SYSTEM_PROPERTY_IDS.CONTACTS)
+ .exhaustive();
+}
+
+/** The entity type of a reference to this kind of record. */
+export function crmRecordReferenceType(
+ scope: CrmRecordScope
+): 'COMPANY' | 'CONTACT' {
+ return match(scope.type)
+ .with('company', () => 'COMPANY' as const)
+ .with('contact', () => 'CONTACT' as const)
+ .exhaustive();
+}
+
+type AstNode = Record<string, unknown>;
+
+const leaf = (literal: AstNode): AstNode => ({ l: literal });
+const or = (nodes: AstNode[]): AstNode =>
+ nodes.reduce((acc, node) => ({ '|': [acc, node] }));
+
+/** Every soup target pinned to an id that cannot exist. */
+const NO_ITEMS = {
+ calf: leaf({ id: NIL_UUID }),
+ df: leaf({ id: NIL_UUID }),
+ chanf: leaf({ ChannelId: NIL_UUID }),
+ cthf: leaf({ ThreadId: NIL_UUID }),
+ cf: leaf({ cid: NIL_UUID }),
+ pf: leaf({ pid: NIL_UUID }),
+ callf: leaf({ CallId: NIL_UUID }),
+ ccf: leaf({ id: NIL_UUID }),
+ fef: leaf({ id: NIL_UUID }),
+ ef: leaf({ ThreadId: NIL_UUID }),
+};
+
+/** The record's Companies/Contacts reference, as a property literal. */
+const associatedLiteral = (scope: CrmRecordScope): AstNode => ({
+ pd: crmRecordPropertyId(scope),
+ v: { er: scope.id },
+});
+
+/** Email addresses or domains of the people at the record. */
+const participants = (scope: CrmRecordScope): AstNode[] =>
+ match(scope)
+ .with({ type: 'company' }, ({ domains }) =>
+ domains.map((domain) => leaf({ eap: { Domain: domain } }))
+ )
+ .with({ type: 'contact' }, ({ email }) => [
+ leaf({ eap: { Complete: email } }),
+ ])
+ .exhaustive();
+
+/**
+ * Non-task documents associated with the record through its Companies or
+ * Contacts property, plus attachments of emails exchanged with its people.
+ */
+export function recordFilesBody(scope: CrmRecordScope) {
+ return {
+ ...NO_ITEMS,
+ df: {
+ '&': [
+ { '!': leaf({ dst: 'task' }) },
+ or([leaf({ prop: associatedLiteral(scope) }), ...participants(scope)]),
+ ],
+ },
+ };
+}
+
+/**
+ * Calls associated with the record. Calls are linked to the CRM records of
+ * their participants when they end, so the property alone covers both.
+ */
+export function recordCallsBody(scope: CrmRecordScope) {
+ const { callf: _calls, ...others } = NO_ITEMS;
+ return { ...others, propf: leaf(associatedLiteral(scope)) };
+}
+
+const PARAMS = { limit: 100, sort_method: 'updated_at' } as const;
+
+/** Files associated with a CRM record, via `/soup/ast`. */
+export function useRecordFilesQuery(
+ createQuery: typeof useSoupAstItemsQuery,
+ scope: Accessor<CrmRecordScope | undefined>
+) {
+ return createQuery(
+ () => {
+ const current = scope();
+ return {
+ params: PARAMS,
+ body: current ? recordFilesBody(current) : NO_ITEMS,
+ };
+ },
+ () => ({ enabled: !!scope() })
+ );
+}
+
+/** Calls associated with a CRM record, via `/soup/ast`. */
+export function useRecordCallsQuery(
+ createQuery: typeof useSoupAstItemsQuery,
+ scope: Accessor<CrmRecordScope | undefined>
+) {
+ return createQuery(
+ () => {
+ const current = scope();
+ return {
+ params: PARAMS,
+ body: current ? recordCallsBody(current) : NO_ITEMS,
+ };
+ },
+ () => ({ enabled: !!scope() })
+ );
+}
diff --git a/apps/web/src/features/crm/record-tasks-adapter.tsx b/apps/web/src/features/crm/record-tasks-adapter.tsx
new file mode 100644
index 0000000000..d9fc1eca7c
--- /dev/null
+++ b/apps/web/src/features/crm/record-tasks-adapter.tsx
@@ -0,0 +1,126 @@
+import { SearchBar } from '@app/components/view-shell';
+import { TasksControls } from '@app/features/tasks-view/components/TasksControls';
+import { TaskList } from '@app/features/tasks-view/components/task-list/TaskList';
+import { useTasksDataSource } from '@app/features/tasks-view/queries/use-tasks-query';
+import {
+ TasksViewProvider,
+ useTasksView,
+} from '@app/features/tasks-view/tasks-view-context';
+import { createTaskWithProperties } from '@block-md/util/taskComposerProperties';
+import { useSplitLayout } from '@components/app/split-layout/layout';
+import { TagSetsQueryProvider } from '@property/tags/tag-sets-context';
+import type { PropertyApiValues } from '@property/types';
+import { Button } from '@ui';
+import { Show } from 'solid-js';
+import { RecordSection } from './components/record-section';
+import type { CrmRecordScope } from './core/record';
+import {
+ crmRecordPropertyId,
+ crmRecordReferenceType,
+} from './queries/record-items';
+
+/**
+ * The record's Tasks tab: the production Tasks list, scoped to tasks whose
+ * Companies or Contacts property references the record. It owns its tag
+ * sets because a standalone record has no list provider above it.
+ */
+export function CrmRecordTasks(props: { scope: CrmRecordScope }) {
+ const layout = useSplitLayout();
+ return (
+ <Show when={props.scope} keyed>
+ {(scope) => (
+ <TagSetsQueryProvider>
+ <TasksViewProvider
+ initialState={{ tab: 'team-tasks', groupBy: 'status', facets: {} }}
+ restoreEntryState
+ scopeKey={`crm:${scope.type}:${scope.id}:tasks`}
+ onOpenTask={(task, options) => {
+ layout.openWithSplit(
+ { type: 'md', id: task.id },
+ { preferNewSplit: options?.event?.shiftKey }
+ );
+ return true;
+ }}
+ onCloseTask={() => {}}
+ sourceFactory={(state, options) =>
+ useTasksDataSource(state, {
+ ...options,
+ reference: () => ({
+ propertyDefinitionId: crmRecordPropertyId(scope),
+ entityId: scope.id,
+ }),
+ })
+ }
+ >
+ <RecordTasksBody scope={scope} />
+ </TasksViewProvider>
+ </TagSetsQueryProvider>
+ )}
+ </Show>
+ );
+}
+
+function RecordTasksBody(props: { scope: CrmRecordScope }) {
+ const { state, setState } = useTasksView();
+ const layout = useSplitLayout();
+ let listElement: HTMLDivElement | undefined;
+
+ // New tasks start associated with the record, like project tasks start
+ // in their project.
+ const association = (): [string, PropertyApiValues] => [
+ crmRecordPropertyId(props.scope),
+ {
+ valueType: 'ENTITY',
+ refs: [
+ {
+ entity_id: props.scope.id,
+ entity_type: crmRecordReferenceType(props.scope),
+ },
+ ],
+ },
+ ];
+ const composeTask = () =>
+ layout.popoverSplit({
+ type: 'component',
+ id: 'task-compose',
+ params: {
+ createTask: (
+ ...[title, content, properties, ...rest]: Parameters<
+ typeof createTaskWithProperties
+ >
+ ) =>
+ createTaskWithProperties(
+ title,
+ content,
+ [...properties, association()],
+ ...rest
+ ),
+ },
+ });
+
+ return (
+ <RecordSection
+ title="Tasks"
+ actions={
+ <>
+ <SearchBar
+ label={`Search ${props.scope.type} tasks`}
+ placeholder="Search tasks"
+ class="w-56"
+ value={state.search}
+ onValueChange={(search) => setState('search', search)}
+ onEscape={() => listElement?.focus()}
+ />
+ <TasksControls />
+ <Button onClick={composeTask}>New task</Button>
+ </>
+ }
+ >
+ <TaskList
+ ref={(element) => {
+ listElement = element;
+ }}
+ />
+ </RecordSection>
+ );
+}
diff --git a/apps/web/src/features/crm/views/company-contacts-section.tsx b/apps/web/src/features/crm/views/company-contacts-section.tsx
index 61f3c52773..bfa66f6b39 100644
--- a/apps/web/src/features/crm/views/company-contacts-section.tsx
+++ b/apps/web/src/features/crm/views/company-contacts-section.tsx
@@ -45,14 +45,7 @@ export function CompanyContactsSection(props: {
<div class="text-sm text-ink-muted">No matching contacts.</div>
}
>
- <div
- class="flex flex-col gap-2"
- classList={{
- // ~5 two-line rows tall; scroll for the rest.
- 'max-h-[13.5rem] overflow-y-auto scrollbar-hidden':
- filtered().length > 5,
- }}
- >
+ <div class="flex flex-col gap-1">
<For each={filtered()}>
{(contact) => (
<button
@@ -70,7 +63,7 @@ export function CompanyContactsSection(props: {
{ 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]"
+ class="flex min-w-0 flex-col gap-0.5 rounded-md px-2 py-1.5 text-left hover:bg-ink-muted/[0.06]"
>
<span class="truncate text-sm">
{contact.name ?? contact.email}
diff --git a/apps/web/src/features/crm/views/company-detail.tsx b/apps/web/src/features/crm/views/company-detail.tsx
index 8d5ae4655d..0b62dac210 100644
--- a/apps/web/src/features/crm/views/company-detail.tsx
+++ b/apps/web/src/features/crm/views/company-detail.tsx
@@ -1,53 +1,130 @@
import { SidePanel } from '@components/app/side-panel';
import PlusIcon from '@phosphor/plus.svg';
import { Button } from '@ui';
-import { Show, Suspense } from 'solid-js';
+import { createMemo, Match, Show, Suspense, Switch } from 'solid-js';
+import { RecordSection } from '../components/record-section';
import { useCrmContext } from '../context/crm-context';
import type { CrmContact as CompanyContact } from '../core/contact';
+import {
+ type CompanySection,
+ type CrmRecordScope,
+ sameRecordScope,
+} from '../core/record';
import { CompanyContactsSection } from './company-contacts-section';
import { CompanyDiscussionSection } from './company-discussion-section';
import { CompanyEmailsSection } from './company-emails-section';
import { CompanyHeader } from './company-header';
import { CompanyListsSection } from './company-list-membership';
-import { CompanyMetadataSection } from './company-metadata-section';
import { CompanyPropertiesSection } from './company-properties-section';
import { CompanySharingSection } from './company-sharing-section';
+import { RecordCallsSection, RecordFilesSection } from './record-associations';
import { useCompanyQuery } from './use-crm';
/**
- * Root of the company detail view. Owns the company query and pushes the
- * resolved entity down to presentational children. Layout mirrors the task
- * page: middle content constrained to a centered column, additional info in
- * the right-hand SidePanel.
+ * Root of the company detail view, laid out like a project: the host's top
+ * bar picks the section, Overview shows the company with its description and
+ * discussion, and the other sections list its team, emails, files, tasks and
+ * calls. Properties and sharing stay in the right-hand SidePanel.
*/
export function Company(props: {
companyId: string;
+ section?: CompanySection;
headerToggle?: boolean;
onHidden?: () => void;
onOpenContact?: (contact: CompanyContact) => void;
}) {
- const openCreateContactModal = useCrmContext().openCreateContact;
- const listsEnabled = useCrmContext().listsEnabled();
+ const context = useCrmContext();
+ const openCreateContactModal = context.openCreateContact;
+ const listsEnabled = context.listsEnabled();
const { company, contacts } = useCompanyQuery(() => props.companyId);
+ const section = () => props.section ?? 'overview';
+ const scope = createMemo(
+ (): CrmRecordScope | undefined => {
+ const current = company();
+ if (!current) return;
+ return {
+ type: 'company',
+ id: current.id,
+ domains: current.domains.map((domain) => domain.domain),
+ };
+ },
+ undefined,
+ { equals: sameRecordScope }
+ );
return (
<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()} />
- <CompanyDiscussionSection companyId={props.companyId} />
- <CompanyEmailsSection company={company()} />
- </div>
+ <div class="size-full min-h-0 min-w-0">
+ <Switch>
+ <Match when={section() === 'overview'}>
+ <div class="h-full overflow-y-auto px-6 pb-12 pt-12 scrollbar-hidden touch:pt-6">
+ <div class="mx-auto flex max-w-3xl min-w-0 flex-col gap-6">
+ <CompanyHeader company={company()} />
+ <CompanyDiscussionSection companyId={props.companyId} />
+ </div>
+ </div>
+ </Match>
+ <Match when={section() === 'team'}>
+ <RecordSection
+ title="Team"
+ actions={
+ <Button
+ variant="ghost"
+ size="sm"
+ // Contact emails are pinned to the company's primary
+ // domain; disabled until the company has loaded.
+ disabled={!company()?.domains[0]}
+ onClick={() => {
+ const domain = company()?.domains[0]?.domain;
+ if (domain) openCreateContactModal(props.companyId, domain);
+ }}
+ >
+ <PlusIcon class="size-3.5" />
+ Add contact
+ </Button>
+ }
+ >
+ <div class="px-2">
+ <CompanyContactsSection
+ company={company()}
+ contacts={contacts()}
+ onOpenContact={props.onOpenContact}
+ />
+ </div>
+ </RecordSection>
+ </Match>
+ <Match when={section() === 'emails'}>
+ <CompanyEmailsSection company={company()} />
+ </Match>
+ <Match when={section() === 'files'}>
+ <RecordFilesSection scope={scope()} />
+ </Match>
+ <Match when={section() === 'tasks'}>
+ <Suspense
+ fallback={
+ <div class="p-6 text-center text-sm text-ink-muted">
+ Loading…
+ </div>
+ }
+ >
+ <Show
+ when={scope()}
+ fallback={
+ <div class="p-6 text-center text-sm text-ink-muted">
+ Loading…
+ </div>
+ }
+ >
+ {(current) => <context.RecordTasks scope={current()} />}
+ </Show>
+ </Suspense>
+ </Match>
+ <Match when={section() === 'calls'}>
+ <RecordCallsSection scope={scope()} />
+ </Match>
+ </Switch>
</div>
- <SidePanel.Section
- id="company-details"
- title="Details"
- order={10}
- defaultOpen
- >
- <CompanyMetadataSection company={company()} />
- </SidePanel.Section>
<SidePanel.Section
id="company-properties"
title="Properties"
@@ -61,35 +138,6 @@ export function Company(props: {
<CompanyListsSection companyId={props.companyId} />
</Suspense>
</Show>
- <SidePanel.Section
- id="company-contacts"
- title="Contacts"
- order={20}
- defaultOpen
- actions={
- <Button
- variant="ghost"
- size="icon-sm"
- label="Add contact"
- tooltip="Add contact"
- // Contact emails are pinned to the company's primary domain;
- // disabled until the company (and its domains) has loaded.
- disabled={!company()?.domains[0]}
- onClick={() => {
- const domain = company()?.domains[0]?.domain;
- if (domain) openCreateContactModal(props.companyId, domain);
- }}
- >
- <PlusIcon class="size-3.5" />
- </Button>
- }
- >
- <CompanyContactsSection
- company={company()}
- contacts={contacts()}
- onOpenContact={props.onOpenContact}
- />
- </SidePanel.Section>
<SidePanel.Section id="company-sharing" title="Sharing" order={25}>
<CompanySharingSection company={company()} onHidden={props.onHidden} />
</SidePanel.Section>
diff --git a/apps/web/src/features/crm/views/company-emails-section.tsx b/apps/web/src/features/crm/views/company-emails-section.tsx
index cc29827cdf..b84ef46ba6 100644
--- a/apps/web/src/features/crm/views/company-emails-section.tsx
+++ b/apps/web/src/features/crm/views/company-emails-section.tsx
@@ -1,38 +1,21 @@
import { TabsInset } from '@core/component/TabsInset';
-import {
- type CrmCompanyEntity,
- ListEntity,
- ListEntityMetadataQueryProvider,
- ListLayoutProvider,
-} from '@entity';
-import { createMemo, createSignal, For, Show } from 'solid-js';
-import { useInfiniteScrollSentinel } from '../../../lib/primitives/infinite-scroll-sentinel';
-import { useCrmContext } from '../context/crm-context';
+import type { CrmCompanyEntity } from '@entity';
+import { createMemo, createSignal } from 'solid-js';
+import { RecordSection } from '../components/record-section';
import type {
CrmEmailSignal as EmailSignalView,
CrmEmailScope as EmailView,
} from '../context/crm-sources';
+import { RecordItemList } from './record-item-list';
import { useCompanyEmailsQuery } from './use-crm';
export function CompanyEmailsSection(props: { company?: CrmCompanyEntity }) {
- const { openEmail } = useCrmContext().createNavigation();
const domains = createMemo(
() => props.company?.domains.map((domain) => domain.domain) ?? []
);
const [view, setView] = createSignal<EmailView>('team');
const [signalView, setSignalView] = createSignal<EmailSignalView>('all');
const emailsQuery = useCompanyEmailsQuery(domains, view, signalView);
- const emails = () => emailsQuery.data?.entities ?? [];
-
- const [listRef, setListRef] = createSignal<HTMLElement>();
- const [sentinelRef, setSentinelRef] = createSignal<HTMLDivElement>();
-
- useInfiniteScrollSentinel({
- sentinel: sentinelRef,
- hasNextPage: () => emailsQuery.hasNextPage ?? false,
- isFetchingNextPage: () => emailsQuery.isFetchingNextPage,
- fetchNextPage: () => emailsQuery.fetchNextPage(),
- });
const emptyMessage = () => {
const kind = signalView() === 'signal' ? 'signal emails' : 'emails';
@@ -44,10 +27,10 @@ export function CompanyEmailsSection(props: { company?: CrmCompanyEntity }) {
};
return (
- <div class="flex flex-col gap-2">
- <div class="flex items-center justify-between gap-2">
- <h2 class="text-sm font-medium text-ink-muted">Emails</h2>
- <div class="flex items-center gap-2.5">
+ <RecordSection
+ title="Emails"
+ actions={
+ <>
<TabsInset
list={[
{ value: 'signal', label: 'Signal' },
@@ -64,49 +47,14 @@ export function CompanyEmailsSection(props: { company?: CrmCompanyEntity }) {
value={view()}
onChange={(v) => setView(v as EmailView)}
/>
- </div>
- </div>
- <Show
- when={props.company && !emailsQuery.isLoading}
- fallback={
- <div class="p-6 text-center text-sm text-ink-muted">Loading…</div>
- }
- >
- <Show
- when={emails().length > 0}
- fallback={
- <div class="rounded-lg border border-dashed border-edge-muted p-6 text-center text-sm text-ink-muted">
- {emptyMessage()}
- </div>
- }
- >
- <div class="max-h-96 overflow-y-auto">
- <ListEntityMetadataQueryProvider>
- <ListLayoutProvider ref={listRef}>
- <div ref={setListRef} class="flex flex-col">
- <For each={emails()}>
- {(entity) => (
- <ListEntity
- entity={entity}
- timestamp={entity.updatedAt}
- onClick={() => openEmail(entity)}
- />
- )}
- </For>
- </div>
- </ListLayoutProvider>
- </ListEntityMetadataQueryProvider>
- <Show when={emailsQuery.hasNextPage}>
- <div ref={setSentinelRef} class="h-px" />
- </Show>
- <Show when={emailsQuery.isFetchingNextPage}>
- <div class="p-3 text-center text-xs text-ink-muted">
- Loading more…
- </div>
- </Show>
- </div>
- </Show>
- </Show>
- </div>
+ </>
+ }
+ >
+ <RecordItemList
+ source={emailsQuery}
+ pending={!props.company}
+ empty={emptyMessage()}
+ />
+ </RecordSection>
);
}
diff --git a/apps/web/src/features/crm/views/company-header.tsx b/apps/web/src/features/crm/views/company-header.tsx
index 9908995ab5..f718fac5b3 100644
--- a/apps/web/src/features/crm/views/company-header.tsx
+++ b/apps/web/src/features/crm/views/company-header.tsx
@@ -1,7 +1,15 @@
import { EntityIcon } from '@core/component/EntityIcon';
import { InlineTitleEditor } from '@core/component/InlineTitleEditor';
-import type { CrmCompanyEntity } from '@entity';
-import { createEffect, createSignal, Show } from 'solid-js';
+import {
+ type CrmCompanyEntity,
+ formatDateAndTime,
+ formatRelativeTimestamp,
+} from '@entity';
+import ClockIcon from '@phosphor/clock.svg';
+import GlobeIcon from '@phosphor/globe.svg';
+import { createResizeObserver } from '@solid-primitives/resize-observer';
+import { Badge, Tooltip } from '@ui';
+import { createEffect, createSignal, For, onMount, Show } from 'solid-js';
import { useSetCompanyNameMutation } from './use-crm';
function Description(props: { text: string }) {
@@ -9,22 +17,26 @@ function Description(props: { text: string }) {
const [hasOverflow, setHasOverflow] = createSignal(false);
let ref: HTMLParagraphElement | undefined;
- // Measure overflow while clamped; rerun when the text changes or after
- // collapsing back. Skip while expanded — clientHeight then equals
+ // Measure overflow while clamped; rerun when the text changes, after
+ // collapsing back, and when the width changes (the header mounts before
+ // its layout settles). Skip while expanded — clientHeight then equals
// scrollHeight and would flip hasOverflow off incorrectly.
+ const measure = () => {
+ if (ref && !expanded())
+ setHasOverflow(ref.scrollHeight > ref.clientHeight + 1);
+ };
createEffect(() => {
props.text;
if (expanded()) return;
- requestAnimationFrame(() => {
- if (ref) setHasOverflow(ref.scrollHeight > ref.clientHeight + 1);
- });
+ requestAnimationFrame(measure);
});
+ onMount(() => createResizeObserver(() => ref, measure));
return (
<div class="flex flex-col items-start gap-0.5">
<p
ref={ref}
- class={`text-sm text-ink-muted ${expanded() ? '' : 'line-clamp-2'}`}
+ class={`text-sm text-ink-muted ${expanded() ? '' : 'line-clamp-3'}`}
>
{props.text}
</p>
@@ -50,6 +62,7 @@ function TitleEditor(props: { company: CrmCompanyEntity }) {
value={props.company.name}
placeholder="Company"
ariaLabel="Company name"
+ class="w-full text-2xl"
onRename={(name) =>
renameMutation.mutate({ companyId: props.company.id, name })
}
@@ -57,22 +70,55 @@ function TitleEditor(props: { company: CrmCompanyEntity }) {
);
}
+/**
+ * Company overview header laid out like a project: the name, the company's
+ * facts as pills beneath it, then its pre-generated description.
+ */
export function CompanyHeader(props: { company?: CrmCompanyEntity }) {
return (
- <div class="flex items-start gap-3">
- <div class="size-10 shrink-0">
- <EntityIcon targetType="crm_company" size="fill" />
- </div>
- <div class="flex min-w-0 flex-col gap-1">
- <h1 class="min-w-0 text-xl font-semibold">
+ <div>
+ <div class="flex items-center gap-3">
+ <div class="size-8 shrink-0">
+ <EntityIcon targetType="crm_company" size="fill" />
+ </div>
+ <h1 class="min-w-0 flex-1 text-2xl font-semibold">
<Show when={props.company} fallback={'Loading company…'}>
{(company) => <TitleEditor company={company()} />}
</Show>
</h1>
- <Show when={props.company?.description}>
- {(description) => <Description text={description()} />}
- </Show>
</div>
+ <Show when={props.company}>
+ {(company) => (
+ <div
+ class="mb-6 mt-3 flex flex-wrap items-center gap-2"
+ aria-label="Company details"
+ >
+ <For each={company().domains}>
+ {(domain) => (
+ <Badge variant="outline" size="sm">
+ <GlobeIcon class="size-3" />
+ {domain.domain}
+ </Badge>
+ )}
+ </For>
+ {/* `updatedAt` carries `crm_companies.last_interaction`, which
+ the backend keeps fresh from synced workspace emails. */}
+ <Show when={company().updatedAt}>
+ {(lastInteraction) => (
+ <Tooltip label={formatDateAndTime(lastInteraction())}>
+ <Badge variant="outline" size="sm">
+ <ClockIcon class="size-3" />
+ Last interacted {formatRelativeTimestamp(lastInteraction())}
+ </Badge>
+ </Tooltip>
+ )}
+ </Show>
+ </div>
+ )}
+ </Show>
+ <Show when={props.company?.description}>
+ {(description) => <Description text={description()} />}
+ </Show>
</div>
);
}
diff --git a/apps/web/src/features/crm/views/company-metadata-section.tsx b/apps/web/src/features/crm/views/company-metadata-section.tsx
deleted file mode 100644
index d045bc55d7..0000000000
--- a/apps/web/src/features/crm/views/company-metadata-section.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import { type CrmCompanyEntity, formatDateAndTime } from '@entity';
-import { For, type JSX, Show } from 'solid-js';
-
-function Field(props: { label: string; children: JSX.Element }) {
- return (
- <div class="flex flex-col gap-0.5">
- <span class="text-xs text-ink-muted">{props.label}</span>
- <div class="text-sm">{props.children}</div>
- </div>
- );
-}
-
-export function CompanyMetadataSection(props: { company?: CrmCompanyEntity }) {
- return (
- <Show
- when={props.company}
- fallback={<div class="text-sm text-ink-muted">Loading…</div>}
- >
- {(company) => (
- <div class="flex flex-col gap-3">
- <Field label="Domains">
- <For
- each={company().domains}
- fallback={<span class="text-ink-muted">None</span>}
- >
- {(domain) => <div class="truncate">{domain.domain}</div>}
- </For>
- </Field>
- {/* `updatedAt` carries `crm_companies.last_interaction`, which the
- backend keeps fresh from synced workspace emails. */}
- <Field label="Last interaction">
- <Show
- when={company().updatedAt}
- fallback={<span class="text-ink-muted">None</span>}
- >
- {(ts) => <span>{formatDateAndTime(ts())}</span>}
- </Show>
- </Field>
- </div>
- )}
- </Show>
- );
-}
diff --git a/apps/web/src/features/crm/views/contact-emails-section.tsx b/apps/web/src/features/crm/views/contact-emails-section.tsx
index 20768cd5eb..e7dacc7e57 100644
--- a/apps/web/src/features/crm/views/contact-emails-section.tsx
+++ b/apps/web/src/features/crm/views/contact-emails-section.tsx
@@ -15,12 +15,16 @@ import type { CrmContact as CrmContactResponse } from '../core/contact';
import { useContactEmailsQuery } from './use-crm';
export function ContactEmailsSection(props: { contact?: CrmContactResponse }) {
- const { openEmail } = useCrmContext().createNavigation();
+ const { openEntity } = useCrmContext().createNavigation();
const email = () => props.contact?.email;
const [view, setView] = createSignal<EmailView>('team');
const [signalView, setSignalView] = createSignal<EmailSignalView>('all');
const emailsQuery = useContactEmailsQuery(email, view, signalView);
const emails = () => emailsQuery.data?.entities ?? [];
+ // An enabled query is loading until its first page is readable, including
+ // paused requests; a disabled one shows the empty state instead.
+ const loading = () =>
+ !props.contact || (emailsQuery.isPending && emailsQuery.isEnabled);
const [listRef, setListRef] = createSignal<HTMLElement>();
const [sentinelRef, setSentinelRef] = createSignal<HTMLDivElement>();
@@ -56,7 +60,7 @@ export function ContactEmailsSection(props: { contact?: CrmContactResponse }) {
</div>
</div>
<Show
- when={props.contact && !emailsQuery.isLoading}
+ when={!loading()}
fallback={
<div class="p-6 text-center text-sm text-ink-muted">Loading…</div>
}
@@ -78,7 +82,7 @@ export function ContactEmailsSection(props: { contact?: CrmContactResponse }) {
<ListEntity
entity={entity}
timestamp={entity.updatedAt}
- onClick={() => openEmail(entity)}
+ onClick={() => openEntity(entity)}
/>
)}
</For>
diff --git a/apps/web/src/features/crm/views/record-associations.tsx b/apps/web/src/features/crm/views/record-associations.tsx
new file mode 100644
index 0000000000..15db8fedc3
--- /dev/null
+++ b/apps/web/src/features/crm/views/record-associations.tsx
@@ -0,0 +1,35 @@
+import { RecordSection } from '../components/record-section';
+import { useCrmContext } from '../context/crm-context';
+import type { CrmRecordScope } from '../core/record';
+import { RecordItemList } from './record-item-list';
+
+/**
+ * Documents associated with the record, plus attachments of emails
+ * exchanged with its people.
+ */
+export function RecordFilesSection(props: { scope?: CrmRecordScope }) {
+ const files = useCrmContext().createRecordFiles(() => props.scope);
+ return (
+ <RecordSection title="Files">
+ <RecordItemList
+ source={files}
+ pending={!props.scope}
+ empty={`No files with this ${props.scope?.type ?? 'record'} yet.`}
+ />
+ </RecordSection>
+ );
+}
+
+/** Calls associated with the record, including calls with its people. */
+export function RecordCallsSection(props: { scope?: CrmRecordScope }) {
+ const calls = useCrmContext().createRecordCalls(() => props.scope);
+ return (
+ <RecordSection title="Calls">
+ <RecordItemList
+ source={calls}
+ pending={!props.scope}
+ empty={`No calls with this ${props.scope?.type ?? 'record'} yet.`}
+ />
+ </RecordSection>
+ );
+}
diff --git a/apps/web/src/features/crm/views/record-detail.test.tsx b/apps/web/src/features/crm/views/record-detail.test.tsx
index 3e7a676143..f1378a966e 100644
--- a/apps/web/src/features/crm/views/record-detail.test.tsx
+++ b/apps/web/src/features/crm/views/record-detail.test.tsx
@@ -31,6 +31,7 @@ vi.mock('@components/app/side-panel', () => ({
}));
vi.mock('@core/component/EntityIcon', () => ({ EntityIcon: () => null }));
vi.mock('./copy-link-button', () => ({ CrmCopyLinkButton: () => null }));
+vi.mock('../components/record-tabs', () => ({ RecordTabs: () => null }));
vi.mock('./use-crm', () => ({
useCompanyQuery: () => ({
query: { isError: false },
diff --git a/apps/web/src/features/crm/views/record-detail.tsx b/apps/web/src/features/crm/views/record-detail.tsx
index 1e1109ec28..3ebfb1704a 100644
--- a/apps/web/src/features/crm/views/record-detail.tsx
+++ b/apps/web/src/features/crm/views/record-detail.tsx
@@ -11,7 +11,9 @@ import {
Show,
Suspense,
} from 'solid-js';
+import { RecordTabs } from '../components/record-tabs';
import type { CrmContact as CompanyContact } from '../core/contact';
+import { COMPANY_SECTIONS, type CompanySection } from '../core/record';
import { Company } from './company-detail';
import { Contact } from './contact-detail';
import { CrmCopyLinkButton } from './copy-link-button';
@@ -26,6 +28,8 @@ export function CrmCompanyDetail(props: {
const { query, company } = useCompanyQuery(() => props.company.id);
const companyName = () => company()?.name ?? props.company.name;
const [selectedContact, setSelectedContact] = createSignal<CompanyContact>();
+ const [companySection, setCompanySection] =
+ createSignal<CompanySection>('overview');
const contactQuery = useContactQuery(() => selectedContact()?.id ?? '');
const contactName = () => {
const contact = contactQuery.isSuccess
@@ -118,8 +122,17 @@ export function CrmCompanyDetail(props: {
{props.navigation}
<ViewBreadcrumbs.Outlet
aria-label="CRM record location"
- class="flex-1"
+ class="min-w-0 shrink"
/>
+ <Show when={!selectedContact()}>
+ <div class="min-w-0 overflow-x-auto">
+ <RecordTabs
+ sections={COMPANY_SECTIONS}
+ value={companySection()}
+ onChange={setCompanySection}
+ />
+ </div>
+ </Show>
<div class="ml-auto flex shrink-0 items-center gap-2">
<CrmCopyLinkButton
type={selectedContact() ? 'contact' : 'company'}
@@ -173,6 +186,7 @@ export function CrmCompanyDetail(props: {
fallback={
<Company
companyId={props.company.id}
+ section={companySection()}
headerToggle={false}
onHidden={props.onClose}
onOpenContact={setSelectedContact}
diff --git a/apps/web/src/features/crm/views/record-item-list.tsx b/apps/web/src/features/crm/views/record-item-list.tsx
new file mode 100644
index 0000000000..cc4f01aa33
--- /dev/null
+++ b/apps/web/src/features/crm/views/record-item-list.tsx
@@ -0,0 +1,81 @@
+import {
+ ListEntity,
+ ListEntityMetadataQueryProvider,
+ ListLayoutProvider,
+} from '@entity';
+import { createSignal, For, type JSX, Show } from 'solid-js';
+import { useInfiniteScrollSentinel } from '../../../lib/primitives/infinite-scroll-sentinel';
+import { useCrmContext } from '../context/crm-context';
+import type { ItemListSource } from '../context/crm-sources';
+
+/**
+ * One of a CRM record's soup lists (emails, files or calls): unified-list
+ * rows that open in a split, paging in as the end scrolls into view.
+ */
+export function RecordItemList(props: {
+ source: ItemListSource;
+ /** Hold the loading state, e.g. while the record itself loads. */
+ pending?: boolean;
+ empty: JSX.Element;
+}) {
+ const { openEntity } = useCrmContext().createNavigation();
+ // Reading `data` before the first page resolves would suspend the tab.
+ const items = () =>
+ props.source.isPending ? [] : (props.source.data?.entities ?? []);
+ const [listRef, setListRef] = createSignal<HTMLElement>();
+ const [sentinelRef, setSentinelRef] = createSignal<HTMLDivElement>();
+
+ useInfiniteScrollSentinel({
+ sentinel: sentinelRef,
+ hasNextPage: () => props.source.hasNextPage ?? false,
+ isFetchingNextPage: () => props.source.isFetchingNextPage,
+ fetchNextPage: () => props.source.fetchNextPage(),
+ });
+
+ // An enabled query is loading until its first page is readable, including
+ // paused requests; a disabled one shows the empty state instead.
+ const loading = () =>
+ props.pending || (props.source.isPending && props.source.isEnabled);
+
+ return (
+ <Show
+ when={!loading()}
+ fallback={
+ <div class="p-6 text-center text-sm text-ink-muted">Loading…</div>
+ }
+ >
+ <Show
+ when={items().length > 0}
+ fallback={
+ <div class="rounded-lg border border-dashed border-edge-muted p-6 text-center text-sm text-ink-muted">
+ {props.empty}
+ </div>
+ }
+ >
+ <ListEntityMetadataQueryProvider>
+ <ListLayoutProvider ref={listRef}>
+ <div ref={setListRef} class="flex flex-col">
+ <For each={items()}>
+ {(entity) => (
+ <ListEntity
+ entity={entity}
+ timestamp={entity.updatedAt}
+ onClick={() => openEntity(entity)}
+ />
+ )}
+ </For>
+ </div>
+ </ListLayoutProvider>
+ </ListEntityMetadataQueryProvider>
+ <Show when={props.source.hasNextPage}>
+ <div ref={setSentinelRef} class="h-px" />
+ </Show>
+ <Show when={props.source.isFetchingNextPage}>
+ <div class="p-3 text-center text-xs text-ink-muted">
+ Loading more…
+ </div>
+ </Show>
+ </Show>
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/entity/index.ts b/apps/web/src/features/entity/index.ts
index e7d548d5ff..8db2f7114c 100644
--- a/apps/web/src/features/entity/index.ts
+++ b/apps/web/src/features/entity/index.ts
@@ -71,6 +71,7 @@ export {
COMPANY_STAGE_OPTIONS,
getPropertyOptionLabel,
getTaskAssigneeIds,
+ getTaskReferencedEntityIds,
getTaskStatusOptionId,
} from './utils/task-properties';
export {
diff --git a/apps/web/src/features/entity/utils/task-properties.ts b/apps/web/src/features/entity/utils/task-properties.ts
index d31f41b0c7..4383e0ac35 100644
--- a/apps/web/src/features/entity/utils/task-properties.ts
+++ b/apps/web/src/features/entity/utils/task-properties.ts
@@ -118,6 +118,27 @@ export const getTaskAssigneeIds = (
.map((reference) => reference.entity_id);
};
+/**
+ * Ids of the entities a task's entity-reference property points at, e.g.
+ * the CRM companies in its Companies property.
+ */
+export const getTaskReferencedEntityIds = (
+ entity: TaskEntityWithProperties,
+ propertyDefinitionId: string
+): string[] => {
+ const value = getTaskPropertyByDefinitionId(
+ entity,
+ propertyDefinitionId
+ )?.value;
+ if (
+ value?.type !== 'EntityReference' ||
+ !isEntityReferenceArray(value.value)
+ ) {
+ return [];
+ }
+ return value.value.map((reference) => reference.entity_id);
+};
+
/**
* Gets the status option id from task properties.
*/
diff --git a/apps/web/src/features/property/identifiers.ts b/apps/web/src/features/property/identifiers.ts
index f4b6072275..67d44c1675 100644
--- a/apps/web/src/features/property/identifiers.ts
+++ b/apps/web/src/features/property/identifiers.ts
@@ -18,6 +18,7 @@ export const SYSTEM_PROPERTY_IDS = {
STAGE: '00000001-0000-0000-0000-000000000010',
COMPANY_OWNER: '00000001-0000-0000-0000-000000000011',
REVENUE: '00000001-0000-0000-0000-000000000012',
+ CONTACTS: '00000001-0000-0000-0000-000000000013',
} as const;
/** Stable option IDs, kept independent of UI/block registries for tooling. */
diff --git a/apps/web/src/features/tasks-view/queries/task-query.test.ts b/apps/web/src/features/tasks-view/queries/task-query.test.ts
index 08dfffa8df..f53bddbd00 100644
--- a/apps/web/src/features/tasks-view/queries/task-query.test.ts
+++ b/apps/web/src/features/tasks-view/queries/task-query.test.ts
@@ -80,3 +80,36 @@ describe('project task membership scope', () => {
expect(search.body.filters?.document_filters?.document_ids).toEqual(ids);
});
});
+
+describe('task reference scope', () => {
+ const reference = {
+ propertyDefinitionId: '00000001-0000-0000-0000-00000000000c',
+ entityId: 'company-1',
+ };
+
+ it('ANDs the referencing property into the list query', () => {
+ const query = buildTaskQuery({ ...options, facets: {}, reference });
+ expect(query.body.df).toEqual({ l: { dst: 'task' } });
+ expect(query.body.propf).toEqual({
+ l: { pd: reference.propertyDefinitionId, v: { er: 'company-1' } },
+ });
+ });
+
+ it('keeps the scope when searching', () => {
+ const request = buildTaskSearchRequest({
+ query: 'renewal',
+ matchType: 'partial',
+ tab: 'team-tasks',
+ userId: 'user',
+ facets: {},
+ reference,
+ });
+ expect(request.body.filters?.property_filters).toEqual([
+ {
+ property_definition_id: reference.propertyDefinitionId,
+ entity_type: 'TASK',
+ entity_ids: ['company-1'],
+ },
+ ]);
+ });
+});
diff --git a/apps/web/src/features/tasks-view/queries/task-query.ts b/apps/web/src/features/tasks-view/queries/task-query.ts
index 5bd043c70b..4e8a74adce 100644
--- a/apps/web/src/features/tasks-view/queries/task-query.ts
+++ b/apps/web/src/features/tasks-view/queries/task-query.ts
@@ -15,7 +15,12 @@ import {
TASK_FACETS,
type TaskFacetContext,
} from '../filters/task-facets';
-import type { TaskGroupBy, TaskSortId, TaskTab } from '../types';
+import type {
+ TaskGroupBy,
+ TaskReferenceScope,
+ TaskSortId,
+ TaskTab,
+} from '../types';
import { taskMembershipScope } from './task-membership';
@@ -43,7 +48,8 @@ const documentScope = (tab: TaskTab, userId: string | undefined): TaskAst => {
const propertyScope = (
tab: TaskTab,
userId: string | undefined,
- compiledFacets: TaskAst | undefined
+ compiledFacets: TaskAst | undefined,
+ reference: TaskReferenceScope | undefined
): TaskAst | undefined => {
const groups: TaskAst[] = [];
if (compiledFacets) groups.push(compiledFacets);
@@ -51,6 +57,11 @@ const propertyScope = (
if (tab === 'my-tasks' && userId) {
groups.push(entityPropertyLiteral(SYSTEM_PROPERTY_IDS.ASSIGNEES, userId));
}
+ if (reference) {
+ groups.push(
+ entityPropertyLiteral(reference.propertyDefinitionId, reference.entityId)
+ );
+ }
return combine('&', groups);
};
@@ -104,6 +115,8 @@ export type BuildTaskQueryOptions = {
sort: SortSelection<TaskSortId>[];
/** Authorized membership scope; an empty set deliberately matches no tasks. */
taskIds?: readonly string[];
+ /** Only tasks whose property references this entity. */
+ reference?: TaskReferenceScope;
};
/** Builds the concrete Soup AST used only by the production Tasks view. */
@@ -126,7 +139,8 @@ export function buildTaskQuery(
const properties = propertyScope(
options.tab,
options.userId,
- compiledFacets.propf
+ compiledFacets.propf,
+ options.reference
);
const taskDocuments = documentScope(options.tab, options.userId);
diff --git a/apps/web/src/features/tasks-view/queries/task-search.ts b/apps/web/src/features/tasks-view/queries/task-search.ts
index c443001fd2..7abb3d15e1 100644
--- a/apps/web/src/features/tasks-view/queries/task-search.ts
+++ b/apps/web/src/features/tasks-view/queries/task-search.ts
@@ -14,7 +14,7 @@ import {
getTaskFacetOption,
type TaskFacetContext,
} from '../filters/task-facets';
-import type { TaskTab } from '../types';
+import type { TaskReferenceScope, TaskTab } from '../types';
const nonTaskFilters: EntityFilters = {
calendar_event_filters: { calendar_event_ids: [NIL_UUID] },
@@ -86,6 +86,7 @@ export function buildTaskSearchRequest(options: {
facets: FacetSelection;
facetContext?: TaskFacetContext;
taskIds?: readonly string[];
+ reference?: TaskReferenceScope;
}): SearchSoupQueryArgs {
const facetContext = options.facetContext ?? EMPTY_TASK_FACET_CONTEXT;
const propertyFilters = selectedPropertyFilters(options.facets, facetContext);
@@ -97,6 +98,13 @@ export function buildTaskSearchRequest(options: {
entity_ids: [options.userId ?? NIL_UUID],
});
}
+ if (options.reference) {
+ propertyFilters.push({
+ property_definition_id: options.reference.propertyDefinitionId,
+ entity_type: 'TASK',
+ entity_ids: [options.reference.entityId],
+ });
+ }
const owners = selectedCreators(options.facets, options.tab, options.userId);
// Like the list query, a selected tag that no longer exists stops filtering.
diff --git a/apps/web/src/features/tasks-view/queries/use-tasks-query.test.ts b/apps/web/src/features/tasks-view/queries/use-tasks-query.test.ts
index 587a7efa2b..3000f6be0f 100644
--- a/apps/web/src/features/tasks-view/queries/use-tasks-query.test.ts
+++ b/apps/web/src/features/tasks-view/queries/use-tasks-query.test.ts
@@ -2,7 +2,10 @@ import type { TaskEntityWithProperties } from '@entity/types/entity';
import { createRoot, createSignal } from 'solid-js';
import { expect, it, vi } from 'vitest';
-const fixture = vi.hoisted(() => ({ query: {} as Record<string, unknown> }));
+const fixture = vi.hoisted(() => ({
+ query: {} as Record<string, unknown>,
+ groupQueries: new Map<string, unknown>(),
+}));
vi.mock('@app/features/soup', async () => ({
...(await import('@app/features/soup/filters')),
...(await import('@app/features/soup/collection/rows')),
@@ -29,7 +32,7 @@ vi.mock('@queries/soup/items', () => ({
useSoupAstItemsQuery: () => fixture.query,
}));
vi.mock('@queries/soup/grouped/create-grouped-soup-queries', () => ({
- createGroupedSoupQueries: () => ({ map: () => new Map() }),
+ createGroupedSoupQueries: () => ({ map: () => fixture.groupQueries }),
}));
import { useTasksDataSource } from './use-tasks-query';
@@ -94,3 +97,90 @@ it('retains cached rows during membership changes but filters them by current ac
}
});
});
+
+it('scopes grouped load-more pages to the referenced entity', () => {
+ const companies = 'companies-definition';
+ const task = (id: string, companyId: string) =>
+ ({
+ type: 'document',
+ fileType: 'md',
+ id,
+ name: id,
+ ownerId: 'viewer',
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ subType: { type: 'task', is_completed: false },
+ properties: [
+ {
+ definition: { id: companies },
+ value: {
+ type: 'EntityReference',
+ value: [{ entity_type: 'COMPANY', entity_id: companyId }],
+ },
+ },
+ ],
+ }) as unknown as TaskEntityWithProperties;
+ fixture.query = {
+ isLoading: false,
+ isPlaceholderData: false,
+ data: {
+ entities: [],
+ itemsById: {},
+ groups: [
+ {
+ key: 'todo',
+ label: 'To do',
+ displayOrder: 0,
+ totalCount: 2,
+ itemIds: [],
+ nextCursor: 'next',
+ },
+ ],
+ },
+ };
+ // A "Load more" page holding one task that no longer references Acme.
+ fixture.groupQueries = new Map([
+ [
+ 'todo',
+ {
+ data: () => ({
+ entities: [task('linked', 'acme'), task('unlinked', 'globex')],
+ }),
+ hasNextPage: () => false,
+ isFetchingNextPage: () => false,
+ fetchNextPage: async () => {},
+ },
+ ],
+ ]);
+ createRoot((dispose) => {
+ try {
+ const source = useTasksDataSource(
+ {
+ tab: 'team-tasks',
+ search: '',
+ facets: {},
+ groupBy: 'status',
+ sort: [],
+ },
+ {
+ userId: () => 'viewer',
+ tagSets: () => [],
+ tagSetsReady: () => true,
+ isGroupExpanded: () => true,
+ reference: () => ({
+ propertyDefinitionId: companies,
+ entityId: 'acme',
+ }),
+ }
+ );
+ expect(
+ source
+ .items()
+ .flatMap((row) => (row.kind === 'entity' ? [row.entity.id] : []))
+ ).toEqual(['linked']);
+ } finally {
+ dispose();
+ fixture.groupQueries = new Map();
+ }
+ });
+});
diff --git a/apps/web/src/features/tasks-view/queries/use-tasks-query.ts b/apps/web/src/features/tasks-view/queries/use-tasks-query.ts
index e41065bad0..ac785feca2 100644
--- a/apps/web/src/features/tasks-view/queries/use-tasks-query.ts
+++ b/apps/web/src/features/tasks-view/queries/use-tasks-query.ts
@@ -17,6 +17,7 @@ import { withEntityNotifications } from '@app/features/soup/entity-notifications
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
import {
type EntityData,
+ getTaskReferencedEntityIds,
isTaskEntity,
type TaskEntityWithProperties,
} from '@entity';
@@ -31,7 +32,7 @@ import {
type TaskViewContext,
taskMatchesView,
} from '../filters/task-predicates';
-import type { TasksViewState } from '../types';
+import type { TaskReferenceScope, TasksViewState } from '../types';
import { buildTaskQuery } from './task-query';
import { buildTaskSearchRequest } from './task-search';
@@ -46,6 +47,8 @@ export type UseTasksDataSourceOptions = {
tagSetsReady: Accessor<boolean>;
isGroupExpanded: (groupId: string) => boolean;
taskIds?: Accessor<readonly string[]>;
+ /** Only tasks whose property references this entity. */
+ reference?: Accessor<TaskReferenceScope>;
enabled?: Accessor<boolean>;
networkPaused?: Accessor<boolean>;
};
@@ -63,6 +66,16 @@ type TaskGroupContinuationReader = {
loadMore: (groupId: string) => Promise<void>;
};
+function referencesEntity(
+ task: TaskEntityWithProperties,
+ reference: TaskReferenceScope
+) {
+ return getTaskReferencedEntityIds(
+ task,
+ reference.propertyDefinitionId
+ ).includes(reference.entityId);
+}
+
/** Query, service search, and row assembly owned by the production Tasks view. */
export function useTasksDataSource(
state: TasksDataSourceInput,
@@ -89,19 +102,24 @@ export function useTasksDataSource(
groupBy: state.groupBy,
sort: state.sort,
taskIds: options.taskIds?.(),
+ reference: options.reference?.(),
});
+ const scoped = Boolean(options.taskIds || options.reference);
const query = useSoupAstItemsQuery(queryArgs, () => ({
enabled: facetOptionsReady(),
networkPaused: options.networkPaused?.(),
- keepPreviousData: Boolean(options.taskIds),
- // Project lists admit optimistic rows only where this view shows them.
- meta: options.taskIds
+ keepPreviousData: scoped,
+ // Scoped lists admit optimistic rows only where this view shows them.
+ meta: scoped
? {
insertFilter: (item) => {
const entity = mapApiSoupItemToEntity(item);
+ const reference = options.reference?.();
return (
- isTaskEntity(entity) && taskMatchesView(entity, viewContext())
+ isTaskEntity(entity) &&
+ taskMatchesView(entity, viewContext()) &&
+ (!reference || referencesEntity(entity, reference))
);
},
}
@@ -119,9 +137,11 @@ export function useTasksDataSource(
const selected: TaskEntityWithProperties[] = [];
const context = viewContext();
const memberIds = options.taskIds ? new Set(options.taskIds()) : undefined;
+ const reference = options.reference?.();
for (const entity of entities) {
if (!isTaskEntity(entity)) continue;
if (memberIds && !memberIds.has(entity.id)) continue;
+ if (reference && !referencesEntity(entity, reference)) continue;
if (!taskMatchesView(entity, context)) continue;
selected.push(attachNotifications(entity));
@@ -166,6 +186,7 @@ export function useTasksDataSource(
facets: state.facets,
facetContext: facetContext(),
taskIds: options.taskIds?.(),
+ reference: options.reference?.(),
}),
});
@@ -243,11 +264,13 @@ export function useTasksDataSource(
const task = tasksById.get(id);
return task ? [task] : [];
});
+ const reference = options.reference?.();
const continuationTasks = continuations
.entities(group.key)
.filter(
(task) =>
(!options.taskIds || options.taskIds().includes(task.id)) &&
+ (!reference || referencesEntity(task, reference)) &&
taskMatchesView(task, viewContext())
);
const entities = sortItems(
diff --git a/apps/web/src/features/tasks-view/types.ts b/apps/web/src/features/tasks-view/types.ts
index ecfe0d7328..fef111dd40 100644
--- a/apps/web/src/features/tasks-view/types.ts
+++ b/apps/web/src/features/tasks-view/types.ts
@@ -13,6 +13,12 @@ export type TaskGroupBy =
export type TaskSortId = 'updated_at' | 'created_at' | 'viewed_at';
+/** Scopes a task list to tasks whose entity-reference property points at an entity. */
+export type TaskReferenceScope = {
+ propertyDefinitionId: string;
+ entityId: string;
+};
+
export type TaskDetailTarget = {
id: string;
fallbackName?: string;
diff --git a/apps/web/src/lib/queries/gate.test.tsx b/apps/web/src/lib/queries/gate.test.tsx
index 8adb98b56c..6aa815de3c 100644
--- a/apps/web/src/lib/queries/gate.test.tsx
+++ b/apps/web/src/lib/queries/gate.test.tsx
@@ -21,6 +21,8 @@ function mount(options: {
enabled?: boolean;
initialData?: string;
queryFn?: () => Promise<string>;
+ /** Read through a narrow feature contract instead of the TanStack result. */
+ contract?: boolean;
}) {
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
@@ -36,9 +38,19 @@ function mount(options: {
initialData: options.initialData,
}));
const result = query;
+ const contract: {
+ readonly isPending: boolean;
+ readonly data: string | undefined;
+ } = result;
return (
<div data-testid="content">
- {queryReadyGate(result) ? result.data : 'pending'}
+ {options.contract
+ ? queryReadyGate(contract)
+ ? contract.data
+ : 'pending'
+ : queryReadyGate(result)
+ ? result.data
+ : 'pending'}
</div>
);
}
@@ -102,6 +114,14 @@ describe('queryReadyGate', () => {
expectContent('pending');
});
+ it('gates a narrow query contract the same way', async () => {
+ const response = Promise.withResolvers<string>();
+ mount({ contract: true, queryFn: () => response.promise });
+ expectContent('pending');
+ response.resolve('loaded');
+ await waitFor(() => expectContent('loaded'));
+ });
+
it('recognizes falsy cached values as available', () => {
mount({ enabled: false, initialData: '' });
expectContent('');
diff --git a/apps/web/src/lib/queries/gate.ts b/apps/web/src/lib/queries/gate.ts
index 54957b8878..8063519831 100644
--- a/apps/web/src/lib/queries/gate.ts
+++ b/apps/web/src/lib/queries/gate.ts
@@ -3,11 +3,18 @@ import type {
UseQueryResult,
} from '@tanstack/solid-query';
+/** A query surface built on a TanStack query, such as a feature contract. */
+type QueryLike = { readonly isPending: boolean; readonly data: unknown };
+
export function queryReadyGate<T>(
query: UseQueryResult<T> | UseInfiniteQueryResult<T>
): query is
| (UseQueryResult<T, never> & { data: T })
- | (UseInfiniteQueryResult<T, never> & { data: T }) {
+ | (UseInfiniteQueryResult<T, never> & { data: T });
+export function queryReadyGate<Q extends QueryLike>(
+ query: Q
+): query is Q & { readonly data: Exclude<Q['data'], undefined> };
+export function queryReadyGate(query: QueryLike): boolean {
// Disabled and paused queries are pending without being loading. Reading
// their data still suspends, so check the broader initial-pending state.
return !query.isPending && query.data !== undefined;
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 30a09aad6e..3d8d79f984 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -1458,7 +1458,7 @@ segment to return with the same filters, layout, and list scroll position. Selec
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
+Clicking a contact in an embedded company's Team tab 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
@@ -1468,6 +1468,18 @@ 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.
+A company is laid out like a project. Its top bar (the split header, or the
+embedded breadcrumb header) has `Overview`, `Team`, `Emails`, `Files`, `Tasks`
+and `Calls` tabs, collapsing to icons when narrow. Overview shows the name, pills
+for each domain and `Last interacted`, the generated description and the
+Discussion. Team lists the contacts with `Add contact`. Emails keeps the
+`Signal`/`All` and `Team`/`Me` toggles. Files lists non-task documents whose
+`Companies` property references the company, plus attachments of emails with
+its domains. Tasks is the Tasks list scoped to the `Companies` property; its
+`New task` composer pre-fills the company. Calls lists calls linked to the
+company, including those linked automatically from their participants. The side
+panel keeps Properties and Sharing.
+
Company and contact pages have a **Discussion** section built from the same
message conversation as a document's Discussion: threaded replies, reactions,
attachments, and edit/delete from the message menu. `@` suggests the team's