Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(crm): replace the Databases view with generic pipelines (#9652)
teo43359e7f014d
diff --git a/.sqlx/query-652bbe1537469bf4b32115c6e4ff23ef6f105f52b3395b115e235b371c7b4a55.json b/.sqlx/query-652bbe1537469bf4b32115c6e4ff23ef6f105f52b3395b115e235b371c7b4a55.jsonindex 28a04c2a98..3eee417b4b 100644--- a/.sqlx/query-652bbe1537469bf4b32115c6e4ff23ef6f105f52b3395b115e235b371c7b4a55.json+++ b/.sqlx/query-652bbe1537469bf4b32115c6e4ff23ef6f105f52b3395b115e235b371c7b4a55.json@@ -67,7 +67,7 @@"nullable": [false,false,- false,+ true,false,false,false,diff --git a/apps/docs/AI/mcp/tools/add-to-pipeline.mdx b/apps/docs/AI/mcp/tools/add-to-pipeline.mdxindex 9f34df12de..38b1b02f7a 100644--- a/apps/docs/AI/mcp/tools/add-to-pipeline.mdx+++ b/apps/docs/AI/mcp/tools/add-to-pipeline.mdx@@ -7,12 +7,12 @@ description: >-# AddToPipeline-Add companies or contacts to a CRM pipeline as new deals (entries), optionally setting their stage, owner, revenue or other fields. A company pipeline takes companies and a contact pipeline takes contacts (see ListPipelines' `tracks`). A record already in the pipeline is not added again unless allowDuplicates is true (for a second, separate deal); its existing entry is returned in alreadyPresent instead. Returns the new entries with their entryIds and fields as saved.+Add companies or contacts to a CRM pipeline as new deals (entries), optionally setting their stage, owner, revenue or other fields. A company pipeline takes companies and a contact pipeline takes contacts (see ListPipelines' `tracks`); a generic pipeline, with no `tracks`, takes rows that name only their fields. A record already in the pipeline is not added again unless allowDuplicates is true (for a second, separate deal); its existing entry is returned in alreadyPresent instead. Returns the new entries with their entryIds and fields as saved.## Parameters| Parameter | Type | Required | Description || --- | --- | --- | --- || `pipelineId` | string | Yes | The pipeline's id from ListPipelines. |-| `entries` | ToolNewEntry[] | Yes | The companies or contacts to add, each with its starting fields. |+| `entries` | ToolNewEntry[] | Yes | The companies or contacts to add, each with its starting fields, or a generic pipeline's new rows. || `allowDuplicates` | boolean | No | Add a record again even if it already has an entry in this pipeline. Only for a genuinely separate second deal. Defaults to false. |diff --git a/apps/docs/AI/mcp/tools/create-pipeline.mdx b/apps/docs/AI/mcp/tools/create-pipeline.mdxindex b7ef3fdef7..e5ad3bf76e 100644--- a/apps/docs/AI/mcp/tools/create-pipeline.mdx+++ b/apps/docs/AI/mcp/tools/create-pipeline.mdx@@ -7,14 +7,14 @@ description: >-# CreatePipeline-Create a CRM pipeline: a board of deals that move through stages, such as a sales, renewals, fundraising, hiring or partnership pipeline. Each entry tracks either a company or a contact. Every pipeline starts with the tracked record, Stage, Owner and Revenue fields; Stage starts with the team's default stages unless `stages` gives others. Only when the user asked for a new pipeline: check ListPipelines first so you do not create a duplicate. Returns the pipeline with its id and fields.+Create a CRM pipeline: a board of deals that move through stages, such as a sales, renewals, fundraising, hiring or partnership pipeline. Each entry tracks a company or a contact, and the pipeline starts with the tracked record, Stage, Owner and Revenue fields; Stage starts with the team's default stages unless `stages` gives others. Leave out `tracks` for a generic pipeline: a free-form table of entries that needs no company or contact, starting with only a Name field, plus a Stage field when `stages` is given. Only when the user asked for a new pipeline: check ListPipelines first so you do not create a duplicate. Returns the pipeline with its id and fields.## Parameters| Parameter | Type | Required | Description || --- | --- | --- | --- || `name` | string | Yes | The pipeline's name, e.g. "Q4 Renewals". |-| `tracks` | `"company"` \| `"contact"` | Yes | What a pipeline's entries track. Documented on the fields that use it: a doc comment on a variant would turn the schema into `oneOf`. |+| `tracks` | `"company"` \| `"contact"` | No | "company" for deals with organizations, "contact" for deals with individual people (candidates, investors, partners). Leave out for a generic pipeline whose entries need no company or contact. || `sharedWithTeam` | boolean | No | Let the user's team see and edit it. Defaults to false: only the user can see it. || `stages` | string[] | No | The stages, first to last, e.g. ["Sourced", "Screen", "Interview", "Offer", "Hired"]. Leave empty for the team's default stages. |-| `fields` | ToolNewField[] | No | Fields to add after Company/Contact, Stage, Owner and Revenue. |+| `fields` | ToolNewField[] | No | Fields to add after Company/Contact, Stage, Owner and Revenue, or after a generic pipeline's Name. |diff --git a/apps/docs/AI/mcp/tools/find-pipeline-entries.mdx b/apps/docs/AI/mcp/tools/find-pipeline-entries.mdxindex c88be5286a..15cd77a688 100644--- a/apps/docs/AI/mcp/tools/find-pipeline-entries.mdx+++ b/apps/docs/AI/mcp/tools/find-pipeline-entries.mdx@@ -7,7 +7,7 @@ description: >-# FindPipelineEntries-Find deals (entries) in a CRM pipeline: which companies or contacts are in which stage, who owns them, their revenue and other fields. Filter by field values (e.g. Stage is Demo or Trial, Owner is me), by company or contact name/domain/email with `search`, or by record id; sort by any field (Stage sorts in pipeline order). Returns each entry's entryId, the record it tracks (id and name) and its filled-in fields, plus, over every match, the count per stage (and per option of each single-select field) and the total of each number field such as Revenue: use these for questions like "how many deals are in Negotiation" or "what is the pipeline worth". To find where a company or contact is across all pipelines ("what stage is Acme in?"), leave out pipelineId and pass its name as `search` (or its recordIds). Get pipeline ids and field names from ListPipelines.+Find deals (entries) in a CRM pipeline: which companies or contacts are in which stage, who owns them, their revenue and other fields. Filter by field values (e.g. Stage is Demo or Trial, Owner is me), by company or contact name/domain/email with `search` (in a generic pipeline, by any text field), or by record id; sort by any field (Stage sorts in pipeline order). Returns each entry's entryId, the record it tracks (id and name) and its filled-in fields, plus, over every match, the count per stage (and per option of each single-select field) and the total of each number field such as Revenue: use these for questions like "how many deals are in Negotiation" or "what is the pipeline worth". To find where a company or contact is across all pipelines ("what stage is Acme in?"), leave out pipelineId and pass its name as `search` (or its recordIds). Get pipeline ids and field names from ListPipelines.## Parametersdiff --git a/apps/docs/AI/mcp/tools/list-pipelines.mdx b/apps/docs/AI/mcp/tools/list-pipelines.mdxindex 5dccda5a8f..f8fc6c9d02 100644--- a/apps/docs/AI/mcp/tools/list-pipelines.mdx+++ b/apps/docs/AI/mcp/tools/list-pipelines.mdx@@ -7,4 +7,4 @@ description: >-# ListPipelines-List the user's CRM pipelines (deal pipelines, sales pipelines, hiring or partner pipelines) with their stages and fields. A pipeline holds entries (deals); each entry tracks one CRM company or contact and has its own fields, such as Stage, Owner and Revenue. Each pipeline lists its id, whether it tracks companies or contacts, the user's access, and its fields in order with their types; a select field lists its options, so Stage lists the pipeline's stages from first to last. Call this first whenever the user talks about deals, a pipeline, a stage, or moving a company or contact along, then use FindPipelineEntries, AddToPipeline and UpdatePipelineEntries with the returned pipelineId and field names. When the user names no pipeline and there is exactly one, use it; when several could match, ask which one.+List the user's CRM pipelines (deal pipelines, sales pipelines, hiring or partner pipelines) with their stages and fields. A pipeline holds entries (deals); each entry tracks one CRM company or contact and has its own fields, such as Stage, Owner and Revenue. A generic pipeline has no `tracks`: its entries are free-form rows of fields, with no company or contact. Each pipeline lists its id, whether it tracks companies or contacts, the user's access, and its fields in order with their types; a select field lists its options, so Stage lists the pipeline's stages from first to last. Call this first whenever the user talks about deals, a pipeline, a stage, or moving a company or contact along, then use FindPipelineEntries, AddToPipeline and UpdatePipelineEntries with the returned pipelineId and field names. When the user names no pipeline and there is exactly one, use it; when several could match, ask which one.diff --git a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts b/apps/web/src/components/app/split-layout/split-router/app-middleware.tsindex 76432c79c6..8d8dc862f5 100644--- a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts+++ b/apps/web/src/components/app/split-layout/split-router/app-middleware.ts@@ -9,7 +9,9 @@ import { channelsSearch } from '@app/features/channels-view/channels-route';import {crmPeopleSearch,crmRecordSearch,+ isCrmRetiredDatabasesRoute,legacyCrmPipelineId,+ retiredCrmDatabasesPath,} from '@app/features/crm/crm-route';import {driveDocumentFromContent,@@ -65,6 +67,19 @@ function redirectLegacyCrmPipeline({return redirect(crmPipelinePath(pipelineId));}+/** Customers no longer lists databases; old links go to the record or database. */+function redirectRetiredCrmDatabases({+ to,+ redirect,+}: SplitRouterMiddlewareContext): SplitRouterMiddlewareResult | undefined {+ const route = to.location.route;+ const leaf = route.matches.at(-1)?.id;+ if (!leaf || !isCrmRetiredDatabasesRoute(leaf)) return;++ const destination = retiredCrmDatabasesPath(routeParams(route));+ return destination ? redirect(destination) : undefined;+}+/** Upgrade legacy component and block URLs when supported; on touch, keep* document details in their full-block routes instead of inline Drive views. */function redirectLegacyRoutes(@@ -298,6 +313,7 @@ export function createAppSplitRouterMiddleware(// First: a cmd+click becomes a tab with the proposed entry as-is; legacy// redirects still run when that tab is activated.openInNewTabMiddleware,+ redirectRetiredCrmDatabases,(context) => redirectLegacyRoutes(context, state),redirectLegacyCrmPipeline,migrateLegacySearch,diff --git a/apps/web/src/features/crm/README.md b/apps/web/src/features/crm/README.mdindex ca2cff83ba..989dd85c16 100644--- a/apps/web/src/features/crm/README.md+++ b/apps/web/src/features/crm/README.md@@ -152,14 +152,15 @@ links; Notes excludes task, snippet and skill Markdown subtypes. Email matchesvisible company domains/contact addresses in the viewer's own mailbox, withoutteam-scope widening or requiring a property link on the email.-Databases is a row-linked activity view, not a direct database-to-CRM relation.-It opts into database rows with the same server-resolved CRM selector and lists-each containing database once, intersected with authorized database discovery.-A company includes rows linked to its visible contacts; a contact does not inherit-its company's rows. Empty row matches never fall back to all databases. Preserve-Soup pagination and CRM-link invalidation rather than enumerating CRM IDs or table-IDs in the browser. Database creation uses the existing app action; a database-joins the CRM list only after a row has a Companies or Contacts link.+Customers has no Databases view or record section. A database that holds work+outside companies and contacts is a generic pipeline: `recordType` is null, the+primary column starts as an optional Name text column anyone can retype or delete+(the first column then titles rows), and rows are added directly in+the shared editor with no record picker or stage requirements. CSV import needs+a record to resolve, so it is hidden for generic pipelines; export includes Name.+Retired routes keep old links working: middleware sends a record's `databases`+section to the record, and a database opened under Customers to `/database/<id>`.+A saved `databases` workspace tab opens Companies.CRM collection and record lists use full-height empty states, horizontallycentered and raised toward the toolbar, with@@ -192,9 +193,9 @@ a record independently of the row; additional values use the shared overflow menEmail still matches visible company domains and contact addresses for feedmembership, but the row displays only stored properties, not inferred matches.No separate CRM association metadata lookup or row footer runs during paging.-Linked Tasks, Email, Notes, Calls and Databases open through nested Customers-routes from workspace activity and record sections. Tasks, Emails, Calls and-Databases record sections append only `<item-id>` because their section determines+Linked Tasks, Email, Notes and Calls open through nested Customers+routes from workspace activity and record sections. Tasks, Emails and Calls+record sections append only `<item-id>` because their section determinesthe renderer; Tasks also omit the redundant `md/task` suffix. These sections rejectredundant typed item URLs rather than retaining fallback routes. Workspace activityretains `<item-type>/<item-id>` and document metadata; record Files and overviewdiff --git a/apps/web/src/features/crm/activity-filters-adapter.tsx b/apps/web/src/features/crm/activity-filters-adapter.tsxindex 8ccf181436..9a3c168050 100644--- a/apps/web/src/features/crm/activity-filters-adapter.tsx+++ b/apps/web/src/features/crm/activity-filters-adapter.tsx@@ -9,11 +9,11 @@ import { CALL_AUDIENCES } from '../calls-view/core/call-filters';import { createEmailFilters } from '../email-view/filters/use-email-filters';import type { ActivityFilters } from './context/crm-context';import type { CrmActivityViewState } from './core/activity-view';-import type { CrmSoupActivityTab } from './core/navigation';+import type { CrmActivityTab } from './core/navigation';/** Normal Email facets and the applicable Notes/Calls filters, with local intent. */export function createCrmActivityFilters(- tab: CrmSoupActivityTab,+ tab: CrmActivityTab,state: Store<CrmActivityViewState>,setState: SetStoreFunction<CrmActivityViewState>): ActivityFilters {diff --git a/apps/web/src/features/crm/activity-state-adapter.ts b/apps/web/src/features/crm/activity-state-adapter.tsindex 436f08684c..f84890a730 100644--- a/apps/web/src/features/crm/activity-state-adapter.ts+++ b/apps/web/src/features/crm/activity-state-adapter.ts@@ -8,7 +8,7 @@ import { createStore } from 'solid-js/store';import { z } from 'zod';import { normalizeFacetSelection } from '../soup';import type { CrmActivityViewState } from './core/activity-view';-import type { CrmSoupActivityTab } from './core/navigation';+import type { CrmActivityTab } from './core/navigation';const stateSchema = z.object({search: z.string(),@@ -19,7 +19,7 @@ const stateSchema = z.object({});/** Per-entry, per-activity controls never modify the ordinary app views. */-export function createCrmActivityState(tab: CrmSoupActivityTab) {+export function createCrmActivityState(tab: CrmActivityTab) {const panel = useSplitPanelOrThrow();const key = `crm.activity.${tab}`;const [state, setState] = withSplitPanelOwner(key, () =>diff --git a/apps/web/src/features/crm/browser-test/pipelines.browser.e2e.ts b/apps/web/src/features/crm/browser-test/pipelines.browser.e2e.tsindex 23f4caa751..7911a70e12 100644--- a/apps/web/src/features/crm/browser-test/pipelines.browser.e2e.ts+++ b/apps/web/src/features/crm/browser-test/pipelines.browser.e2e.ts@@ -2,6 +2,38 @@ import { expect, test } from '@playwright/test';const fixture = '/src/features/crm/browser-test/pipelines.html';+test('create a generic pipeline that tracks no company or contact', async ({+ page,+}) => {+ await page.routeWebSocket('**', (socket) => socket.close());+ await page.route('https://**', (route) => route.abort());+ await page.route('**/__macro_dev/**', (route) => route.abort());+ await page.goto(fixture, { waitUntil: 'domcontentloaded' });+ await page.getByRole('button', { name: 'New pipeline', exact: true }).click();+ const dialog = page.getByRole('dialog');+ await dialog.getByRole('textbox', { name: 'Pipeline name' }).fill('Launch');+ await dialog.getByRole('button', { name: 'Track Companies' }).click();+ await page.getByRole('menuitemradio', { name: 'Generic' }).click();+ await expect(+ dialog.getByRole('button', { name: 'Track Generic' })+ ).toBeVisible();+ await dialog.getByRole('button', { name: 'Create pipeline' }).click();+ await expect(dialog).not.toBeVisible();+ await expect(+ page.getByRole('columnheader', { name: 'Name', exact: true })+ ).toBeVisible();+ await expect(+ page.getByRole('columnheader', { name: 'Company', exact: true })+ ).toHaveCount(0);+ await page.getByRole('button', { name: 'Pipeline actions' }).click();+ await expect(+ page.getByRole('menuitem', { name: 'Export CSV' })+ ).toBeVisible();+ await expect(page.getByRole('menuitem', { name: 'Import CSV' })).toHaveCount(+ 0+ );+});+test('create a private company pipeline and customize a column', async ({page,}) => {diff --git a/apps/web/src/features/crm/browser-test/pipelines.tsx b/apps/web/src/features/crm/browser-test/pipelines.tsxindex 54a2a6014d..0e4316c09c 100644--- a/apps/web/src/features/crm/browser-test/pipelines.tsx+++ b/apps/web/src/features/crm/browser-test/pipelines.tsx@@ -15,29 +15,44 @@ import { PipelineView } from '../views/pipeline';// Real creation, navigation and column-header controls. Persistence is// local; the Rust integration suite exercises the same contract against Postgres.function Editor(props: { pipeline: Pipeline }) {- const [columns, setColumns] = createSignal<DatabaseViewColumn[]>([- {- id: 'primary',- name: props.pipeline.recordType === 'company' ? 'Company' : 'Contact',- dataType: 'ENTITY',- specificEntityType:- props.pipeline.recordType === 'company' ? 'COMPANY' : 'CONTACT',- primary: true,- protections: ['delete', 'change_type'],- nullable: false,- writable: true,- isMultiSelect: false,- options: [],- },- {- id: 'stage',- name: 'Stage',- dataType: 'STRING',- writable: true,- isMultiSelect: false,- options: [],- },- ]);+ const generic: DatabaseViewColumn = {+ id: 'primary',+ name: 'Name',+ dataType: 'STRING',+ primary: true,+ protections: ['delete', 'change_type'],+ writable: true,+ isMultiSelect: false,+ options: [],+ };+ const [columns, setColumns] = createSignal<DatabaseViewColumn[]>(+ props.pipeline.recordType === null+ ? [generic]+ : [+ {+ id: 'primary',+ name:+ props.pipeline.recordType === 'company' ? 'Company' : 'Contact',+ dataType: 'ENTITY',+ specificEntityType:+ props.pipeline.recordType === 'company' ? 'COMPANY' : 'CONTACT',+ primary: true,+ protections: ['delete', 'change_type'],+ nullable: false,+ writable: true,+ isMultiSelect: false,+ options: [],+ },+ {+ id: 'stage',+ name: 'Stage',+ dataType: 'STRING',+ writable: true,+ isMultiSelect: false,+ options: [],+ },+ ]+ );return (<div class="flex border-b border-edge-muted" role="row"><For each={columns()}>diff --git a/apps/web/src/features/crm/browser-test/stage-requirements.tsx b/apps/web/src/features/crm/browser-test/stage-requirements.tsxindex dabb38ef9c..acda85f638 100644--- a/apps/web/src/features/crm/browser-test/stage-requirements.tsx+++ b/apps/web/src/features/crm/browser-test/stage-requirements.tsx@@ -17,7 +17,6 @@ const unused = (): never => {};const context: CrmContext = {createPipelines: unused,- createDatabases: unused,openCreateItem: unused,openEmailComposer: unused,PipelineEditor: unused,diff --git a/apps/web/src/features/crm/components/crm-mobile-tabs.tsx b/apps/web/src/features/crm/components/crm-mobile-tabs.tsxindex 65f7c9c84a..0006fff6a0 100644--- a/apps/web/src/features/crm/components/crm-mobile-tabs.tsx+++ b/apps/web/src/features/crm/components/crm-mobile-tabs.tsx@@ -1,9 +1,6 @@import { useFeatureFlag } from '@app/lib/analytics/posthog';import { type PillTabItem, PillTabs } from '@components/app/mobile/PillTabs';-import {- enableCrmActivity,- enableDatabases,-} from '@core/constant/featureFlags';+import { enableCrmActivity } from '@core/constant/featureFlags';import type { JSX } from 'solid-js';import {CRM_ACTIVITY_TABS,@@ -19,15 +16,10 @@ export function CrmMobileTabs(props: {onNavigate(id: string): void;}) {const activityFlag = useFeatureFlag(enableCrmActivity);- const databasesFlag = useFeatureFlag(enableDatabases);const items = (): PillTabItem[] => [...[...CRM_RECORDS,- ...(activityFlag().enabled- ? CRM_ACTIVITY_TABS.filter(- (tab) => tab.id !== 'databases' || databasesFlag().enabled- )- : []),+ ...(activityFlag().enabled ? CRM_ACTIVITY_TABS : []),].map((record) => ({value: record.id,label: record.label,diff --git a/apps/web/src/features/crm/components/crm-sidebar.tsx b/apps/web/src/features/crm/components/crm-sidebar.tsxindex 9b8aca61fb..d1ac5ab90d 100644--- a/apps/web/src/features/crm/components/crm-sidebar.tsx+++ b/apps/web/src/features/crm/components/crm-sidebar.tsx@@ -1,10 +1,7 @@import { CollapsibleSection, ViewSidebar } from '@app/components/view-shell';import { useFeatureFlag } from '@app/lib/analytics/posthog';import { getIconConfig } from '@core/component/EntityIcon';-import {- enableCrmActivity,- enableDatabases,-} from '@core/constant/featureFlags';+import { enableCrmActivity } from '@core/constant/featureFlags';import { isTouchDevice } from '@core/mobile/isTouchDevice';import BuildingsIcon from '@icon/system/regular/buildings.svg';import ExportIcon from '@icon/system/regular/download-simple.svg';@@ -29,7 +26,6 @@ const RECORD_ICONS = {email: getIconConfig('email').icon,notes: getIconConfig('md').icon,calls: getIconConfig('call').icon,- databases: getIconConfig('database').icon,};export function CrmSidebar(props: {@@ -58,7 +54,6 @@ export function CrmSidebar(props: {searchLabel?: string;}) {const activityFlag = useFeatureFlag(enableCrmActivity);- const databasesFlag = useFeatureFlag(enableDatabases);const [recordsOpen, setRecordsOpen] = createSignal(true);const [listsOpen, setListsOpen] = createSignal(true);return (@@ -117,12 +112,7 @@ export function CrmSidebar(props: {<Foreach={[...CRM_RECORDS,- ...(activityFlag().enabled- ? CRM_ACTIVITY_TABS.filter(- (tab) =>- tab.id !== 'databases' || databasesFlag().enabled- )- : []),+ ...(activityFlag().enabled ? CRM_ACTIVITY_TABS : []),]}>{(record) => (diff --git a/apps/web/src/features/crm/components/pipeline-dialog.tsx b/apps/web/src/features/crm/components/pipeline-dialog.tsxindex a0e96afe46..97fa1348ba 100644--- a/apps/web/src/features/crm/components/pipeline-dialog.tsx+++ b/apps/web/src/features/crm/components/pipeline-dialog.tsx@@ -1,7 +1,9 @@+import { t } from '@app/lib/i18n';import { fireAndForget } from '@core/util/fireAndForget';import BuildingsIcon from '@icon/system/regular/buildings.svg';import CaretDownIcon from '@icon/system/regular/caret-down.svg';import CheckIcon from '@icon/system/regular/check.svg';+import TableIcon from '@icon/system/regular/table.svg';import UsersIcon from '@icon/system/regular/users.svg';import XIcon from '@icon/system/regular/x.svg';import { Button, Checkbox, Dialog, Dropdown, EntityComposer, Panel } from '@ui';@@ -10,32 +12,53 @@ import { Dynamic } from 'solid-js/web';import type { NewPipeline } from '../core/pipeline';const RECORD_TYPES = [- { value: 'company', label: 'Companies', icon: BuildingsIcon },- { value: 'contact', label: 'Contacts', icon: UsersIcon },+ {+ value: 'company',+ icon: BuildingsIcon,+ get label() {+ return t('crm.pipelineTrackCompanies');+ },+ },+ {+ value: 'contact',+ icon: UsersIcon,+ get label() {+ return t('crm.pipelineTrackContacts');+ },+ },+ {+ value: 'generic',+ icon: TableIcon,+ get label() {+ return t('crm.pipelineTrackGeneric');+ },+ },] as const;+type Tracking = (typeof RECORD_TYPES)[number]['value'];+/** One creation session; cancel preserves existing CRM data. */export function PipelineDialog(props: {onCreate(input: NewPipeline): Promise<void>;onClose(): void;}) {const [name, setName] = createSignal('');- const [recordType, setRecordType] =- createSignal<NewPipeline['recordType']>('company');+ const [tracking, setTracking] = createSignal<Tracking>('company');const [shareWithTeam, setShareWithTeam] = createSignal(false);const [pending, setPending] = createSignal(false);const [error, setError] = createSignal(false);const tracked = () =>- RECORD_TYPES.find((type) => type.value === recordType()) ?? RECORD_TYPES[0];+ RECORD_TYPES.find((type) => type.value === tracking()) ?? RECORD_TYPES[0];const close = () => !pending() && props.onClose();async function submit() {if (pending() || !name().trim()) return;setPending(true);setError(false);try {+ const current = tracking();await props.onCreate({name: name().trim(),- recordType: recordType(),+ recordType: current === 'generic' ? null : current,sharing: shareWithTeam() ? 'team' : 'private',});props.onClose();@@ -100,7 +123,9 @@ export function PipelineDialog(props: {<EntityComposer.Properties class="px-2"><Dropdown placement="bottom-start"><Dropdown.Trigger- aria-label={`Track ${tracked().label}`}+ aria-label={t('crm.pipelineTrackChoice', {+ choice: tracked().label,+ })}class="rounded-full"disabled={pending()}>@@ -113,12 +138,12 @@ export function PipelineDialog(props: {</Dropdown.Trigger><Dropdown.Content class="min-w-40"><Dropdown.Group>- <Dropdown.GroupLabel>Track</Dropdown.GroupLabel>+ <Dropdown.GroupLabel>+ {t('crm.pipelineTrack')}+ </Dropdown.GroupLabel><Dropdown.RadioGroup- value={recordType()}- onChange={(value) =>- setRecordType(value as NewPipeline['recordType'])- }+ value={tracking()}+ onChange={(value) => setTracking(value as Tracking)}><For each={RECORD_TYPES}>{(type) => (diff --git a/apps/web/src/features/crm/components/record-search.tsx b/apps/web/src/features/crm/components/record-search.tsxindex d7086de2d3..98111b5046 100644--- a/apps/web/src/features/crm/components/record-search.tsx+++ b/apps/web/src/features/crm/components/record-search.tsx@@ -4,7 +4,7 @@ import { Combobox } from '@kobalte/core/combobox';import { Layer } from '@ui';import { createSignal, Show } from 'solid-js';import { PropertyIcon } from '../../database/components/property-icon';-import type { Pipeline } from '../core/pipeline';+import type { PipelineRecordType } from '../core/pipeline';import { type RecordOption, recordDetail } from '../core/pipeline-record';/** A search result row: a record to pick, or the search itself as a record to create. */@@ -16,7 +16,7 @@ const MAX_RESULTS = 50;/** Find a company or contact by name or detail, or start a new one from the search. */export function RecordSearch(props: {- recordType: Pipeline['recordType'];+ recordType: PipelineRecordType;options: RecordOption[];loading: boolean;/** Mount the menu here, e.g. a modal dialog's content, which hides body portals. */diff --git a/apps/web/src/features/crm/components/record-tabs.tsx b/apps/web/src/features/crm/components/record-tabs.tsxindex 7b263a3525..17f59d13d6 100644--- a/apps/web/src/features/crm/components/record-tabs.tsx+++ b/apps/web/src/features/crm/components/record-tabs.tsx@@ -1,9 +1,7 @@-import { useFeatureFlag } from '@app/lib/analytics/posthog';import { t } from '@app/lib/i18n';import { MobileDrawer } from '@components/app/mobile/MobileDrawer';import { HeaderIsland } from '@components/app/split-layout/components/HeaderIsland';import { getIconConfig } from '@core/component/EntityIcon';-import { enableDatabases } from '@core/constant/featureFlags';import { isTouchDevice } from '@core/mobile/isTouchDevice';import CaretDownIcon from '@icon/system/regular/caret-down.svg';import CheckIcon from '@icon/system/regular/check.svg';@@ -24,7 +22,6 @@ const SECTION_ICONS: Record<files: getIconConfig('files').icon,tasks: getIconConfig('task').icon,calls: getIconConfig('call').icon,- databases: getIconConfig('database').icon,};/** Desktop section tabs and a touch header island with a section drawer. */@@ -34,13 +31,8 @@ export function RecordTabs<S extends CrmRecordSection>(props: {onChange: (section: S) => void;compact?: boolean;}) {- const databasesFlag = useFeatureFlag(enableDatabases);const [open, setOpen] = createSignal(false);const [trigger, setTrigger] = createSignal<HTMLButtonElement>();- const sections = () =>- props.sections.filter(- (section) => section !== 'databases' || databasesFlag().enabled- );const label = (section: CrmRecordSection) => t(`tabs.record-${section}`);const icon = (section: CrmRecordSection) => SECTION_ICONS[section];@@ -51,7 +43,7 @@ export function RecordTabs<S extends CrmRecordSection>(props: {<Tabsaria-label={t('tabs.recordSections')}class="shrink-0"- options={sections().map((section) => ({+ options={props.sections.map((section) => ({value: section,label: label(section),icon: props.compact ? SECTION_ICONS[section] : undefined,@@ -102,7 +94,7 @@ export function RecordTabs<S extends CrmRecordSection>(props: {aria-label={t('tabs.recordSections')}class="flex flex-col">- <For each={sections()}>+ <For each={props.sections}>{(section) => (<MobileDrawer.Closeas={MobileDrawer.Item}diff --git a/apps/web/src/features/crm/components/tool-pipelines.tsx b/apps/web/src/features/crm/components/tool-pipelines.tsxindex 3f41ec58a4..ddab6aa60b 100644--- a/apps/web/src/features/crm/components/tool-pipelines.tsx+++ b/apps/web/src/features/crm/components/tool-pipelines.tsx@@ -6,7 +6,8 @@ import { For, Show } from 'solid-js';type Pipeline = {name: string;- tracks: string;+ /** Missing for a generic pipeline. */+ tracks?: string | null;fields: { name: string; options?: string[] | null }[];};type TrackedRecord = {@@ -14,9 +15,13 @@ type TrackedRecord = {name?: string | null;detail?: string | null;};-type Entry = { record: TrackedRecord; fields: { [field: string]: unknown } };+type Entry = {+ /** Missing in a generic pipeline. */+ record?: TrackedRecord | null;+ fields: { [field: string]: unknown };+};type UpdatedEntry = {- record: TrackedRecord;+ record?: TrackedRecord | null;changes: { field: string; before: unknown; after: unknown }[];};@@ -29,10 +34,18 @@ export function formatFieldValue(value: unknown): string {return String(value);}-export function recordName(record: TrackedRecord) {+export function recordName(record: TrackedRecord | null | undefined) {+ if (!record) return 'Entry';return record.name ?? record.detail ?? record.id;}+/** A generic pipeline's entry reads by its first filled-in field. */+function entryName(entry: Entry) {+ if (entry.record) return recordName(entry.record);+ const [first] = Object.values(entry.fields);+ return first === undefined ? recordName(null) : formatFieldValue(first);+}+function entrySummary(entry: Entry) {return Object.entries(entry.fields).slice(0, 3)@@ -40,11 +53,13 @@ function entrySummary(entry: Entry) {.join(' · ');}-function RecordIcon(props: { record: TrackedRecord }) {- const isContact = () => props.record.detail?.includes('@') === true;+function RecordIcon(props: { record?: TrackedRecord | null }) {+ const isContact = () => props.record?.detail?.includes('@') === true;return (- <Show when={isContact()} fallback={<Buildings class="size-4" />}>- <User class="size-4" />+ <Show when={props.record} fallback={<Kanban class="size-4" />}>+ <Show when={isContact()} fallback={<Buildings class="size-4" />}>+ <User class="size-4" />+ </Show></Show>);}@@ -77,7 +92,10 @@ export function PipelinesToolResponse(props: { pipelines: Pipeline[] }) {subtitle={pipeline.fields.find((field) => field.name === 'Stage')- ?.options?.join(' → ') ?? `Tracks ${pipeline.tracks}s`+ ?.options?.join(' → ') ??+ (pipeline.tracks+ ? `Tracks ${pipeline.tracks}s`+ : 'Generic pipeline')}/></Tool.ListItem>@@ -103,10 +121,7 @@ export function PipelineEntriesToolResponse(props: {<For each={props.entries}>{(entry) => (<Tool.ListItem icon={<RecordIcon record={entry.record} />}>- <Line- title={recordName(entry.record)}- subtitle={entrySummary(entry)}- />+ <Line title={entryName(entry)} subtitle={entrySummary(entry)} /></Tool.ListItem>)}</For>@@ -114,7 +129,7 @@ export function PipelineEntriesToolResponse(props: {{(entry) => (<Tool.ListItem icon={<RecordIcon record={entry.record} />}><Line- title={recordName(entry.record)}+ title={entryName(entry)}subtitle={[props.noted?.note, entrySummary(entry)].filter(Boolean).join(' · ')}diff --git a/apps/web/src/features/crm/context/crm-context.tsx b/apps/web/src/features/crm/context/crm-context.tsxindex 00de11cfe1..0bef4b83fe 100644--- a/apps/web/src/features/crm/context/crm-context.tsx+++ b/apps/web/src/features/crm/context/crm-context.tsx@@ -22,7 +22,7 @@ import type {CrmDisplayOptions,CrmListColumnId,} from '../core/display-options';-import type { CrmSoupActivityTab } from '../core/navigation';+import type { CrmActivityTab } from '../core/navigation';import type { Pipeline } from '../core/pipeline';import type { CrmRecordScope, CrmTaskRecord } from '../core/record';import type {@@ -97,21 +97,19 @@ export type CrmContext = {): ItemListSource;/** Paged CRM-wide activity, limited to associated records. */createActivity(- tab: Accessor<CrmSoupActivityTab>,+ tab: Accessor<CrmActivityTab>,options?: Accessor<CrmActivityViewState>): ItemListSource;- /** Databases containing CRM-linked rows; undefined selects the workspace scope. */- createDatabases(scope: Accessor<CrmRecordScope | undefined>): ItemListSource;- openCreateItem(kind: 'notes' | 'calls' | 'databases'): void;+ openCreateItem(kind: 'notes' | 'calls'): void;openEmailComposer(recipient?: string): void;createActivityState(- tab: CrmSoupActivityTab+ tab: CrmActivityTab): readonly [Store<CrmActivityViewState>,SetStoreFunction<CrmActivityViewState>,];createActivityFilters(- tab: CrmSoupActivityTab,+ tab: CrmActivityTab,state: Store<CrmActivityViewState>,setState: SetStoreFunction<CrmActivityViewState>): ActivityFilters;diff --git a/apps/web/src/features/crm/context/workspace-context.tsx b/apps/web/src/features/crm/context/workspace-context.tsxindex c1e81b6b7e..0968971d19 100644--- a/apps/web/src/features/crm/context/workspace-context.tsx+++ b/apps/web/src/features/crm/context/workspace-context.tsx@@ -26,7 +26,7 @@ export type CrmRecordNavigation = {setSection(section: CrmRecordSection): void;item: Accessor<| {- itemType: 'document' | 'email' | 'call' | 'database';+ itemType: 'document' | 'email' | 'call';itemId: string;itemFileType?: string;itemSubType?: 'task' | 'snippet' | 'skill';diff --git a/apps/web/src/features/crm/core/navigation.ts b/apps/web/src/features/crm/core/navigation.tsindex d8c1fb840a..a1d9a5c858 100644--- a/apps/web/src/features/crm/core/navigation.ts+++ b/apps/web/src/features/crm/core/navigation.ts@@ -10,11 +10,9 @@ export const CRM_ACTIVITY_TABS = [{ id: 'email', label: 'Email' },{ id: 'notes', label: 'Notes' },{ id: 'calls', label: 'Calls' },- { id: 'databases', label: 'Databases' },] as const;export type CrmActivityTab = (typeof CRM_ACTIVITY_TABS)[number]['id'];-export type CrmSoupActivityTab = Exclude<CrmActivityTab, 'databases'>;export function isCrmActivityTab(value: string): value is CrmActivityTab {return CRM_ACTIVITY_TABS.some((tab) => tab.id === value);diff --git a/apps/web/src/features/crm/core/pipeline-csv.test.ts b/apps/web/src/features/crm/core/pipeline-csv.test.tsindex 4444f6114f..40e1f508a1 100644--- a/apps/web/src/features/crm/core/pipeline-csv.test.ts+++ b/apps/web/src/features/crm/core/pipeline-csv.test.ts@@ -175,3 +175,36 @@ describe('pipeline CSV', () => {});});});++describe('a generic pipeline', () => {+ it('exports its primary column like any other, with no record columns', () => {+ const csv = encodePipelineCsv({+ recordType: null,+ primaryColumnId: 'name',+ columns: [+ {+ id: 'name',+ name: 'Name',+ dataType: 'STRING',+ isMultiSelect: false,+ options: [],+ writable: true,+ },+ {+ id: 'stage',+ name: 'Stage',+ dataType: 'SELECT_STRING',+ isMultiSelect: false,+ options: [],+ writable: true,+ },+ ],+ rows: [{ cells: { name: 'Launch site', stage: 'Doing' } }],+ record: () => undefined,+ });+ expect(csv.split(/\r?\n/).filter(Boolean)).toEqual([+ 'Name,Stage',+ 'Launch site,Doing',+ ]);+ });+});diff --git a/apps/web/src/features/crm/core/pipeline-csv.ts b/apps/web/src/features/crm/core/pipeline-csv.tsindex 470f5365c6..9b221e24a1 100644--- a/apps/web/src/features/crm/core/pipeline-csv.ts+++ b/apps/web/src/features/crm/core/pipeline-csv.ts@@ -13,7 +13,7 @@ import type {DatabaseViewColumn,} from '../../database/core/database-view';import { importedDomain, importedText } from './import-companies';-import type { Pipeline } from './pipeline';+import type { Pipeline, PipelineRecordType } from './pipeline';/** The company or contact a pipeline row is for: its name, and its domain or email. */export type PipelineCsvRecord = { name: string; key: string };@@ -41,12 +41,12 @@ export type PipelineImportPlan = {};export type PipelineImportFailure =- | { kind: 'no-record-column'; recordType: Pipeline['recordType'] }+ | { kind: 'no-record-column'; recordType: PipelineRecordType }| { kind: 'no-rows' };/** The record columns of a pipeline CSV, before the pipeline's own columns. */export function pipelineRecordHeaders(- recordType: Pipeline['recordType']+ recordType: PipelineRecordType): [name: string, key: string] {return recordType === 'company'? ['Company', 'Domain']@@ -90,7 +90,7 @@ function exportedCell(column: DatabaseViewColumn, value: DatabaseCellValue) {: exportedValue(column, value);}-/** A pipeline as CSV: the record's name and key, then every other column. */+/** A pipeline as CSV: the record's name and key, if it tracks one, then every other column. */export function encodePipelineCsv(input: {recordType: Pipeline['recordType'];columns: readonly DatabaseViewColumn[];@@ -98,20 +98,21 @@ export function encodePipelineCsv(input: {rows: readonly PipelineCsvRow[];record(id: string): PipelineCsvRecord | undefined;}): string {- const columns = input.columns.filter(- (column) => column.id !== input.primaryColumnId- );+ const { recordType } = input;+ // A generic pipeline's primary column is plain text, exported like the rest.+ const columns = recordType+ ? input.columns.filter((column) => column.id !== input.primaryColumnId)+ : input.columns;return encodeDatabaseCsv([- ...pipelineRecordHeaders(input.recordType),+ ...(recordType ? pipelineRecordHeaders(recordType) : []),...columns.map((column) => column.name),],input.rows.map((row) => {const id = row.cells[input.primaryColumnId];const record = typeof id === 'string' ? input.record(id) : undefined;return [- record?.name ?? '',- record?.key ?? '',+ ...(recordType ? [record?.name ?? '', record?.key ?? ''] : []),...columns.map((column) =>exportedCell(column, row.cells[column.id] ?? null)),@@ -170,7 +171,7 @@ function gridValue(return column.isMultiSelect ? JSON.stringify(values) : (values[0] ?? '');}-function recordKey(recordType: Pipeline['recordType'], text: string) {+function recordKey(recordType: PipelineRecordType, text: string) {if (recordType === 'company')return text.split(/[;,\s]+/)@@ -188,7 +189,7 @@ function recordKey(recordType: Pipeline['recordType'], text: string) {export function planPipelineImport(csv: DatabaseCsv,pipeline: {- recordType: Pipeline['recordType'];+ recordType: PipelineRecordType;columns: readonly DatabaseViewColumn[];primaryColumnId: string;}diff --git a/apps/web/src/features/crm/core/pipeline.ts b/apps/web/src/features/crm/core/pipeline.tsindex 8943c02a93..9c0b21df41 100644--- a/apps/web/src/features/crm/core/pipeline.ts+++ b/apps/web/src/features/crm/core/pipeline.ts@@ -1,10 +1,13 @@+export type PipelineRecordType = 'company' | 'contact';+/** Pipeline identity and sharing are independent of its customizable table. */export type Pipeline = {id: string;teamId: string;name: string;userId: string;- recordType: 'company' | 'contact';+ /** What each row tracks; null for a generic pipeline of free-form rows. */+ recordType: PipelineRecordType | null;databaseId: string;tableId: string;primaryColumnId: string;@@ -15,3 +18,10 @@ export type Pipeline = {};export type NewPipeline = Pick<Pipeline, 'name' | 'recordType' | 'sharing'>;++/** A pipeline whose rows each track a company or contact. */+export type TrackedPipeline = Pipeline & { recordType: PipelineRecordType };++export const isTrackedPipeline = (+ pipeline: Pipeline+): pipeline is TrackedPipeline => pipeline.recordType !== null;diff --git a/apps/web/src/features/crm/core/record.ts b/apps/web/src/features/crm/core/record.tsindex d6be2a5d00..acc26a3ce2 100644--- a/apps/web/src/features/crm/core/record.ts+++ b/apps/web/src/features/crm/core/record.ts@@ -47,7 +47,6 @@ export const COMPANY_SECTIONS = ['files','tasks','calls',- 'databases',] as const;export const CONTACT_SECTIONS = ['overview',@@ -55,7 +54,6 @@ export const CONTACT_SECTIONS = ['files','tasks','calls',- 'databases',] as const;export type CompanySection = (typeof COMPANY_SECTIONS)[number];diff --git a/apps/web/src/features/crm/crm-adapter.ts b/apps/web/src/features/crm/crm-adapter.tsindex 7c095799f8..8d363c88e9 100644--- a/apps/web/src/features/crm/crm-adapter.ts+++ b/apps/web/src/features/crm/crm-adapter.ts@@ -11,7 +11,6 @@ import {enableCrmActivity,enableCrmLists,enableCrmPipelines,- enableDatabases,} from '@core/constant/featureFlags';import { useUserId } from '@core/context/user';import { useProfilePictureUrl } from '@core/signal/profilePicture';@@ -23,17 +22,11 @@ import { useTagSets, useTagSetsReady } from '@property/tags/tag-sets-context';import { queryReadyGate } from '@queries/gate';import { useListPropertiesQuery } from '@queries/properties/definitions';import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';-import { createSoupLiveQuery } from '@queries/soup/graphql/create-soup-live-query';import {type SoupAstItemsQuery,useSoupAstItemsQuery,} from '@queries/soup/items';import { getSoupEntityById } from '@queries/soup/normalized-cache';-import {- onDatabaseBatchCommitted,- onDatabaseTableAdvanced,- useDatabasesQuery,-} from '@queries/storage/databases';import {invalidateUserTeams,useCurrentTeamQuery,@@ -84,7 +77,6 @@ import {useSetContactHiddenMutation,useSetContactNameMutation,} from './queries/contacts';-import { createCrmDatabasesSource } from './queries/databases';import { fetchCrmExportCompanies } from './queries/export';import { useCrmLists } from './queries/lists';import { createPipelineTransfer } from './queries/pipeline-transfer';@@ -203,19 +195,14 @@ export function createAppCrmContext(): CrmContext {const panel = useSplitPanel();const createContext = useCreateContext();const activityFlag = useFeatureFlag(enableCrmActivity);- const databasesFlag = useFeatureFlag(enableDatabases);const navigate = useNavigate();- const openCreateItem = async (kind: 'notes' | 'calls' | 'databases') => {+ const openCreateItem = async (kind: 'notes' | 'calls') => {if (kind === 'calls') {navigate('/meet/new');return;}const { runCreateAction } = await import('@app/features/command/Launcher');- const type = {- notes: 'md',- databases: 'database',- } as const;- runCreateAction(type[kind], { source: 'crm' });+ runCreateAction('md', { source: 'crm' });};const createSettings = () => useTeamCrmConfig(deps);return {@@ -260,17 +247,6 @@ export function createAppCrmContext(): CrmContext {withRowNotifications(useContactEmailsQuery(useSoupAstItemsQuery, ...args)),- createDatabases: (scope) =>- createCrmDatabasesSource(- {- createRows: createSoupLiveQuery,- createListing: useDatabasesQuery,- onCommitted: onDatabaseBatchCommitted,- onTableAdvanced: onDatabaseTableAdvanced,- },- scope,- () => !!userId() && databasesFlag().enabled- ),openCreateItem: (kind) => fireAndForget(openCreateItem(kind), 'crm'),openEmailComposer: (recipient) =>composeEmail(diff --git a/apps/web/src/features/crm/crm-route.test.ts b/apps/web/src/features/crm/crm-route.test.tsindex b0016386c5..364c5110a0 100644--- a/apps/web/src/features/crm/crm-route.test.ts+++ b/apps/web/src/features/crm/crm-route.test.ts@@ -16,10 +16,14 @@ import {crmPipelineRecordFileItemRoute,crmPipelineRecordItemRoute,crmPipelineRecordRoute,+ crmPipelineRetiredDatabaseRoute,+ crmPipelineRetiredRecordDatabasesRoute,crmPipelineRoute,crmRecordFileItemRoute,crmRecordItemRoute,crmRecordRoute,+ crmRetiredDatabaseRoute,+ crmRetiredRecordDatabasesRoute,legacyContentRoute,notFoundRoute,taskDetailRoute,@@ -64,12 +68,16 @@ const routes = createRoutesManifest({crmPipelineRecordRoute,crmPipelineRecordItemRoute,crmPipelineRecordFileItemRoute,+ crmPipelineRetiredDatabaseRoute,+ crmPipelineRetiredRecordDatabasesRoute,],},crmItemRoute,crmRecordRoute,crmRecordItemRoute,crmRecordFileItemRoute,+ crmRetiredDatabaseRoute,+ crmRetiredRecordDatabasesRoute,],},legacyContentRoute,@@ -193,7 +201,6 @@ describe('CRM item URLs', () => {['tasks', 'document', 'md', 'task', 'task'],['emails', 'email', undefined, undefined, 'email'],['calls', 'call', undefined, undefined, 'call'],- ['databases', 'database', undefined, undefined, 'database'],])('decodes a %s record item and references the item, not the record',(section, itemType, itemFileType, itemSubType, block) => {@@ -329,7 +336,6 @@ describe('CRM item URLs', () => {`companies/company/${companyId}/tasks/document/${itemId}/md/task`,`companies/contact/${contactId}/emails/email/${itemId}`,`companies/company/${companyId}/calls/call/${itemId}`,- `companies/contact/${contactId}/databases/database/${itemId}`,`companies/pipeline/${pipelineId}/contact/${contactId}/tasks/document/${itemId}/md/task`,`companies/pipeline/${pipelineId}/company/${companyId}/emails/email/${itemId}`,])('rejects obsolete typed record item URLs: %s', (path) => {@@ -584,3 +590,69 @@ describe('legacy CRM URLs', () => {expect(url.searchParams.get('s0.crm-record.commentId')).toBe('message');});});++describe('retired Databases links', () => {+ const itemId = '01a1212c-74e5-79bd-8767-0d4943d55b18';+ const redirectOf = (path: string) => {+ const route = decodePane(routes, path.split('/').filter(Boolean));+ if (!route) throw new Error(`${path} does not decode`);+ const to: Entry = { id: 'entry', location: { route } };+ for (const handler of createAppSplitRouterMiddleware({+ isTouchDevice: () => true,+ })) {+ const result = handler({+ routes,+ from: undefined,+ to,+ path,+ cause: 'initial',+ signal: new AbortController().signal,+ redirect: (destination) => ({ type: 'redirect', to: destination }),+ cancel: () => ({ type: 'cancel' }),+ });+ if (result) return result;+ }+ return undefined;+ };++ it.each([+ [+ `/companies/company/${companyId}/databases`,+ `/companies/company/${companyId}`,+ ],+ [+ `/companies/contact/${contactId}/databases`,+ `/companies/contact/${contactId}`,+ ],+ [+ `/companies/pipeline/${pipelineId}/company/${companyId}/databases`,+ `/companies/pipeline/${pipelineId}/company/${companyId}`,+ ],+ [+ `/companies/contact/${contactId}/databases/${itemId}`,+ `/database/${itemId}`,+ ],+ [+ `/companies/pipeline/${pipelineId}/contact/${contactId}/databases/${itemId}`,+ `/database/${itemId}`,+ ],+ [`/companies/database/${itemId}`, `/database/${itemId}`],+ [+ `/companies/pipeline/${pipelineId}/database/${itemId}`,+ `/database/${itemId}`,+ ],+ ])('sends %s to %s', (path, destination) => {+ expect(redirectOf(path)).toEqual({ type: 'redirect', to: destination });+ });++ it('keeps pasted links as mentions of what they open', () => {+ expect(+ resolveMention(appUrl(`/companies/company/${companyId}/databases`))+ ).toEqual({ id: companyId, block: 'company', params: {} });+ expect(resolveMention(appUrl(`/companies/database/${itemId}`))).toEqual({+ id: itemId,+ block: 'database',+ params: {},+ });+ });+});diff --git a/apps/web/src/features/crm/crm-route.ts b/apps/web/src/features/crm/crm-route.tsindex 4c14e521ae..f13c786f9c 100644--- a/apps/web/src/features/crm/crm-route.ts+++ b/apps/web/src/features/crm/crm-route.ts@@ -51,7 +51,7 @@ export type CrmRecordParams = z.infer<typeof crmRecordParams>;/** A CRM-linked item keeps its source record trail and display name in history. */export const crmItemParams = z.object({- itemType: z.enum(['document', 'email', 'call', 'database']),+ itemType: z.enum(['document', 'email', 'call']),itemId: z.string().min(1),itemFileType: z.string().optional(),itemSubType: z.enum(['task', 'snippet', 'skill']).optional(),@@ -63,13 +63,12 @@ const CRM_SECTION_ITEM_TYPES = {tasks: { itemType: 'document', itemFileType: 'md', itemSubType: 'task' },emails: { itemType: 'email' },calls: { itemType: 'call' },- databases: { itemType: 'database' },} as const;/** Typed record sections supply all renderer metadata without extra URL segments. */export const crmRecordItemParams = crmRecordParams.extend({- section: z.enum(['tasks', 'emails', 'calls', 'databases']),+ section: z.enum(['tasks', 'emails', 'calls']),itemId: crmItemParams.shape.itemId,}).transform((params) => ({@@ -122,6 +121,56 @@ export function crmRecordReference({return uuidRouteReference(recordId, recordType);}+export const CRM_RETIRED_DATABASES_ROUTE_IDS = {+ database: 'companies-retired-database',+ pipelineDatabase: 'companies-pipeline-retired-database',+ record: 'companies-retired-record-databases',+ pipelineRecord: 'companies-pipeline-retired-record-databases',+} as const;++export function isCrmRetiredDatabasesRoute(routeId: string) {+ return Object.values<string>(CRM_RETIRED_DATABASES_ROUTE_IDS).includes(+ routeId+ );+}++/** Links to the retired Customers Databases views, kept so they still open. */+export const crmRetiredDatabaseParams = z.object({+ databaseId: z.string().min(1),+});++export const crmRetiredRecordDatabasesParams = z.object({+ recordType: crmRecordParams.shape.recordType,+ recordId: crmRecordParams.shape.recordId,+ databaseId: z.string().min(1).optional(),+});++/**+ * Where a retired Databases link now goes: a database to the database, and a+ * record's Databases section to the record.+ */+export function retiredCrmDatabasesPath({+ pipelineId,+ recordType,+ recordId,+ databaseId,+}: {+ pipelineId?: unknown;+ recordType?: unknown;+ recordId?: unknown;+ databaseId?: unknown;+}): string | undefined {+ if (typeof databaseId === 'string')+ return `/database/${encodeURIComponent(databaseId)}`;+ if (typeof recordType !== 'string' || typeof recordId !== 'string')+ return undefined;+ const source =+ typeof pipelineId === 'string'+ ? `/companies/pipeline/${encodeURIComponent(pipelineId)}`+ : '/companies';+ return `${source}/${recordType}/${encodeURIComponent(recordId)}`;+}+/** A pipeline link references the pipeline, not a place within it. */export function crmPipelineReference(pipelineId: stringdiff --git a/apps/web/src/features/crm/pipeline-adapter.tsx b/apps/web/src/features/crm/pipeline-adapter.tsxindex 407f366035..fb859e5faa 100644--- a/apps/web/src/features/crm/pipeline-adapter.tsx+++ b/apps/web/src/features/crm/pipeline-adapter.tsx@@ -1,3 +1,4 @@+import { t } from '@app/lib/i18n';import { usePreference } from '@app/preferences/use-preference';import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { getPermissions } from '@core/component/SharePermissions';@@ -46,7 +47,7 @@ import { DatabaseRecords } from '../database/views/database-records';import type { DatabaseRecordsActions } from '../database/views/database-records-view';import { CrmListSkeleton } from './components/list-state';import { StageRequirementsDialog } from './components/stage-requirements-dialog';-import type { Pipeline } from './core/pipeline';+import { isTrackedPipeline, type Pipeline } from './core/pipeline';import { createPipelineApi } from './queries/pipeline-data';import {createPipelineViews,@@ -193,7 +194,9 @@ function PipelineRecords(props: {changeView({ query: { ...view().query, filter: null } })}boardPositions={boardPositions}- onComposeRecord={setComposing}+ onComposeRecord={+ isTrackedPipeline(props.pipeline) ? setComposing : undefined+ }renderTextEditor={(editor) => <DatabaseTextEditor {...editor} />}renderTextValue={(value) => <DatabaseTextValue value={value} />}renderMentionPicker={(picker) => (@@ -252,6 +255,8 @@ function PipelineToolbar(props: {props.pipeline.id);const [configuring, setConfiguring] = createSignal(false);+ const tracked = () =>+ isTrackedPipeline(props.pipeline) ? props.pipeline : undefined;const columns = () => database.data.rows.columns();// A column added with a board shows once the table is read again.const refreshColumns = () => {@@ -314,7 +319,16 @@ function PipelineToolbar(props: {}}actions={<>- <Show when={props.canEdit}>+ <Show when={props.canEdit && !tracked()}>+ <Button+ variant="secondary"+ onClick={() => fireAndForget(props.actions.createRecord(), 'crm')}+ >+ <PlusIcon class="size-4" />+ {t('crm.addEntry')}+ </Button>+ </Show>+ <Show when={props.canEdit && tracked()}><Buttonvariant="secondary"disabled={!queryReadyGate(requirements.query)}@@ -341,35 +355,41 @@ function PipelineToolbar(props: {: 'Add contact'}</Button></Show>- <Show when={props.canEdit && props.composing} keyed>- {(initialValues) => (- <AddPipelineRecordDialog- pipeline={props.pipeline}- columns={columns()}- initialValues={initialValues}- requirements={- queryReadyGate(requirements.query)- ? requirements.query.data- : undefined- }- requirementsLoading={requirements.query.isPending}- requirementsError={- !queryReadyGate(requirements.query) &&- requirements.query.isError- }- onCreate={props.actions.createRow}- onClose={() => props.onCompose(undefined)}- renderTextEditor={(editor) => (- <DatabaseTextEditor {...editor} />+ <Show when={tracked()}>+ {(pipeline) => (+ <Show when={props.canEdit && props.composing} keyed>+ {(initialValues) => (+ <AddPipelineRecordDialog+ pipeline={pipeline()}+ columns={columns()}+ initialValues={initialValues}+ requirements={+ queryReadyGate(requirements.query)+ ? requirements.query.data+ : undefined+ }+ requirementsLoading={requirements.query.isPending}+ requirementsError={+ !queryReadyGate(requirements.query) &&+ requirements.query.isError+ }+ onCreate={props.actions.createRow}+ onClose={() => props.onCompose(undefined)}+ renderTextEditor={(editor) => (+ <DatabaseTextEditor {...editor} />+ )}+ renderTextValue={(value) => (+ <DatabaseTextValue value={value} />+ )}+ renderMentionPicker={(picker) => (+ <DatabaseMentionPicker {...picker} />+ )}+ renderMentionValue={(id, entityType) => (+ <DatabaseMentionValue id={id} entityType={entityType} />+ )}+ />)}- renderTextValue={(value) => <DatabaseTextValue value={value} />}- renderMentionPicker={(picker) => (- <DatabaseMentionPicker {...picker} />- )}- renderMentionValue={(id, entityType) => (- <DatabaseMentionValue id={id} entityType={entityType} />- )}- />+ </Show>)}</Show>{props.pipelineActions}diff --git a/apps/web/src/features/crm/primitives/import-companies.ts b/apps/web/src/features/crm/primitives/import-companies.tsindex 8ce8b30312..f103019518 100644--- a/apps/web/src/features/crm/primitives/import-companies.ts+++ b/apps/web/src/features/crm/primitives/import-companies.ts@@ -150,6 +150,8 @@ export function createCompanyImport(try {target ??= await targetPipeline(span, data.name);span.setAttr('crm.pipeline_id', target.id);+ // Only company pipelines are offered as this import's destination.+ if (!target.recordType) return false;const transfer = pipelines.transfer(target);const table = await span.span('crm.pipeline.read_table', () =>transfer.readTable(signal)diff --git a/apps/web/src/features/crm/primitives/pipeline-transfer.test.ts b/apps/web/src/features/crm/primitives/pipeline-transfer.test.tsindex 357a097e5d..f2785cb325 100644--- a/apps/web/src/features/crm/primitives/pipeline-transfer.test.ts+++ b/apps/web/src/features/crm/primitives/pipeline-transfer.test.ts@@ -3,7 +3,7 @@ import { createRoot } from 'solid-js';import { describe, expect, it, vi } from 'vitest';import type { DatabaseViewColumn } from '../../database/core/database-view';import type { PipelineTransfer } from '../context/pipelines';-import type { Pipeline } from '../core/pipeline';+import type { TrackedPipeline } from '../core/pipeline';import {type PipelineCsvRow,PipelineImportRefusal,@@ -13,7 +13,7 @@ import {createPipelineImport,} from './pipeline-transfer';-const pipeline: Pipeline = {+const pipeline: TrackedPipeline = {id: 'pipeline',teamId: 'team',name: 'Q4 Deals',diff --git a/apps/web/src/features/crm/primitives/pipeline-transfer.ts b/apps/web/src/features/crm/primitives/pipeline-transfer.tsindex 61b1b5b39a..a60dedee13 100644--- a/apps/web/src/features/crm/primitives/pipeline-transfer.ts+++ b/apps/web/src/features/crm/primitives/pipeline-transfer.ts@@ -8,7 +8,7 @@ import {} from '../../database/core/csv';import type { DatabaseViewColumn } from '../../database/core/database-view';import type { PipelineTransfer } from '../context/pipelines';-import type { Pipeline } from '../core/pipeline';+import type { Pipeline, TrackedPipeline } from '../core/pipeline';import {encodePipelineCsv,type PipelineCsvRow,@@ -61,7 +61,10 @@ export function createPipelineExport(transfer.readTable(signal));span.setAttr('crm.pipeline.rows', table.rows.length);- const ids = [...recordIds(pipeline(), table.rows)];+ // A generic pipeline's rows name no records to describe.+ const ids = pipeline().recordType+ ? [...recordIds(pipeline(), table.rows)]+ : [];span.setAttr('crm.pipeline.records', ids.length);const records = await span.span('crm.pipeline.describe_records', () =>transfer.describeRecords(ids, signal)@@ -151,7 +154,7 @@ export async function addPipelineRows(input: {* failure adds only what is still missing.*/export function createPipelineImport(- pipeline: Pipeline,+ pipeline: TrackedPipeline,transfer: PipelineTransfer) {const [plan, setPlan] = createSignal<PipelineImportPlan>();diff --git a/apps/web/src/features/crm/queries/activity-filter.ts b/apps/web/src/features/crm/queries/activity-filter.tsindex 5c9403d12d..03d16f2b11 100644--- a/apps/web/src/features/crm/queries/activity-filter.ts+++ b/apps/web/src/features/crm/queries/activity-filter.ts@@ -1,7 +1,7 @@import type { SoupAstBody } from '@queries/soup/items';import { NIL_UUID } from '../../next-soup/filters/filter-store';import type { BackendAstMap } from '../../soup';-import type { CrmSoupActivityTab } from '../core/navigation';+import type { CrmActivityTab } from '../core/navigation';const NO_CRM_ACTIVITY = {calf: { l: { id: NIL_UUID } },@@ -18,7 +18,7 @@ const NO_CRM_ACTIVITY = {/** The server resolves all visible CRM records before filtering and pagination. */export function crmActivityBody(- tab: CrmSoupActivityTab+ tab: CrmActivityTab): BackendAstMap & Pick<SoupAstBody, 'crma' | 'emailView'> {const base = { ...NO_CRM_ACTIVITY, crma: 'activity' as const };if (tab === 'email') {diff --git a/apps/web/src/features/crm/queries/activity-options.ts b/apps/web/src/features/crm/queries/activity-options.tsindex 62dbd28f80..ff2cf738dd 100644--- a/apps/web/src/features/crm/queries/activity-options.ts+++ b/apps/web/src/features/crm/queries/activity-options.ts@@ -14,12 +14,12 @@ import {testFacets,} from '../../soup';import type { CrmActivityViewState } from '../core/activity-view';-import type { CrmSoupActivityTab } from '../core/navigation';+import type { CrmActivityTab } from '../core/navigation';import { crmActivityBody } from './activity-filter';/** Refine, never replace, the fixed CRM and entity-type predicates. */export function buildCrmActivityQuery(- tab: CrmSoupActivityTab,+ tab: CrmActivityTab,options?: CrmActivityViewState,facetContext: TagFacetContext = EMPTY_TAG_FACET_CONTEXT): SoupAstItemsQueryArgs {@@ -42,7 +42,7 @@ export function buildCrmActivityQuery(/** Attachment and audience predicates mirror the ordinary Email and Calls lists. */export function crmActivityItemMatches(entity: EntityData,- tab: CrmSoupActivityTab,+ tab: CrmActivityTab,options: CrmActivityViewState,facetContext: TagFacetContext): boolean {diff --git a/apps/web/src/features/crm/queries/activity.test.ts b/apps/web/src/features/crm/queries/activity.test.tsindex f91471b6da..eb8328afc5 100644--- a/apps/web/src/features/crm/queries/activity.test.ts+++ b/apps/web/src/features/crm/queries/activity.test.ts@@ -7,7 +7,7 @@ import { createRoot, createSignal } from 'solid-js';import { describe, expect, it, vi } from 'vitest';import { EMPTY_TAG_FACET_CONTEXT } from '../../soup';import type { CrmActivityViewState } from '../core/activity-view';-import type { CrmSoupActivityTab } from '../core/navigation';+import type { CrmActivityTab } from '../core/navigation';import { useCrmActivityQuery } from './activity';import { crmActivityBody } from './activity-filter';import {@@ -15,7 +15,7 @@ import {crmActivityItemMatches,} from './activity-options';-const tabs: CrmSoupActivityTab[] = ['tasks', 'notes', 'calls', 'email'];+const tabs: CrmActivityTab[] = ['tasks', 'notes', 'calls', 'email'];describe('CRM activity queries', () => {it.each(tabs)(@@ -58,7 +58,7 @@ describe('CRM activity queries', () => {it('starts with the authenticated viewer and delegates errors, retries, and paging to Soup', () => {createRoot((dispose) => {const [userId, setUserId] = createSignal<string>();- const [tab, setTab] = createSignal<CrmSoupActivityTab>('tasks');+ const [tab, setTab] = createSignal<CrmActivityTab>('tasks');const query: SoupAstItemsQuery = {data: undefined,error: new Error('Request failed'),diff --git a/apps/web/src/features/crm/queries/activity.ts b/apps/web/src/features/crm/queries/activity.tsindex 5ed3fe63e9..ecb0764625 100644--- a/apps/web/src/features/crm/queries/activity.ts+++ b/apps/web/src/features/crm/queries/activity.ts@@ -6,13 +6,13 @@ import {tagFacetReady,} from '../../soup';import type { CrmActivityViewState } from '../core/activity-view';-import type { CrmSoupActivityTab } from '../core/navigation';+import type { CrmActivityTab } from '../core/navigation';import { buildCrmActivityQuery } from './activity-options';/** A bounded query for the complete authorized CRM activity feed. */export function useCrmActivityQuery(createQuery: typeof useSoupAstItemsQuery,- tab: Accessor<CrmSoupActivityTab>,+ tab: Accessor<CrmActivityTab>,userId: Accessor<string | undefined>,options?: Accessor<CrmActivityViewState>,facetContext: Accessor<TagFacetContext> = () => EMPTY_TAG_FACET_CONTEXT,diff --git a/apps/web/src/features/crm/queries/databases.ts b/apps/web/src/features/crm/queries/databases.tsdeleted file mode 100644index 647189ff36..0000000000--- a/apps/web/src/features/crm/queries/databases.ts+++ /dev/null@@ -1,143 +0,0 @@-import { fireAndForget } from '@core/util/fireAndForget';-import type { DatabaseEntity } from '@entity';-import { registerActiveGraphqlSoupQuery } from '@queries/soup/graphql/active-queries';-import type {- createSoupLiveQuery,- SoupLiveQueryInput,-} from '@queries/soup/graphql/create-soup-live-query';-import { buildGraphqlEntitySoupInput } from '@queries/soup/graphql/entity-input';-import type {- onDatabaseBatchCommitted,- onDatabaseTableAdvanced,- useDatabasesQuery,-} from '@queries/storage/databases';-import type { ListedDatabase } from '@service-storage/generated/schemas/listedDatabase';-import type { Accessor } from 'solid-js';-import { createMemo, onCleanup } from 'solid-js';-import { NIL as NIL_UUID } from 'uuid';-import type { ItemListSource } from '../context/crm-sources';-import type { CrmRecordScope } from '../core/record';-import { crmAssociation } from './record-items';--/** Opt into database rows while excluding every other Soup source. */-export function crmDatabasesInput(- scope?: CrmRecordScope-): SoupLiveQueryInput | undefined {- const input = buildGraphqlEntitySoupInput('DATABASE_ROW', NIL_UUID)?.initial;- if (!input) return undefined;- return {- ...input,- limit: 100,- filters: {- ...input.filters,- databaseRowFilter: { literal: { include: true } },- crmAssociation: scope ? crmAssociation(scope) : { activity: true },- },- };-}--/** A database appears once, only after an authorized associated row names it. */-export function selectCrmDatabases(- rows: readonly { databaseId: string }[],- listed: readonly ListedDatabase[]-): DatabaseEntity[] {- const databases = new Map(listed.map((entry) => [entry.database.id, entry]));- return [...new Set(rows.map((row) => row.databaseId))].flatMap((id) => {- const entry = databases.get(id);- if (!entry || entry.database.trashed_at) return [];- return [- {- type: 'database',- id,- name: entry.database.name,- ownerId: entry.database.owner_id,- createdAt: entry.database.created_at,- grant: entry.grant,- },- ];- });-}--/** Reuse Soup's authorization, cursor chain, and CRM-link invalidation. */-export function createCrmDatabasesSource(- sources: {- createRows: typeof createSoupLiveQuery;- createListing: typeof useDatabasesQuery;- onCommitted: typeof onDatabaseBatchCommitted;- onTableAdvanced: typeof onDatabaseTableAdvanced;- },- scope: Accessor<CrmRecordScope | undefined>,- enabled: Accessor<boolean>-): ItemListSource {- const rows = sources.createRows(- () => crmDatabasesInput(scope()),- () => ({- enabled: enabled(),- keepPreviousData: false,- })- );- const listing = sources.createListing();- const refresh = async () => {- await Promise.all([- rows.refresh(),- listing.refetch({ throwOnError: true }),- ]);- };- onCleanup(- registerActiveGraphqlSoupQuery({- isEnabled: enabled,- body: () => {- const current = scope();- return { crma: current ? crmAssociation(current) : 'activity' };- },- refresh,- })- );- const refreshAfterWrite = () => {- if (enabled()) fireAndForget(refresh(), 'crm');- };- onCleanup(sources.onCommitted(refreshAfterWrite));- onCleanup(sources.onTableAdvanced(refreshAfterWrite));- const data = createMemo(() => {- const items = rows.data();- if (listing.isPending || !items) return undefined;- return {- entities: selectCrmDatabases(- items.flatMap((item) =>- item.__typename === 'GraphqlSoupDatabaseRow' ? [item] : []- ),- listing.data ?? []- ),- };- });- return {- get data() {- return data();- },- get isPending() {- return !listing.isError && !rows.error() && data() === undefined;- },- get isEnabled() {- return enabled();- },- get isLoading() {- return rows.isLoading() || listing.isLoading;- },- get isError() {- return (- listing.isError || (!!rows.error() && !rows.isFetchNextPageError())- );- },- get isFetchNextPageError() {- return rows.isFetchNextPageError();- },- get hasNextPage() {- return rows.hasNextPage();- },- get isFetchingNextPage() {- return rows.isFetchingNextPage();- },- fetchNextPage: () => rows.fetchNextPage(),- refetch: refresh,- };-}diff --git a/apps/web/src/features/crm/queries/pipeline-data.ts b/apps/web/src/features/crm/queries/pipeline-data.tsindex 7ef29914cd..ca02ab01b0 100644--- a/apps/web/src/features/crm/queries/pipeline-data.ts+++ b/apps/web/src/features/crm/queries/pipeline-data.ts@@ -63,7 +63,7 @@ export function trackPipelineEntryWrites(return;analytics.track('crm_pipeline_entries_edited', {pipelineId: pipeline.id,- recordType: pipeline.recordType,+ recordType: pipeline.recordType === null ? 'generic' : pipeline.recordType,surface,...counts,});diff --git a/apps/web/src/features/crm/route-adapter.test.tsx b/apps/web/src/features/crm/route-adapter.test.tsxindex e60c8b9aea..d77045bc99 100644--- a/apps/web/src/features/crm/route-adapter.test.tsx+++ b/apps/web/src/features/crm/route-adapter.test.tsx@@ -376,13 +376,13 @@ it('opens a pipeline email at its compact URL and restores it after close', asynit.each([[- '/companies/contact/maya/databases/db-1',+ '/companies/contact/maya/calls/call-2','contact','maya',- 'databases',- 'database',- 'db-1',- '/companies/contact/maya/databases',+ 'calls',+ 'call',+ 'call-2',+ '/companies/contact/maya/calls',],['/companies/pipeline/sales/company/acme/calls/call-1',diff --git a/apps/web/src/features/crm/route-adapter.ts b/apps/web/src/features/crm/route-adapter.tsindex 6734a9142f..8e2cda300c 100644--- a/apps/web/src/features/crm/route-adapter.ts+++ b/apps/web/src/features/crm/route-adapter.ts@@ -207,8 +207,7 @@ export function createCrmRoute(captureEntryState?: () => void): CrmRoute {if (entity.type !== 'document' &&entity.type !== 'email' &&- entity.type !== 'call' &&- entity.type !== 'database'+ entity.type !== 'call')return false;const itemParams: CrmItemParams = {diff --git a/apps/web/src/features/crm/views/activity.tsx b/apps/web/src/features/crm/views/activity.tsxindex 7575affa0a..b08d230a8f 100644--- a/apps/web/src/features/crm/views/activity.tsx+++ b/apps/web/src/features/crm/views/activity.tsx@@ -7,9 +7,8 @@ import { type JSX, Show } from 'solid-js';import { ActivityControls } from '../components/activity-controls';import { CrmListEmpty } from '../components/list-state';import { useCrmContext } from '../context/crm-context';-import type { CrmActivityTab, CrmSoupActivityTab } from '../core/navigation';+import type { CrmActivityTab } from '../core/navigation';import { ActivitySection } from './activity-section';-import { CrmDatabasesView } from './databases';import { RecordItemList } from './record-item-list';const CONTENT = {@@ -42,32 +41,23 @@ export function CrmActivityView(props: {title?: JSX.Element;}) {const crm = useCrmContext();- const tab = () => (props.tab === 'databases' ? undefined : props.tab);return (<Show- when={tab()}+ when={props.tab !== 'tasks' ? props.tab : undefined}keyed- fallback={<CrmDatabasesView title={props.title} />}+ fallback={<crm.ActivityTasks title={props.title} />}>- {(current) => (- <Show- when={current !== 'tasks' ? current : undefined}- keyed- fallback={<crm.ActivityTasks title={props.title} />}- >- {(activity) => (- <TagSetsQueryProvider>- <ActivityList tab={activity} title={props.title} />- </TagSetsQueryProvider>- )}- </Show>+ {(activity) => (+ <TagSetsQueryProvider>+ <ActivityList tab={activity} title={props.title} />+ </TagSetsQueryProvider>)}</Show>);}function ActivityList(props: {- tab: Exclude<CrmSoupActivityTab, 'tasks'>;+ tab: Exclude<CrmActivityTab, 'tasks'>;title?: JSX.Element;}) {const crm = useCrmContext();diff --git a/apps/web/src/features/crm/views/add-pipeline-record.tsx b/apps/web/src/features/crm/views/add-pipeline-record.tsxindex ca891aeae6..57b3462c7c 100644--- a/apps/web/src/features/crm/views/add-pipeline-record.tsx+++ b/apps/web/src/features/crm/views/add-pipeline-record.tsx@@ -35,7 +35,7 @@ import { canEditCell, titleColumn } from '../../database/core/table';import type { RecordCreation } from '../../database/primitives/record-actions';import { CompanySelect } from '../components/company-select';import { RecordSearch } from '../components/record-search';-import type { Pipeline } from '../core/pipeline';+import type { PipelineRecordType, TrackedPipeline } from '../core/pipeline';import {contactCompany,type DomainCompany,@@ -70,7 +70,7 @@ type CellRenderers = Pick</** A form for a whole pipeline row: its company or contact, then every field the pipeline has. */export function AddPipelineRecordDialog(props: CellRenderers & {- pipeline: Pick<Pipeline, 'name' | 'recordType'>;+ pipeline: Pick<TrackedPipeline, 'name' | 'recordType'>;columns: DatabaseViewColumn[];requirements?: StageRequirement[];requirementsLoading?: boolean;@@ -615,7 +615,7 @@ function StackedField(props: {}function PickedRecord(props: {- recordType: Pipeline['recordType'];+ recordType: PipelineRecordType;record: RecordOption;disabled: boolean;onChange: () => void;diff --git a/apps/web/src/features/crm/views/company-detail.tsx b/apps/web/src/features/crm/views/company-detail.tsxindex c36d6ee65e..acf1a3259b 100644--- a/apps/web/src/features/crm/views/company-detail.tsx+++ b/apps/web/src/features/crm/views/company-detail.tsx@@ -19,7 +19,6 @@ import { CompanyPropertiesSection } from './company-properties-section';import { CompanySharingSection } from './company-sharing-section';import {RecordCallsSection,- RecordDatabasesSection,RecordFilesSection,RecordReferencesSection,} from './record-associations';@@ -127,9 +126,6 @@ function CompanyContent(props: CompanyProps) {</Show></Suspense></Match>- <Match when={section() === 'databases'}>- <RecordDatabasesSection scope={scope()} />- </Match><Match when={section() === 'calls'}><RecordCallsSection scope={scope()} /></Match>diff --git a/apps/web/src/features/crm/views/contact-detail.tsx b/apps/web/src/features/crm/views/contact-detail.tsxindex cfad9e3e03..c03d764709 100644--- a/apps/web/src/features/crm/views/contact-detail.tsx+++ b/apps/web/src/features/crm/views/contact-detail.tsx@@ -14,7 +14,6 @@ import { ContactEmailsSection } from './contact-emails-section';import { ContactHeader } from './contact-header';import {RecordCallsSection,- RecordDatabasesSection,RecordFilesSection,RecordReferencesSection,} from './record-associations';@@ -119,9 +118,6 @@ function ContactContent(props: ContactProps) {</Show></Suspense></Match>- <Match when={section() === 'databases'}>- <RecordDatabasesSection scope={scope()} />- </Match><Match when={section() === 'calls'}><RecordCallsSection scope={scope()} /></Match>diff --git a/apps/web/src/features/crm/views/crm-workspace.test.tsx b/apps/web/src/features/crm/views/crm-workspace.test.tsxindex 55f413b458..11ba2024fb 100644--- a/apps/web/src/features/crm/views/crm-workspace.test.tsx+++ b/apps/web/src/features/crm/views/crm-workspace.test.tsx@@ -367,21 +367,13 @@ it('omits pipelines and lists when those features are disabled', () => {const tabs = within(screen.getByRole('navigation', { name: 'CRM views' }));expect(tabs.getAllByRole('button').map((button) => button.textContent)- ).toEqual([- 'Companies',- 'People',- 'Tasks',- 'Email',- 'Notes',- 'Calls',- 'Databases',- ]);+ ).toEqual(['Companies', 'People', 'Tasks', 'Email', 'Notes', 'Calls']);});it('opens each CRM activity feed instead of the company list', () => {const { activeTab } = setup();const tabs = within(screen.getByRole('navigation', { name: 'CRM views' }));- for (const label of ['Tasks', 'Email', 'Notes', 'Calls', 'Databases']) {+ for (const label of ['Tasks', 'Email', 'Notes', 'Calls']) {fireEvent.click(tabs.getByRole('button', { name: label }));expect(activeTab()).toBe(label.toLowerCase());expect(screen.getByText(`${label.toLowerCase()} feed`)).toBeTruthy();diff --git a/apps/web/src/features/crm/views/crm-workspace.tsx b/apps/web/src/features/crm/views/crm-workspace.tsxindex a564d7684a..8e873dde3b 100644--- a/apps/web/src/features/crm/views/crm-workspace.tsx+++ b/apps/web/src/features/crm/views/crm-workspace.tsx@@ -24,10 +24,7 @@ import { useFeatureFlag } from '@app/lib/analytics/posthog';import { usePreference } from '@app/preferences/use-preference';import { HeaderActionGroup } from '@components/app/HeaderActionGroup';import { SplitPanel } from '@components/app/split-panel';-import {- enableCrmActivity,- enableDatabases,-} from '@core/constant/featureFlags';+import { enableCrmActivity } from '@core/constant/featureFlags';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { debounce } from '@core/util/debounce';import { fireAndForget } from '@core/util/fireAndForget';@@ -256,7 +253,6 @@ export function CrmWorkspaceView(props: {}) => JSX.Element;}) {const activityFlag = useFeatureFlag(enableCrmActivity);- const databasesFlag = useFeatureFlag(enableDatabases);const {openCreateCompany: openCreateCompanyModal,openCreateContact: openCreateContactModal,@@ -358,16 +354,10 @@ export function CrmWorkspaceView(props: {const peopleActive = () => active() === 'people';const activityTab = () => {const tab = active();- return activityFlag().enabled &&- (tab !== 'databases' || databasesFlag().enabled) &&- isCrmActivityTab(tab)- ? tab- : undefined;+ return activityFlag().enabled && isCrmActivityTab(tab) ? tab : undefined;};const activityPending = () =>- isCrmActivityTab(active()) &&- (activityFlag().loading ||- (active() === 'databases' && databasesFlag().loading));+ isCrmActivityTab(active()) && activityFlag().loading;const [exporting, setExporting] = createSignal(false);const activeList = () =>lists.lists().find((list) => `list:${list.id}` === active());@@ -419,7 +409,6 @@ export function CrmWorkspaceView(props: {settings.close();if (!listsEnabled() && id.startsWith('list:')) id = 'active';if (!activityFlag().enabled && isCrmActivityTab(id)) id = 'active';- if (id === 'databases' && !databasesFlag().enabled) id = 'active';if (id !== 'people' && !id.startsWith('list:') && !isCrmActivityTab(id))id = 'active';if (id === active()) view.host.record.close();@@ -459,6 +448,8 @@ export function CrmWorkspaceView(props: {};onMount(() => {if (!listsEnabled() && active().startsWith('list:')) navigate('active');+ // Saved and shared links to the retired Databases view open Companies.+ if (active() === 'databases') navigate('active');});const toolbarCreateMenu = () => (<CrmCreateMenu@@ -478,19 +469,9 @@ export function CrmWorkspaceView(props: {// Keep cold activity links intact until PostHog resolves; off falls back to Companies.createEffect(on(- () =>- [- activityPending(),- activityFlag().enabled,- databasesFlag().enabled,- active(),- ] as const,- ([loading, activityEnabled, databasesEnabled, tab]) => {- if (- !loading &&- isCrmActivityTab(tab) &&- (!activityEnabled || (tab === 'databases' && !databasesEnabled))- )+ () => [activityPending(), activityFlag().enabled, active()] as const,+ ([loading, activityEnabled, tab]) => {+ if (!loading && isCrmActivityTab(tab) && !activityEnabled)navigate('active');})diff --git a/apps/web/src/features/crm/views/databases.tsx b/apps/web/src/features/crm/views/databases.tsxdeleted file mode 100644index 8dad6ef111..0000000000--- a/apps/web/src/features/crm/views/databases.tsx+++ /dev/null@@ -1,99 +0,0 @@-import { ListHeader } from '@app/components/view-shell/ListHeader';-import { useFeatureFlag } from '@app/lib/analytics/posthog';-import { enableDatabases } from '@core/constant/featureFlags';-import { isTouchDevice } from '@core/mobile/isTouchDevice';-import EmptyStateDatabaseGraphic from '@design/empty-state-folder.svg';-import { createSignal, type JSX, Show } from 'solid-js';-import { CrmListEmpty, CrmListSkeleton } from '../components/list-state';-import { RecordSection } from '../components/record-section';-import { useCrmContext } from '../context/crm-context';-import type { CrmRecordScope } from '../core/record';-import { ActivitySection } from './activity-section';-import { RecordItemList } from './record-item-list';--/** Lists whole databases discovered through their authorized CRM-linked rows. */-export function CrmDatabasesView(props: {- scope?: CrmRecordScope;- title?: JSX.Element;-}) {- const flag = useFeatureFlag(enableDatabases);- return (- <Show- when={flag().enabled}- fallback={- <div class="flex min-h-0 min-w-0 flex-1 flex-col">- <Show when={!props.scope && !isTouchDevice()}>- <ListHeader title={props.title ?? 'Databases'} />- </Show>- <Show- when={flag().loading}- fallback={- <CrmListEmpty- graphic={EmptyStateDatabaseGraphic}- title="Databases are unavailable"- description="Database access is not enabled for this account."- />- }- >- <CrmListSkeleton label="Loading databases" />- </Show>- </div>- }- >- <DatabasesList scope={props.scope} title={props.title} />- </Show>- );-}--function DatabasesList(props: { scope?: CrmRecordScope; title?: JSX.Element }) {- const crm = useCrmContext();- const source = crm.createDatabases(() => props.scope);- const [search, setSearch] = createSignal('');- const create = () => crm.openCreateItem('databases');- const list = () => (- <RecordItemList- source={source}- search={search()}- onClearSearch={() => setSearch('')}- emptyContent={- <CrmListEmpty- graphic={EmptyStateDatabaseGraphic}- title="No linked databases yet"- description={- props.scope- ? `Databases appear here when a row links to this ${props.scope.type}. Add a company or contact reference to a row to get started.`- : 'Databases appear here when a row links to a CRM company or person. Add a company or contact reference to a row to get started.'- }- action={{ label: 'New database', onClick: create }}- />- }- />- );- return (- <Show- when={props.scope}- fallback={- <ActivitySection- label="Databases"- title={props.title}- search={search()}- onSearchChange={setSearch}- createLabel="New database"- onCreate={create}- >- {list()}- </ActivitySection>- }- >- <RecordSection- title="Databases"- search={search()}- onSearchChange={setSearch}- createAction={{ label: 'New database', onClick: create }}- toolbarCreate- >- {list()}- </RecordSection>- </Show>- );-}diff --git a/apps/web/src/features/crm/views/pipeline-import.tsx b/apps/web/src/features/crm/views/pipeline-import.tsxindex 01c7521b02..7afb31bc21 100644--- a/apps/web/src/features/crm/views/pipeline-import.tsx+++ b/apps/web/src/features/crm/views/pipeline-import.tsx@@ -3,7 +3,7 @@ import { Button, Dialog, Panel } from '@ui';import { Show } from 'solid-js';import { PipelineImportFailures } from '../components/pipeline-import-failures';import type { PipelineTransfer } from '../context/pipelines';-import type { Pipeline } from '../core/pipeline';+import type { TrackedPipeline } from '../core/pipeline';import { pipelineRecordHeaders } from '../core/pipeline-csv';import { createPipelineImport } from '../primitives/pipeline-transfer';@@ -11,7 +11,7 @@ const entries = (count: number) =>`${count.toLocaleString()} ${count === 1 ? 'entry' : 'entries'}`;export function PipelineImport(props: {- pipeline: Pipeline;+ pipeline: TrackedPipeline;transfer: PipelineTransfer;onClose: () => void;}) {diff --git a/apps/web/src/features/crm/views/pipeline.tsx b/apps/web/src/features/crm/views/pipeline.tsxindex efbbc07bd8..5cac8bf404 100644--- a/apps/web/src/features/crm/views/pipeline.tsx+++ b/apps/web/src/features/crm/views/pipeline.tsx@@ -21,7 +21,7 @@ import type {PipelinesSource,PipelineTransfer,} from '../context/pipelines';-import type { Pipeline } from '../core/pipeline';+import { isTrackedPipeline, type Pipeline } from '../core/pipeline';import { createPipelineExport } from '../primitives/pipeline-transfer';import { PipelineImport } from './pipeline-import';@@ -53,6 +53,8 @@ export function PipelineView(props: {let mobileNameInput: HTMLInputElement | undefined;const canEdit = () => ['owner', 'edit'].includes(props.pipeline.grant);const isOwner = () => props.pipeline.grant === 'owner';+ const tracked = () =>+ isTrackedPipeline(props.pipeline) ? props.pipeline : undefined;// A host supplies one transfer for the page's lifetime.const transfer = props.transfer;const exporter =@@ -162,7 +164,7 @@ export function PipelineView(props: {<DownloadIcon class="size-4" />Export CSV</Dropdown.Item>- <Show when={canEdit()}>+ <Show when={canEdit() && tracked()}><Dropdown.Item onSelect={() => setImporting(true)}><UploadIcon class="size-4" />Import CSV@@ -276,7 +278,7 @@ export function PipelineView(props: {<DownloadIcon class="size-4" />Export CSV</Button>- <Show when={canEdit()}>+ <Show when={canEdit() && tracked()}><Buttonvariant="ghost"class="w-full justify-start"@@ -329,11 +331,15 @@ export function PipelineView(props: {</Dialog><Show when={importing() && transfer}>{(current) => (- <PipelineImport- pipeline={props.pipeline}- transfer={current().source}- onClose={() => setImporting(false)}- />+ <Show when={tracked()}>+ {(pipeline) => (+ <PipelineImport+ pipeline={pipeline()}+ transfer={current().source}+ onClose={() => setImporting(false)}+ />+ )}+ </Show>)}</Show><DeleteDialog@@ -343,8 +349,11 @@ export function PipelineView(props: {title="Trash pipeline?"body={<p>- The pipeline and its entries will move to trash. The companies and- contacts remain in your CRM.+ The pipeline and its entries will move to trash.+ <Show when={tracked()}>+ {' '}+ The companies and contacts remain in your CRM.+ </Show></p>}onDelete={() =>diff --git a/apps/web/src/features/crm/views/record-associations.tsx b/apps/web/src/features/crm/views/record-associations.tsxindex 85c683d736..ba3aac6075 100644--- a/apps/web/src/features/crm/views/record-associations.tsx+++ b/apps/web/src/features/crm/views/record-associations.tsx@@ -1,11 +1,10 @@import EmptyStateCallsGraphic from '@design/empty-state-calls.svg';import EmptyStateDocGraphic from '@design/empty-state-doc.svg';-import { createSignal, Show } from 'solid-js';-import { CrmListEmpty, CrmListSkeleton } from '../components/list-state';+import { createSignal } from 'solid-js';+import { CrmListEmpty } from '../components/list-state';import { RecordSection } from '../components/record-section';import { useCrmContext } from '../context/crm-context';import type { CrmRecordScope } from '../core/record';-import { CrmDatabasesView } from './databases';import { RecordItemList } from './record-item-list';/**@@ -86,18 +85,6 @@ export function RecordCallsSection(props: { scope?: CrmRecordScope }) {);}-/** Databases require a loaded record so pending details never request workspace scope. */-export function RecordDatabasesSection(props: { scope?: CrmRecordScope }) {- return (- <Show- when={props.scope}- fallback={<CrmListSkeleton label="Loading databases" />}- >- {(scope) => <CrmDatabasesView scope={scope()} />}- </Show>- );-}-/*** Items of any type associated with the record: what names it in a* Companies or Contacts property and what references it, including through adiff --git a/apps/web/src/lib/analytics/app-events.ts b/apps/web/src/lib/analytics/app-events.tsindex 438706707f..f3cfff8ce7 100644--- a/apps/web/src/lib/analytics/app-events.ts+++ b/apps/web/src/lib/analytics/app-events.ts@@ -379,7 +379,7 @@ export type AppEvents = {*/crm_pipeline_entries_edited: {pipelineId: string;- recordType?: 'company' | 'contact';+ recordType?: 'company' | 'contact' | 'generic';/** The pipeline editor or the record page's pipeline cards. */surface: 'pipeline' | 'record';insertedRows: number;diff --git a/apps/web/src/lib/i18n/locales/en/crm.ts b/apps/web/src/lib/i18n/locales/en/crm.tsindex 5d58cfa7a0..7f43a8ee9b 100644--- a/apps/web/src/lib/i18n/locales/en/crm.ts+++ b/apps/web/src/lib/i18n/locales/en/crm.ts@@ -1,4 +1,10 @@export default {+ pipelineTrack: 'Track',+ pipelineTrackChoice: 'Track {{choice}}',+ pipelineTrackCompanies: 'Companies',+ pipelineTrackContacts: 'Contacts',+ pipelineTrackGeneric: 'Generic',+ addEntry: 'Add entry',customerContact: 'Customer / Contact',searchCustomerContact: 'Search customers and contacts...',noCustomerContactFound: 'No customers or contacts found',diff --git a/apps/web/src/lib/i18n/locales/en/tabs.ts b/apps/web/src/lib/i18n/locales/en/tabs.tsindex 851466ab02..af2453e787 100644--- a/apps/web/src/lib/i18n/locales/en/tabs.ts+++ b/apps/web/src/lib/i18n/locales/en/tabs.ts@@ -19,7 +19,6 @@ export default {'record-files': 'Files','record-tasks': 'Tasks','record-calls': 'Calls',- 'record-databases': 'Databases',// Project sections.projectSections: 'Project sections',diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex 5c200d5c41..2690c83727 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts@@ -85,22 +85,32 @@ export const AddToPipelineResponse = z.object({added: z.array(z.object({entryId: z.string().uuid(),- record: z.object({- id: z.string().uuid(),- name: z.union([z.string(), z.null()]).optional(),- detail: z.union([z.string(), z.null()]).optional(),- }),+ record: z+ .union([+ z.object({+ id: z.string().uuid(),+ name: z.union([z.string(), z.null()]).optional(),+ detail: z.union([z.string(), z.null()]).optional(),+ }),+ z.null(),+ ])+ .optional(),fields: z.record(z.any()),})),alreadyPresent: z.array(z.object({entryId: z.string().uuid(),- record: z.object({- id: z.string().uuid(),- name: z.union([z.string(), z.null()]).optional(),- detail: z.union([z.string(), z.null()]).optional(),- }),+ record: z+ .union([+ z.object({+ id: z.string().uuid(),+ name: z.union([z.string(), z.null()]).optional(),+ detail: z.union([z.string(), z.null()]).optional(),+ }),+ z.null(),+ ])+ .optional(),fields: z.record(z.any()),})),@@ -5247,7 +5257,7 @@ export const ProjectDetails = z.object({export const CreatePipeline = z.object({name: z.string(),- tracks: z.enum(['company', 'contact']),+ tracks: z.union([z.enum(['company', 'contact']), z.null()]).optional(),sharedWithTeam: z.union([z.boolean(), z.null()]).optional(),stages: z.array(z.string()).optional(),fields: z@@ -5275,7 +5285,7 @@ export const CreatePipelineResponse = z.object({pipeline: z.object({id: z.string().uuid(),name: z.string(),- tracks: z.enum(['company', 'contact']),+ tracks: z.union([z.enum(['company', 'contact']), z.null()]).optional(),access: z.any().superRefine((x, ctx) => {const schemas = [z.literal('view'),@@ -7835,7 +7845,7 @@ export const EditPipelineResponse = z.object({pipeline: z.object({id: z.string().uuid(),name: z.string(),- tracks: z.enum(['company', 'contact']),+ tracks: z.union([z.enum(['company', 'contact']), z.null()]).optional(),access: z.any().superRefine((x, ctx) => {const schemas = [z.literal('view'),@@ -10587,11 +10597,16 @@ export const FindPipelineEntriesResponse = z.object({entries: z.array(z.object({entryId: z.string().uuid(),- record: z.object({- id: z.string().uuid(),- name: z.union([z.string(), z.null()]).optional(),- detail: z.union([z.string(), z.null()]).optional(),- }),+ record: z+ .union([+ z.object({+ id: z.string().uuid(),+ name: z.union([z.string(), z.null()]).optional(),+ detail: z.union([z.string(), z.null()]).optional(),+ }),+ z.null(),+ ])+ .optional(),fields: z.record(z.any()),})),@@ -13110,7 +13125,7 @@ export const ListPipelinesResponse = z.object({z.object({id: z.string().uuid(),name: z.string(),- tracks: z.enum(['company', 'contact']),+ tracks: z.union([z.enum(['company', 'contact']), z.null()]).optional(),access: z.any().superRefine((x, ctx) => {const schemas = [z.literal('view'),@@ -17763,11 +17778,16 @@ export const RemoveFromPipelineResponse = z.object({removed: z.array(z.object({entryId: z.string().uuid(),- record: z.object({- id: z.string().uuid(),- name: z.union([z.string(), z.null()]).optional(),- detail: z.union([z.string(), z.null()]).optional(),- }),+ record: z+ .union([+ z.object({+ id: z.string().uuid(),+ name: z.union([z.string(), z.null()]).optional(),+ detail: z.union([z.string(), z.null()]).optional(),+ }),+ z.null(),+ ])+ .optional(),fields: z.record(z.any()),})),@@ -19691,11 +19711,16 @@ export const UpdatePipelineEntriesResponse = z.object({updated: z.array(z.object({entryId: z.string().uuid(),- record: z.object({- id: z.string().uuid(),- name: z.union([z.string(), z.null()]).optional(),- detail: z.union([z.string(), z.null()]).optional(),- }),+ record: z+ .union([+ z.object({+ id: z.string().uuid(),+ name: z.union([z.string(), z.null()]).optional(),+ detail: z.union([z.string(), z.null()]).optional(),+ }),+ z.null(),+ ])+ .optional(),changes: z.array(z.object({ field: z.string(), before: z.any(), after: z.any() })),diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex 839d03d9c4..4347b52ab8 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -5121,7 +5121,7 @@ export interface ToolEventAttendee {isOptional: boolean;}/**- * Add companies or contacts to a CRM pipeline as new deals (entries), optionally setting their stage, owner, revenue or other fields. A company pipeline takes companies and a contact pipeline takes contacts (see ListPipelines' `tracks`). A record already in the pipeline is not added again unless allowDuplicates is true (for a second, separate deal); its existing entry is returned in alreadyPresent instead. Returns the new entries with their entryIds and fields as saved.+ * Add companies or contacts to a CRM pipeline as new deals (entries), optionally setting their stage, owner, revenue or other fields. A company pipeline takes companies and a contact pipeline takes contacts (see ListPipelines' `tracks`); a generic pipeline, with no `tracks`, takes rows that name only their fields. A record already in the pipeline is not added again unless allowDuplicates is true (for a second, separate deal); its existing entry is returned in alreadyPresent instead. Returns the new entries with their entryIds and fields as saved.*/export interface AddToPipeline {/**@@ -5129,7 +5129,7 @@ export interface AddToPipeline {*/pipelineId: string;/**- * The companies or contacts to add, each with its starting fields.+ * The companies or contacts to add, each with its starting fields, or a generic pipeline's new rows.*/entries: ToolNewEntry[];/**@@ -5138,11 +5138,11 @@ export interface AddToPipeline {allowDuplicates?: boolean | null;}/**- * One company or contact to add.+ * One company or contact to add, or one row of a generic pipeline.*/export interface ToolNewEntry {/**- * The CRM company or contact id to add (company ids come from ListCompanies). Give this or email.+ * The CRM company or contact id to add (company ids come from ListCompanies). Give this or email; leave both out in a generic pipeline, which tracks no records.*/recordId?: string | null;/**@@ -5150,7 +5150,7 @@ export interface ToolNewEntry {*/email?: string | null;/**- * Fields to fill in on the new entry, e.g. [{"field": "Stage", "value": "Lead"}, {"field": "Owner", "value": "me"}].+ * Fields to fill in on the new entry, e.g. [{"field": "Stage", "value": "Lead"}, {"field": "Owner", "value": "me"}]. In a generic pipeline, e.g. [{"field": "Name", "value": "Launch site"}].*/set?: ToolFieldValue[];}@@ -5200,7 +5200,10 @@ export interface ToolEntry {* Pass as `entryId`.*/entryId: string;- record: ToolRecord;+ /**+ * The company or contact it tracks; missing in a generic pipeline.+ */+ record?: ToolRecord | null;/*** Its filled-in fields by name: text, a number, true/false, a date, or a* list when a field holds several values. People are macro| user ids.@@ -8247,14 +8250,17 @@ export interface ProjectChannelShare {access: string;}/**- * Create a CRM pipeline: a board of deals that move through stages, such as a sales, renewals, fundraising, hiring or partnership pipeline. Each entry tracks either a company or a contact. Every pipeline starts with the tracked record, Stage, Owner and Revenue fields; Stage starts with the team's default stages unless `stages` gives others. Only when the user asked for a new pipeline: check ListPipelines first so you do not create a duplicate. Returns the pipeline with its id and fields.+ * Create a CRM pipeline: a board of deals that move through stages, such as a sales, renewals, fundraising, hiring or partnership pipeline. Each entry tracks a company or a contact, and the pipeline starts with the tracked record, Stage, Owner and Revenue fields; Stage starts with the team's default stages unless `stages` gives others. Leave out `tracks` for a generic pipeline: a free-form table of entries that needs no company or contact, starting with only a Name field, plus a Stage field when `stages` is given. Only when the user asked for a new pipeline: check ListPipelines first so you do not create a duplicate. Returns the pipeline with its id and fields.*/export interface CreatePipeline {/*** The pipeline's name, e.g. "Q4 Renewals".*/name: string;- tracks: ToolRecordType;+ /**+ * "company" for deals with organizations, "contact" for deals with individual people (candidates, investors, partners). Leave out for a generic pipeline whose entries need no company or contact.+ */+ tracks?: ToolRecordType | null;/*** Let the user's team see and edit it. Defaults to false: only the user can see it.*/@@ -8264,7 +8270,7 @@ export interface CreatePipeline {*/stages?: string[];/**- * Fields to add after Company/Contact, Stage, Owner and Revenue.+ * Fields to add after Company/Contact, Stage, Owner and Revenue, or after a generic pipeline's Name.*/fields?: ToolNewField[];}@@ -8304,14 +8310,19 @@ export interface ToolPipeline {* Its name.*/name: string;- tracks: ToolRecordType;+ /**+ * What each entry tracks: `company` or `contact`. Missing for a generic+ * pipeline, whose entries are free-form rows that track no CRM record.+ */+ tracks?: ToolRecordType | null;access: ToolPipelineAccess;/*** Whether the owner's team may edit it; otherwise it is private.*/sharedWithTeam: boolean;/**- * Its fields in column order; the first names the tracked record.+ * Its fields in column order; the first names the tracked record, or in a+ * generic pipeline the entry itself.*/fields: ToolField[];/**@@ -10020,7 +10031,7 @@ export interface ExportPipelineCsvResponse {summary: string;}/**- * Find deals (entries) in a CRM pipeline: which companies or contacts are in which stage, who owns them, their revenue and other fields. Filter by field values (e.g. Stage is Demo or Trial, Owner is me), by company or contact name/domain/email with `search`, or by record id; sort by any field (Stage sorts in pipeline order). Returns each entry's entryId, the record it tracks (id and name) and its filled-in fields, plus, over every match, the count per stage (and per option of each single-select field) and the total of each number field such as Revenue: use these for questions like "how many deals are in Negotiation" or "what is the pipeline worth". To find where a company or contact is across all pipelines ("what stage is Acme in?"), leave out pipelineId and pass its name as `search` (or its recordIds). Get pipeline ids and field names from ListPipelines.+ * Find deals (entries) in a CRM pipeline: which companies or contacts are in which stage, who owns them, their revenue and other fields. Filter by field values (e.g. Stage is Demo or Trial, Owner is me), by company or contact name/domain/email with `search` (in a generic pipeline, by any text field), or by record id; sort by any field (Stage sorts in pipeline order). Returns each entry's entryId, the record it tracks (id and name) and its filled-in fields, plus, over every match, the count per stage (and per option of each single-select field) and the total of each number field such as Revenue: use these for questions like "how many deals are in Negotiation" or "what is the pipeline worth". To find where a company or contact is across all pipelines ("what stage is Acme in?"), leave out pipelineId and pass its name as `search` (or its recordIds). Get pipeline ids and field names from ListPipelines.*/export interface FindPipelineEntries {/**@@ -12499,7 +12510,7 @@ export interface NotificationItem {senderId?: string | null;}/**- * List the user's CRM pipelines (deal pipelines, sales pipelines, hiring or partner pipelines) with their stages and fields. A pipeline holds entries (deals); each entry tracks one CRM company or contact and has its own fields, such as Stage, Owner and Revenue. Each pipeline lists its id, whether it tracks companies or contacts, the user's access, and its fields in order with their types; a select field lists its options, so Stage lists the pipeline's stages from first to last. Call this first whenever the user talks about deals, a pipeline, a stage, or moving a company or contact along, then use FindPipelineEntries, AddToPipeline and UpdatePipelineEntries with the returned pipelineId and field names. When the user names no pipeline and there is exactly one, use it; when several could match, ask which one.+ * List the user's CRM pipelines (deal pipelines, sales pipelines, hiring or partner pipelines) with their stages and fields. A pipeline holds entries (deals); each entry tracks one CRM company or contact and has its own fields, such as Stage, Owner and Revenue. A generic pipeline has no `tracks`: its entries are free-form rows of fields, with no company or contact. Each pipeline lists its id, whether it tracks companies or contacts, the user's access, and its fields in order with their types; a select field lists its options, so Stage lists the pipeline's stages from first to last. Call this first whenever the user talks about deals, a pipeline, a stage, or moving a company or contact along, then use FindPipelineEntries, AddToPipeline and UpdatePipelineEntries with the returned pipelineId and field names. When the user names no pipeline and there is exactly one, use it; when several could match, ask which one.*/export type ListPipelines = {};/**@@ -16106,7 +16117,10 @@ export interface ToolUpdatedEntry {* The entry.*/entryId: string;- record: ToolRecord;+ /**+ * The company or contact it tracks; missing in a generic pipeline.+ */+ record?: ToolRecord | null;/*** The fields set.*/diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPipeline.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPipeline.tsindex 1dd2212438..1b8ce6c726 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPipeline.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPipeline.ts@@ -4,17 +4,17 @@* document_storage_service* OpenAPI spec version: 0.1.0*/-import type { PipelineRecordType } from './pipelineRecordType';+import type { CreatePipelineRecordType } from './createPipelineRecordType';import type { PipelineSharing } from './pipelineSharing';/**- * Request to create an empty pipeline with the standard CRM columns.+ * Request to create an empty pipeline: the standard CRM columns for a tracked+record, or one Name column, like a new database, for a generic pipeline.*/export interface CreatePipeline {/** Pipeline name. */name: string;- /** Company or contact entries. */- recordType: PipelineRecordType;+ recordType?: CreatePipelineRecordType;/** Defaults to private. */sharing?: PipelineSharing;}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPipelineRecordType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPipelineRecordType.tsnew file mode 100644index 0000000000..674176e280--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPipelineRecordType.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { PipelineRecordType } from './pipelineRecordType';++export type CreatePipelineRecordType = null | PipelineRecordType;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.tsindex 7dd3055bd6..b8fd103464 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts@@ -607,6 +607,7 @@ export * from './createMeetingRequestTitle';export * from './createPairingRequest';export * from './createPairingRequestHost';export * from './createPipeline';+export * from './createPipelineRecordType';export * from './createProjectRequest';export * from './createProjectRequestProjectParentId';export * from './createProjectResponse';@@ -1589,6 +1590,7 @@ export * from './pinnedItem';export * from './pinRequest';export * from './pipeline';export * from './pipelineRecordType';+export * from './pipelineRecordTypeProperty';export * from './pipelineSharing';export * from './pipelineTrashedAt';export * from './postActivityRequest';diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/pipeline.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pipeline.tsindex f50263e78a..b70adbe4b9 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/pipeline.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pipeline.ts@@ -4,7 +4,7 @@* document_storage_service* OpenAPI spec version: 0.1.0*/-import type { PipelineRecordType } from './pipelineRecordType';+import type { PipelineRecordTypeProperty } from './pipelineRecordTypeProperty';import type { PipelineSharing } from './pipelineSharing';import type { PipelineTrashedAt } from './pipelineTrashedAt';@@ -20,10 +20,10 @@ export interface Pipeline {id: string;/** Pipeline display name. */name: string;- /** Protected primary column. */+ /** A tracked pipeline's protected record reference. A generic pipeline's+Name, which names no column once someone deletes it. */primaryColumnId: string;- /** Kind of the primary reference. */- recordType: PipelineRecordType;+ recordType: PipelineRecordTypeProperty;/** Whether the pipeline has a team grant. */sharing: PipelineSharing;/** Table of entries. */diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/pipelineRecordTypeProperty.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pipelineRecordTypeProperty.tsnew file mode 100644index 0000000000..4e653cbdf7--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pipelineRecordTypeProperty.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { PipelineRecordType } from './pipelineRecordType';++export type PipelineRecordTypeProperty = null | PipelineRecordType;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.tsindex c9ac897927..9b8963b03f 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts@@ -5351,12 +5351,19 @@ export const listCrmPipelinesResponseItem = zod.uuid().describe('Entity identity, used with `CrmPipeline` access receipts.'),name: zod.string().describe('Pipeline display name.'),- primaryColumnId: zod.uuid().describe('Protected primary column.'),- recordType: zod- .enum(['company', 'contact'])+ primaryColumnId: zod+ .uuid().describe(- 'Which CRM entity each row references. Fixed when a pipeline is created.'+ "A tracked pipeline's protected record reference. A generic pipeline's\nName, which names no column once someone deletes it."),+ recordType: zod.union([+ zod.null(),+ zod+ .enum(['company', 'contact'])+ .describe(+ 'Which CRM entity each row references. Fixed when a pipeline is created.'+ ),+ ]),sharing: zod.enum(['private', 'team']).describe(@@ -5396,10 +5403,15 @@ export const createCrmPipelineBody = zod.object({name: zod.string().describe('Pipeline name.'),recordType: zod- .enum(['company', 'contact'])- .describe(- 'Which CRM entity each row references. Fixed when a pipeline is created.'- ),+ .union([+ zod.null(),+ zod+ .enum(['company', 'contact'])+ .describe(+ 'Which CRM entity each row references. Fixed when a pipeline is created.'+ ),+ ])+ .optional(),sharing: zod.enum(['private', 'team']).optional()@@ -5408,7 +5420,7 @@ export const createCrmPipelineBody = zod),}).describe(- 'Request to create an empty pipeline with the standard CRM columns.'+ 'Request to create an empty pipeline: the standard CRM columns for a tracked\nrecord, or one Name column, like a new database, for a generic pipeline.');export const createCrmPipelineResponse = zod@@ -5419,12 +5431,19 @@ export const createCrmPipelineResponse = zod.uuid().describe('Entity identity, used with `CrmPipeline` access receipts.'),name: zod.string().describe('Pipeline display name.'),- primaryColumnId: zod.uuid().describe('Protected primary column.'),- recordType: zod- .enum(['company', 'contact'])+ primaryColumnId: zod+ .uuid().describe(- 'Which CRM entity each row references. Fixed when a pipeline is created.'+ "A tracked pipeline's protected record reference. A generic pipeline's\nName, which names no column once someone deletes it."),+ recordType: zod.union([+ zod.null(),+ zod+ .enum(['company', 'contact'])+ .describe(+ 'Which CRM entity each row references. Fixed when a pipeline is created.'+ ),+ ]),sharing: zod.enum(['private', 'team']).describe(@@ -5471,12 +5490,19 @@ export const getCrmPipelineResponse = zod.uuid().describe('Entity identity, used with `CrmPipeline` access receipts.'),name: zod.string().describe('Pipeline display name.'),- primaryColumnId: zod.uuid().describe('Protected primary column.'),- recordType: zod- .enum(['company', 'contact'])+ primaryColumnId: zod+ .uuid().describe(- 'Which CRM entity each row references. Fixed when a pipeline is created.'+ "A tracked pipeline's protected record reference. A generic pipeline's\nName, which names no column once someone deletes it."),+ recordType: zod.union([+ zod.null(),+ zod+ .enum(['company', 'contact'])+ .describe(+ 'Which CRM entity each row references. Fixed when a pipeline is created.'+ ),+ ]),sharing: zod.enum(['private', 'team']).describe(diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex f46e38bf70..0e58ebef6e 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -27585,16 +27585,23 @@},"CreatePipeline": {"type": "object",- "description": "Request to create an empty pipeline with the standard CRM columns.",- "required": ["name", "recordType"],+ "description": "Request to create an empty pipeline: the standard CRM columns for a tracked\nrecord, or one Name column, like a new database, for a generic pipeline.",+ "required": ["name"],"properties": {"name": {"type": "string","description": "Pipeline name."},"recordType": {- "$ref": "#/components/schemas/PipelineRecordType",- "description": "Company or contact entries."+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/PipelineRecordType",+ "description": "Company or contact entries; omitted, a generic pipeline of free-form rows."+ }+ ]},"sharing": {"$ref": "#/components/schemas/PipelineSharing",@@ -39054,11 +39061,18 @@"primaryColumnId": {"type": "string","format": "uuid",- "description": "Protected primary column."+ "description": "A tracked pipeline's protected record reference. A generic pipeline's\nName, which names no column once someone deletes it."},"recordType": {- "$ref": "#/components/schemas/PipelineRecordType",- "description": "Kind of the primary reference."+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/PipelineRecordType",+ "description": "Kind of the primary reference; `None` for a generic pipeline, whose\nprimary column is plain text."+ }+ ]},"sharing": {"$ref": "#/components/schemas/PipelineSharing",diff --git a/apps/web/src/routes/app-router-view.tsx b/apps/web/src/routes/app-router-view.tsxindex c87a0e4cb2..810b35c6bb 100644--- a/apps/web/src/routes/app-router-view.tsx+++ b/apps/web/src/routes/app-router-view.tsx@@ -111,10 +111,14 @@ import {crmPipelineRecordFileItemRoute,crmPipelineRecordItemRoute,crmPipelineRecordRoute,+ crmPipelineRetiredDatabaseRoute,+ crmPipelineRetiredRecordDatabasesRoute,crmPipelineRoute,crmRecordFileItemRoute,crmRecordItemRoute,crmRecordRoute,+ crmRetiredDatabaseRoute,+ crmRetiredRecordDatabasesRoute,debugRoutes,driveCallRoute,driveFolderDocumentRoute,@@ -476,11 +480,15 @@ export function AppRouterView() {<Route definition={crmPipelineRecordRoute} /><Route definition={crmPipelineRecordItemRoute} /><Route definition={crmPipelineRecordFileItemRoute} />+ <Route definition={crmPipelineRetiredDatabaseRoute} />+ <Route definition={crmPipelineRetiredRecordDatabasesRoute} /></Route><Route definition={crmItemRoute} /><Route definition={crmRecordRoute} /><Route definition={crmRecordItemRoute} /><Route definition={crmRecordFileItemRoute} />+ <Route definition={crmRetiredDatabaseRoute} />+ <Route definition={crmRetiredRecordDatabasesRoute} /></Route><Route definition={foldersRoute} component={FoldersRouteView} /><Route definition={searchRoute} component={SearchRouteView} />diff --git a/apps/web/src/routes/routes.ts b/apps/web/src/routes/routes.tsindex 950361f66d..055ee37dfe 100644--- a/apps/web/src/routes/routes.ts+++ b/apps/web/src/routes/routes.ts@@ -11,6 +11,7 @@ import { CALENDAR_VIEW_ID } from '@app/features/calendar-view/types';import { changesSearch } from '@app/features/changes/changes-search';import { mobileSearchRouteStateSchema } from '@app/features/command/mobile/mobile-search-route-state';import {+ CRM_RETIRED_DATABASES_ROUTE_IDS,crmItemBlockType,crmItemParams,crmItemStateSchema,@@ -22,6 +23,8 @@ import {crmRecordParams,crmRecordReference,crmRecordTrailSchema,+ crmRetiredDatabaseParams,+ crmRetiredRecordDatabasesParams,crmViewReference,} from '@app/features/crm/crm-route';import { driveDetailTrailSchema } from '@app/features/drive-view/primitives/drive-detail-trail';@@ -767,6 +770,35 @@ export const crmPipelineRecordFileItemRoute = defineRoute({id: 'companies-pipeline-record-file-item',});+/** A database opened from the retired Customers Databases view; redirects to it. */+export const crmRetiredDatabaseRoute = defineRoute({+ id: CRM_RETIRED_DATABASES_ROUTE_IDS.database,+ path: 'database/:databaseId',+ params: crmRetiredDatabaseParams,+ toReference: ({ databaseId }) => uuidRouteReference(databaseId, 'database'),+});++export const crmPipelineRetiredDatabaseRoute = defineRoute({+ ...crmRetiredDatabaseRoute,+ id: CRM_RETIRED_DATABASES_ROUTE_IDS.pipelineDatabase,+});++/** A record's retired Databases section, or a database opened from it; redirects. */+export const crmRetiredRecordDatabasesRoute = defineRoute({+ id: CRM_RETIRED_DATABASES_ROUTE_IDS.record,+ path: ':recordType/:recordId/databases/:databaseId?',+ params: crmRetiredRecordDatabasesParams,+ toReference: ({ recordType, recordId, databaseId }) =>+ databaseId+ ? uuidRouteReference(databaseId, 'database')+ : uuidRouteReference(recordId, recordType),+});++export const crmPipelineRetiredRecordDatabasesRoute = defineRoute({+ ...crmRetiredRecordDatabasesRoute,+ id: CRM_RETIRED_DATABASES_ROUTE_IDS.pipelineRecord,+});+export const crmPipelineRoute = defineRoute({id: 'companies-pipeline',path: 'pipeline/:pipelineId',diff --git a/crates/crm/AGENTS.md b/crates/crm/AGENTS.mdindex 325a017f94..baac27ecc2 100644--- a/crates/crm/AGENTS.md+++ b/crates/crm/AGENTS.md@@ -64,6 +64,11 @@ tools/HTTP/GraphQL surfaces over them.## Gotchas+- A generic pipeline has `record_type: None` and an unprotected primary column,+ which can change type or be deleted, leaving `primary_column_id` naming no+ column. Don't pass one to `referencing_rows`: its SQL reads primary cells as+ reference arrays. Don't add `ON DELETE` actions touching the pipeline row: they+ wait on the row lock the write guard holds, and the request hangs.- Pipeline board-position reads require a pipeline View receipt, hold its livelifecycle guard, and scope the view to its backing table/database through`DatabaseStorage::storage_view_positions`.diff --git a/crates/crm/src/domain/crm_transfer.rs b/crates/crm/src/domain/crm_transfer.rsindex 49fbc838dc..95b9e6741b 100644--- a/crates/crm/src/domain/crm_transfer.rs+++ b/crates/crm/src/domain/crm_transfer.rs@@ -114,6 +114,17 @@ fn email_domain(email: &str) -> Option<&str> {email.split_once('@').map(|(_, domain)| domain)}+/// What an import resolves its rows to; a generic pipeline tracks nothing.+fn tracked_record_type(overview: &PipelineOverview) -> Result<PipelineRecordType, TransferError> {+ let pipeline = &overview.pipeline.pipeline;+ pipeline.record_type.ok_or_else(|| {+ TransferError::Invalid(format!(+ "\"{}\" tracks no companies or contacts, so it takes no CSV import. Add its entries with AddToPipeline.",+ pipeline.name+ ))+ })+}+/// The headers that name a record, so are never matched to a field.fn record_headers(record_type: PipelineRecordType) -> [&'static str; 2] {match record_type {@@ -429,7 +440,7 @@ wheredomains: &SharedDomains,) -> Result<PipelineImportOutcome, TransferError> {let pipeline = &overview.pipeline.pipeline;- let record_type = pipeline.record_type;+ let record_type = tracked_record_type(overview)?;let reserved = record_headers(record_type);let mut fields: Vec<(String, &PipelineField)> = Vec::new();let mut ignored_columns = Vec::new();@@ -464,7 +475,8 @@ where.await?.into_iter().filter(|found| found.pipeline.pipeline.id == pipeline.id)- .flat_map(|found| found.entries.into_iter().map(|entry| entry.record.id))+ .flat_map(|found| found.entries)+ .filter_map(|entry| entry.record.map(|record| record.id)).collect()};@@ -490,7 +502,7 @@ where}).collect();additions.push(EntryAddition {- record: RecordTarget::Id(id),+ record: Some(RecordTarget::Id(id)),set,});keys.push(row.key.clone());@@ -615,9 +627,9 @@ where}) {PipelineDestination::Existing(id) => {let overview = self.pipeline(viewer, id).await?;- if overview.pipeline.pipeline.record_type != PipelineRecordType::Company {+ if overview.pipeline.pipeline.record_type != Some(PipelineRecordType::Company) {return Err(TransferError::Invalid(format!(- "\"{}\" tracks contacts; choose a company pipeline for Stage, Owner and Revenue.",+ "\"{}\" does not track companies; choose a company pipeline for Stage, Owner and Revenue.",overview.pipeline.pipeline.name)));}@@ -632,7 +644,7 @@ where.or(file_name).filter(|name| !name.trim().is_empty()).unwrap_or_else(|| DEFAULT_PIPELINE_NAME.to_owned()),- record_type: PipelineRecordType::Company,+ record_type: Some(PipelineRecordType::Company),sharing,stages: Vec::new(),fields: Vec::new(),@@ -674,8 +686,9 @@ wherecsv: CsvInput,) -> Result<PipelineImportOutcome, TransferError> {let overview = self.pipeline(viewer, pipeline).await?;+ let record_type = tracked_record_type(&overview)?;let (table, _) = self.read(viewer, csv).await?;- let parsed = record_rows(&table, overview.pipeline.pipeline.record_type)?;+ let parsed = record_rows(&table, record_type)?;if parsed.rows.is_empty() {return Err(TransferError::Invalid("No rows name a company by domain or a contact by email.".into(),@@ -717,29 +730,36 @@ where.iter().filter(|field| !field.is_record()).collect();- let headers: Vec<String> = record_headers(overview.pipeline.pipeline.record_type)- .iter()- .map(|header| (*header).to_owned())+ let record_type = overview.pipeline.pipeline.record_type;+ let headers: Vec<String> = record_type+ .map(record_headers)+ .into_iter()+ .flatten()+ .map(str::to_owned).chain(fields.iter().map(|field| field.name.clone())).collect();let rows: Vec<Vec<String>> = found.entries.iter().map(|entry| {- [- entry.record.name.clone().unwrap_or_default(),- entry.record.detail.clone().unwrap_or_default(),- ]- .into_iter()- .chain(fields.iter().map(|field| {- entry- .fields- .iter()- .find(|(name, _)| name == &field.name)- .map(|(_, value)| exported_value(value))- .unwrap_or_default()- }))- .collect()+ entry+ .record+ .iter()+ .flat_map(|record| {+ [+ record.name.clone().unwrap_or_default(),+ record.detail.clone().unwrap_or_default(),+ ]+ })+ .chain(fields.iter().map(|field| {+ entry+ .fields+ .iter()+ .find(|(name, _)| name == &field.name)+ .map(|(_, value)| exported_value(value))+ .unwrap_or_default()+ }))+ .collect()}).collect();let file_name = overview.pipeline.pipeline.name.clone();diff --git a/crates/crm/src/domain/crm_transfer/test.rs b/crates/crm/src/domain/crm_transfer/test.rsindex 5bb0060c75..f244608f07 100644--- a/crates/crm/src/domain/crm_transfer/test.rs+++ b/crates/crm/src/domain/crm_transfer/test.rs@@ -44,7 +44,7 @@ fn overview(record_type: PipelineRecordType) -> PipelineOverview {team_id: Uuid::now_v7(),user_id: "macro|[email protected]".into(),name: "Deals".into(),- record_type,+ record_type: Some(record_type),database_id: DatabaseId::new(),table_id: TableId::new(),primary_column_id: ColumnId::new(),@@ -74,11 +74,11 @@ fn overview(record_type: PipelineRecordType) -> PipelineOverview {fn entry(id: Uuid) -> PipelineEntryView {PipelineEntryView {entry_id: RowId::new(),- record: PipelineRecord {+ record: Some(PipelineRecord {id,name: None,detail: None,- },+ }),fields: Vec::new(),}}@@ -177,8 +177,8 @@ impl PipelineWorkflowService for Workflows {let added = additions.iter().map(|addition| match addition.record {- RecordTarget::Id(id) => entry(id),- RecordTarget::Email(_) => unreachable!("imports add records by id"),+ Some(RecordTarget::Id(id)) => entry(id),+ _ => unreachable!("imports add records by id"),}).collect();self.added.lock().unwrap().extend(additions);@@ -367,12 +367,12 @@ async fn a_companies_export_restores_stage_and_owner_on_a_new_private_pipeline()[("Stage".to_owned(), vec!["Churned".to_owned()])]);let added = service.workflows.added.lock().unwrap();- assert_eq!(added[0].record, RecordTarget::Id(acme));+ assert_eq!(added[0].record, Some(RecordTarget::Id(acme)));assert_eq!(added[0].set,[("Stage".to_owned(), FieldInput::One("Lead".into()))]);- assert_eq!(added[1].record, RecordTarget::Id(id_of("beta.io")));+ assert_eq!(added[1].record, Some(RecordTarget::Id(id_of("beta.io"))));assert_eq!(added[1].set,[@@ -531,10 +531,13 @@ async fn ambiguous_contacts_are_unresolved_without_blocking_other_csv_rows() {[(id_of("new.example.com"), "[email protected]".into())]);let added = service.workflows.added.lock().unwrap();- assert_eq!(added[0].record, RecordTarget::Id(known));+ assert_eq!(added[0].record, Some(RecordTarget::Id(known)));assert_eq!(added[1].record,- RecordTarget::Id(Uuid::new_v5(&Uuid::NAMESPACE_OID, b"[email protected]"))+ Some(RecordTarget::Id(Uuid::new_v5(+ &Uuid::NAMESPACE_OID,+ b"[email protected]"+ ))));}@@ -577,11 +580,11 @@ async fn an_export_writes_people_as_emails_and_reimports() {let mut workflows = Workflows::new(overview(PipelineRecordType::Company));workflows.exported = vec![PipelineEntryView {entry_id: RowId::new(),- record: PipelineRecord {+ record: Some(PipelineRecord {id: Uuid::now_v7(),name: Some("=Acme".into()),detail: Some("acme.com".into()),- },+ }),fields: vec![("Stage".into(), FieldValue::Labels(vec!["Lead".into()])),(@@ -606,3 +609,33 @@ async fn an_export_writes_people_as_emails_and_reimports() {let rows = record_rows(&table, PipelineRecordType::Company).unwrap();assert_eq!(rows.rows[0].name, "=Acme");}++#[tokio::test]+async fn a_generic_pipeline_exports_its_fields_and_refuses_a_record_import() {+ let mut generic = overview(PipelineRecordType::Company);+ generic.pipeline.pipeline.record_type = None;+ generic.fields = vec![field("Name", FieldKind::Text)];+ let id = generic.pipeline.pipeline.id;+ let mut workflows = Workflows::new(generic);+ workflows.exported = vec![PipelineEntryView {+ entry_id: RowId::new(),+ record: None,+ fields: vec![("Name".into(), FieldValue::Text("Launch site".into()))],+ }];+ let service =+ CrmTransferServiceImpl::new(Arc::new(workflows), Records::default(), Files::default());++ let refused = service+ .import_to_pipeline(&viewer(), id, CsvInput::Text("Name\nLaunch site\n".into()))+ .await;+ assert!(matches!(refused, Err(TransferError::Invalid(_))));+ assert!(service.workflows.added.lock().unwrap().is_empty());++ service.export_pipeline(&viewer(), id).await.unwrap();+ let saved = service.files.saved.lock().unwrap();+ let (_, csv) = saved.last().unwrap();+ assert_eq!(+ csv.trim_start_matches('\u{feff}').trim(),+ "Name\nLaunch site"+ );+}diff --git a/crates/crm/src/domain/pipeline_workflows.rs b/crates/crm/src/domain/pipeline_workflows.rsindex c65b0f7149..431cbdca69 100644--- a/crates/crm/src/domain/pipeline_workflows.rs+++ b/crates/crm/src/domain/pipeline_workflows.rs@@ -1,5 +1,6 @@//! Pipeline use cases addressed the way people talk about a pipeline: entries-//! by the company or contact they track, fields by name, stages by label.+//! by the company or contact they track, fields by name, stages by label. A+//! generic pipeline tracks no record, so its entries are addressed by id.//!//! Each workflow resolves those names against the pipeline's current schema,//! then reads and writes through [`PipelineService`], so the pipeline's@@ -47,7 +48,9 @@ pub use models::{};pub use records::PipelineRecord;-use entries::{entry_view, field_values, option_counts, record_id, totals, value_of};+use entries::{+ entry_view, field_values, matches_search, option_counts, record_id, totals, value_of,+};use ops::{STAGE_FIELD, add_field, add_options, cells, select_field};/// Pipeline workflows for a viewer, who may be an agent acting for a user.@@ -66,9 +69,9 @@ pub trait PipelineWorkflowService: Send + Sync + 'static {query: EntryQuery,) -> impl Future<Output = Result<FoundEntries, WorkflowError>> + Send;- /// Entries of every pipeline the viewer can see whose company or contact- /// matches `search`, at most `limit` per pipeline; pipelines without a- /// match are left out.+ /// Entries of every pipeline the viewer can see whose company or contact,+ /// or in a generic pipeline text field, matches `search`, at most `limit`+ /// per pipeline; pipelines without a match are left out.fn search_entries(&self,viewer: &Viewer,@@ -84,7 +87,8 @@ pub trait PipelineWorkflowService: Send + Sync + 'static {) -> impl Future<Output = Result<Vec<RecordEntries>, WorkflowError>> + Send;/// Add entries; a record already in the pipeline is added again only- /// when `allow_duplicates`.+ /// when `allow_duplicates`. A generic pipeline's entries name no record,+ /// so each is a new row.fn add(&self,viewer: &Viewer,@@ -202,7 +206,12 @@ whereoverview: &PipelineOverview,rows: &[&StorageRow],) -> Result<HashMap<Uuid, PipelineRecord>, WorkflowError> {- let record_field = overview.record_field();+ let (Some(record_type), Some(record_field)) = (+ overview.pipeline.pipeline.record_type,+ overview.record_field(),+ ) else {+ return Ok(HashMap::new());+ };let ids: Vec<Uuid> = rows.iter().filter_map(|row| record_id(row.cells.get(&record_field.id)))@@ -213,7 +222,7 @@ whereself.crm.as_ref(),team,viewer.user_id.as_ref(),- overview.pipeline.pipeline.record_type,+ record_type,&ids,).await?)@@ -290,6 +299,127 @@ where.collect()}+ /// The rows `additions` insert into a tracked pipeline, and the entries of+ /// records already in it that are not added again.+ #[expect(+ clippy::too_many_arguments,+ reason = "one private step of `add`, sharing what it has already read"+ )]+ async fn tracked_inserts(+ &self,+ viewer: &Viewer,+ view: &EntityAccessReceipt<ViewAccessLevel>,+ overview: &PipelineOverview,+ record_type: PipelineRecordType,+ team: Option<&CrmTeamReceipt<MemberTeamRole>>,+ additions: Vec<EntryAddition>,+ allow_duplicates: bool,+ ) -> Result<(Vec<Vec<CellWrite>>, Vec<RowId>), WorkflowError> {+ let record_field = overview+ .record_field()+ .ok_or_else(|| {+ WorkflowError::Invalid(format!(+ "Pipeline \"{}\" has lost its record field.",+ overview.pipeline.pipeline.name+ ))+ })?+ .id;+ let mut resolved = Vec::with_capacity(additions.len());+ for addition in additions {+ let id = match &addition.record {+ None => {+ return Err(WorkflowError::Invalid(+ "Give each entry exactly one of recordId or email.".into(),+ ));+ }+ Some(RecordTarget::Id(id)) => *id,+ Some(RecordTarget::Email(email)) => {+ let team = team.ok_or(WorkflowError::NoTeam)?;+ let contact = self+ .crm+ .get_contact_by_email(team, email)+ .await?+ .ok_or_else(|| {+ WorkflowError::Invalid(format!(+ "No contact in the team's CRM has the email {email}."+ ))+ })?;+ match record_type {+ PipelineRecordType::Company => contact.company_id.ok_or_else(|| {+ WorkflowError::Invalid(format!(+ "The contact with the email {email} has no company."+ ))+ })?,+ PipelineRecordType::Contact => contact.id,+ }+ }+ };+ self.access+ .generate_entity_access_receipt::<ViewAccessLevel>(+ &viewer.user_id,+ None,+ &id.to_string(),+ match record_type {+ PipelineRecordType::Company => EntityType::CrmCompany,+ PipelineRecordType::Contact => EntityType::CrmContact,+ },+ )+ .await+ .map_err(|error| match error {+ AccessError::NotFound(_)+ | AccessError::Unauthorized+ | AccessError::UnauthorizedWithMessage(_)+ | AccessError::BadRequest(_) => WorkflowError::Invalid(match record_type {+ PipelineRecordType::Company => format!(+ "{id} is not a CRM company the user can see. Find company ids with \+ ListCompanies, or add a company by one of its contacts' email."+ ),+ PipelineRecordType::Contact => format!(+ "{id} is not a CRM contact the user can see. Add a contact by its \+ email address."+ ),+ }),+ other => other.into(),+ })?;+ let cells = cells(overview, &addition.set, viewer)?;+ resolved.push((id, cells));+ }++ let ids: Vec<Uuid> = resolved.iter().map(|(id, _)| *id).collect();+ let mut present: HashMap<Uuid, RowId> = HashMap::new();+ for reference in self.pipelines.record_rows(view.clone(), &ids).await? {+ present+ .entry(reference.record_id)+ .or_insert(reference.row_id);+ }+ let mut seen = HashSet::new();+ let mut already = Vec::new();+ let mut inserts = Vec::new();+ for (id, mut cells) in resolved {+ if !allow_duplicates {+ if !seen.insert(id) {+ continue;+ }+ if let Some(row) = present.get(&id) {+ already.push(*row);+ continue;+ }+ }+ cells.insert(+ 0,+ CellWrite {+ column: record_field,+ value: CellValue::Entities(vec![EntityRef {+ entity_type: record_type.entity_kind(),+ entity_id: id.to_string(),+ }]),+ },+ );+ inserts.push(cells);+ }+ Ok((inserts, already))+ }+/// Apply `ops` as the viewer, with the table's version after the write.async fn apply(&self,@@ -319,6 +449,28 @@ where}}+/// The rows `additions` insert into a generic pipeline: free-form, so each+/// names only its fields and is always a new row.+fn generic_inserts(+ overview: &PipelineOverview,+ additions: &[EntryAddition],+ viewer: &Viewer,+) -> Result<Vec<Vec<CellWrite>>, WorkflowError> {+ let name = &overview.pipeline.pipeline.name;+ additions+ .iter()+ .map(|addition| {+ if addition.record.is_some() {+ return Err(WorkflowError::Invalid(format!(+ "Pipeline \"{name}\" tracks no companies or contacts. Leave out recordId and \+ email, and fill in its fields with `set`."+ )));+ }+ cells(overview, &addition.set, viewer)+ })+ .collect()+}+impl<Pipelines, Crm, Access> PipelineWorkflowServicefor PipelineWorkflowServiceImpl<Pipelines, Crm, Access>where@@ -367,11 +519,11 @@ where.transpose()?;let (rows, complete) = self.scan(&receipt).await?;- let record_field = overview.record_field();+ let record_field = overview.record_field().map(|field| field.id);let wanted_records: HashSet<Uuid> = query.records.iter().copied().collect();let mut matched = Vec::new();for row in &rows {- let tracked = record_id(row.cells.get(&record_field.id));+ let tracked = record_field.and_then(|id| record_id(row.cells.get(&id)));if !wanted_records.is_empty() && !tracked.is_some_and(|id| wanted_records.contains(&id)){continue;@@ -401,7 +553,7 @@ wherequery.search.as_deref()- .is_none_or(|search| entry.record.matches(search))+ .is_none_or(|search| matches_search(entry, search))}).collect();let counts = option_counts(&overview, &entries);@@ -486,10 +638,12 @@ where.collect();let view = PipelineEntryView {entry_id: entry.row_id,- record: named- .get(&entry.record_id)- .cloned()- .unwrap_or_else(|| PipelineRecord::unnamed(entry.record_id)),+ record: Some(+ named+ .get(&entry.record_id)+ .cloned()+ .unwrap_or_else(|| PipelineRecord::unnamed(entry.record_id)),+ ),fields: field_values(&fields, &entry.cells),};match found@@ -517,103 +671,28 @@ where) -> Result<AddedEntries, WorkflowError> {if additions.is_empty() {return Err(WorkflowError::Invalid(- "Name at least one company or contact to add.".into(),+ "Name at least one entry to add.".into(),));}let receipt = self.receipt::<EditAccessLevel>(viewer, pipeline).await?;let view = receipt.clone().try_into_requirement::<ViewAccessLevel>()?;let overview = self.overview(&view).await?;- let record_type = overview.pipeline.pipeline.record_type;let team = self.team(viewer).await?;-- let mut resolved = Vec::with_capacity(additions.len());- for addition in additions {- let id = match &addition.record {- RecordTarget::Id(id) => *id,- RecordTarget::Email(email) => {- let team = team.as_ref().ok_or(WorkflowError::NoTeam)?;- let contact = self- .crm- .get_contact_by_email(team, email)- .await?- .ok_or_else(|| {- WorkflowError::Invalid(format!(- "No contact in the team's CRM has the email {email}."- ))- })?;- match record_type {- PipelineRecordType::Company => contact.company_id.ok_or_else(|| {- WorkflowError::Invalid(format!(- "The contact with the email {email} has no company."- ))- })?,- PipelineRecordType::Contact => contact.id,- }- }- };- self.access- .generate_entity_access_receipt::<ViewAccessLevel>(- &viewer.user_id,- None,- &id.to_string(),- match record_type {- PipelineRecordType::Company => EntityType::CrmCompany,- PipelineRecordType::Contact => EntityType::CrmContact,- },+ let (inserts, already) = match overview.pipeline.pipeline.record_type {+ Some(record_type) => {+ self.tracked_inserts(+ viewer,+ &view,+ &overview,+ record_type,+ team.as_ref(),+ additions,+ allow_duplicates,)- .await- .map_err(|error| match error {- AccessError::NotFound(_)- | AccessError::Unauthorized- | AccessError::UnauthorizedWithMessage(_)- | AccessError::BadRequest(_) => WorkflowError::Invalid(match record_type {- PipelineRecordType::Company => format!(- "{id} is not a CRM company the user can see. Find company ids with \- ListCompanies, or add a company by one of its contacts' email."- ),- PipelineRecordType::Contact => format!(- "{id} is not a CRM contact the user can see. Add a contact by its \- email address."- ),- }),- other => other.into(),- })?;- let cells = cells(&overview, &addition.set, viewer)?;- resolved.push((id, cells));- }-- let ids: Vec<Uuid> = resolved.iter().map(|(id, _)| *id).collect();- let mut present: HashMap<Uuid, RowId> = HashMap::new();- for reference in self.pipelines.record_rows(view.clone(), &ids).await? {- present- .entry(reference.record_id)- .or_insert(reference.row_id);- }- let mut seen = HashSet::new();- let mut already = Vec::new();- let mut inserts = Vec::new();- for (id, mut cells) in resolved {- if !allow_duplicates {- if !seen.insert(id) {- continue;- }- if let Some(row) = present.get(&id) {- already.push(*row);- continue;- }+ .await?}- cells.insert(- 0,- CellWrite {- column: overview.record_field().id,- value: CellValue::Entities(vec![EntityRef {- entity_type: overview.record_kind(),- entity_id: id.to_string(),- }]),- },- );- inserts.push(cells);- }+ None => (generic_inserts(&overview, &additions, viewer)?, Vec::new()),+ };let (added, version) = if inserts.is_empty() {(Vec::new(), None)@@ -729,14 +808,16 @@ where.unwrap_or_default()};let (old, new) = (cells_of(&before), cells_of(&after));- let record = record_id(new.get(&overview.record_field().id))- .map(|id| {- records- .get(&id)- .cloned()- .unwrap_or_else(|| PipelineRecord::unnamed(id))- })- .unwrap_or_else(|| PipelineRecord::unnamed(Uuid::nil()));+ let record = overview.record_field().map(|field| {+ record_id(new.get(&field.id))+ .map(|id| {+ records+ .get(&id)+ .cloned()+ .unwrap_or_else(|| PipelineRecord::unnamed(id))+ })+ .unwrap_or_else(|| PipelineRecord::unnamed(Uuid::nil()))+ });let changes = update.set.iter()@@ -829,7 +910,16 @@ wherereturn Ok(overview);}let mut ops = Vec::new();- if !input.stages.is_empty() {+ if !input.stages.is_empty() && input.record_type.is_none() {+ ops.push(add_field(+ &overview,+ &NewField {+ name: STAGE_FIELD.to_owned(),+ kind: NewFieldKind::Select,+ options: input.stages.clone(),+ },+ )?);+ } else if !input.stages.is_empty() {let stage = overview.field(STAGE_FIELD)?;ops.extend(stage.options.iter().map(|(option, _)| DatabaseOp::Column {table: overview.pipeline.pipeline.table_id,diff --git a/crates/crm/src/domain/pipeline_workflows/entries.rs b/crates/crm/src/domain/pipeline_workflows/entries.rsindex 33eef7416a..aa9065de57 100644--- a/crates/crm/src/domain/pipeline_workflows/entries.rs+++ b/crates/crm/src/domain/pipeline_workflows/entries.rs@@ -1,4 +1,4 @@-//! Entries as read back: the record each tracks, its fields by name, and the+//! Entries as read back: the record each tracks, if any, its fields by name, and the//! counts and totals over a set of them.use std::collections::{BTreeMap, HashMap};@@ -43,14 +43,16 @@ pub(super) fn entry_view(row: &StorageRow,records: &HashMap<Uuid, PipelineRecord>,) -> PipelineEntryView {- let record = record_id(row.cells.get(&overview.record_field().id))- .map(|id| {- records- .get(&id)- .cloned()- .unwrap_or_else(|| PipelineRecord::unnamed(id))- })- .unwrap_or_else(|| PipelineRecord::unnamed(Uuid::nil()));+ let record = overview.record_field().map(|field| {+ record_id(row.cells.get(&field.id))+ .map(|id| {+ records+ .get(&id)+ .cloned()+ .unwrap_or_else(|| PipelineRecord::unnamed(id))+ })+ .unwrap_or_else(|| PipelineRecord::unnamed(Uuid::nil()))+ });PipelineEntryView {entry_id: row.row_id,record,@@ -58,6 +60,20 @@ pub(super) fn entry_view(}}+/// Whether `entry` is what `search` looks for: the record it tracks, or in a+/// generic pipeline one of its text fields.+pub(super) fn matches_search(entry: &PipelineEntryView, search: &str) -> bool {+ match &entry.record {+ Some(record) => record.matches(search),+ None => {+ let search = search.trim().to_lowercase();+ entry.fields.iter().any(|(_, value)| {+ matches!(value, FieldValue::Text(text) if text.to_lowercase().contains(&search))+ })+ }+ }+}+pub(super) fn value_of<'a>(entry: &'a PipelineEntryView, field: &str) -> Option<&'a FieldValue> {entry.fieldsdiff --git a/crates/crm/src/domain/pipeline_workflows/fields.rs b/crates/crm/src/domain/pipeline_workflows/fields.rsindex 9b5ed5af10..70b2e950af 100644--- a/crates/crm/src/domain/pipeline_workflows/fields.rs+++ b/crates/crm/src/domain/pipeline_workflows/fields.rs@@ -72,8 +72,11 @@ pub struct PipelineField {impl PipelineField {/// The field `column` of `pipeline`.pub(crate) fn new(column: &ColumnDetail, pipeline: &Pipeline) -> Self {- let kind = if column.column.id == pipeline.primary_column_id {- FieldKind::Record(pipeline.record_type)+ let tracked = pipeline+ .record_type+ .filter(|_| column.column.id == pipeline.primary_column_id);+ let kind = if let Some(record_type) = tracked {+ FieldKind::Record(record_type)} else if column.column.formula().is_some() {FieldKind::Formula} else if column.column.is_relation() {diff --git a/crates/crm/src/domain/pipeline_workflows/models.rs b/crates/crm/src/domain/pipeline_workflows/models.rsindex 6651e7dd78..03d091cb0a 100644--- a/crates/crm/src/domain/pipeline_workflows/models.rs+++ b/crates/crm/src/domain/pipeline_workflows/models.rs@@ -2,7 +2,6 @@use databases::domain::models::{RowId, TableDetail, TableVersion};use entity_access::domain::models::AccessError;-use models_databases::EntityKind;use uuid::Uuid;use super::super::{@@ -19,7 +18,7 @@ pub const MAX_SCANNED_ROWS: usize = 5_000;pub struct PipelineOverview {/// The pipeline and the viewer's grant on it.pub pipeline: AccessiblePipeline,- /// Its fields, the record field first.+ /// Its fields; a tracked pipeline's record field comes first.pub fields: Vec<PipelineField>,/// Its table's version when it was read.pub version: TableVersion,@@ -54,28 +53,19 @@ impl PipelineOverview {})}- pub(super) fn record_field(&self) -> &PipelineField {- self.fields- .iter()- .find(|field| field.is_record())- .expect("a pipeline's table has its record column")- }-- pub(super) fn record_kind(&self) -> EntityKind {- match self.pipeline.pipeline.record_type {- PipelineRecordType::Company => EntityKind::Company,- PipelineRecordType::Contact => EntityKind::Contact,- }+ /// The field naming the tracked record; a generic pipeline has none.+ pub(super) fn record_field(&self) -> Option<&PipelineField> {+ self.fields.iter().find(|field| field.is_record())}}-/// One entry: the record it tracks and its filled-in fields.+/// One entry: the record it tracks, if any, and its filled-in fields.#[derive(Debug, Clone, PartialEq)]pub struct PipelineEntryView {/// The entry, a row of the pipeline.pub entry_id: RowId,- /// The company or contact it tracks.- pub record: PipelineRecord,+ /// The company or contact it tracks; `None` in a generic pipeline.+ pub record: Option<PipelineRecord>,/// Its other fields that hold a value, in column order.pub fields: Vec<(String, FieldValue)>,}@@ -87,7 +77,8 @@ pub struct EntryQuery {pub filters: Vec<(String, FieldInput)>,/// Only entries tracking one of these records.pub records: Vec<Uuid>,- /// Text the record's name, domain or email must contain.+ /// Text the record's name, domain or email must contain; in a generic+ /// pipeline, one of the entry's text fields.pub search: Option<String>,/// The field to order by, and whether to put the largest first.pub sort: Option<(String, bool)>,@@ -145,8 +136,8 @@ pub enum RecordTarget {/// One entry to add.#[derive(Debug, Clone)]pub struct EntryAddition {- /// The record it tracks.- pub record: RecordTarget,+ /// The record it tracks; a generic pipeline's entries name none.+ pub record: Option<RecordTarget>,/// Fields to fill in, by name.pub set: Vec<(String, FieldInput)>,}@@ -196,8 +187,8 @@ pub struct FieldChange {pub struct UpdatedEntry {/// The entry.pub entry_id: RowId,- /// The record it tracks.- pub record: PipelineRecord,+ /// The record it tracks; `None` in a generic pipeline.+ pub record: Option<PipelineRecord>,/// The fields set, as they were and are.pub changes: Vec<FieldChange>,}@@ -236,13 +227,15 @@ pub struct NewField {pub struct NewPipeline {/// Its name.pub name: String,- /// Whether entries track companies or contacts.- pub record_type: PipelineRecordType,+ /// Whether entries track companies or contacts; `None` for a generic+ /// pipeline, whose entries are free-form rows.+ pub record_type: Option<PipelineRecordType>,/// Whether the team may edit it.pub sharing: PipelineSharing,- /// Its stages in order, replacing the team's default stages.+ /// Its stages in order, replacing the team's default stages. A generic+ /// pipeline starts without a Stage field, so these add one.pub stages: Vec<String>,- /// Fields to add after the standard ones.+ /// Fields to add after the standard ones, or a generic pipeline's Name.pub fields: Vec<NewField>,}diff --git a/crates/crm/src/domain/pipeline_workflows/ops.rs b/crates/crm/src/domain/pipeline_workflows/ops.rsindex 9461f510d0..9bcde482c0 100644--- a/crates/crm/src/domain/pipeline_workflows/ops.rs+++ b/crates/crm/src/domain/pipeline_workflows/ops.rs@@ -11,7 +11,7 @@ use super::{FieldInput, FieldKind, NewField, PipelineField, PipelineOverview, WorkflowError, fields,};-/// The stage field every pipeline starts with.+/// The stage field every tracked pipeline starts with.pub(super) const STAGE_FIELD: &str = "Stage";/// The cells `set` writes, by field name.diff --git a/crates/crm/src/domain/pipelines.rs b/crates/crm/src/domain/pipelines.rsindex 7c725963ba..3a8dd8a300 100644--- a/crates/crm/src/domain/pipelines.rs+++ b/crates/crm/src/domain/pipelines.rs@@ -1,7 +1,9 @@//! Company/contact pipelines: CRM policy over reusable database storage.+mod columns;mod references;mod sharing;+use columns::{generic_columns, tracked_columns};use sharing::{requested_channel_grants, share_permission};pub mod requirements;use references::primary_references;@@ -16,10 +18,10 @@ use bot_id::BotId;use chrono::{DateTime, Utc};use databases::domain::{models::{- AppliedOps, CardPosition, ColumnDetail, ColumnId, ColumnProtection, DatabaseId, OpBatch,- RowId, TableDetail, TableId, ViewId, Viewer,+ AppliedOps, CardPosition, ColumnDetail, ColumnId, DatabaseId, OpBatch, RowId, TableDetail,+ TableId, ViewId, Viewer,},- provisioning::{ProvisionedColumn, StorageBlueprint},+ provisioning::StorageBlueprint,storage::{DatabaseStorageService, StorageRow, StorageRows, StorageRowsQuery},};use entity_access::domain::{@@ -36,10 +38,8 @@ use models_permissions::share_permission::{ChannelSharePermission, UpdateChannelSharePermission, UpdateOperation,},};-use models_properties::service::{- property_option::PropertyOptionValue, property_value::PropertyValue,-};-use models_properties::{DataType, EntityType as PropertyEntityType};+use models_properties::EntityType as PropertyEntityType;+use models_properties::service::property_value::PropertyValue;use serde::{Deserialize, Serialize};use std::{collections::HashMap, sync::Arc};use uuid::Uuid;@@ -69,6 +69,13 @@ impl PipelineRecordType {Self::Contact => PropertyEntityType::Contact,}}+ /// The kind of record the primary column's cells reference.+ pub fn entity_kind(self) -> models_databases::EntityKind {+ match self {+ Self::Company => models_databases::EntityKind::Company,+ Self::Contact => models_databases::EntityKind::Contact,+ }+ }}/// Initial sharing, or the desired team grant. Individual ownership is preserved.@@ -82,14 +89,16 @@ pub enum PipelineSharing {Team,}-/// Request to create an empty pipeline with the standard CRM columns.+/// Request to create an empty pipeline: the standard CRM columns for a tracked+/// record, or one Name column, like a new database, for a generic pipeline.#[derive(Debug, Deserialize, utoipa::ToSchema)]#[serde(rename_all = "camelCase", deny_unknown_fields)]pub struct CreatePipeline {/// Pipeline name.pub name: String,- /// Company or contact entries.- pub record_type: PipelineRecordType,+ /// Company or contact entries; omitted, a generic pipeline of free-form rows.+ #[serde(default)]+ pub record_type: Option<PipelineRecordType>,/// Defaults to private.#[serde(default)]pub sharing: PipelineSharing,@@ -107,15 +116,18 @@ pub struct Pipeline {pub user_id: String,/// Pipeline display name.pub name: String,- /// Kind of the primary reference.- pub record_type: PipelineRecordType,+ /// Kind of the primary reference; `None` for a generic pipeline, whose+ /// primary column is plain text.+ #[schema(required = true)]+ pub record_type: Option<PipelineRecordType>,/// Dedicated backing database.#[schema(value_type = Uuid)]pub database_id: DatabaseId,/// Table of entries.#[schema(value_type = Uuid)]pub table_id: TableId,- /// Protected primary column.+ /// A tracked pipeline's protected record reference. A generic pipeline's+ /// Name, which names no column once someone deletes it.#[schema(value_type = Uuid)]pub primary_column_id: ColumnId,/// Whether the pipeline has a team grant.@@ -170,8 +182,8 @@ pub struct PipelineBlueprint {pub id: Uuid,/// CRM team.pub team_id: Uuid,- /// Primary reference kind.- pub record_type: PipelineRecordType,+ /// Primary reference kind, if it tracks a record.+ pub record_type: Option<PipelineRecordType>,/// Initial grants.pub sharing: PipelineSharing,/// Schema owned by the database domain.@@ -180,7 +192,7 @@ pub struct PipelineBlueprint {pub name: String,/// Initial owner.pub creator: MacroUserIdStr<'static>,- /// Protected company/contact reference.+ /// Protected company/contact reference, or a generic pipeline's Name.pub primary_column_id: ColumnId,}@@ -249,8 +261,8 @@ pub trait PipelineRepo: Send + Sync + 'static {&self,ids: &[Uuid],) -> impl Future<Output = Result<Vec<Pipeline>, Self::Error>> + Send;- /// Rows of these live pipelines whose primary column references one of- /// `records`, grouped by pipeline in each one's row order.+ /// Rows of these live tracked pipelines whose primary column references one+ /// of `records`, grouped by pipeline in each one's row order.fn referencing_rows(&self,pipelines: &[Uuid],@@ -460,7 +472,8 @@ impl<R: PipelineRepo, D, A, S> PipelineServiceImpl<R, D, A, S> {}}-/// Build the common CRM schema without performing I/O. Callers validate the name.+/// Build the initial schema without performing I/O. Callers validate the name.+/// `labels` are a tracked pipeline's stages.pub(crate) fn pipeline_blueprint(team_id: Uuid,creator: MacroUserIdStr<'static>,@@ -469,57 +482,10 @@ pub(crate) fn pipeline_blueprint() -> PipelineBlueprint {let id = macro_uuid::generate_uuid_v7();let primary_column_id = ColumnId::new();- let primary = ProvisionedColumn {- id: primary_column_id,- name: match input.record_type {- PipelineRecordType::Company => "Company",- PipelineRecordType::Contact => "Contact",- }- .into(),- data_type: DataType::Entity,- entity_type: Some(input.record_type.property_type()),- options: vec![],- nullable: false,- protections: vec![ColumnProtection::Delete, ColumnProtection::ChangeType],+ let columns = match input.record_type {+ Some(record_type) => tracked_columns(primary_column_id, record_type, labels),+ None => generic_columns(primary_column_id),};- let columns = vec![- primary,- ProvisionedColumn {- id: ColumnId::new(),- nullable: true,- protections: vec![],- name: "Stage".into(),- data_type: DataType::SelectString,- entity_type: None,- options: labels- .into_iter()- .map(|label| {- (- macro_uuid::generate_uuid_v7(),- PropertyOptionValue::String(label),- )- })- .collect(),- },- ProvisionedColumn {- id: ColumnId::new(),- nullable: true,- protections: vec![],- name: "Owner".into(),- data_type: DataType::Entity,- entity_type: Some(PropertyEntityType::User),- options: vec![],- },- ProvisionedColumn {- id: ColumnId::new(),- nullable: true,- protections: vec![],- name: "Revenue".into(),- data_type: DataType::Number,- entity_type: None,- options: vec![],- },- ];PipelineBlueprint {id,team_id,@@ -558,21 +524,27 @@ where{return Err(super::model::CrmError::CrmDisabledForTeam.into());}- let stages = self.stages.get_team_stage_set(&team).await?;- let labels = stages- .map(|set| {- set.stages- .into_iter()- .map(|stage| stage.label)- .collect::<Vec<_>>()- })- .unwrap_or_else(|| {- use system_properties::StageOption::*;- [Lead, Qualified, Demo, Trial, Negotiation, Customer, Churned]- .into_iter()- .map(|stage| stage.display_value().to_owned())- .collect()- });+ // The team's stages describe its sales process, which a generic+ // pipeline makes no assumption about.+ let labels = if input.record_type.is_some() {+ let stages = self.stages.get_team_stage_set(&team).await?;+ stages+ .map(|set| {+ set.stages+ .into_iter()+ .map(|stage| stage.label)+ .collect::<Vec<_>>()+ })+ .unwrap_or_else(|| {+ use system_properties::StageOption::*;+ [Lead, Qualified, Demo, Trial, Negotiation, Customer, Churned]+ .into_iter()+ .map(|stage| stage.display_value().to_owned())+ .collect()+ })+ } else {+ Vec::new()+ };let blueprint = pipeline_blueprint(team.team_id(),creator.clone(),@@ -645,7 +617,7 @@ where.await.map_err(storage)?.into_iter()- .filter(|p| p.trashed_at.is_none() && p.record_type == record_type)+ .filter(|p| p.trashed_at.is_none() && p.record_type == Some(record_type)).map(|p| (p.id, p)).collect();let live = pipelines.keys().copied().collect::<Vec<_>>();@@ -941,7 +913,8 @@ whereif pipeline.trashed_at.is_some() {return Err(PipelineError::NotFound);}- if records.is_empty() {+ // A generic pipeline's primary cells are text, not references.+ if records.is_empty() || pipeline.record_type.is_none() {return Ok(Vec::new());}self.repo@@ -982,18 +955,20 @@ where};// A pipeline grant does not grant access to the records it references.// The editor may reference records from any team they can access.- for id in primary_references(&pipeline, &batch)? {- self.access- .generate_entity_access_receipt::<ViewAccessLevel>(- &viewer.user_id,- None,- &id.to_string(),- match pipeline.record_type {- PipelineRecordType::Company => EntityType::CrmCompany,- PipelineRecordType::Contact => EntityType::CrmContact,- },- )- .await?;+ if let Some(record_type) = pipeline.record_type {+ for id in primary_references(&pipeline, record_type, &batch)? {+ self.access+ .generate_entity_access_receipt::<ViewAccessLevel>(+ &viewer.user_id,+ None,+ &id.to_string(),+ match record_type {+ PipelineRecordType::Company => EntityType::CrmCompany,+ PipelineRecordType::Contact => EntityType::CrmContact,+ },+ )+ .await?;+ }}let _guard = self.repodiff --git a/crates/crm/src/domain/pipelines/columns.rs b/crates/crm/src/domain/pipelines/columns.rsnew file mode 100644index 0000000000..e53c6405e2--- /dev/null+++ b/crates/crm/src/domain/pipelines/columns.rs@@ -0,0 +1,82 @@+//! The columns a new pipeline starts with.++use databases::domain::{+ models::{ColumnId, ColumnProtection},+ provisioning::ProvisionedColumn,+};+use models_properties::service::property_option::PropertyOptionValue;+use models_properties::{DataType, EntityType as PropertyEntityType};++use super::PipelineRecordType;++/// The columns a pipeline tracking `record_type` starts with.+pub(super) fn tracked_columns(+ primary_column_id: ColumnId,+ record_type: PipelineRecordType,+ labels: Vec<String>,+) -> Vec<ProvisionedColumn> {+ vec![+ ProvisionedColumn {+ id: primary_column_id,+ name: match record_type {+ PipelineRecordType::Company => "Company",+ PipelineRecordType::Contact => "Contact",+ }+ .into(),+ data_type: DataType::Entity,+ entity_type: Some(record_type.property_type()),+ options: vec![],+ nullable: false,+ protections: vec![ColumnProtection::Delete, ColumnProtection::ChangeType],+ },+ ProvisionedColumn {+ id: ColumnId::new(),+ nullable: true,+ protections: vec![],+ name: "Stage".into(),+ data_type: DataType::SelectString,+ entity_type: None,+ options: labels+ .into_iter()+ .map(|label| {+ (+ macro_uuid::generate_uuid_v7(),+ PropertyOptionValue::String(label),+ )+ })+ .collect(),+ },+ ProvisionedColumn {+ id: ColumnId::new(),+ nullable: true,+ protections: vec![],+ name: "Owner".into(),+ data_type: DataType::Entity,+ entity_type: Some(PropertyEntityType::User),+ options: vec![],+ },+ ProvisionedColumn {+ id: ColumnId::new(),+ nullable: true,+ protections: vec![],+ name: "Revenue".into(),+ data_type: DataType::Number,+ entity_type: None,+ options: vec![],+ },+ ]+}++/// A generic pipeline starts like a new database: one Name column, optional in+/// every row and as open to change as any other.+pub(super) fn generic_columns(primary_column_id: ColumnId) -> Vec<ProvisionedColumn> {+ vec![ProvisionedColumn {+ id: primary_column_id,+ name: "Name".into(),+ data_type: DataType::String,+ entity_type: None,+ options: vec![],+ nullable: true,+ protections: vec![],+ }]+}diff --git a/crates/crm/src/domain/pipelines/references.rs b/crates/crm/src/domain/pipelines/references.rsindex e9048d3548..eac08b36ee 100644--- a/crates/crm/src/domain/pipelines/references.rs+++ b/crates/crm/src/domain/pipelines/references.rs@@ -4,6 +4,7 @@ use super::*;/// unchanged references do not require the editor to reselect the record.pub(super) fn primary_references(pipeline: &Pipeline,+ record_type: PipelineRecordType,batch: &OpBatch,) -> Result<std::collections::BTreeSet<Uuid>, PipelineError> {use models_databases::{CellValue, CellWrite, DatabaseOp, RowChanges, RowsChange};@@ -36,11 +37,7 @@ pub(super) fn primary_references(}if let CellValue::Entities(values) = &cell.value {for value in values {- let expected = match pipeline.record_type {- PipelineRecordType::Company => models_databases::EntityKind::Company,- PipelineRecordType::Contact => models_databases::EntityKind::Contact,- };- if value.entity_type != expected {+ if value.entity_type != record_type.entity_kind() {return Err(PipelineError::Invalid("Choose the required CRM record type",));diff --git a/crates/crm/src/domain/pipelines/requirements.rs b/crates/crm/src/domain/pipelines/requirements.rsindex 221b6a1aed..42d7984523 100644--- a/crates/crm/src/domain/pipelines/requirements.rs+++ b/crates/crm/src/domain/pipelines/requirements.rs@@ -8,6 +8,7 @@ use models_databases::{ViewChange, ViewId,views::{RequestedLayout, ViewLayout},};+use models_properties::{DataType, service::property_option::PropertyOptionValue};use std::collections::{BTreeMap, HashSet};/// Fields required when a deal enters a particular option of a stage column.diff --git a/crates/crm/src/domain/pipelines/test.rs b/crates/crm/src/domain/pipelines/test.rsindex f320eb6727..8bd6358f6d 100644--- a/crates/crm/src/domain/pipelines/test.rs+++ b/crates/crm/src/domain/pipelines/test.rs@@ -1,4 +1,5 @@use super::*;+use models_properties::DataType;#[test]fn creation_is_private_unless_requested_otherwise() {@@ -7,8 +8,9 @@ fn creation_is_private_unless_requested_otherwise() {})).unwrap();assert_eq!(input.sharing, PipelineSharing::Private);+ assert_eq!(input.record_type, Some(PipelineRecordType::Company));assert_eq!(- input.record_type.property_type(),+ PipelineRecordType::Company.property_type(),PropertyEntityType::Company);assert_eq!(@@ -17,6 +19,26 @@ fn creation_is_private_unless_requested_otherwise() {);}+#[test]+fn a_pipeline_without_a_record_type_starts_like_a_new_database() {+ let input: CreatePipeline = serde_json::from_value(serde_json::json!({+ "name": "Hiring"+ }))+ .unwrap();+ let creator = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();+ let blueprint = pipeline_blueprint(Uuid::nil(), creator, input, vec!["Lead".to_owned()]);+ assert_eq!(blueprint.record_type, None);+ let [name] = blueprint.database.columns.as_slice() else {+ panic!("a generic pipeline starts with one column");+ };+ assert_eq!(name.id, blueprint.primary_column_id);+ assert_eq!(name.name, "Name");+ assert_eq!(name.data_type, DataType::String);+ assert_eq!(name.entity_type, None);+ assert!(name.nullable);+ assert!(name.protections.is_empty());+}+#[test]fn names_are_trimmed_and_limited_by_characters() {assert_eq!(name(" Renewals ").unwrap(), "Renewals");diff --git a/crates/crm/src/inbound/toolset/pipelines.rs b/crates/crm/src/inbound/toolset/pipelines.rsindex 261929ffe5..382d5717a8 100644--- a/crates/crm/src/inbound/toolset/pipelines.rs+++ b/crates/crm/src/inbound/toolset/pipelines.rs@@ -1,6 +1,7 @@//! Agent tools over CRM pipelines, in the CRM's own words: pipelines hold-//! entries, each entry tracks a company or contact, and fields such as Stage,-//! Owner and Revenue belong to the entry. Every tool is a thin adapter over+//! entries, each entry tracks a company or contact (a generic pipeline's track+//! nothing), and fields such as Stage, Owner and Revenue belong to the entry.+//! Every tool is a thin adapter over//! [`PipelineWorkflowService`], which resolves names and labels against the//! pipeline's schema and writes through the pipeline's own access boundary.@@ -340,13 +341,16 @@ pub struct ToolPipeline {pub id: Uuid,/// Its name.pub name: String,- /// What each entry tracks: `company` or `contact`.- pub tracks: ToolRecordType,+ /// What each entry tracks: `company` or `contact`. Missing for a generic+ /// pipeline, whose entries are free-form rows that track no CRM record.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub tracks: Option<ToolRecordType>,/// What the user may do with it.pub access: ToolPipelineAccess,/// Whether the owner's team may edit it; otherwise it is private.pub shared_with_team: bool,- /// Its fields in column order; the first names the tracked record.+ /// Its fields in column order; the first names the tracked record, or in a+ /// generic pipeline the entry itself.pub fields: Vec<ToolField>,/// Its version now; pass as `baseVersion` to refuse an update if the/// pipeline changed in between.@@ -359,7 +363,7 @@ impl From<&PipelineOverview> for ToolPipeline {Self {id: pipeline.id,name: pipeline.name.clone(),- tracks: pipeline.record_type.into(),+ tracks: pipeline.record_type.map(Into::into),access: match overview.pipeline.grant {AccessLevel::View | AccessLevel::Comment => ToolPipelineAccess::View,AccessLevel::Edit => ToolPipelineAccess::Edit,@@ -402,8 +406,9 @@ impl From<&PipelineRecord> for ToolRecord {pub struct ToolEntry {/// Pass as `entryId`.pub entry_id: Uuid,- /// The company or contact it tracks.- pub record: ToolRecord,+ /// The company or contact it tracks; missing in a generic pipeline.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub record: Option<ToolRecord>,/// Its filled-in fields by name: text, a number, true/false, a date, or a/// list when a field holds several values. People are macro| user ids.pub fields: BTreeMap<String, serde_json::Value>,@@ -413,7 +418,7 @@ impl From<&PipelineEntryView> for ToolEntry {fn from(entry: &PipelineEntryView) -> Self {Self {entry_id: entry.entry_id.into_uuid(),- record: (&entry.record).into(),+ record: entry.record.as_ref().map(Into::into),fields: entry.fields.iter()@@ -444,8 +449,11 @@ pub(crate) fn json(value: &FieldValue) -> serde_json::Value {}}-/// The record a summary line names.-pub(crate) fn record_name(record: &ToolRecord) -> String {+/// What a summary line calls an entry: its record, or its id in a generic pipeline.+pub(crate) fn entry_name(record: Option<&ToolRecord>, entry_id: Uuid) -> String {+ let Some(record) = record else {+ return format!("entry {entry_id}");+ };record.name.clone()diff --git a/crates/crm/src/inbound/toolset/pipelines/add_to_pipeline.rs b/crates/crm/src/inbound/toolset/pipelines/add_to_pipeline.rsindex 2d9927d23d..273b97a6dd 100644--- a/crates/crm/src/inbound/toolset/pipelines/add_to_pipeline.rs+++ b/crates/crm/src/inbound/toolset/pipelines/add_to_pipeline.rs@@ -1,4 +1,5 @@-//! AddToPipeline: put companies or contacts into a pipeline as new deals.+//! AddToPipeline: put companies or contacts into a pipeline as new deals, or+//! free-form rows into a generic pipeline.use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,@@ -9,16 +10,16 @@ use schemars::JsonSchema;use serde::{Deserialize, Serialize};use uuid::Uuid;-use super::{PipelineToolContext, ToolEntry, ToolFieldValue, pairs, record_name, workflow_error};+use super::{PipelineToolContext, ToolEntry, ToolFieldValue, entry_name, pairs, workflow_error};use crate::domain::pipeline_workflows::{EntryAddition, PipelineWorkflowService, RecordTarget};-/// One company or contact to add.+/// One company or contact to add, or one row of a generic pipeline.#[derive(Debug, Clone, Deserialize, JsonSchema)]#[serde(rename_all = "camelCase")]pub struct ToolNewEntry {/// The record's id.#[schemars(- description = "The CRM company or contact id to add (company ids come from ListCompanies). Give this or email."+ description = "The CRM company or contact id to add (company ids come from ListCompanies). Give this or email; leave both out in a generic pipeline, which tracks no records.")]#[serde(default)]pub record_id: Option<Uuid>,@@ -30,7 +31,7 @@ pub struct ToolNewEntry {pub email: Option<String>,/// Fields to fill in.#[schemars(- description = "Fields to fill in on the new entry, e.g. [{\"field\": \"Stage\", \"value\": \"Lead\"}, {\"field\": \"Owner\", \"value\": \"me\"}]."+ description = "Fields to fill in on the new entry, e.g. [{\"field\": \"Stage\", \"value\": \"Lead\"}, {\"field\": \"Owner\", \"value\": \"me\"}]. In a generic pipeline, e.g. [{\"field\": \"Name\", \"value\": \"Launch site\"}].")]#[serde(default)]pub set: Vec<ToolFieldValue>,@@ -41,14 +42,16 @@ pub struct ToolNewEntry {#[serde(rename_all = "camelCase")]#[schemars(title = "AddToPipeline",- description = "Add companies or contacts to a CRM pipeline as new deals (entries), optionally setting their stage, owner, revenue or other fields. A company pipeline takes companies and a contact pipeline takes contacts (see ListPipelines' `tracks`). A record already in the pipeline is not added again unless allowDuplicates is true (for a second, separate deal); its existing entry is returned in alreadyPresent instead. Returns the new entries with their entryIds and fields as saved."+ description = "Add companies or contacts to a CRM pipeline as new deals (entries), optionally setting their stage, owner, revenue or other fields. A company pipeline takes companies and a contact pipeline takes contacts (see ListPipelines' `tracks`); a generic pipeline, with no `tracks`, takes rows that name only their fields. A record already in the pipeline is not added again unless allowDuplicates is true (for a second, separate deal); its existing entry is returned in alreadyPresent instead. Returns the new entries with their entryIds and fields as saved.")]pub struct AddToPipeline {/// The pipeline.#[schemars(description = "The pipeline's id from ListPipelines.")]pub pipeline_id: Uuid,/// What to add.- #[schemars(description = "The companies or contacts to add, each with its starting fields.")]+ #[schemars(+ description = "The companies or contacts to add, each with its starting fields, or a generic pipeline's new rows."+ )]pub entries: Vec<ToolNewEntry>,/// Whether to add a record that is already in the pipeline.#[schemars(@@ -95,13 +98,14 @@ impl<Workflows: PipelineWorkflowService> AsyncTool<PipelineToolContext<Workflows.iter().map(|entry| {let record = match (entry.record_id, &entry.email) {- (Some(id), None) => RecordTarget::Id(id),- (None, Some(email)) => RecordTarget::Email(email.trim().to_owned()),- _ => {+ (Some(id), None) => Some(RecordTarget::Id(id)),+ (None, Some(email)) => Some(RecordTarget::Email(email.trim().to_owned())),+ (None, None) => None,+ (Some(_), Some(_)) => {return Err(ToolCallError {description: "Give each entry exactly one of recordId or email.".to_owned(),- internal_error: anyhow::anyhow!("entry without one record"),+ internal_error: anyhow::anyhow!("entry with two records"),});}};@@ -130,7 +134,7 @@ impl<Workflows: PipelineWorkflowService> AsyncTool<PipelineToolContext<Workflows"Added {}.",entries.iter()- .map(|entry| record_name(&entry.record))+ .map(|entry| entry_name(entry.record.as_ref(), entry.entry_id)).collect::<Vec<_>>().join(", ")),@@ -140,7 +144,7 @@ impl<Workflows: PipelineWorkflowService> AsyncTool<PipelineToolContext<Workflows" Already in the pipeline, so not added again: {}.",present.iter()- .map(|entry| record_name(&entry.record))+ .map(|entry| entry_name(entry.record.as_ref(), entry.entry_id)).collect::<Vec<_>>().join(", ")));diff --git a/crates/crm/src/inbound/toolset/pipelines/create_pipeline.rs b/crates/crm/src/inbound/toolset/pipelines/create_pipeline.rsindex 0b074f6b61..ffe67df014 100644--- a/crates/crm/src/inbound/toolset/pipelines/create_pipeline.rs+++ b/crates/crm/src/inbound/toolset/pipelines/create_pipeline.rs@@ -18,7 +18,7 @@ use crate::domain::{#[serde(rename_all = "camelCase")]#[schemars(title = "CreatePipeline",- description = "Create a CRM pipeline: a board of deals that move through stages, such as a sales, renewals, fundraising, hiring or partnership pipeline. Each entry tracks either a company or a contact. Every pipeline starts with the tracked record, Stage, Owner and Revenue fields; Stage starts with the team's default stages unless `stages` gives others. Only when the user asked for a new pipeline: check ListPipelines first so you do not create a duplicate. Returns the pipeline with its id and fields."+ description = "Create a CRM pipeline: a board of deals that move through stages, such as a sales, renewals, fundraising, hiring or partnership pipeline. Each entry tracks a company or a contact, and the pipeline starts with the tracked record, Stage, Owner and Revenue fields; Stage starts with the team's default stages unless `stages` gives others. Leave out `tracks` for a generic pipeline: a free-form table of entries that needs no company or contact, starting with only a Name field, plus a Stage field when `stages` is given. Only when the user asked for a new pipeline: check ListPipelines first so you do not create a duplicate. Returns the pipeline with its id and fields.")]pub struct CreatePipeline {/// Its name.@@ -26,9 +26,10 @@ pub struct CreatePipeline {pub name: String,/// What entries track.#[schemars(- description = "\"company\" for deals with organizations, \"contact\" for deals with individual people (candidates, investors, partners)."+ description = "\"company\" for deals with organizations, \"contact\" for deals with individual people (candidates, investors, partners). Leave out for a generic pipeline whose entries need no company or contact.")]- pub tracks: ToolRecordType,+ #[serde(default)]+ pub tracks: Option<ToolRecordType>,/// Team sharing.#[schemars(description = "Let the user's team see and edit it. Defaults to false: only the user can see it."@@ -42,7 +43,9 @@ pub struct CreatePipeline {#[serde(default)]pub stages: Vec<String>,/// More fields.- #[schemars(description = "Fields to add after Company/Contact, Stage, Owner and Revenue.")]+ #[schemars(+ description = "Fields to add after Company/Contact, Stage, Owner and Revenue, or after a generic pipeline's Name."+ )]#[serde(default)]pub fields: Vec<ToolNewField>,}@@ -80,7 +83,7 @@ impl<Workflows: PipelineWorkflowService> AsyncTool<PipelineToolContext<Workflows&viewer,NewPipeline {name: self.name.clone(),- record_type: self.tracks.into(),+ record_type: self.tracks.map(Into::into),sharing: if self.shared_with_team.unwrap_or(false) {PipelineSharing::Team} else {diff --git a/crates/crm/src/inbound/toolset/pipelines/find_pipeline_entries.rs b/crates/crm/src/inbound/toolset/pipelines/find_pipeline_entries.rsindex 5632891be3..bf18c9466c 100644--- a/crates/crm/src/inbound/toolset/pipelines/find_pipeline_entries.rs+++ b/crates/crm/src/inbound/toolset/pipelines/find_pipeline_entries.rs@@ -23,7 +23,7 @@ const MAX_LIMIT: u16 = 200;#[serde(rename_all = "camelCase")]#[schemars(title = "FindPipelineEntries",- description = "Find deals (entries) in a CRM pipeline: which companies or contacts are in which stage, who owns them, their revenue and other fields. Filter by field values (e.g. Stage is Demo or Trial, Owner is me), by company or contact name/domain/email with `search`, or by record id; sort by any field (Stage sorts in pipeline order). Returns each entry's entryId, the record it tracks (id and name) and its filled-in fields, plus, over every match, the count per stage (and per option of each single-select field) and the total of each number field such as Revenue: use these for questions like \"how many deals are in Negotiation\" or \"what is the pipeline worth\". To find where a company or contact is across all pipelines (\"what stage is Acme in?\"), leave out pipelineId and pass its name as `search` (or its recordIds). Get pipeline ids and field names from ListPipelines."+ description = "Find deals (entries) in a CRM pipeline: which companies or contacts are in which stage, who owns them, their revenue and other fields. Filter by field values (e.g. Stage is Demo or Trial, Owner is me), by company or contact name/domain/email with `search` (in a generic pipeline, by any text field), or by record id; sort by any field (Stage sorts in pipeline order). Returns each entry's entryId, the record it tracks (id and name) and its filled-in fields, plus, over every match, the count per stage (and per option of each single-select field) and the total of each number field such as Revenue: use these for questions like \"how many deals are in Negotiation\" or \"what is the pipeline worth\". To find where a company or contact is across all pipelines (\"what stage is Acme in?\"), leave out pipelineId and pass its name as `search` (or its recordIds). Get pipeline ids and field names from ListPipelines.")]pub struct FindPipelineEntries {/// The pipeline to read.@@ -188,9 +188,12 @@ impl<Workflows: PipelineWorkflowService> AsyncTool<PipelineToolContext<Workflows.into_iter().map(|mut group| {if !self.record_ids.is_empty() {- group- .entries- .retain(|entry| self.record_ids.contains(&entry.record.id));+ group.entries.retain(|entry| {+ entry+ .record+ .as_ref()+ .is_some_and(|record| self.record_ids.contains(&record.id))+ });}group})diff --git a/crates/crm/src/inbound/toolset/pipelines/list_pipelines.rs b/crates/crm/src/inbound/toolset/pipelines/list_pipelines.rsindex b9767910c8..c6887b161d 100644--- a/crates/crm/src/inbound/toolset/pipelines/list_pipelines.rs+++ b/crates/crm/src/inbound/toolset/pipelines/list_pipelines.rs@@ -14,7 +14,7 @@ use crate::domain::pipeline_workflows::PipelineWorkflowService;#[derive(Debug, Clone, Default, Deserialize, JsonSchema)]#[schemars(title = "ListPipelines",- description = "List the user's CRM pipelines (deal pipelines, sales pipelines, hiring or partner pipelines) with their stages and fields. A pipeline holds entries (deals); each entry tracks one CRM company or contact and has its own fields, such as Stage, Owner and Revenue. Each pipeline lists its id, whether it tracks companies or contacts, the user's access, and its fields in order with their types; a select field lists its options, so Stage lists the pipeline's stages from first to last. Call this first whenever the user talks about deals, a pipeline, a stage, or moving a company or contact along, then use FindPipelineEntries, AddToPipeline and UpdatePipelineEntries with the returned pipelineId and field names. When the user names no pipeline and there is exactly one, use it; when several could match, ask which one."+ description = "List the user's CRM pipelines (deal pipelines, sales pipelines, hiring or partner pipelines) with their stages and fields. A pipeline holds entries (deals); each entry tracks one CRM company or contact and has its own fields, such as Stage, Owner and Revenue. A generic pipeline has no `tracks`: its entries are free-form rows of fields, with no company or contact. Each pipeline lists its id, whether it tracks companies or contacts, the user's access, and its fields in order with their types; a select field lists its options, so Stage lists the pipeline's stages from first to last. Call this first whenever the user talks about deals, a pipeline, a stage, or moving a company or contact along, then use FindPipelineEntries, AddToPipeline and UpdatePipelineEntries with the returned pipelineId and field names. When the user names no pipeline and there is exactly one, use it; when several could match, ask which one.")]pub struct ListPipelines {}diff --git a/crates/crm/src/inbound/toolset/pipelines/remove_from_pipeline.rs b/crates/crm/src/inbound/toolset/pipelines/remove_from_pipeline.rsindex 43546bfbca..984f7bb0a3 100644--- a/crates/crm/src/inbound/toolset/pipelines/remove_from_pipeline.rs+++ b/crates/crm/src/inbound/toolset/pipelines/remove_from_pipeline.rs@@ -9,7 +9,7 @@ use schemars::JsonSchema;use serde::{Deserialize, Serialize};use uuid::Uuid;-use super::{PipelineToolContext, ToolEntry, record_name, workflow_error};+use super::{PipelineToolContext, ToolEntry, entry_name, workflow_error};use crate::domain::pipeline_workflows::{EntryTarget, PipelineWorkflowService};/// Remove entries from a pipeline.@@ -81,7 +81,7 @@ impl<Workflows: PipelineWorkflowService> AsyncTool<PipelineToolContext<Workflows"Removed {} from the pipeline; the records stay in the CRM.",entries.iter()- .map(|entry| record_name(&entry.record))+ .map(|entry| entry_name(entry.record.as_ref(), entry.entry_id)).collect::<Vec<_>>().join(", ")),diff --git a/crates/crm/src/inbound/toolset/pipelines/update_pipeline_entries.rs b/crates/crm/src/inbound/toolset/pipelines/update_pipeline_entries.rsindex 9d5c8c91c0..09106efdba 100644--- a/crates/crm/src/inbound/toolset/pipelines/update_pipeline_entries.rs+++ b/crates/crm/src/inbound/toolset/pipelines/update_pipeline_entries.rs@@ -11,7 +11,7 @@ use serde::{Deserialize, Serialize};use uuid::Uuid;use super::{- PipelineToolContext, ToolFieldValue, ToolRecord, json, pairs, record_name, workflow_error,+ PipelineToolContext, ToolFieldValue, ToolRecord, entry_name, json, pairs, workflow_error,};use crate::domain::pipeline_workflows::{EntryTarget, EntryUpdate, PipelineWorkflowService};@@ -76,8 +76,9 @@ pub struct ToolFieldChange {pub struct ToolUpdatedEntry {/// The entry.pub entry_id: Uuid,- /// The company or contact it tracks.- pub record: ToolRecord,+ /// The company or contact it tracks; missing in a generic pipeline.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub record: Option<ToolRecord>,/// The fields set.pub changes: Vec<ToolFieldChange>,}@@ -150,7 +151,7 @@ impl<Workflows: PipelineWorkflowService> AsyncTool<PipelineToolContext<Workflows.iter().map(|entry| ToolUpdatedEntry {entry_id: entry.entry_id.into_uuid(),- record: (&entry.record).into(),+ record: entry.record.as_ref().map(Into::into),changes: entry.changes.iter()@@ -174,7 +175,8 @@ impl<Workflows: PipelineWorkflowService> AsyncTool<PipelineToolContext<Workflowsformat!("{} {} → {}", change.field, change.before, change.after)}).collect();- format!("{} ({})", record_name(&entry.record), fields.join("; "))+ let name = entry_name(entry.record.as_ref(), entry.entry_id);+ format!("{name} ({})", fields.join("; "))}).collect::<Vec<_>>().join(", ")diff --git a/crates/crm/src/outbound/pipelines.rs b/crates/crm/src/outbound/pipelines.rsindex 3ad4d0c2bb..e400905c0c 100644--- a/crates/crm/src/outbound/pipelines.rs+++ b/crates/crm/src/outbound/pipelines.rs@@ -55,7 +55,7 @@ wheresqlx::query!("INSERT INTO crm_pipeline_entities (id, team_id, database_id, table_id, record_type, name, user_id, primary_column_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",blueprint.id, blueprint.team_id, blueprint.database.id.into_uuid(),- blueprint.database.table_id.into_uuid(), blueprint.record_type.as_str(), &blueprint.name, blueprint.creator.as_ref(), blueprint.primary_column_id.into_uuid(),+ blueprint.database.table_id.into_uuid(), blueprint.record_type.map(PipelineRecordType::as_str), &blueprint.name, blueprint.creator.as_ref(), blueprint.primary_column_id.into_uuid(),).execute(&mut **transaction).await?;entity_access_db_utils::insert_entity_access_row(transaction,@@ -111,10 +111,11 @@ where.await?;rows.into_iter().map(|row| {- let record_type = match row.record_type.as_str() {- "company" => PipelineRecordType::Company,- "contact" => PipelineRecordType::Contact,- _ => {+ let record_type = match row.record_type.as_deref() {+ None => None,+ Some("company") => Some(PipelineRecordType::Company),+ Some("contact") => Some(PipelineRecordType::Contact),+ Some(_) => {return Err(sqlx::Error::Decode("Invalid pipeline record type".into()).into());diff --git a/crates/crm/tests/pipeline_workflows.rs b/crates/crm/tests/pipeline_workflows.rsindex 524a395fb0..49d4bd5152 100644--- a/crates/crm/tests/pipeline_workflows.rs+++ b/crates/crm/tests/pipeline_workflows.rs@@ -176,7 +176,7 @@ async fn fixture(pool: &PgPool) -> Fixture {let sam = Uuid::now_v7();sqlx::query!("INSERT INTO crm_contacts (id, company_id, email, name, first_interaction, last_interaction)- VALUES ($1, $2, '[email protected]', 'Sam Lee', now(), now())",+ VALUES ($1, $2, '[email protected]', 'Sam Lee', now(), now())",sam,acme)@@ -238,7 +238,7 @@ async fn sales(workflows: &Workflows, sharing: PipelineSharing) -> PipelineOverv&viewer(OWNER),NewPipeline {name: "Sales".into(),- record_type: PipelineRecordType::Company,+ record_type: Some(PipelineRecordType::Company),sharing,stages: Vec::new(),fields: Vec::new(),@@ -274,7 +274,7 @@ async fn deals_are_added_found_moved_and_removed_by_name(pool: PgPool) {id,vec![EntryAddition {- record: RecordTarget::Id(acme),+ record: Some(RecordTarget::Id(acme)),set: vec![set("stage", "prospect"),set("Owner", "me"),@@ -282,7 +282,7 @@ async fn deals_are_added_found_moved_and_removed_by_name(pool: PgPool) {],},EntryAddition {- record: RecordTarget::Id(globex),+ record: Some(RecordTarget::Id(globex)),set: Vec::new(),},],@@ -292,8 +292,14 @@ async fn deals_are_added_found_moved_and_removed_by_name(pool: PgPool) {.unwrap();assert_eq!(added.added.len(), 2);let acme_entry = &added.added[0];- assert_eq!(acme_entry.record.name.as_deref(), Some("Acme"));- assert_eq!(acme_entry.record.detail.as_deref(), Some("acme.com"));+ assert_eq!(+ acme_entry.record.as_ref().unwrap().name.as_deref(),+ Some("Acme")+ );+ assert_eq!(+ acme_entry.record.as_ref().unwrap().detail.as_deref(),+ Some("acme.com")+ );assert_eq!(field(acme_entry, "Stage"), labels("Prospect").as_ref());assert_eq!(field(acme_entry, "Owner"),@@ -310,7 +316,7 @@ async fn deals_are_added_found_moved_and_removed_by_name(pool: PgPool) {&owner,id,vec![EntryAddition {- record: RecordTarget::Id(acme),+ record: Some(RecordTarget::Id(acme)),set: Vec::new(),}],false,@@ -332,7 +338,7 @@ async fn deals_are_added_found_moved_and_removed_by_name(pool: PgPool) {.unwrap();assert_eq!(prospects.matched, 1);assert!(prospects.complete);- assert_eq!(prospects.entries[0].record.id, acme);+ assert_eq!(prospects.entries[0].record.as_ref().unwrap().id, acme);let all = workflows.find(&owner, id, query(Vec::new(), None)).await@@ -354,7 +360,7 @@ async fn deals_are_added_found_moved_and_removed_by_name(pool: PgPool) {.await.unwrap();assert_eq!(found.entries.len(), 1);- assert_eq!(found.entries[0].record.id, globex);+ assert_eq!(found.entries[0].record.as_ref().unwrap().id, globex);let mine = workflows.find(&owner, id, query(vec![set("Owner", "me")], None)).await@@ -381,7 +387,10 @@ async fn deals_are_added_found_moved_and_removed_by_name(pool: PgPool) {let change = &moved.updated[0].changes[0];assert_eq!(change.before, labels("Prospect"));assert_eq!(change.after, labels("Won"));- assert_eq!(moved.updated[0].record.name.as_deref(), Some("Acme"));+ assert_eq!(+ moved.updated[0].record.as_ref().unwrap().name.as_deref(),+ Some("Acme")+ );// Every write is the user's, made by the agent acting for them.let changes = sqlx::query!("SELECT actor, acting_bot FROM database_changes WHERE database_id = $1",@@ -436,7 +445,7 @@ async fn deals_are_added_found_moved_and_removed_by_name(pool: PgPool) {);let by_name = workflows.search_entries(&owner, "acme", 50).await.unwrap();assert_eq!(by_name.len(), 1);- assert_eq!(by_name[0].entries[0].record.id, acme);+ assert_eq!(by_name[0].entries[0].record.as_ref().unwrap().id, acme);assert!(workflows.search_entries(&owner, "nobody", 50)@@ -449,7 +458,7 @@ async fn deals_are_added_found_moved_and_removed_by_name(pool: PgPool) {.remove(&owner, id, vec![EntryTarget::Record(globex)]).await.unwrap();- assert_eq!(removed.removed[0].record.id, globex);+ assert_eq!(removed.removed[0].record.as_ref().unwrap().id, globex);let left = workflows.find(&owner, id, query(Vec::new(), None)).await@@ -485,7 +494,7 @@ async fn contacts_are_added_by_email_and_a_record_with_two_deals_needs_an_entry_&owner,NewPipeline {name: "Partners".into(),- record_type: PipelineRecordType::Contact,+ record_type: Some(PipelineRecordType::Contact),sharing: PipelineSharing::Private,stages: Vec::new(),fields: Vec::new(),@@ -498,28 +507,31 @@ async fn contacts_are_added_by_email_and_a_record_with_two_deals_needs_an_entry_&owner,people.pipeline.pipeline.id,vec![EntryAddition {- record: RecordTarget::Email("[email protected]".into()),+ record: Some(RecordTarget::Email("[email protected]".into())),set: Vec::new(),}],false,).await.unwrap();- assert_eq!(added.added[0].record.id, sam);- assert_eq!(added.added[0].record.name.as_deref(), Some("Sam Lee"));+ assert_eq!(added.added[0].record.as_ref().unwrap().id, sam);+ assert_eq!(+ added.added[0].record.as_ref().unwrap().name.as_deref(),+ Some("Sam Lee")+ );// In a company pipeline, a contact's email adds its company.let sales = sales(&workflows, PipelineSharing::Private).await;let id = sales.pipeline.pipeline.id;let email = || EntryAddition {- record: RecordTarget::Email("[email protected]".into()),+ record: Some(RecordTarget::Email("[email protected]".into())),set: Vec::new(),};let added = workflows.add(&owner, id, vec![email()], false).await.unwrap();- assert_eq!(added.added[0].record.id, acme);+ assert_eq!(added.added[0].record.as_ref().unwrap().id, acme);let second = workflows.add(&owner, id, vec![email()], true).await@@ -557,7 +569,7 @@ async fn contacts_are_added_by_email_and_a_record_with_two_deals_needs_an_entry_&owner,id,vec![EntryAddition {- record: RecordTarget::Id(Uuid::now_v7()),+ record: Some(RecordTarget::Id(Uuid::now_v7())),set: Vec::new(),}],false,@@ -576,7 +588,7 @@ async fn pipelines_are_created_with_stages_and_edited_by_name(pool: PgPool) {&owner,NewPipeline {name: "Hiring".into(),- record_type: PipelineRecordType::Contact,+ record_type: Some(PipelineRecordType::Contact),sharing: PipelineSharing::Team,stages: vec!["Sourced".into(), "Interview".into(), "Hired".into()],fields: vec![@@ -684,3 +696,152 @@ async fn pipelines_are_created_with_stages_and_edited_by_name(pool: PgPool) {#[path = "pipeline_workflows/requirements.rs"]mod requirements;++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_generic_pipeline_takes_entries_by_their_fields(pool: PgPool) {+ let Fixture { workflows, .. } = fixture(&pool).await;+ let owner = viewer(OWNER);+ let launch = workflows+ .create(+ &owner,+ NewPipeline {+ name: "Launch".into(),+ record_type: None,+ sharing: PipelineSharing::Private,+ stages: vec!["Planned".into(), "Done".into()],+ fields: Vec::new(),+ },+ )+ .await+ .unwrap();+ let id = launch.pipeline.pipeline.id;+ let names: Vec<&str> = launch.fields.iter().map(|f| f.name.as_str()).collect();+ assert_eq!(names, ["Name", "Stage"]);+ assert_eq!(launch.field("Name").unwrap().kind, FieldKind::Text);+ assert!(!launch.field("Name").unwrap().required);++ let site = |name: &str| EntryAddition {+ record: None,+ set: vec![+ ("Name".into(), FieldInput::One(name.into())),+ ("Stage".into(), FieldInput::One("Planned".into())),+ ],+ };+ let added = workflows+ .add(+ &owner,+ id,+ vec![site("Site"), site("Site"), site("Docs")],+ false,+ )+ .await+ .unwrap();+ assert_eq!(added.added.len(), 3, "rows name no record, so none repeats");+ assert_eq!(added.added[0].record, None);+ assert_eq!(+ added.added[0].fields[0],+ ("Name".to_owned(), FieldValue::Text("Site".into()))+ );++ assert!(matches!(+ workflows+ .add(+ &owner,+ id,+ vec![EntryAddition {+ record: Some(RecordTarget::Id(Uuid::now_v7())),+ set: site("Site").set,+ }],+ false,+ )+ .await,+ Err(WorkflowError::Invalid(_))+ ));+ let blank = workflows+ .add(+ &owner,+ id,+ vec![EntryAddition {+ record: None,+ set: Vec::new(),+ }],+ false,+ )+ .await+ .unwrap();+ assert_eq!(+ blank.added.len(),+ 1,+ "a row may start empty, as in the editor"+ );++ let found = workflows+ .find(+ &owner,+ id,+ EntryQuery {+ search: Some("doc".into()),+ limit: 10,+ ..Default::default()+ },+ )+ .await+ .unwrap();+ assert_eq!(found.matched, 1);+ let docs = found.entries[0].entry_id;++ let updated = workflows+ .update(+ &owner,+ id,+ vec![EntryUpdate {+ target: EntryTarget::Entry(docs),+ set: vec![("Stage".into(), FieldInput::One("Done".into()))],+ }],+ None,+ )+ .await+ .unwrap();+ assert_eq!(updated.updated[0].record, None);++ let removed = workflows+ .remove(&owner, id, vec![EntryTarget::Entry(docs)])+ .await+ .unwrap();+ assert_eq!(removed.removed.len(), 1);++ let listed = workflows.pipelines(&owner).await.unwrap();+ assert!(listed.iter().any(|o| o.pipeline.pipeline.id == id));+ let edited = workflows+ .edit(+ &owner,+ id,+ PipelineEdit {+ remove_fields: vec!["Name".into()],+ ..Default::default()+ },+ )+ .await+ .unwrap();+ assert!(edited.field("Name").is_err());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_tracked_pipeline_still_requires_a_record(pool: PgPool) {+ let Fixture { workflows, .. } = fixture(&pool).await;+ let deals = sales(&workflows, PipelineSharing::Private).await;+ assert!(matches!(+ workflows+ .add(+ &viewer(OWNER),+ deals.pipeline.pipeline.id,+ vec![EntryAddition {+ record: None,+ set: vec![("Stage".into(), FieldInput::One("Lead".into()))],+ }],+ false,+ )+ .await,+ Err(WorkflowError::Invalid(_))+ ));+}diff --git a/crates/crm/tests/pipeline_workflows/requirements.rs b/crates/crm/tests/pipeline_workflows/requirements.rsindex 8ca6d85596..0e101018e6 100644--- a/crates/crm/tests/pipeline_workflows/requirements.rs+++ b/crates/crm/tests/pipeline_workflows/requirements.rs@@ -31,7 +31,7 @@ async fn agent_add_and_csv_import_enforce_stage_rules_and_report_invalid_rows(po&owner,pipeline,vec![EntryAddition {- record: RecordTarget::Id(acme),+ record: Some(RecordTarget::Id(acme)),set: vec![set("Stage", "Prospect")],}],true,diff --git a/crates/crm/tests/pipelines.rs b/crates/crm/tests/pipelines.rsindex 117a567896..bf0bd07f33 100644--- a/crates/crm/tests/pipelines.rs+++ b/crates/crm/tests/pipelines.rs@@ -184,7 +184,7 @@ async fn create(s: &Service, team: Uuid, record_type: PipelineRecordType) -> Pipteam_receipt(team, OWNER),CreatePipeline {name: " Renewals ".into(),- record_type,+ record_type: Some(record_type),sharing: PipelineSharing::Private,},)@@ -193,7 +193,7 @@ async fn create(s: &Service, team: Uuid, record_type: PipelineRecordType) -> Pip.pipeline}fn insert(p: &Pipeline, entity: Uuid) -> DatabaseOp {- serde_json::from_value(json!({"kind":"rows", "table":p.table_id, "change":{"kind":"insert", "rows":[[{"column":p.primary_column_id, "value":{"type":"entities","value":[{"entityType":p.record_type.as_str().to_uppercase(),"entityId":entity.to_string()}]}}]]}})).unwrap()+ serde_json::from_value(json!({"kind":"rows", "table":p.table_id, "change":{"kind":"insert", "rows":[[{"column":p.primary_column_id, "value":{"type":"entities","value":[{"entityType":p.record_type.unwrap().as_str().to_uppercase(),"entityId":entity.to_string()}]}}]]}})).unwrap()}async fn write(s: &Service,@@ -457,6 +457,89 @@ async fn primary_record_is_required_and_protected_but_can_repeat(pool: PgPool) {write(&s, &a, &p, vec![insert(&p, company)]).await.unwrap();}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn generic_pipeline_holds_free_form_rows_without_record_references(pool: PgPool) {+ let (s, _db, a, team, company) = fixture(&pool).await;+ let p = s+ .create(+ team_receipt(team, OWNER),+ CreatePipeline {+ name: "Launch".into(),+ record_type: None,+ sharing: PipelineSharing::Private,+ },+ )+ .await+ .unwrap()+ .pipeline;+ assert_eq!(p.record_type, None);++ let view = access(&a, p.id, EntityType::CrmPipeline, OWNER).await;+ let table = s.table(view.clone()).await.unwrap();+ let names: Vec<&str> = table.columns.iter().map(|column| column.name()).collect();+ assert_eq!(names, ["Name"]);+ assert_eq!(table.columns[0].column.id, p.primary_column_id);++ // No company or contact is needed: a row may even start empty.+ let blank = serde_json::from_value(+ json!({"kind":"rows","table":p.table_id,"change":{"kind":"insert","rows":[[]]}}),+ )+ .unwrap();+ let blank_row = inserted(&write(&s, &a, &p, vec![blank]).await.unwrap());+ let named = serde_json::from_value(json!({"kind":"rows","table":p.table_id,"change":{"kind":"insert","rows":[[{"column":p.primary_column_id,"value":{"type":"text","value":"Launch site"}}]]}})).unwrap();+ let named_row = inserted(&write(&s, &a, &p, vec![named]).await.unwrap());+ let rows = s.rows(view.clone(), None).await.unwrap().rows;+ assert_eq!(+ rows.iter().map(|row| row.row_id).collect::<Vec<_>>(),+ [blank_row, named_row]+ );++ // It shows in navigation, and never as a place a CRM record is tracked.+ let listed = s.list(team_receipt(team, OWNER)).await.unwrap();+ assert!(listed.iter().any(|entry| entry.pipeline.id == p.id));+ let owner = MacroUserIdStr::try_from(OWNER.to_string()).unwrap();+ assert!(+ s.entries(&owner, PipelineRecordType::Company, &[company])+ .await+ .unwrap()+ .is_empty()+ );+ assert!(+ s.record_rows(view.clone(), &[company])+ .await+ .unwrap()+ .is_empty()+ );++ // Name is an ordinary column: it can change type and be deleted.+ let empty = s+ .create(+ team_receipt(team, OWNER),+ CreatePipeline {+ name: "Numbers".into(),+ record_type: None,+ sharing: PipelineSharing::Private,+ },+ )+ .await+ .unwrap()+ .pipeline;+ let retype = serde_json::from_value(json!({"kind":"column","table":empty.table_id,"column":empty.primary_column_id,"change":{"kind":"change_type","to":{"type":"number"}}})).unwrap();+ write(&s, &a, &empty, vec![retype]).await.unwrap();+ let delete_name = serde_json::from_value(+ json!({"kind":"column","table":p.table_id,"column":p.primary_column_id,"change":{"kind":"delete"}}),+ )+ .unwrap();+ write(&s, &a, &p, vec![delete_name]).await.unwrap();+ assert_eq!(s.get(view.clone()).await.unwrap().pipeline.id, p.id);+ assert!(s.table(view.clone()).await.unwrap().columns.is_empty());+ let row = serde_json::from_value(+ json!({"kind":"rows","table":p.table_id,"change":{"kind":"insert","rows":[[]]}}),+ )+ .unwrap();+ write(&s, &a, &p, vec![row]).await.unwrap();+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn references_can_cross_teams_only_when_the_editor_has_record_access(pool: PgPool) {let (s, _, a, team, _) = fixture(&pool).await;@@ -649,7 +732,7 @@ async fn disabled_crm_cannot_create_pipeline_storage(pool: PgPool) {team_receipt(team, OWNER),CreatePipeline {name: "Sales".into(),- record_type: PipelineRecordType::Company,+ record_type: Some(PipelineRecordType::Company),sharing: PipelineSharing::Team,},)@@ -1255,7 +1338,7 @@ async fn editors_share_with_people_and_only_the_owner_changes_team_access(pool:team_receipt(team, &owner),CreatePipeline {name: "Renewals".into(),- record_type: PipelineRecordType::Company,+ record_type: Some(PipelineRecordType::Company),sharing: PipelineSharing::Private,},)diff --git a/crates/graphql_crm/src/objects.rs b/crates/graphql_crm/src/objects.rsindex 3c81fda94d..4067249fc3 100644--- a/crates/graphql_crm/src/objects.rs+++ b/crates/graphql_crm/src/objects.rs@@ -105,8 +105,13 @@ impl GraphqlCrmPipeline {}/// Which CRM record its rows reference.- async fn record_type(&self) -> GraphqlCrmPipelineRecordType {- self.0.pipeline.record_type.into()+ async fn record_type(&self) -> async_graphql::Result<GraphqlCrmPipelineRecordType> {+ // Reached only through a record's entries, which a generic pipeline never has.+ self.0+ .pipeline+ .record_type+ .map(Into::into)+ .ok_or_else(|| "This pipeline tracks no CRM records".into())}/// Whether the pipeline is shared with its team.diff --git a/crates/graphql_crm/src/test.rs b/crates/graphql_crm/src/test.rsindex 2c258948ab..f89eade273 100644--- a/crates/graphql_crm/src/test.rs+++ b/crates/graphql_crm/src/test.rs@@ -129,7 +129,7 @@ async fn one_read_per_record_type_answers_every_record_without_its_own_column()team_id: Uuid::now_v7(),name: "Deals".into(),user_id: "macro|[email protected]".into(),- record_type: PipelineRecordType::Company,+ record_type: Some(PipelineRecordType::Company),database_id: DatabaseId::new(),table_id: table,primary_column_id: primary.column.id,diff --git a/crates/macro_db_client/migrations/20261105000846_crm_generic_pipelines.sql b/crates/macro_db_client/migrations/20261105000846_crm_generic_pipelines.sqlnew file mode 100644index 0000000000..f462e31470--- /dev/null+++ b/crates/macro_db_client/migrations/20261105000846_crm_generic_pipelines.sql@@ -0,0 +1,3 @@+-- A generic pipeline tracks no CRM record: its rows are free-form, like a database's.+SET LOCAL lock_timeout = '5s';+ALTER TABLE crm_pipeline_entities ALTER COLUMN record_type DROP NOT NULL;diff --git a/crates/macro_db_client/migrations/20261105015628_crm_generic_pipeline_primary_column.sql b/crates/macro_db_client/migrations/20261105015628_crm_generic_pipeline_primary_column.sqlnew file mode 100644index 0000000000..755d05e6c1--- /dev/null+++ b/crates/macro_db_client/migrations/20261105015628_crm_generic_pipeline_primary_column.sql@@ -0,0 +1,6 @@+-- A generic pipeline's Name is an ordinary column, so it can be deleted, leaving+-- primary_column_id naming no column. A tracked pipeline's record column stays:+-- ColumnProtection::Delete refuses deleting it in the domain and in the cell store.+-- No ON DELETE SET NULL: it would wait on the row lock the pipeline's write guard holds.+SET LOCAL lock_timeout = '5s';+ALTER TABLE crm_pipeline_entities DROP CONSTRAINT crm_pipeline_entities_primary_column_id_fkey;diff --git a/docs/agent-guide/crm.md b/docs/agent-guide/crm.mdindex 3688a606b1..bf1e8d0f2d 100644--- a/docs/agent-guide/crm.md+++ b/docs/agent-guide/crm.md@@ -6,7 +6,7 @@ On desktop, the local sidebar uses the same navigation primitives as Email and TIts **New** menu creates a **Company**, a **Contact**, or a **Pipeline** (Pipelineonly when pipelines are enabled; disabled until the team's CRM is enabled). The**Records** section lists **Companies**, **People**, **Tasks**, **Email**, **Notes**,-**Calls**, and **Databases**, in that order; Pipelines and Lists follow.+and **Calls**, in that order; Pipelines and Lists follow.There are no built-in company views or Board/List layout. Companies and Peopleare plain soup lists with the shared pagination. Existing personal/team savedviews stay in the toolbar's Views menu.@@ -16,7 +16,7 @@ dot, including desktop preview activation, keyboard opening, and phone navigatioThe read is saved in the background; a failed request restores the dot so openingit again can retry. Marking read does not mark the notification done.-**Rollout:** Tasks, Email, Notes, Calls and Databases require PostHog `enable-crm-activity`+**Rollout:** Tasks, Email, Notes and Calls require PostHog `enable-crm-activity`(off by default; local override: `VITE_ENABLE_CRM_ACTIVITY=true`). CRM also usesthis flag to decide whether to supply its task-composer preset, and with`enable-crm` to show the Customer / Contact pill when creating any task. With it off, only Companies and People@@ -24,9 +24,6 @@ appear in Records, activity queries do not run, and activity deep links return tCompanies after flags finish loading. Global task creation uses the standardcomposer; record-level New task still associates the new task with that record.With it on, the activity and contextual composer behavior below applies.-Databases additionally requires `enable-databases`, including record tabs and direct tab links.-Database flag loading and unavailable states keep the desktop title and navigation-toggle visible, without mounting the list query or creation controls.Task creation opens immediately from the focused pane's registered preset,without fetching record details. Contact company prefills use already-loadeddetails. If CRM's flag is still loading, CRM supplies no preset. Later flag,@@ -35,7 +32,7 @@ context. If an embedded record shows a loading error, global task creation stilltargets the selected record until you close its details.The selected Customers list is stored on the pane as `sN.crm.tab`. People uses-`people`, activity tabs use `tasks`, `email`, `notes`, `calls`, or `databases`, a list uses+`people`, activity tabs use `tasks`, `email`, `notes`, or `calls`, a list uses`list:<uuid>`, and hidden companies use `hidden`. Companies is the default andomits the key. A pipeline has its own path, `/app/companies/pipeline/<uuid>`;older `sN.crm.tab=pipeline:<uuid>` URLs and shared `crmView` links that show a@@ -60,14 +57,6 @@ same preset. With an embedded company or contact detail open, global Createprefills the current breadcrumb record; a contact also includes its company.Closing the detail returns global Create to the unassociated CRM preset.-**Databases** lists each accessible database that contains a CRM-linked row once.-A company's tab includes rows linked to that company or its visible contacts; a-contact's tab matches that contact only. The sidebar view matches all visible CRM-records. Unlinked databases, trashed databases, and databases without access stay-out. These are row associations, not whole-database associations or new sharing-grants. **New database** opens the existing creation flow. Add a Companies or-Contacts column and link a row before the database appears in CRM.-Empty collection and record lists fill the available height with a horizontallycentered illustration, guidance, and a relevant creation action, raised towardthe toolbar rather than vertically centered. Search-empty states use a@@ -145,7 +134,7 @@ and expand into the shared Email/Tasks search bar. Command-F expands and focusesthe field; Close or Escape clears the query and returns to the icon.On touch devices, CRM uses the same scrollable pill tabs as Tasks in the top-header: Companies, People, Tasks, Email, Notes, Calls, Databases, available pipelines, and+header: Companies, People, Tasks, Email, Notes, Calls, available pipelines, andenabled lists. Swipe thestrip horizontally to reach every destination; the selected tab stays visible.The tabs remain available inside pipelines, with no hamburger button. Company@@ -160,7 +149,7 @@ row navigates in place.Verify touch spacing with a nonzero top safe area (for example 47px): the CRMtab strip clears the status bar, while standalone company/contact Overview and-Team, Emails, Files, Tasks, Calls, and Databases clear both the status bar and floating+Team, Emails, Files, Tasks, and Calls clear both the status bar and floatingrecord navigation. Switch tabs and check the first title/search control isvisible and tappable. Scroll to the end to check content clears the dock. Repeatat tablet width; desktop retains its usual spacing. An embedded record header@@ -207,11 +196,8 @@ and actions so the record name and navigation retain space. Tap the switcher toopen the shared **Switch view** bottom drawer: every available sectionhas an icon and label, with a check beside the current section. Choosing a sectioncloses the drawer and updates the header label; Escape, backdrop tap, and drag-also dismiss it. Focus returns to the section trigger. Databases remains gated-by its feature flag, and contacts do not show Team. The workspace's scrollable-mobile view strip is unchanged. A direct Databases section link retains its-title with the unavailable-state message when the flag is off, without database-queries or creation actions. Copy-link islands are 40px square on touch with+also dismiss it. Focus returns to the section trigger. Contacts do not show Team.+The workspace's scrollable mobile view strip is unchanged. Copy-link islands are 40px square on touch witha 24px icon. Verify both record types, section changes, dismissal, copy feedback,and header fit at phone and tablet widths.@@ -263,16 +249,16 @@ the toggle to dismiss it; the open state is not restored on a later visit.It copies the record's direct URL and shows a confirmation toast; this is alsoavailable in the embedded company and contact breadcrumb header.-The Team, Emails, Files, Tasks, Calls, and Databases views share a compact+The Team, Emails, Files, Tasks, and Calls views share a compacttoolbar. On desktop, search stays on the left with existing filters and creationactions on the right. On touch, search has 16px of space below the header andfills the row beside the filter button, or the whole row without filters.Email importance and inbox choices open in the shared filter drawer.Section creation actions appear at the bottom right above the navigation dock,replacing the default app-wide action: Add contact, New email, New note, New task,-New call, or New database. Add contact is available once the company is loaded and visible,+or New call. Add contact is available once the company is loaded and visible,including companies without a domain; contact emails may use any valid domain.-Email-sync and database gates, recipients, and task associations still apply. With company email+Email-sync gates, recipients, and task associations still apply. With company emailsync off, New email stays visible but disabled; New company must not replace it.Keyboard focus andhigher-priority composers suppress the floating action; leaving the section@@ -291,7 +277,7 @@ checkboxes, including on touch devices.A company is laid out like a project. On desktop, its split header or embeddedbreadcrumb header shows rounded view tabs for `Overview`, `Team`, `Emails`,-`Files`, `Tasks`, `Calls`, and `Databases`, collapsing to icons when narrow.+`Files`, `Tasks`, and `Calls`, collapsing to icons when narrow.Touch headers use the section drawer described above. Overview shows the name, pillsfor each domain and `Last interacted`, the generated description, a**Pipelines** section and the Discussion. Pipelines stacks one full-width card@@ -330,8 +316,8 @@ When a record list fails to refresh (for example, the record becameinaccessible), it replaces its rows with `Couldn't load this list.` and`Try again` reloads it; a failed later page keeps the rows and shows `Couldn'tload more.`-A contact has the same layout with `Overview`, `Emails`, `Files`, `Tasks`, `Calls`, and-`Databases`: Overview pills show the email, the company (opens it) and `Last+A contact has the same layout with `Overview`, `Emails`, `Files`, `Tasks`, and+`Calls`: Overview pills show the email, the company (opens it) and `Lastinteracted`, followed by the contact's Pipelines cards. Its Files, Tasks, Calls,and References show items associated with the contact itself (its `Contacts`property or an @mention of it), not everything associated with its company;@@ -343,13 +329,13 @@ contact also reference its company. The side panel contains References, with noempty Sharing section.In workspace activity and a company or contact's embedded sections, clicking a-Task, Email, Note, Call, or Database opens its authorized detail inside Customers.+Task, Email, Note, or Call opens its authorized detail inside Customers.The CRM sidebar stays in place and the breadcrumb shows the source view, recordtrail (when present), and selected item, without section labels such as Tasks orFiles or an extra separator before preview titles. The current record breadcrumbreturns to the captured section and entry state. The item URL is nested under`/app/companies` or `/app/companies/pipeline/<uuid>`. Typed record sections use-`/<record-type>/<record-id>/<tasks-emails-calls-or-databases>/<item-id>`, without+`/<record-type>/<record-id>/<tasks-emails-or-calls>/<item-id>`, withoutrepeating the item type or a task's `md/task` suffix. Redundant typed URLs forthese sections do not resolve. Workspace activity retains`/<item-type>/<item-id>` and document metadata. Record Files and overview notes@@ -361,8 +347,9 @@ split behavior; modified row clicks keep the existing split behavior. On touch,the existing header and breadcrumb conventions apply without a new navigation UI.Verify that tasks display their status and properties, not the Drive editor.-Verify the real CRM routes separately with accessible and inaccessible databases,-multiple matching rows per database, empty matches, and a second page of results.+Links to the retired Databases views still resolve: a record's `/databases`+section opens the record, `/databases/<id>` and `/app/companies/database/<id>`+open the database itself, and a saved `databases` tab opens Companies.Mentioning a company or contact with `@` in a document or task records it as areference of that record (removing the chip removes it) without sharing the@@ -398,15 +385,15 @@ before either toggle, including on a pipeline, and stays hidden when the splitcannot close.The sidebar's Records and Lists sections can also collapse independently.-**Pipelines** in the CRM sidebar hold company or contact entries in the shared-records editor. They have their own identity, ownership and sharing; their+**Pipelines** in the CRM sidebar hold company or contact entries, or free-form+rows in a generic pipeline, in the shared records editor. They have their own identity, ownership and sharing; theirstorage does not appear as a separate database in navigation.**New pipeline** is disabled until the team's CRM is enabled. For a new team,use **Open CRM settings** in the empty state to enable CRM, then use the backarrow to return to Customers and create a pipeline. Verify this with a newly created team as well asan existing CRM-enabled team.Choose **New pipeline**, enter a name in the dialog's first row, pick-**Companies** (the default) or **Contacts** from the record-type pill, and tick+**Companies** (the default), **Contacts**, or **Generic** from the record-type pill, and tick**Share with my team** to share it (unticked keeps it private). **Createpipeline** or Command-Enter submits. Creating opens the pipeline'seditable table. Team members can edit shared pipelines; the creator owns them.@@ -421,7 +408,13 @@ pasted into an editor it becomes a pipeline mention (see[CRM pipeline mentions](documents.md#crm-pipeline-mentions)). On mobile, teamaccess is in the **Team** tab.-The first column is a required company/contact reference. Clicking a filled+A **Generic** pipeline needs no company or contact. It starts like a new database,+with one optional **Name** text column and no Stage, Owner or Revenue. Name is an+ordinary column, so it can be renamed, retyped or deleted; add any columns and+views from there. **Add entry** starts a row in place, with no record+form or stage requirements. **Import CSV** is not offered; **Export CSV** is.++In a company or contact pipeline, the first column is a required company/contact reference. Clicking a filledreference, or pressing Enter on it, opens that company or contact; on desktop itopens in place with the pipeline name in its breadcrumb (choose it to return),and on mobile in its own view. The same applies to the reference shown as adiff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex 08e27870aa..d8de70a56f 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -4547,17 +4547,15 @@ export type CreatePairingRequest = {};/**- * Request to create an empty pipeline with the standard CRM columns.+ * Request to create an empty pipeline: the standard CRM columns for a tracked+ * record, or one Name column, like a new database, for a generic pipeline.*/export type CreatePipeline = {/*** Pipeline name.*/name: string;- /**- * Company or contact entries.- */- recordType: PipelineRecordType;+ recordType?: null | PipelineRecordType;/*** Defaults to private.*/@@ -11668,13 +11666,11 @@ export type Pipeline = {*/name: string;/**- * Protected primary column.+ * A tracked pipeline's protected record reference. A generic pipeline's+ * Name, which names no column once someone deletes it.*/primaryColumnId: string;- /**- * Kind of the primary reference.- */- recordType: PipelineRecordType;+ recordType: null | PipelineRecordType;/*** Whether the pipeline has a team grant.*/diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex f46e38bf70..0e58ebef6e 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -27585,16 +27585,23 @@},"CreatePipeline": {"type": "object",- "description": "Request to create an empty pipeline with the standard CRM columns.",- "required": ["name", "recordType"],+ "description": "Request to create an empty pipeline: the standard CRM columns for a tracked\nrecord, or one Name column, like a new database, for a generic pipeline.",+ "required": ["name"],"properties": {"name": {"type": "string","description": "Pipeline name."},"recordType": {- "$ref": "#/components/schemas/PipelineRecordType",- "description": "Company or contact entries."+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/PipelineRecordType",+ "description": "Company or contact entries; omitted, a generic pipeline of free-form rows."+ }+ ]},"sharing": {"$ref": "#/components/schemas/PipelineSharing",@@ -39054,11 +39061,18 @@"primaryColumnId": {"type": "string","format": "uuid",- "description": "Protected primary column."+ "description": "A tracked pipeline's protected record reference. A generic pipeline's\nName, which names no column once someone deletes it."},"recordType": {- "$ref": "#/components/schemas/PipelineRecordType",- "description": "Kind of the primary reference."+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/PipelineRecordType",+ "description": "Kind of the primary reference; `None` for a generic pipeline, whose\nprimary column is plain text."+ }+ ]},"sharing": {"$ref": "#/components/schemas/PipelineSharing",