Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(crm): allow name-only companies and personal email contacts (#8847)

gbirmand33cc2bf6a8a
diff --git a/.sqlx/query-13583c73aad2e1af32f85c6d1313747afb7af618c98ae9d23ece74ff751ff538.json b/.sqlx/query-13583c73aad2e1af32f85c6d1313747afb7af618c98ae9d23ece74ff751ff538.json
new file mode 100644
index 0000000000..df66fdd9e3
--- /dev/null
+++ b/.sqlx/query-13583c73aad2e1af32f85c6d1313747afb7af618c98ae9d23ece74ff751ff538.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT id FROM team WHERE id = $1 FOR KEY SHARE",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "13583c73aad2e1af32f85c6d1313747afb7af618c98ae9d23ece74ff751ff538"
+}
diff --git a/.sqlx/query-8f27aa55aa502bac325c84ab62c854ede412158bf7ca13b931b56636431c71ff.json b/.sqlx/query-17b2cb7baf6fa3f5e5f00a7d29c939f9f92944eee30b52b964ff86f85ba63962.json
similarity index 57%
rename from .sqlx/query-8f27aa55aa502bac325c84ab62c854ede412158bf7ca13b931b56636431c71ff.json
rename to .sqlx/query-17b2cb7baf6fa3f5e5f00a7d29c939f9f92944eee30b52b964ff86f85ba63962.json
index 9dc3d05273..aa909674fd 100644
--- a/.sqlx/query-8f27aa55aa502bac325c84ab62c854ede412158bf7ca13b931b56636431c71ff.json
+++ b/.sqlx/query-17b2cb7baf6fa3f5e5f00a7d29c939f9f92944eee30b52b964ff86f85ba63962.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO crm_companies\n (team_id, custom_name, manually_created, first_interaction, last_interaction)\n VALUES ($1, $2, $3, $4, $5)\n RETURNING id\n ",
+ "query": "\n INSERT INTO crm_companies\n (id, team_id, custom_name, manually_created, first_interaction, last_interaction)\n VALUES ($6, $1, $2, $3, $4, $5)\n RETURNING id\n ",
"describe": {
"columns": [
{
@@ -15,12 +15,13 @@
"Text",
"Bool",
"Timestamptz",
- "Timestamptz"
+ "Timestamptz",
+ "Uuid"
]
},
"nullable": [
false
]
},
- "hash": "8f27aa55aa502bac325c84ab62c854ede412158bf7ca13b931b56636431c71ff"
+ "hash": "17b2cb7baf6fa3f5e5f00a7d29c939f9f92944eee30b52b964ff86f85ba63962"
}
diff --git a/.sqlx/query-71ae6483d5e25a648f7ff586d9bf235ebb615029f7fecd1016045e9b4418fbfb.json b/.sqlx/query-71ae6483d5e25a648f7ff586d9bf235ebb615029f7fecd1016045e9b4418fbfb.json
new file mode 100644
index 0000000000..029cd4f8e1
--- /dev/null
+++ b/.sqlx/query-71ae6483d5e25a648f7ff586d9bf235ebb615029f7fecd1016045e9b4418fbfb.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT crm_enabled\n FROM team_crm_settings\n WHERE team_id = $1\n FOR SHARE\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "crm_enabled",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "71ae6483d5e25a648f7ff586d9bf235ebb615029f7fecd1016045e9b4418fbfb"
+}
diff --git a/.sqlx/query-b845e01904b9e9f8d1f322e788b7cf6555ee13b3de24bbe50bbc801a2730e446.json b/.sqlx/query-8cb401c9e89e73f3f4193970a3462df2a4105c2f10dbb1fb57f627235c147068.json
similarity index 67%
rename from .sqlx/query-b845e01904b9e9f8d1f322e788b7cf6555ee13b3de24bbe50bbc801a2730e446.json
rename to .sqlx/query-8cb401c9e89e73f3f4193970a3462df2a4105c2f10dbb1fb57f627235c147068.json
index 45964bff36..fd1a094c38 100644
--- a/.sqlx/query-b845e01904b9e9f8d1f322e788b7cf6555ee13b3de24bbe50bbc801a2730e446.json
+++ b/.sqlx/query-8cb401c9e89e73f3f4193970a3462df2a4105c2f10dbb1fb57f627235c147068.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n input.address AS \"address!\",\n (m.email IS NOT NULL) AS \"exists!\",\n COALESCE(m.contact_hidden, FALSE) AS \"contact_hidden!\",\n COALESCE(m.company_hidden, FALSE) AS \"company_hidden!\",\n COALESCE(m.email_sync, FALSE) AS \"email_sync!\"\n FROM UNNEST($2::text[]) WITH ORDINALITY AS input(address, ord)\n LEFT JOIN (\n SELECT\n ct.email AS email,\n ct.hidden AS contact_hidden,\n c.hidden AS company_hidden,\n c.email_sync AS email_sync\n FROM crm_contacts ct\n JOIN crm_companies c ON c.id = ct.company_id\n WHERE c.team_id = $1\n ) m ON m.email = input.address\n ORDER BY input.ord\n ",
+ "query": "\n SELECT\n input.address AS \"address!\",\n (m.email IS NOT NULL) AS \"exists!\",\n COALESCE(m.contact_hidden, FALSE) AS \"contact_hidden!\",\n COALESCE(m.company_hidden, FALSE) AS \"company_hidden!\",\n COALESCE(m.email_sync, FALSE) AS \"email_sync!\"\n FROM UNNEST($2::text[]) WITH ORDINALITY AS input(address, ord)\n LEFT JOIN (\n SELECT\n ct.email AS email,\n BOOL_OR(ct.hidden) AS contact_hidden,\n BOOL_OR(c.hidden) AS company_hidden,\n BOOL_AND(c.email_sync) AS email_sync\n FROM crm_contacts ct\n JOIN crm_companies c ON c.id = ct.company_id\n WHERE c.team_id = $1 AND ct.email = ANY($2::text[])\n GROUP BY ct.email\n ) m ON m.email = input.address\n ORDER BY input.ord\n ",
"describe": {
"columns": [
{
@@ -43,5 +43,5 @@
null
]
},
- "hash": "b845e01904b9e9f8d1f322e788b7cf6555ee13b3de24bbe50bbc801a2730e446"
+ "hash": "8cb401c9e89e73f3f4193970a3462df2a4105c2f10dbb1fb57f627235c147068"
}
diff --git a/.sqlx/query-9f1042f72a5c1a5137fbb9cbaee798f5df26e8da3fa98c5afec3cb8d130ab293.json b/.sqlx/query-9f1042f72a5c1a5137fbb9cbaee798f5df26e8da3fa98c5afec3cb8d130ab293.json
deleted file mode 100644
index fe312dd6eb..0000000000
--- a/.sqlx/query-9f1042f72a5c1a5137fbb9cbaee798f5df26e8da3fa98c5afec3cb8d130ab293.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT EXISTS (\n SELECT 1 FROM crm_domains\n WHERE company_id = $1 AND LOWER(domain) = $2\n ) AS \"exists!\"\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "exists!",
- "type_info": "Bool"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "9f1042f72a5c1a5137fbb9cbaee798f5df26e8da3fa98c5afec3cb8d130ab293"
-}
diff --git a/.sqlx/query-cc9cd9c1d19f49627d619e8111ccf71139a34878ece29560f7a1c48a73c974d8.json b/.sqlx/query-cc9cd9c1d19f49627d619e8111ccf71139a34878ece29560f7a1c48a73c974d8.json
deleted file mode 100644
index 6134ab08e0..0000000000
--- a/.sqlx/query-cc9cd9c1d19f49627d619e8111ccf71139a34878ece29560f7a1c48a73c974d8.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT COALESCE(\n (SELECT crm_enabled FROM team_crm_settings WHERE team_id = $1),\n FALSE\n ) AS \"crm_enabled!\"\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "crm_enabled!",
- "type_info": "Bool"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "cc9cd9c1d19f49627d619e8111ccf71139a34878ece29560f7a1c48a73c974d8"
-}
diff --git a/.sqlx/query-9ebc27f64f534146a85303cb8270dab4f5aba378fd5d3cc1aecfde08b5dff5bb.json b/.sqlx/query-e0a7b7dfad2f3937e936f4e6641428dc95d2381d586fa8699252e7ca6ad33cf8.json
similarity index 90%
rename from .sqlx/query-9ebc27f64f534146a85303cb8270dab4f5aba378fd5d3cc1aecfde08b5dff5bb.json
rename to .sqlx/query-e0a7b7dfad2f3937e936f4e6641428dc95d2381d586fa8699252e7ca6ad33cf8.json
index a6e8619c7b..60ee69aa5a 100644
--- a/.sqlx/query-9ebc27f64f534146a85303cb8270dab4f5aba378fd5d3cc1aecfde08b5dff5bb.json
+++ b/.sqlx/query-e0a7b7dfad2f3937e936f4e6641428dc95d2381d586fa8699252e7ca6ad33cf8.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n ct.id,\n ct.company_id,\n ct.email,\n ct.name,\n ct.hidden,\n ct.first_interaction,\n ct.last_interaction,\n ct.created_at,\n ct.updated_at\n FROM crm_contacts ct\n JOIN crm_companies co ON co.id = ct.company_id\n WHERE ct.email = LOWER($1)\n AND co.team_id = $2\n AND ($3 OR (ct.hidden = FALSE AND co.hidden = FALSE))\n ORDER BY ct.id DESC\n LIMIT 1\n ",
+ "query": "\n SELECT\n ct.id,\n ct.company_id,\n ct.email,\n ct.name,\n ct.hidden,\n ct.first_interaction,\n ct.last_interaction,\n ct.created_at,\n ct.updated_at\n FROM crm_contacts ct\n JOIN crm_companies co ON co.id = ct.company_id\n WHERE ct.email = LOWER($1)\n AND co.team_id = $2\n AND ($3 OR (ct.hidden = FALSE AND co.hidden = FALSE))\n LIMIT 2\n ",
"describe": {
"columns": [
{
@@ -68,5 +68,5 @@
false
]
},
- "hash": "9ebc27f64f534146a85303cb8270dab4f5aba378fd5d3cc1aecfde08b5dff5bb"
+ "hash": "e0a7b7dfad2f3937e936f4e6641428dc95d2381d586fa8699252e7ca6ad33cf8"
}
diff --git a/apps/docs/AI/mcp/tools/create-company.mdx b/apps/docs/AI/mcp/tools/create-company.mdx
index d8aaf1dfda..1f5136e287 100644
--- a/apps/docs/AI/mcp/tools/create-company.mdx
+++ b/apps/docs/AI/mcp/tools/create-company.mdx
@@ -1,17 +1,17 @@
---
title: CreateCompany
description: >-
- Add a company to the user's team CRM by name and web domain, as New Company in
- the CRM does.
+ Add a company to the user's team CRM by name and optional web domain, as New
+ Company in the CRM does.
---
# CreateCompany
-Add a company to the user's team CRM by name and web domain, as New Company in the CRM does. Companies a team emails are usually added automatically, so check ListCompanies first. Set its stage, owner, and other properties afterwards with SetEntityProperty (entity type company).
+Add a company to the user's team CRM by name and optional web domain, as New Company in the CRM does. Companies a team emails are usually added automatically, so check ListCompanies first. Set its stage, owner, and other properties afterwards with SetEntityProperty (entity type company).
## Parameters
| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `name` | string | Yes | The company's display name, e.g. "Acme". |
-| `domain` | string | Yes | The company's web domain, e.g. "acme.com" — no scheme or path. Contacts are matched to the company by this domain. |
+| `domain` | string | No | Optional company web domain; omit when unknown. For example, "acme.com" — no scheme or path. Contacts are matched to the company by this domain. |
diff --git a/apps/docs/AI/mcp/tools/create-contact.mdx b/apps/docs/AI/mcp/tools/create-contact.mdx
index 1f52b133dd..3eb7e8b0cb 100644
--- a/apps/docs/AI/mcp/tools/create-contact.mdx
+++ b/apps/docs/AI/mcp/tools/create-contact.mdx
@@ -7,7 +7,7 @@ description: >-
# CreateContact
-Add a contact person to a company in the user's team CRM, as Add Contact on a company does. The email's domain must be one of the company's domains. Find the company with ListCompanies, or add it first with CreateCompany.
+Add a contact person to a company in the user's team CRM, as Add Contact on a company does. Personal email and addresses with a different domain are accepted; selecting a company is an explicit association. Find the company with ListCompanies, or add it first with CreateCompany.
## Parameters
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index f7a18fff49..be29ed7612 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -68,6 +68,12 @@ prompt under an open sheet and its picker, above a transient notice, and that
notice on top of the sheet:
`bunx playwright test --config src/components/app/mobile/browser-test/playwright.config.ts`.
+CRM creation has backend-free desktop/phone coverage for name-only companies,
+personal-email contacts and explicit company selection:
+`bunx playwright test --config src/features/crm/browser-test/creation/playwright.config.ts`.
+Nested picker selection must keep its containing drawer open when the option
+unmounts during the tap; drawer dismissal checks the original event path.
+
Composer typeahead menus choosing the side with room for their full list
(`floatWithSelection`'s `fullHeight`), above a composer at the bottom of a
phone screen and below one near the top, and the floating format menu staying
@@ -331,6 +337,11 @@ resolved session ID; keep the existing `AgentSessionProvider` subscription to
`agent_session` rather than enabling legacy block tracking of placeholder IDs.
- Share URL recognition with `packages/lexical-core/utils/auto-link.ts`; preserve explicit unlink markers when saving and rendering messages. See `packages/lexical-core/README.md` at the repository root.
+- CRM creation accepts name-only companies and full contact email addresses.
+ Company selection is explicit; a matching domain only suggests a company.
+ Keep the standalone and pipeline forms consistent (see
+ `docs/agent-guide/crm.md` at the repository root).
+
- Empty human DMs use the shared centered conversations graphic and explain email delivery to nonusers; keep this state out of agent DMs, loading/error states, and populated timelines.
- Keep CRM database discovery row-linked and permission-scoped; use horizontally
centered actionable list states raised toward the toolbar and shared skeletons,
diff --git a/apps/web/src/components/app/mobile/MobileDrawer.tsx b/apps/web/src/components/app/mobile/MobileDrawer.tsx
index 261ea4f59a..60b209a741 100644
--- a/apps/web/src/components/app/mobile/MobileDrawer.tsx
+++ b/apps/web/src/components/app/mobile/MobileDrawer.tsx
@@ -241,7 +241,20 @@ function MobileDrawerHandle<T extends ValidComponent = 'div'>(
* drawer as usual.
*/
function dismissesDrawer(event: PointerEvent) {
- return event.target !== document.documentElement;
+ if (event.target === document.documentElement) return false;
+ // A nested picker can remove its selected option during pointerup, before
+ // Corvu checks containment. The original event path still identifies the
+ // drawer that contained the tap; selecting an option must not dismiss it.
+ if (event.target instanceof Node && !event.target.isConnected) {
+ return !event
+ .composedPath()
+ .some(
+ (node) =>
+ node instanceof HTMLElement &&
+ node.hasAttribute('data-corvu-drawer-content')
+ );
+ }
+ return true;
}
/**
diff --git a/apps/web/src/features/crm/browser-test/creation/creation.browser.e2e.ts b/apps/web/src/features/crm/browser-test/creation/creation.browser.e2e.ts
new file mode 100644
index 0000000000..59c11564ee
--- /dev/null
+++ b/apps/web/src/features/crm/browser-test/creation/creation.browser.e2e.ts
@@ -0,0 +1,126 @@
+import { expect, test } from '@playwright/test';
+
+test('creates a named company without inventing a domain', async ({
+ page,
+}, testInfo) => {
+ await page.goto('/');
+ await page.getByRole('button', { name: 'New company', exact: true }).click();
+ await page
+ .getByRole('textbox', { name: 'Company name' })
+ .fill('Community group');
+ await page.screenshot({ path: testInfo.outputPath('name-only-company.png') });
+ await page.getByRole('button', { name: /^Create Company/ }).click();
+ await expect(page.getByTestId('created')).toHaveText(
+ '{"name":"Community group"}'
+ );
+});
+
+for (const company of ['Acme', 'Community group']) {
+ test(`creates a personal-email contact at ${company}`, async ({
+ page,
+ }, testInfo) => {
+ await page.goto('/');
+ await page
+ .getByRole('button', { name: 'New contact', exact: true })
+ .click();
+ await page.getByRole('textbox', { name: 'Contact name' }).fill('Jane');
+ await page
+ .getByRole('textbox', { name: 'Email', exact: true })
+ .fill('[email protected]');
+ await page
+ .getByRole('button', { name: 'Choose a company', exact: true })
+ .click();
+ await page.getByRole('option', { name: new RegExp(company) }).click();
+ await page.screenshot({
+ path: testInfo.outputPath('personal-email-contact.png'),
+ });
+ await page.getByRole('button', { name: /^Create Contact/ }).click();
+ await expect(page.getByTestId('created')).toHaveText(
+ JSON.stringify({
+ companyId: company === 'Acme' ? 'acme' : 'name-only',
+ name: 'Jane',
+ email: '[email protected]',
+ })
+ );
+ });
+}
+
+test('creates a name-only company while adding a deal', async ({ page }) => {
+ await page.goto('/');
+ await page.getByRole('button', { name: 'New deal', exact: true }).click();
+ await page
+ .getByRole('combobox', { name: 'Find or add a company' })
+ .fill('New group');
+ await page.getByRole('option', { name: 'Add company “New group”' }).click();
+ await page.getByRole('button', { name: /^Add deal/ }).click();
+ await expect(page.getByTestId('created')).toHaveText('{"name":"New group"}');
+});
+
+test('selects a different company for a pipeline contact', async ({ page }) => {
+ await page.goto('/');
+ await page
+ .getByRole('button', { name: 'New pipeline contact', exact: true })
+ .click();
+ await page
+ .getByRole('combobox', { name: 'Find or add a contact' })
+ .fill('[email protected]');
+ await page
+ .getByRole('option', { name: 'Add contact “[email protected]”' })
+ .click();
+ await page.getByRole('textbox', { name: 'Contact name' }).fill('Jane');
+ await page
+ .getByRole('button', { name: 'Choose a company', exact: true })
+ .click();
+ await page.getByRole('option', { name: /Community group/ }).click();
+ await page
+ .getByRole('textbox', { name: 'Email', exact: true })
+ .fill('[email protected]');
+ await page.getByRole('button', { name: /^Add contact/ }).click();
+ await expect(page.getByTestId('created')).toHaveText(
+ '{"companyId":"name-only","name":"Jane","email":"[email protected]"}'
+ );
+});
+
+test('requires accepting a suggested company before creating a pipeline contact', async ({
+ page,
+}, testInfo) => {
+ const errors: string[] = [];
+ page.on('pageerror', (error) => errors.push(error.message));
+ await page.goto('/');
+ await page
+ .getByRole('button', { name: 'New pipeline contact', exact: true })
+ .click();
+ await page
+ .getByRole('combobox', { name: 'Find or add a contact' })
+ .fill('[email protected]');
+ await page
+ .getByRole('option', { name: 'Add contact “[email protected]”' })
+ .click();
+ await page.getByRole('textbox', { name: 'Contact name' }).fill('Jane');
+ await page.getByRole('button', { name: /^Add contact/ }).click();
+ await expect(page.getByRole('alert')).toHaveText(
+ 'Choose a company for this contact'
+ );
+ await expect(page.getByTestId('created')).toBeEmpty();
+ const suggestion = page.getByRole('button', {
+ name: 'Use suggested company: Acme',
+ exact: true,
+ });
+ if (testInfo.project.name === 'desktop') {
+ await suggestion.focus();
+ await expect(page.locator('[role="tooltip"]')).toHaveText('Acme');
+ await page.keyboard.press('Enter');
+ await expect(page.locator('[role="tooltip"]')).toHaveCount(0);
+ await expect(page.getByTestId('created')).toBeEmpty();
+ } else {
+ await suggestion.click();
+ }
+ await page
+ .getByRole('textbox', { name: 'Email', exact: true })
+ .fill('[email protected]');
+ await page.getByRole('button', { name: /^Add contact/ }).click();
+ await expect(page.getByTestId('created')).toHaveText(
+ '{"companyId":"acme","name":"Jane","email":"[email protected]"}'
+ );
+ expect(errors).toEqual([]);
+});
diff --git a/apps/web/src/features/crm/browser-test/creation/fixture.tsx b/apps/web/src/features/crm/browser-test/creation/fixture.tsx
new file mode 100644
index 0000000000..1016fe4ac8
--- /dev/null
+++ b/apps/web/src/features/crm/browser-test/creation/fixture.tsx
@@ -0,0 +1,83 @@
+import '../../../../index.css';
+import { Button } from '@ui';
+import { createSignal, Show } from 'solid-js';
+import { render } from 'solid-js/web';
+import { AddPipelineRecordDialog } from '../../views/add-pipeline-record';
+import { CreateCompanyModal } from '../../views/create-company';
+import { CreateContactModal } from '../../views/create-contact';
+import { created, setCreated } from './preview-adapters';
+
+function Fixture() {
+ const [open, setOpen] = createSignal<
+ 'company' | 'contact' | 'deal' | 'pipeline-contact'
+ >();
+ const close = () => setOpen(undefined);
+ return (
+ <main class="min-h-dvh bg-page p-6 text-ink">
+ <Button
+ onClick={() => {
+ setCreated('');
+ setOpen('company');
+ }}
+ >
+ New company
+ </Button>
+ <Button
+ onClick={() => {
+ setCreated('');
+ setOpen('contact');
+ }}
+ >
+ New contact
+ </Button>
+ <Button
+ onClick={() => {
+ setCreated('');
+ setOpen('deal');
+ }}
+ >
+ New deal
+ </Button>
+ <Button
+ onClick={() => {
+ setCreated('');
+ setOpen('pipeline-contact');
+ }}
+ >
+ New pipeline contact
+ </Button>
+ <Show when={open() === 'deal' || open() === 'pipeline-contact'}>
+ <AddPipelineRecordDialog
+ pipeline={{
+ name: 'Sales',
+ recordType: open() === 'deal' ? 'company' : 'contact',
+ }}
+ columns={[
+ {
+ id: 'record',
+ name: 'Record',
+ dataType: 'ENTITY',
+ specificEntityType: open() === 'deal' ? 'COMPANY' : 'CONTACT',
+ isMultiSelect: false,
+ options: [],
+ writable: true,
+ },
+ ]}
+ initialValues={{}}
+ onCreate={async () => true}
+ onClose={close}
+ />
+ </Show>
+ <Show when={open() === 'company'}>
+ <CreateCompanyModal open onClose={close} onCreated={close} />
+ </Show>
+ <Show when={open() === 'contact'}>
+ <CreateContactModal target={{}} onClose={close} onCreated={close} />
+ </Show>
+ <pre data-testid="created">{created()}</pre>
+ </main>
+ );
+}
+
+const root = document.getElementById('root');
+if (root) render(() => <Fixture />, root);
diff --git a/apps/web/src/features/crm/browser-test/creation/index.html b/apps/web/src/features/crm/browser-test/creation/index.html
new file mode 100644
index 0000000000..f612a8e791
--- /dev/null
+++ b/apps/web/src/features/crm/browser-test/creation/index.html
@@ -0,0 +1,5 @@
+<!doctype html>
+<html lang="en" data-modality="keyboard">
+ <head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>CRM creation</title></head>
+ <body><div id="root"></div><script type="module" src="/fixture.tsx"></script></body>
+</html>
diff --git a/apps/web/src/features/crm/browser-test/creation/playwright.config.ts b/apps/web/src/features/crm/browser-test/creation/playwright.config.ts
new file mode 100644
index 0000000000..216962efcb
--- /dev/null
+++ b/apps/web/src/features/crm/browser-test/creation/playwright.config.ts
@@ -0,0 +1,40 @@
+import { fileURLToPath } from 'node:url';
+import { defineConfig, devices } from '@playwright/test';
+
+const directory = fileURLToPath(new URL('.', import.meta.url));
+const webDirectory = fileURLToPath(new URL('../../../../../', import.meta.url));
+const port = Number(process.env.CRM_CREATION_BROWSER_PORT ?? 23939);
+const launchOptions = {
+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
+};
+
+export default defineConfig({
+ testDir: directory,
+ testMatch: '*.browser.e2e.ts',
+ outputDir: `${directory}/test-results`,
+ timeout: 45_000,
+ workers: 1,
+ use: {
+ baseURL: `http://127.0.0.1:${port}`,
+ screenshot: 'only-on-failure',
+ trace: 'retain-on-failure',
+ },
+ webServer: {
+ command: `bunx vite --config src/features/crm/browser-test/creation/vite.config.ts --port ${port}`,
+ cwd: webDirectory,
+ url: `http://127.0.0.1:${port}`,
+ reuseExistingServer: false,
+ timeout: 120_000,
+ },
+ projects: [
+ { name: 'desktop', use: { ...devices['Desktop Chrome'], launchOptions } },
+ {
+ name: 'phone',
+ use: {
+ ...devices['iPhone 13'],
+ defaultBrowserType: 'chromium',
+ launchOptions,
+ },
+ },
+ ],
+});
diff --git a/apps/web/src/features/crm/browser-test/creation/preview-adapters.ts b/apps/web/src/features/crm/browser-test/creation/preview-adapters.ts
new file mode 100644
index 0000000000..1d0b3bd1f0
--- /dev/null
+++ b/apps/web/src/features/crm/browser-test/creation/preview-adapters.ts
@@ -0,0 +1,31 @@
+import { createSignal } from 'solid-js';
+
+// Keep the full adapter surface available when Vite scans other CRM views.
+export * from '../../views/use-crm';
+
+export const [created, setCreated] = createSignal('');
+export const useCreateCompanyMutation = () => ({
+ isPending: false,
+ async mutateAsync(input: { name: string; domain?: string }) {
+ setCreated(JSON.stringify(input));
+ return { id: 'new-company' };
+ },
+});
+export const useCreateContactMutation = () => ({
+ isPending: false,
+ async mutateAsync(input: { companyId: string; name: string; email: string }) {
+ setCreated(JSON.stringify(input));
+ return { id: 'new-contact' };
+ },
+});
+export const useQuickAccessCrmCompaniesQuery = () => ({
+ companies: () => [
+ { id: 'acme', name: 'Acme', domains: [{ domain: 'example.com' }] },
+ { id: 'name-only', name: 'Community group', domains: [] },
+ ],
+ query: { isLoading: false },
+});
+export const useQuickAccessCrmContactsQuery = () => ({
+ contacts: () => [],
+ query: { isLoading: false },
+});
diff --git a/apps/web/src/features/crm/browser-test/creation/vite.config.ts b/apps/web/src/features/crm/browser-test/creation/vite.config.ts
new file mode 100644
index 0000000000..30c87531f6
--- /dev/null
+++ b/apps/web/src/features/crm/browser-test/creation/vite.config.ts
@@ -0,0 +1,35 @@
+import { fileURLToPath } from 'node:url';
+import tailwind from '@tailwindcss/vite';
+import { defineConfig } from 'vite';
+import solidPlugin from 'vite-plugin-solid';
+import solidSvg from 'vite-plugin-solid-svg';
+import tsconfigPaths from 'vite-tsconfig-paths';
+
+const directory = fileURLToPath(new URL('.', import.meta.url));
+const webDirectory = fileURLToPath(new URL('../../../../../', import.meta.url));
+const workspaceDirectory = fileURLToPath(
+ new URL('../../../../../../../', import.meta.url)
+);
+
+export default defineConfig({
+ root: directory,
+ cacheDir: `${directory}/.vite`,
+ plugins: [
+ solidPlugin(),
+ solidSvg({ defaultAsComponent: true }),
+ tsconfigPaths({ projects: [`${webDirectory}/tsconfig.json`] }),
+ tailwind(),
+ ],
+ resolve: {
+ dedupe: ['solid-js'],
+ alias: [
+ { find: './use-crm', replacement: `${directory}/preview-adapters.ts` },
+ ],
+ },
+ optimizeDeps: { esbuildOptions: { target: 'esnext' } },
+ server: {
+ host: '127.0.0.1',
+ strictPort: true,
+ fs: { allow: [workspaceDirectory] },
+ },
+});
diff --git a/apps/web/src/features/crm/components/company-select.tsx b/apps/web/src/features/crm/components/company-select.tsx
index fccbdd8aae..8694bb883f 100644
--- a/apps/web/src/features/crm/components/company-select.tsx
+++ b/apps/web/src/features/crm/components/company-select.tsx
@@ -8,7 +8,7 @@ import { badgeTriggerClasses, Layer } from '@ui';
import { type Accessor, createSignal, Show } from 'solid-js';
import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';
-export type CompanyOption = { id: string; name: string; domain: string };
+export type CompanyOption = { id: string; name: string; domain?: string };
const ITEM_HEIGHT = 32;
@@ -66,13 +66,15 @@ export function CompanySelect(props: {
value: CompanyOption | undefined;
onChange: (company: CompanyOption) => void;
loading: boolean;
+ disabled?: boolean;
/** Mount the menu here, e.g. a modal dialog's content, which hides body portals. */
mount?: HTMLElement;
}) {
const [search, setSearch] = createSignal('');
+ let trigger: HTMLButtonElement | undefined;
const matches = (option: CompanyOption, query: string) =>
option.name.toLowerCase().includes(query) ||
- option.domain.toLowerCase().includes(query);
+ (option.domain?.toLowerCase().includes(query) ?? false);
const hasMatches = () => {
const query = search().trim().toLowerCase();
return props.companies.some((option) => matches(option, query));
@@ -80,13 +82,14 @@ export function CompanySelect(props: {
return (
<Combobox<CompanyOption>
multiple={false}
+ disabled={props.disabled}
options={props.companies}
value={props.value ?? null}
onChange={(option) => option && props.onChange(option)}
onInputChange={setSearch}
onOpenChange={(open) => !open && setSearch('')}
optionValue="id"
- optionTextValue={(option) => `${option.name} ${option.domain}`}
+ optionTextValue={(option) => `${option.name} ${option.domain ?? ''}`}
// The trigger shows the selection; keep the search box empty on open.
optionLabel={() => ''}
defaultFilter={(option, input) =>
@@ -99,6 +102,7 @@ export function CompanySelect(props: {
>
<Combobox.Control>
<Combobox.Trigger
+ ref={trigger}
id={props.id}
type="button"
// Kobalte's default name is "Show suggestions".
@@ -134,7 +138,15 @@ export function CompanySelect(props: {
</Combobox.Control>
<Combobox.Portal mount={props.mount}>
<Layer depth={2}>
- <Combobox.Content class="menu-surface z-action-menu w-72 overflow-hidden">
+ <Combobox.Content
+ class="menu-surface z-action-menu w-72 overflow-hidden"
+ onCloseAutoFocus={(event) => {
+ // The input lives inside this menu and is being removed. Return
+ // focus to the trigger so the containing drawer stays open.
+ event.preventDefault();
+ trigger?.focus({ preventScroll: true });
+ }}
+ >
<div class="flex items-center gap-2 border-b border-edge-muted px-3 py-2">
<SearchIcon class="size-3.5 shrink-0 text-ink-muted" />
<Combobox.Input
diff --git a/apps/web/src/features/crm/context/crm-context.tsx b/apps/web/src/features/crm/context/crm-context.tsx
index 598fdd98a0..9cdfe7762c 100644
--- a/apps/web/src/features/crm/context/crm-context.tsx
+++ b/apps/web/src/features/crm/context/crm-context.tsx
@@ -166,7 +166,7 @@ export type CrmContext = {
};
openCreateCompany(): void;
/** Without a company, the dialog asks which company the contact joins. */
- openCreateContact(company?: { companyId: string; domain: string }): void;
+ openCreateContact(company?: { companyId: string }): void;
userId: Accessor<string | undefined>;
isTeamAdmin: () => Accessor<boolean>;
createCompanySource(id: Accessor<string>): CompanySource;
@@ -179,7 +179,7 @@ export type CrmContext = {
createTeamViews(): TeamViewsSource;
createLists(teamId: Accessor<string | undefined>): ListsSource;
createCompany(): CrmMutation<
- { name: string; domain: string },
+ { name: string; domain?: string },
{ id: string }
>;
createCompanyImporter(): CompanyImporter;
diff --git a/apps/web/src/features/crm/core/pipeline-record.test.ts b/apps/web/src/features/crm/core/pipeline-record.test.ts
index b70b1bd354..e7279c7d7f 100644
--- a/apps/web/src/features/crm/core/pipeline-record.test.ts
+++ b/apps/web/src/features/crm/core/pipeline-record.test.ts
@@ -57,7 +57,7 @@ describe('recordChoiceProblem', () => {
).toBeUndefined();
});
- it('asks a new company for a name and a valid domain', () => {
+ it('requires a company name and validates a supplied domain', () => {
expect(
recordChoiceProblem(
{ kind: 'new-company', name: ' ', domain: 'acme.com' },
@@ -78,7 +78,7 @@ describe('recordChoiceProblem', () => {
).toBeUndefined();
});
- it('asks a new contact for a name and an email at a known company', () => {
+ it('requires an explicit company choice even when the email domain matches', () => {
expect(
recordChoiceProblem(
{ kind: 'new-contact', name: '', email: '[email protected]' },
@@ -96,13 +96,13 @@ describe('recordChoiceProblem', () => {
{ kind: 'new-contact', name: 'Jane', email: '[email protected]' },
companies
)
- ).toBe('No company uses other.com. Add the company first.');
+ ).toBe('Choose a company for this contact');
expect(
recordChoiceProblem(
{ kind: 'new-contact', name: 'Jane', email: '[email protected]' },
companies
)
- ).toBeUndefined();
+ ).toBe('Choose a company for this contact');
});
});
@@ -123,3 +123,31 @@ describe('recordDetail', () => {
).toBe('globex.com');
});
});
+
+it('accepts name-only companies and explicit cross-domain contact links', () => {
+ expect(
+ recordChoiceProblem({ kind: 'new-company', name: 'Acme', domain: '' }, [])
+ ).toBeUndefined();
+ expect(
+ recordChoiceProblem(
+ {
+ kind: 'new-contact',
+ name: 'Jane',
+ email: '[email protected]',
+ companyId: 'acme',
+ },
+ [{ id: 'acme' }]
+ )
+ ).toBeUndefined();
+ expect(
+ recordChoiceProblem(
+ {
+ kind: 'new-contact',
+ name: 'Jane',
+ email: '[email protected]',
+ companyId: 'missing',
+ },
+ [{ id: 'acme' }]
+ )
+ ).toBe('Choose a company for this contact');
+});
diff --git a/apps/web/src/features/crm/core/pipeline-record.ts b/apps/web/src/features/crm/core/pipeline-record.ts
index 9a9fa3764f..8eb4741f22 100644
--- a/apps/web/src/features/crm/core/pipeline-record.ts
+++ b/apps/web/src/features/crm/core/pipeline-record.ts
@@ -16,14 +16,14 @@ export const recordDetail = (record: RecordOption) =>
? ''
: record.detail;
-/** A company a new contact can join, by the domain of its email. */
-export type DomainCompany = { id: string; domain: string };
+/** A company a new contact can select; its domain is only a suggestion signal. */
+export type DomainCompany = { id: string; domain?: string };
/** Whom a new pipeline row is about: a record that exists, or one created with the row. */
export type RecordChoice =
| { kind: 'existing'; record: RecordOption }
| { kind: 'new-company'; name: string; domain: string }
- | { kind: 'new-contact'; name: string; email: string };
+ | { kind: 'new-contact'; name: string; email: string; companyId?: string };
/** A new record seeded from what was searched: a domain or email goes in its field, anything else is the name. */
export function newRecordChoice(
@@ -54,7 +54,7 @@ export function contactCompany(
): DomainCompany | undefined {
const domain = EMAIL_PATTERN.exec(email.trim().toLowerCase())?.[1];
return domain
- ? companies.find((company) => company.domain.toLowerCase() === domain)
+ ? companies.find((company) => company.domain?.toLowerCase() === domain)
: undefined;
}
@@ -69,13 +69,14 @@ export function recordChoiceProblem(
? 'Enter a company name'
: 'Enter a name';
if (choice.kind === 'new-company')
- return isCompanyDomain(choice.domain.trim())
+ return !choice.domain.trim() || isCompanyDomain(choice.domain.trim())
? undefined
: 'Enter a valid domain like acme.com';
const email = choice.email.trim();
const domain = EMAIL_PATTERN.exec(email)?.[1];
if (!domain) return 'Enter an email like [email protected]';
- return contactCompany(email, companies)
- ? undefined
- : `No company uses ${domain.toLowerCase()}. Add the company first.`;
+ const company = choice.companyId
+ ? companies.find((company) => company.id === choice.companyId)
+ : undefined;
+ return company ? undefined : 'Choose a company for this contact';
}
diff --git a/apps/web/src/features/crm/creation-adapter.ts b/apps/web/src/features/crm/creation-adapter.ts
index 36400f5e4c..bcac631387 100644
--- a/apps/web/src/features/crm/creation-adapter.ts
+++ b/apps/web/src/features/crm/creation-adapter.ts
@@ -4,7 +4,7 @@ import { createSignal } from 'solid-js';
// App-level launchers connect global create actions to the one mounted dialog host.
const [companyOpen, setCompanyOpen] = createSignal(false);
type ContactCreationTarget = {
- company?: { companyId: string; domain: string };
+ company?: { companyId: string };
};
const [contactTarget, setContactTarget] = createSignal<ContactCreationTarget>();
const companyLock = useFocusLock('create-company');
@@ -13,10 +13,7 @@ export function openCreateCompanyModal() {
companyLock.acquire();
setCompanyOpen(true);
}
-export function openCreateContactModal(company?: {
- companyId: string;
- domain: string;
-}) {
+export function openCreateContactModal(company?: { companyId: string }) {
contactLock.acquire();
setContactTarget({ company });
}
diff --git a/apps/web/src/features/crm/queries/companies.ts b/apps/web/src/features/crm/queries/companies.ts
index 9e57e5f637..67cbb8b156 100644
--- a/apps/web/src/features/crm/queries/companies.ts
+++ b/apps/web/src/features/crm/queries/companies.ts
@@ -2,6 +2,7 @@ import { NIL_UUID } from '@app/features/next-soup/filters/filter-store';
import { analytics } from '@app/lib/analytics';
import { ThrownResultError, throwOnErr } from '@core/util/result';
import type { CrmCompanyEntity } from '@entity';
+import { Telemetry } from '@macro-inc/observability';
import { soupKeys } from '@queries/soup/keys';
import { invalidateCachedCrmContacts } from '@service-storage/crm-contacts';
import type { CrmCompanyResponse } from '@service-storage/generated/schemas/crmCompanyResponse';
@@ -141,7 +142,7 @@ function wipeCompanyEmailCache(
/**
* Manually creates a CRM company via `POST /crm/companies` (a team-scoped
- * display name + one domain). Seeds the company detail cache from the
+ * display name + optional domain). Seeds the company detail cache from the
* response and invalidates soup so the new company appears in the
* Customers listings. Server-side failures worth surfacing: 409 when the
* team already tracks the domain, 403 when CRM is disabled for the team,
@@ -150,8 +151,15 @@ function wipeCompanyEmailCache(
export function useCreateCompanyMutation(deps: CrmRecordDependencies) {
return useMutation(
() => ({
- mutationFn: ({ name, domain }: { name: string; domain: string }) =>
- throwOnErr(() => deps.storage.createCompany({ name, domain })),
+ mutationFn: ({ name, domain }: { name: string; domain?: string }) =>
+ Telemetry.span('crm.company.create', async (span) => {
+ span.setAttr('crm.company.has_domain', !!domain);
+ const company = await throwOnErr(() =>
+ deps.storage.createCompany({ name, domain })
+ );
+ span.setAttr('crm.company.id', company.id);
+ return company;
+ }),
onSuccess: (data) => {
analytics.track('crm_company_created', { companyId: data.id });
deps.client.setQueryData(crmKeys.company(data.id).queryKey, data);
@@ -208,9 +216,14 @@ export function useCreateContactMutation(deps: CrmRecordDependencies) {
name: string;
email: string;
}) =>
- throwOnErr(() =>
- deps.storage.createContact({ companyId, name, email })
- ),
+ Telemetry.span('crm.contact.create', async (span) => {
+ span.setAttr('crm.company.id', companyId);
+ const contact = await throwOnErr(() =>
+ deps.storage.createContact({ companyId, name, email })
+ );
+ span.setAttr('crm.contact.id', contact.id);
+ return contact;
+ }),
onSuccess: (contact, { companyId }) => {
analytics.track('crm_contact_created', {
companyId,
diff --git a/apps/web/src/features/crm/views/add-pipeline-record.test.tsx b/apps/web/src/features/crm/views/add-pipeline-record.test.tsx
index 148448d256..1aa1a3f0b6 100644
--- a/apps/web/src/features/crm/views/add-pipeline-record.test.tsx
+++ b/apps/web/src/features/crm/views/add-pipeline-record.test.tsx
@@ -11,7 +11,7 @@ import type { DatabaseViewColumn } from '../../database/core/database-view';
import { AddPipelineRecordDialog } from './add-pipeline-record';
const crm = vi.hoisted(() => ({
- createCompany: vi.fn(async (_input: { name: string; domain: string }) => ({
+ createCompany: vi.fn(async (_input: { name: string; domain?: string }) => ({
id: 'new-company',
})),
createContact: vi.fn(),
@@ -213,6 +213,9 @@ describe('AddPipelineRecordDialog', () => {
await userEvent.click(
await screen.findByRole('option', { name: 'Add company “Initech”' })
);
+ fireEvent.input(screen.getByRole('textbox', { name: 'Domain' }), {
+ target: { value: 'https://invalid' },
+ });
fireEvent.click(screen.getByRole('button', { name: /^Add deal/ }));
expect(screen.getByRole('alert').textContent).toBe(
'Enter a valid domain like acme.com'
diff --git a/apps/web/src/features/crm/views/add-pipeline-record.tsx b/apps/web/src/features/crm/views/add-pipeline-record.tsx
index f21fac0e72..1da424fead 100644
--- a/apps/web/src/features/crm/views/add-pipeline-record.tsx
+++ b/apps/web/src/features/crm/views/add-pipeline-record.tsx
@@ -14,6 +14,7 @@ import {
Panel,
} from '@ui';
import {
+ createMemo,
createSignal,
createUniqueId,
type JSX,
@@ -32,10 +33,12 @@ import type {
} from '../../database/core/database-view';
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 {
contactCompany,
+ type DomainCompany,
newRecordChoice,
type RecordChoice,
type RecordOption,
@@ -88,11 +91,21 @@ export function AddPipelineRecordDialog(
detail: entry.domains[0]?.domain ?? '',
}));
const domainCompanies = () =>
- companies
- .companies()
- .flatMap((entry) =>
- entry.domains.map((domain) => ({ id: entry.id, domain: domain.domain }))
- );
+ companies.companies().flatMap<DomainCompany>((entry) =>
+ entry.domains.length
+ ? entry.domains.map((domain) => ({
+ id: entry.id,
+ domain: domain.domain,
+ }))
+ : [{ id: entry.id, domain: undefined }]
+ );
+ const companyOptions = createMemo(() =>
+ companies.companies().map((company) => ({
+ id: company.id,
+ name: company.name,
+ domain: company.domains[0]?.domain,
+ }))
+ );
// One intent per dialog, so submitting again never adds a second row.
const intentId = `pipeline-record:${createUniqueId()}`;
const [choice, setChoice] = createSignal<RecordChoice>();
@@ -122,6 +135,10 @@ export function AddPipelineRecordDialog(
const current = choice();
return current?.kind === 'new-contact' ? current : undefined;
};
+ const suggestedCompany = () => {
+ const match = contactCompany(newContact()?.email ?? '', domainCompanies());
+ return companyOptions().find((company) => company.id === match?.id);
+ };
const changeChoice = (next: RecordChoice | undefined) => {
setChoice(next);
setError(undefined);
@@ -138,7 +155,7 @@ export function AddPipelineRecordDialog(
const domain = current.domain.trim().toLowerCase();
const { id } = await createCompany.mutateAsync({
name: current.name.trim(),
- domain,
+ domain: domain || undefined,
});
setChoice({
kind: 'existing',
@@ -147,7 +164,11 @@ export function AddPipelineRecordDialog(
return id;
}
const email = current.email.trim().toLowerCase();
- const joins = contactCompany(email, domainCompanies());
+ const joins = current.companyId
+ ? companies
+ .companies()
+ .find((company) => company.id === current.companyId)
+ : undefined;
if (!joins) throw new Error('A new contact needs a company.');
const { id } = await createContact.mutateAsync({
companyId: joins.id,
@@ -256,7 +277,7 @@ export function AddPipelineRecordDialog(
/>
<input
aria-label="Domain"
- placeholder="Domain, like acme.com"
+ placeholder="Domain (optional), like acme.com"
autocomplete="off"
spellcheck={false}
data-1p-ignore
@@ -275,36 +296,69 @@ export function AddPipelineRecordDialog(
</Match>
<Match when={newContact()}>
{(draft) => (
- <NewRecordFields
- name={draft().name}
- namePlaceholder="Contact name"
- disabled={pending()}
- onName={(name) => changeChoice({ ...draft(), name })}
- onCancel={() => changeChoice(undefined)}
- cancelLabel="Choose an existing contact"
- >
- <EnvelopeIcon
- aria-hidden="true"
- class="size-4 shrink-0 text-ink-muted"
- />
- <input
- aria-label="Email"
- placeholder="Email, like [email protected]"
- type="email"
- autocomplete="off"
- spellcheck={false}
- data-1p-ignore
- class="ph-no-capture w-full min-w-0 bg-transparent text-ink outline-none placeholder:text-ink-placeholder"
- value={draft().email}
+ <>
+ <NewRecordFields
+ name={draft().name}
+ namePlaceholder="Contact name"
disabled={pending()}
- onInput={(event) =>
- changeChoice({
- ...draft(),
- email: event.currentTarget.value,
- })
+ onName={(name) => changeChoice({ ...draft(), name })}
+ onCancel={() => changeChoice(undefined)}
+ cancelLabel="Choose an existing contact"
+ >
+ <EnvelopeIcon
+ aria-hidden="true"
+ class="size-4 shrink-0 text-ink-muted"
+ />
+ <input
+ aria-label="Email"
+ placeholder="Email, like [email protected]"
+ type="email"
+ autocomplete="off"
+ spellcheck={false}
+ data-1p-ignore
+ class="ph-no-capture w-full min-w-0 bg-transparent text-ink outline-none placeholder:text-ink-placeholder"
+ value={draft().email}
+ disabled={pending()}
+ onInput={(event) =>
+ changeChoice({
+ ...draft(),
+ email: event.currentTarget.value,
+ })
+ }
+ />
+ </NewRecordFields>
+ <CompanySelect
+ companies={companyOptions()}
+ value={companyOptions().find(
+ (company) => company.id === draft().companyId
+ )}
+ onChange={(company) =>
+ changeChoice({ ...draft(), companyId: company.id })
}
+ loading={companies.query.isLoading}
+ disabled={pending()}
+ mount={dialog()}
/>
- </NewRecordFields>
+ <Show when={!draft().companyId && suggestedCompany()} keyed>
+ {(suggestion) => (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ class="max-w-full self-start"
+ tooltip={suggestion.name}
+ disabled={pending()}
+ onClick={() =>
+ changeChoice({ ...draft(), companyId: suggestion.id })
+ }
+ >
+ <span class="truncate">
+ Use suggested company: {suggestion.name}
+ </span>
+ </Button>
+ )}
+ </Show>
+ </>
)}
</Match>
</Switch>
diff --git a/apps/web/src/features/crm/views/company-contacts-section.test.tsx b/apps/web/src/features/crm/views/company-contacts-section.test.tsx
index 6e5de9e80f..62c936eef9 100644
--- a/apps/web/src/features/crm/views/company-contacts-section.test.tsx
+++ b/apps/web/src/features/crm/views/company-contacts-section.test.tsx
@@ -5,6 +5,10 @@ import { afterEach, expect, it, vi } from 'vitest';
import type { CrmContact } from '../core/contact';
import { CompanyContactsSection } from './company-contacts-section';
+const { openCreateContact } = vi.hoisted(() => ({
+ openCreateContact: vi.fn(),
+}));
+
vi.mock('@entity', () => ({
ListEntity: (props: {
entity: { name: string };
@@ -55,12 +59,16 @@ vi.mock('@app/components/view-shell', () => ({
}));
vi.mock('../context/crm-context', () => ({
useCrmContext: () => ({
+ openCreateContact,
createNavigation: () => ({ openWithSplit: vi.fn() }),
createContactPhoto: (email: string) => () =>
email === '[email protected]' ? '/avery.jpg' : undefined,
}),
}));
-afterEach(cleanup);
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
const contacts: CrmContact[] = [
{
@@ -86,6 +94,31 @@ const contacts: CrmContact[] = [
},
];
+it('opens contact creation for a company with no domain from either action', () => {
+ render(() => (
+ <CompanyContactsSection
+ company={{
+ id: 'co',
+ type: 'crm_company',
+ name: 'Community group',
+ ownerId: 'owner',
+ teamId: 'team',
+ hidden: false,
+ domains: [],
+ }}
+ contacts={[]}
+ />
+ ));
+ const actions = screen.getAllByRole('button', { name: 'Add contact' });
+ expect(actions).toHaveLength(2);
+ for (const action of actions) {
+ expect(action.hasAttribute('disabled')).toBe(false);
+ fireEvent.click(action);
+ }
+ expect(openCreateContact).toHaveBeenCalledTimes(2);
+ expect(openCreateContact).toHaveBeenLastCalledWith({ companyId: 'co' });
+});
+
it('shows contact photos or a letter avatar and opens the chosen contact', () => {
const open = vi.fn();
const { container } = render(() => (
diff --git a/apps/web/src/features/crm/views/company-contacts-section.tsx b/apps/web/src/features/crm/views/company-contacts-section.tsx
index 175119ca32..e9a44eeb8d 100644
--- a/apps/web/src/features/crm/views/company-contacts-section.tsx
+++ b/apps/web/src/features/crm/views/company-contacts-section.tsx
@@ -81,9 +81,8 @@ export function CompanyContactsSection(props: {
);
});
const createContact = () => {
- const domain = props.company?.domains?.[0]?.domain;
- if (domain && props.company)
- context.openCreateContact({ companyId: props.company.id, domain });
+ if (props.company)
+ context.openCreateContact({ companyId: props.company.id });
};
return (
@@ -96,7 +95,7 @@ export function CompanyContactsSection(props: {
createAction={{
label: 'Add contact',
onClick: createContact,
- disabled: !props.company?.domains?.[0],
+ disabled: !props.company,
}}
toolbarCreate
>
@@ -114,7 +113,7 @@ export function CompanyContactsSection(props: {
title="No contacts yet"
description="Add a contact to this company to see them here."
action={
- props.company?.domains?.[0]
+ props.company
? { label: 'Add contact', onClick: createContact }
: undefined
}
diff --git a/apps/web/src/features/crm/views/create-company.tsx b/apps/web/src/features/crm/views/create-company.tsx
index aafaa82c2e..d6d6e6c176 100644
--- a/apps/web/src/features/crm/views/create-company.tsx
+++ b/apps/web/src/features/crm/views/create-company.tsx
@@ -32,10 +32,7 @@ export function CreateCompanyModal(props: {
const companyName = createMemo(() => name().trim());
const companyDomain = createMemo(() => domain().trim().toLowerCase());
const canSubmit = createMemo(
- () =>
- companyName().length > 0 &&
- companyDomain().length > 0 &&
- !createCompanyMutation.isPending
+ () => companyName().length > 0 && !createCompanyMutation.isPending
);
function reset() {
@@ -60,7 +57,7 @@ export function CreateCompanyModal(props: {
setError('Enter a company name');
return;
}
- if (!isCompanyDomain(companyDomain())) {
+ if (companyDomain() && !isCompanyDomain(companyDomain())) {
setError('Enter a valid domain like acme.com');
return;
}
@@ -69,7 +66,7 @@ export function CreateCompanyModal(props: {
try {
const { id } = await createCompanyMutation.mutateAsync({
name: companyName(),
- domain: companyDomain(),
+ domain: companyDomain() || undefined,
});
resetAndClose();
props.onCreated(id);
@@ -142,7 +139,7 @@ export function CreateCompanyModal(props: {
/>
<input
aria-label="Domain"
- placeholder="Domain, like acme.com"
+ placeholder="Domain (optional), like acme.com"
autocomplete="off"
spellcheck={false}
data-1p-ignore
@@ -170,7 +167,9 @@ export function CreateCompanyModal(props: {
<span class="flex min-w-0 items-center gap-1.5 px-2 text-xs text-ink-muted">
<EnvelopeIcon class="size-4 shrink-0" />
<span class="truncate">
- Emails from this domain link to the company
+ {companyDomain()
+ ? 'Emails from this domain link to the company'
+ : 'Add contacts to the company by email'}
</span>
</span>
<EntityComposer.Submit
diff --git a/apps/web/src/features/crm/views/create-contact.tsx b/apps/web/src/features/crm/views/create-contact.tsx
index f2d737a132..e747c39e16 100644
--- a/apps/web/src/features/crm/views/create-contact.tsx
+++ b/apps/web/src/features/crm/views/create-contact.tsx
@@ -13,8 +13,7 @@ import {
useQuickAccessCrmCompaniesQuery,
} from './use-crm';
-// The part before the @: non-empty, no whitespace or a second @.
-const LOCAL_PART_PATTERN = /^[^\s@]+$/;
+const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
export function contactCreationError(cause: unknown): string {
if (cause instanceof ThrownResultError) {
@@ -28,25 +27,20 @@ export function contactCreationError(cause: unknown): string {
return 'Failed to create contact. Try again.';
}
-/** Companies without a domain cannot hold contacts, whose emails must match one. */
+/** Explicitly select any company, including one without a domain. */
function ContactCompanySelect(props: {
mount: HTMLElement | undefined;
+ disabled: boolean;
value: CompanyOption | undefined;
onChange: (company: CompanyOption) => void;
}) {
const suggestions = useQuickAccessCrmCompaniesQuery();
const options = createMemo(() =>
- suggestions.companies().flatMap((company) =>
- company.domains[0]
- ? [
- {
- id: company.id,
- name: company.name,
- domain: company.domains[0].domain,
- },
- ]
- : []
- )
+ suggestions.companies().map((company) => ({
+ id: company.id,
+ name: company.name,
+ domain: company.domains[0]?.domain,
+ }))
);
return (
<CompanySelect
@@ -55,6 +49,7 @@ function ContactCompanySelect(props: {
value={props.value}
onChange={props.onChange}
loading={suggestions.query.isLoading}
+ disabled={props.disabled}
mount={props.mount}
/>
);
@@ -62,37 +57,34 @@ function ContactCompanySelect(props: {
export function CreateContactModal(props: {
/** Opens the dialog; without a company, the dialog asks for one. */
- target?: { company?: { companyId: string; domain: string } };
+ target?: { company?: { companyId: string } };
onClose(): void;
onCreated(id: string): void;
}) {
const createContactMutation = useCreateContactMutation();
const [name, setName] = createSignal('');
- const [localPart, setLocalPart] = createSignal('');
+ const [email, setEmail] = createSignal('');
const [pickedCompany, setPickedCompany] = createSignal<CompanyOption>();
// The panel clips overflow, so the company menu mounts on the dialog itself.
const [dialog, setDialog] = createSignal<HTMLElement>();
const [error, setError] = createSignal<string>();
const company = () => {
const picked = pickedCompany();
- return (
- props.target?.company ??
- (picked && { companyId: picked.id, domain: picked.domain })
- );
+ return props.target?.company ?? (picked && { companyId: picked.id });
};
const contactName = createMemo(() => name().trim());
- const emailLocalPart = createMemo(() => localPart().trim().toLowerCase());
+ const contactEmail = createMemo(() => email().trim().toLowerCase());
const canSubmit = createMemo(
() =>
contactName().length > 0 &&
- emailLocalPart().length > 0 &&
+ contactEmail().length > 0 &&
company() !== undefined &&
!createContactMutation.isPending
);
function reset() {
setName('');
- setLocalPart('');
+ setEmail('');
setPickedCompany(undefined);
setError(undefined);
}
@@ -107,19 +99,6 @@ export function CreateContactModal(props: {
resetAndClose();
}
- // Pasting a full address is common — strip our fixed suffix so
- // "[email protected]" collapses to "jane" instead of failing validation.
- function handleLocalPartInput(value: string) {
- const domain = company()?.domain;
- const suffix = domain ? `@${domain}` : undefined;
- setLocalPart(
- suffix && value.toLowerCase().endsWith(suffix)
- ? value.slice(0, -suffix.length)
- : value
- );
- setError(undefined);
- }
-
async function submit() {
if (createContactMutation.isPending) return;
const target = company();
@@ -131,8 +110,8 @@ export function CreateContactModal(props: {
setError('Enter a name');
return;
}
- if (!LOCAL_PART_PATTERN.test(emailLocalPart())) {
- setError('Enter the part of the email before the @');
+ if (!EMAIL_PATTERN.test(contactEmail())) {
+ setError('Enter a valid email address');
return;
}
@@ -141,7 +120,7 @@ export function CreateContactModal(props: {
const { id } = await createContactMutation.mutateAsync({
companyId: target.companyId,
name: contactName(),
- email: `${emailLocalPart()}@${target.domain}`,
+ email: contactEmail(),
});
resetAndClose();
props.onCreated(id);
@@ -219,29 +198,27 @@ export function CreateContactModal(props: {
<span class="flex min-w-0 items-center">
<input
aria-label="Email"
- placeholder="jane"
+ type="email"
+ placeholder="[email protected]"
autocomplete="off"
spellcheck={false}
data-1p-ignore
- aria-invalid={
- error() === 'Enter the part of the email before the @'
- }
+ aria-invalid={error() === 'Enter a valid email address'}
class="ph-no-capture field-sizing-content max-w-full bg-transparent text-ink outline-none placeholder:text-ink-placeholder"
- value={localPart()}
+ value={email()}
disabled={createContactMutation.isPending}
- onInput={(event) =>
- handleLocalPartInput(event.currentTarget.value)
- }
+ onInput={(event) => {
+ setEmail(event.currentTarget.value);
+ setError(undefined);
+ }}
/>
- <span class="shrink-0 select-none text-ink-muted">
- @{company()?.domain ?? 'company domain'}
- </span>
</span>
</label>
<Show when={!props.target?.company}>
<EntityComposer.Properties class="px-2">
<ContactCompanySelect
mount={dialog()}
+ disabled={createContactMutation.isPending}
value={pickedCompany()}
onChange={(picked) => {
setPickedCompany(picked);
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.ts
index 954db90225..c30c39e247 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
@@ -2539,7 +2539,10 @@ export const CreateChannelResponse = z.object({
summary: z.string(),
});
-export const CreateCompany = z.object({ name: z.string(), domain: z.string() });
+export const CreateCompany = z.object({
+ name: z.string(),
+ domain: z.union([z.string(), z.null()]).optional(),
+});
export const CreateCompanyResponse = z.object({
companyId: z.string().uuid(),
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.ts
index 6c49076229..f90ecb274b 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
@@ -7463,7 +7463,7 @@ export interface CreateChannelResponse {
summary: string;
}
/**
- * Add a company to the user's team CRM by name and web domain, as New Company in the CRM does. Companies a team emails are usually added automatically, so check ListCompanies first. Set its stage, owner, and other properties afterwards with SetEntityProperty (entity type company).
+ * Add a company to the user's team CRM by name and optional web domain, as New Company in the CRM does. Companies a team emails are usually added automatically, so check ListCompanies first. Set its stage, owner, and other properties afterwards with SetEntityProperty (entity type company).
*/
export interface CreateCompany {
/**
@@ -7471,9 +7471,9 @@ export interface CreateCompany {
*/
name: string;
/**
- * The company's web domain, e.g. "acme.com" — no scheme or path. Contacts are matched to the company by this domain.
+ * Optional company web domain; omit when unknown. For example, "acme.com" — no scheme or path. Contacts are matched to the company by this domain.
*/
- domain: string;
+ domain?: string | null;
}
/**
* The created company.
@@ -7549,7 +7549,7 @@ export interface CreateConfirmedCalendarEvent {
userConfirmation: string;
}
/**
- * Add a contact person to a company in the user's team CRM, as Add Contact on a company does. The email's domain must be one of the company's domains. Find the company with ListCompanies, or add it first with CreateCompany.
+ * Add a contact person to a company in the user's team CRM, as Add Contact on a company does. Personal email and addresses with a different domain are accepted; selecting a company is an explicit association. Find the company with ListCompanies, or add it first with CreateCompany.
*/
export interface CreateContact {
/**
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createCrmCompanyRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createCrmCompanyRequest.ts
index f71ddef792..3234c17243 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createCrmCompanyRequest.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createCrmCompanyRequest.ts
@@ -4,15 +4,17 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
+import type { CreateCrmCompanyRequestDomain } from './createCrmCompanyRequestDomain';
/**
* Request body for `POST /crm/companies`.
*/
export interface CreateCrmCompanyRequest {
- /** The company's email domain, e.g. "acme.com". Must be a bare
+ /** Optional company domain, e.g. "acme.com". Omit for a name-only
+company. When supplied, must be a bare
domain (no scheme, path, or email) and not a generic email
provider domain. */
- domain: string;
+ domain?: CreateCrmCompanyRequestDomain;
/** Display name for the company. Team-scoped: overrides the
domain-directory name on every read path. */
name: string;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createCrmCompanyRequestDomain.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createCrmCompanyRequestDomain.ts
new file mode 100644
index 0000000000..255036ef21
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createCrmCompanyRequestDomain.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Optional company domain, e.g. "acme.com". Omit for a name-only
+company. When supplied, must be a bare
+domain (no scheme, path, or email) and not a generic email
+provider domain.
+ */
+export type CreateCrmCompanyRequestDomain = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createCrmContactRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createCrmContactRequest.ts
index de6b525b62..98ad05ca1c 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createCrmContactRequest.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createCrmContactRequest.ts
@@ -9,8 +9,8 @@
* Request body for `POST /crm/companies/{company_id}/contacts`.
*/
export interface CreateCrmContactRequest {
- /** The contact's email address, e.g. "[email protected]". Its domain
-must be one of the company's domains (400 otherwise). */
+ /** The contact's email address, including personal email providers.
+It need not match a company domain. */
email: string;
/** Display name for the contact. */
name: string;
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.ts
index a0a8d0fa66..0cca90a54a 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
@@ -543,6 +543,7 @@ export * from './createChannelScopedBotRequestTokenExpiresAt';
export * from './createChannelScopedBotRequestTokenLabel';
export * from './createChannelScopedBotResponse';
export * from './createCrmCompanyRequest';
+export * from './createCrmCompanyRequestDomain';
export * from './createCrmContactRequest';
export * from './createDatabaseRequest';
export * from './createDatabaseWebhookRequest';
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.ts
index 3854b5b45f..9e3123adf7 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
@@ -4455,8 +4455,9 @@ export const createCrmCompanyBody = zod
.object({
domain: zod
.string()
+ .nullish()
.describe(
- 'The company\'s email domain, e.g. \"acme.com\". Must be a bare\ndomain (no scheme, path, or email) and not a generic email\nprovider domain.'
+ 'Optional company domain, e.g. \"acme.com\". Omit for a name-only\ncompany. When supplied, must be a bare\ndomain (no scheme, path, or email) and not a generic email\nprovider domain.'
),
name: zod
.string()
@@ -4717,7 +4718,6 @@ export const listCompanyContactsResponse = zod.array(
[`CrmCompanyAccessLevelExtractor`]: the caller must be on the team
that owns the company (hidden companies are reachable for
admin/owner only, and the new contact then inherits `hidden`). The
-email's domain must be one of the company's domains (400), the
company must not already track the email (409), and the team's CRM
killswitch must be on (403).
*/
@@ -4730,7 +4730,7 @@ export const createCrmContactBody = zod
email: zod
.string()
.describe(
- 'The contact\'s email address, e.g. \"[email protected]\". Its domain\nmust be one of the company\'s domains (400 otherwise).'
+ "The contact's email address, including personal email providers.\nIt need not match a company domain."
),
name: zod.string().describe('Display name for the contact.'),
})
@@ -4900,7 +4900,8 @@ export const searchContactsResponse = zod
* @summary Look up a CRM contact by email in the caller's team. Returns a null
`contact` when no visible contact exists. Any team member may resolve a
visible contact; admin/owner callers may also resolve hidden contacts and
-contacts under hidden companies.
+contacts under hidden companies. Returns 400 when several visible contacts
+match; callers must choose an explicit contact ID instead.
*/
export const getContactByEmailQueryParams = zod.object({
email: zod
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 46d9b03c14..f717973739 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -5848,7 +5848,7 @@
},
"post": {
"tags": ["crm::inbound::axum_router::create_contact"],
- "summary": "Manually create a contact under a CRM company. Access is enforced by\n[`CrmCompanyAccessLevelExtractor`]: the caller must be on the team\nthat owns the company (hidden companies are reachable for\nadmin/owner only, and the new contact then inherits `hidden`). The\nemail's domain must be one of the company's domains (400), the\ncompany must not already track the email (409), and the team's CRM\nkillswitch must be on (403).",
+ "summary": "Manually create a contact under a CRM company. Access is enforced by\n[`CrmCompanyAccessLevelExtractor`]: the caller must be on the team\nthat owns the company (hidden companies are reachable for\nadmin/owner only, and the new contact then inherits `hidden`). The\ncompany must not already track the email (409), and the team's CRM\nkillswitch must be on (403).",
"operationId": "create_crm_contact",
"parameters": [
{
@@ -6222,7 +6222,7 @@
"/crm/contacts/by-email": {
"get": {
"tags": ["crm::inbound::axum_router::get_contact_by_email"],
- "summary": "Look up a CRM contact by email in the caller's team. Returns a null\n`contact` when no visible contact exists. Any team member may resolve a\nvisible contact; admin/owner callers may also resolve hidden contacts and\ncontacts under hidden companies.",
+ "summary": "Look up a CRM contact by email in the caller's team. Returns a null\n`contact` when no visible contact exists. Any team member may resolve a\nvisible contact; admin/owner callers may also resolve hidden contacts and\ncontacts under hidden companies. Returns 400 when several visible contacts\nmatch; callers must choose an explicit contact ID instead.",
"operationId": "get_contact_by_email",
"parameters": [
{
@@ -6247,7 +6247,7 @@
}
},
"400": {
- "description": "",
+ "description": "Invalid email or multiple visible contacts match; choose a contact ID.",
"content": {
"application/json": {
"schema": {
@@ -25808,11 +25808,11 @@
"CreateCrmCompanyRequest": {
"type": "object",
"description": "Request body for `POST /crm/companies`.",
- "required": ["name", "domain"],
+ "required": ["name"],
"properties": {
"domain": {
- "type": "string",
- "description": "The company's email domain, e.g. \"acme.com\". Must be a bare\ndomain (no scheme, path, or email) and not a generic email\nprovider domain."
+ "type": ["string", "null"],
+ "description": "Optional company domain, e.g. \"acme.com\". Omit for a name-only\ncompany. When supplied, must be a bare\ndomain (no scheme, path, or email) and not a generic email\nprovider domain."
},
"name": {
"type": "string",
@@ -25827,7 +25827,7 @@
"properties": {
"email": {
"type": "string",
- "description": "The contact's email address, e.g. \"[email protected]\". Its domain\nmust be one of the company's domains (400 otherwise)."
+ "description": "The contact's email address, including personal email providers.\nIt need not match a company domain."
},
"name": {
"type": "string",
diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.json
index 3f499b5663..afb5277f28 100644
--- a/crates/agent_code_mode/src/domain/documentation.json
+++ b/crates/agent_code_mode/src/domain/documentation.json
@@ -541,7 +541,7 @@
"ConvertedCell": "# Type Alias: ConvertedCell\n\n> **ConvertedCell** = \\{ `row`: `string`; `value`: `CellValue`; \\}\n\nOne row's converted value.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-row\"></a> `row` | `string` | The row. |\n| <a id=\"property-value\"></a> `value` | `CellValue` | Its value under the new type. |",
"CountedReaction": "# Type Alias: CountedReaction\n\n> **CountedReaction** = \\{ `emoji`: `string`; `users`: `string`[]; \\}\n\nReaction emoji and the users who added it.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-emoji\"></a> `emoji` | `string` | Emoji being reacted with. |\n| <a id=\"property-users\"></a> `users` | `string`[] | User identifiers. |",
"CreateAgentRequest": "# Type Alias: CreateAgentRequest\n\n> **CreateAgentRequest** = \\{ `auto_accept_permissions?`: `boolean` \\| `null`; `avatar_url?`: `string` \\| `null`; `channel_ids?`: `string`[]; `channel_scope`: `AgentChannelScope`; `default_model`: `string`; `description?`: `string` \\| `null`; `handle`: `string`; `harness`: `string`; `harness_id?`: `null` \\| `HarnessId`; `instructions`: `string`; `is_coding`: `boolean`; `mcp?`: `AgentMcpServers`; `name`: `string`; `team_id?`: `string` \\| `null`; \\}\n\nRequest to create a persisted AI agent.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-auto_accept_permissions\"></a> `auto_accept_permissions?` | `boolean` \\| `null` | Whether the agent's sessions approve ACP permission requests without asking. Omit to always prompt. |\n| <a id=\"property-avatar_url\"></a> `avatar_url?` | `string` \\| `null` | Optional avatar URL or data URL. |\n| <a id=\"property-channel_ids\"></a> `channel_ids?` | `string`[] | Selected channels. Must be non-empty only for `selected` scope. |\n| <a id=\"property-channel_scope\"></a> `channel_scope` | `AgentChannelScope` | Whether the agent is global or channel-specific. |\n| <a id=\"property-default_model\"></a> `default_model` | `string` | Model selected specifically for this agent. |\n| <a id=\"property-description\"></a> `description?` | `string` \\| `null` | Optional description. |\n| <a id=\"property-handle\"></a> `handle` | `string` | Stable `@` handle. |\n| <a id=\"property-harness\"></a> `harness` | `string` | Harness used to run the agent. |\n| <a id=\"property-harness_id\"></a> `harness_id?` | `null` \\| `HarnessId` | - |\n| <a id=\"property-instructions\"></a> `instructions` | `string` | Instructions supplied to the agent at the start of a conversation. |\n| <a id=\"property-is_coding\"></a> `is_coding` | `boolean` | Whether the agent is a coding agent: a mention is answered with a magic chip into its live session (`true`) or a reply in the thread (`false`). |\n| <a id=\"property-mcp\"></a> `mcp?` | `AgentMcpServers` | Which MCP servers sessions of this agent are handed. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name. |\n| <a id=\"property-team_id\"></a> `team_id?` | `string` \\| `null` | Team owner. Omit for a private, user-owned agent. |",
- "CreateCrmCompanyRequest": "# Type Alias: CreateCrmCompanyRequest\n\n> **CreateCrmCompanyRequest** = \\{ `domain`: `string`; `name`: `string`; \\}\n\nRequest body for `POST /crm/companies`.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-domain\"></a> `domain` | `string` | The company's email domain, e.g. \"acme.com\". Must be a bare domain (no scheme, path, or email) and not a generic email provider domain. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name for the company. Team-scoped: overrides the domain-directory name on every read path. |",
+ "CreateCrmCompanyRequest": "# Type Alias: CreateCrmCompanyRequest\n\n> **CreateCrmCompanyRequest** = \\{ `domain?`: `string` \\| `null`; `name`: `string`; \\}\n\nRequest body for `POST /crm/companies`.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-domain\"></a> `domain?` | `string` \\| `null` | Optional company domain, e.g. \"acme.com\". Omit for a name-only company. When supplied, must be a bare domain (no scheme, path, or email) and not a generic email provider domain. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name for the company. Team-scoped: overrides the domain-directory name on every read path. |",
"CreateMeetingRequest": "# Type Alias: CreateMeetingRequest\n\n> **CreateMeetingRequest** = \\{ `preparationId?`: `string` \\| `null`; `scheduledEnd?`: `string` \\| `null`; `scheduledStart?`: `string` \\| `null`; `title?`: `string` \\| `null`; \\}\n\nInputs for creating a meeting without starting its RTC room.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-preparationid\"></a> `preparationId?` | `string` \\| `null` | Optional unused room reserved by this actor on the setup screen. |\n| <a id=\"property-scheduledend\"></a> `scheduledEnd?` | `string` \\| `null` | Optional scheduled end. |\n| <a id=\"property-scheduledstart\"></a> `scheduledStart?` | `string` \\| `null` | Optional scheduled start. |\n| <a id=\"property-title\"></a> `title?` | `string` \\| `null` | Optional display title. |",
"CreatePairingRequest": "# Type Alias: CreatePairingRequest\n\n> **CreatePairingRequest** = \\{ `allow_permission_bypass?`: `boolean` \\| `null`; `host?`: `string` \\| `null`; `name`: `string`; `scope?`: `null` \\| `RequestedHarnessScope`; \\}\n\nRequest to open a pairing: the daemon asks for a code the user approves.\n\nThe daemon serializes this, so both derives are used.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-allow_permission_bypass\"></a> `allow_permission_bypass?` | `boolean` \\| `null` | Daemon operator consent ceiling. Omitted by older clients; web approval decides. |\n| <a id=\"property-host\"></a> `host?` | `string` \\| `null` | Display-only description of the machine, e.g. `eric@macbook / darwin`. |\n| <a id=\"property-name\"></a> `name` | `string` | Requested harness display name (typically the machine's hostname). |\n| <a id=\"property-scope\"></a> `scope?` | `null` \\| `RequestedHarnessScope` | - |",
"CreatePipeline": "# Type Alias: CreatePipeline\n\n> **CreatePipeline** = \\{ `name`: `string`; `recordType`: `PipelineRecordType`; `sharing?`: `PipelineSharing`; \\}\n\nRequest to create an empty pipeline with the standard CRM columns.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name` | `string` | Pipeline name. |\n| <a id=\"property-recordtype\"></a> `recordType` | `PipelineRecordType` | Company or contact entries. |\n| <a id=\"property-sharing\"></a> `sharing?` | `PipelineSharing` | Defaults to private. |",
diff --git a/crates/crm/AGENTS.md b/crates/crm/AGENTS.md
index 00eb08eba0..99fb06ebb3 100644
--- a/crates/crm/AGENTS.md
+++ b/crates/crm/AGENTS.md
@@ -54,6 +54,10 @@ tools/HTTP/GraphQL surfaces over them.
- `cargo test -p crm` (`SQLX_OFFLINE` unset; needs a local MacroDB — see
`.agents/rules/rust/guardrails.md`). After query/migration changes, run
`nix develop --command just prepare_db` from the repository root.
+- After tool input or description changes, regenerate frontend tool types and
+ public MCP reference pages using the
+ [entity creation guide](../../docs/guides/add-entity.md#13-ai-and-mcp-tools);
+ CI checks both outputs.
## Gotchas
@@ -62,6 +66,16 @@ tools/HTTP/GraphQL surfaces over them.
even for admins. Preserve distinct contact IDs that share an email; returned
domains and addresses constrain the viewer's mailbox, not team email access.
+- Manual companies require a name and accept an optional domain; explicit
+ contact creation accepts any valid email, including personal providers.
+ Email population still infers companies by domain. Do not apply manual
+ creation rules to capture/consent; see `docs/design/crm-contact-creation.md`.
+- Keep CRM write locks ordered: domain advisory locks, parent team `KEY SHARE`,
+ settings `SHARE`, then company/contact rows. Hold them through commit so
+ disable/purge and team deletion cannot race creation.
+- Keep ambiguous CSV contact lookups unresolved without creating records for
+ them; continue valid rows, but propagate lookup storage and authorization failures.
+
- Company names/logos live in the global `crm_domain_directory`. Only the
email pubsub workers carry a real `CompanyMetadataResolver`; every other
binary uses `NoOpCompanyMetadataResolver`, which leaves a pending entry
diff --git a/crates/crm/src/domain/companies_repo.rs b/crates/crm/src/domain/companies_repo.rs
index a8a27935ef..c549b254c8 100644
--- a/crates/crm/src/domain/companies_repo.rs
+++ b/crates/crm/src/domain/companies_repo.rs
@@ -157,42 +157,20 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
is_sent: bool,
) -> impl Future<Output = Result<(), CrmError>> + Send;
- /// Manually creates a company for `(team_id, domain)` with a
- /// team-scoped display `name`, sharing the insert path
- /// [`populate_contact`] uses (same per-`(team, lower(domain))`
- /// advisory lock, same `crm_companies` + `crm_domains` insert). In a
- /// single transaction:
- ///
- /// 1. Take the advisory lock so a concurrent populate/depopulate on
- /// the same `(team, domain)` serializes with us.
- /// 2. Read the team killswitch; returns
- /// [`CrmError::CrmDisabledForTeam`] when off (matching populate,
- /// which no-ops).
- /// 3. Returns [`CrmError::CompanyAlreadyExistsForTeam`] when the
- /// team already tracks the domain (case-insensitively).
- /// 4. Inserts the `crm_companies` row (storing `name` on the
- /// team-scoped `custom_name` column, which read paths COALESCE
- /// over the global directory name) and its
- /// `crm_domains` row. `first_interaction` / `last_interaction`
- /// are both seeded from `now` — there is no email history yet;
- /// the next populate merges real timestamps via LEAST/GREATEST.
- ///
- /// `domain` is normalized to lowercase before storage. The caller is
- /// expected to have validated `name` / `domain` and ensured a
- /// `crm_domain_directory` entry exists for `domain` (mirroring the
- /// populate flow) so the company still picks up icon/description
- /// enrichment.
- ///
- /// Returns the created company hydrated like
- /// [`get_company_for_team`] (domains + display metadata + the —
- /// empty — contact list).
- ///
- /// [`populate_contact`]: CompaniesRepository::populate_contact
- /// [`get_company_for_team`]: CompaniesRepository::get_company_for_team
+ /// Creates a team-owned company by name, optionally with a domain.
+ /// Enforces the CRM killswitch, serializes domain creation with populate,
+ /// and returns [`CrmError::CompanyAlreadyExistsForTeam`] for a domain
+ /// already tracked by the team. Without a domain, creates no directory or
+ /// domain rows. Names need not be unique. The caller validates inputs and
+ /// ensures directory metadata for any supplied domain.
+ ///
+ /// Stores the team's name override and manual-creation marker, seeding
+ /// interaction timestamps from `now`, then hydrates through
+ /// [`Self::get_company_for_team`].
fn create_company_for_team(
&self,
team_id: &uuid::Uuid,
- domain: &str,
+ domain: Option<&str>,
name: &str,
now: DateTime<Utc>,
) -> impl Future<Output = Result<CrmCompanyWithContacts, CrmError>> + Send;
@@ -208,12 +186,7 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
/// Missing, cross-team, or — for `include_hidden = false`
/// (member) callers — hidden companies return
/// [`CrmError::CompanyNotFoundForTeam`].
- /// 3. Requires the email's domain to be one of the company's
- /// `crm_domains` (case-insensitively); returns
- /// [`CrmError::ContactEmailDomainMismatch`] otherwise — a
- /// foreign-domain contact would never receive populate updates,
- /// since its domain resolves to a different company.
- /// 4. Inserts the `crm_contacts` row, inheriting the company's
+ /// 3. Inserts the `crm_contacts` row, inheriting the company's
/// current `hidden` (an admin adding a contact to a hidden
/// company gets a hidden contact, matching populate's
/// inheritance). Returns
@@ -612,6 +585,8 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
/// team, or — for non-admin viewers (`include_hidden = false`) — the
/// contact or its parent company is hidden. With `include_hidden = true`
/// (admin/owner), every owned contact is reachable.
+ /// Returns [`CrmError::InvalidRequest`] if multiple visible contacts match;
+ /// callers must select an explicit contact ID rather than guess a company.
fn get_contact_by_email_for_team(
&self,
team_id: &uuid::Uuid,
diff --git a/crates/crm/src/domain/crm_transfer.rs b/crates/crm/src/domain/crm_transfer.rs
index e4533cbe60..49fbc838dc 100644
--- a/crates/crm/src/domain/crm_transfer.rs
+++ b/crates/crm/src/domain/crm_transfer.rs
@@ -25,6 +25,7 @@ use super::{
CsvTable, RecordRow, company_pipeline_rows, encode_csv, parse_csv, record_rows,
unique_companies,
},
+ model::CrmError,
pipeline_workflows::{
EntryAddition, EntryQuery, FieldInput, FieldKind, FieldValue, MAX_SCANNED_ROWS,
NewPipeline, PipelineEdit, PipelineField, PipelineOverview, PipelineWorkflowService,
@@ -332,17 +333,24 @@ where
rows: &[&RecordRow],
domains: &SharedDomains,
) -> Result<Vec<(String, Found)>, TransferError> {
- let lookups = bounded(
+ let results = bounded(
rows.iter()
- .map(|row| async move {
- let id = self.records.contact(viewer, &row.key).await?;
- Ok::<_, TransferError>((*row, id))
- })
+ .map(|row| async move { (*row, self.records.contact(viewer, &row.key).await) })
.collect(),
)
- .await
- .into_iter()
- .collect::<Result<Vec<(&RecordRow, Option<Uuid>)>, _>>()?;
+ .await;
+ let mut lookups = Vec::new();
+ let mut found = Vec::new();
+ for (row, result) in results {
+ match result {
+ Ok(id) => lookups.push((row, id)),
+ Err(TransferError::Crm(CrmError::InvalidRequest(reason))) => {
+ // A refused lookup must never fall through to record creation.
+ found.push((row.key.clone(), Err(reason)));
+ }
+ Err(error) => return Err(error),
+ }
+ }
let mut new_domains: Vec<String> = lookups
.iter()
@@ -371,7 +379,7 @@ where
}
let refused = &refused;
- let found = bounded(
+ let resolved = bounded(
lookups
.iter()
.map(|&(row, existing)| async move {
@@ -404,7 +412,10 @@ where
.collect(),
)
.await;
- found.into_iter().collect()
+ for result in resolved {
+ found.push(result?);
+ }
+ Ok(found)
}
/// Add `rows` to `overview`'s pipeline: the shared half of both imports.
diff --git a/crates/crm/src/domain/crm_transfer/records.rs b/crates/crm/src/domain/crm_transfer/records.rs
index d2793ca8d4..6f103b3f8c 100644
--- a/crates/crm/src/domain/crm_transfer/records.rs
+++ b/crates/crm/src/domain/crm_transfer/records.rs
@@ -64,9 +64,6 @@ fn refusal(error: CrmError) -> Result<Created, TransferError> {
Ok(Created::Exists)
}
CrmError::InvalidRequest(reason) => Ok(Created::Refused(reason)),
- CrmError::ContactEmailDomainMismatch => Ok(Created::Refused(
- "the email's domain is not one of its company's domains".into(),
- )),
CrmError::CompanyHidden => Ok(Created::Refused("its company is hidden".into())),
other => Err(other.into()),
}
@@ -119,7 +116,7 @@ impl<Crm: CrmService, Access: EntityAccessService> TransferRecords
domain: &str,
) -> Result<Created, TransferError> {
let team = self.team(viewer).await?;
- match self.crm.create_company(&team, name, domain).await {
+ match self.crm.create_company(&team, name, Some(domain)).await {
Ok(company) => Ok(Created::New(company.company.id)),
Err(error) => refusal(error),
}
diff --git a/crates/crm/src/domain/crm_transfer/test.rs b/crates/crm/src/domain/crm_transfer/test.rs
index 8762282de2..5bb0060c75 100644
--- a/crates/crm/src/domain/crm_transfer/test.rs
+++ b/crates/crm/src/domain/crm_transfer/test.rs
@@ -1,4 +1,4 @@
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use std::sync::Mutex;
use chrono::{TimeZone, Utc};
@@ -235,6 +235,8 @@ impl PipelineWorkflowService for Workflows {
struct Records {
domains: HashMap<String, Uuid>,
contacts: HashMap<String, Uuid>,
+ ambiguous_contacts: HashSet<String>,
+ unavailable_contacts: HashSet<String>,
companies_created: Mutex<Vec<String>>,
contacts_created: Mutex<Vec<(Uuid, String)>>,
}
@@ -267,6 +269,15 @@ impl TransferRecords for Records {
}
async fn contact(&self, _: &Viewer, email: &str) -> Result<Option<Uuid>, TransferError> {
+ if self.ambiguous_contacts.contains(email) {
+ return Err(CrmError::InvalidRequest(
+ "Multiple contacts use this email. Select a contact by ID instead.".into(),
+ )
+ .into());
+ }
+ if self.unavailable_contacts.contains(email) {
+ return Err(CrmError::StorageLayerError(anyhow::anyhow!("lookup unavailable")).into());
+ }
Ok(self.contacts.get(email).copied())
}
@@ -472,6 +483,95 @@ async fn new_contacts_at_one_new_domain_share_one_new_company() {
);
}
+#[tokio::test]
+async fn ambiguous_contacts_are_unresolved_without_blocking_other_csv_rows() {
+ let mut contacts = overview(PipelineRecordType::Contact);
+ contacts.fields[0].name = "Contact".into();
+ let pipeline = contacts.pipeline.pipeline.id;
+ let known = Uuid::now_v7();
+ let service = CrmTransferServiceImpl::new(
+ Arc::new(Workflows::new(contacts)),
+ Records {
+ contacts: HashMap::from([("[email protected]".into(), known)]),
+ ambiguous_contacts: HashSet::from(["[email protected]".into()]),
+ ..Records::default()
+ },
+ Files::default(),
+ );
+ let outcome = service
+ .import_to_pipeline(
+ &viewer(),
+ pipeline,
+ CsvInput::Text(
+ "Contact,Email\n\
+ Shared,[email protected]\n\
+ Existing,[email protected]\n\
+ Shared again,[email protected]\n"
+ .into(),
+ ),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!((outcome.added, outcome.created_records), (2, 1));
+ assert_eq!(
+ outcome.unresolved,
+ [SkippedRecord {
+ key: "[email protected]".into(),
+ reason: "Multiple contacts use this email. Select a contact by ID instead.".into(),
+ }]
+ );
+ assert_eq!(
+ *service.records.companies_created.lock().unwrap(),
+ ["new.example.com"]
+ );
+ assert_eq!(
+ *service.records.contacts_created.lock().unwrap(),
+ [(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[1].record,
+ RecordTarget::Id(Uuid::new_v5(&Uuid::NAMESPACE_OID, b"[email protected]"))
+ );
+}
+
+#[tokio::test]
+async fn contact_lookup_storage_failure_stops_import_before_creating_records() {
+ let mut contacts = overview(PipelineRecordType::Contact);
+ contacts.fields[0].name = "Contact".into();
+ let pipeline = contacts.pipeline.pipeline.id;
+ let service = CrmTransferServiceImpl::new(
+ Arc::new(Workflows::new(contacts)),
+ Records {
+ unavailable_contacts: HashSet::from(["[email protected]".into()]),
+ ..Records::default()
+ },
+ Files::default(),
+ );
+ let error = service
+ .import_to_pipeline(
+ &viewer(),
+ pipeline,
+ CsvInput::Text(
+ "Contact,Email\nNew,[email protected]\nUnavailable,[email protected]\n"
+ .into(),
+ ),
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(
+ error,
+ TransferError::Crm(CrmError::StorageLayerError(_))
+ ));
+ assert!(service.records.companies_created.lock().unwrap().is_empty());
+ assert!(service.records.contacts_created.lock().unwrap().is_empty());
+ assert!(service.workflows.added.lock().unwrap().is_empty());
+}
+
#[tokio::test]
async fn an_export_writes_people_as_emails_and_reimports() {
let mut workflows = Workflows::new(overview(PipelineRecordType::Company));
diff --git a/crates/crm/src/domain/model.rs b/crates/crm/src/domain/model.rs
index 65559e7afe..d8ef165af0 100644
--- a/crates/crm/src/domain/model.rs
+++ b/crates/crm/src/domain/model.rs
@@ -47,7 +47,7 @@ pub struct CrmCompanyWithContacts {
}
/// A known external company tracked by a team (CRM-style record). A company
-/// aggregates one or more email domains and individual contacts that are
+/// aggregates zero or more email domains and individual contacts that are
/// considered to belong to the same external party.
///
/// Company display metadata (name, description, icon) lives in
@@ -264,11 +264,11 @@ pub struct CrmAddressStatus {
/// team's company) are reported as `exists = false` so existence
/// doesn't leak across teams.
pub exists: bool,
- /// `crm_contacts.hidden` for the matched contact. `false` when `!exists`.
+ /// Whether any matching team contact is hidden. `false` when `!exists`.
pub contact_hidden: bool,
- /// `crm_companies.hidden` for the matched contact's company. `false` when `!exists`.
+ /// Whether any matching contact's company is hidden. `false` when `!exists`.
pub company_hidden: bool,
- /// `crm_companies.email_sync` for the matched contact's company. `false` when `!exists`.
+ /// Whether every matching contact's company enables email sync. `false` when `!exists`.
pub email_sync: bool,
}
@@ -399,9 +399,6 @@ pub enum CrmError {
/// The company already has a contact with the requested email.
#[error("a crm contact with this email already exists for the company")]
ContactAlreadyExistsForCompany,
- /// The contact's email domain is not one of the company's domains.
- #[error("contact email domain must match one of the company's domains")]
- ContactEmailDomainMismatch,
/// The team-level `team_crm_settings.crm_enabled` killswitch is off.
#[error("crm is not enabled for this team")]
CrmDisabledForTeam,
diff --git a/crates/crm/src/domain/service.rs b/crates/crm/src/domain/service.rs
index 88a5d1d081..a30989b73d 100644
--- a/crates/crm/src/domain/service.rs
+++ b/crates/crm/src/domain/service.rs
@@ -185,59 +185,26 @@ pub trait CrmService: Clone + Send + Sync + 'static {
macro_id: &str,
) -> impl Future<Output = Result<Option<uuid::Uuid>, CrmError>> + Send;
- /// Manually creates a CRM company for the caller's team with a
- /// team-scoped display `name` and a single `domain` — the
- /// user-driven counterpart of the populate flow's automatic company
- /// creation. Any team member may create (the receipt only proves
- /// membership).
+ /// Manually creates a company by name with an optional domain. Any team
+ /// member may create one. A supplied domain must be a bare company domain,
+ /// not a generic email provider, and unique within the team. Omit it for a
+ /// named company without a website; names are not unique identifiers.
///
- /// Validates the inputs first: `name` must be non-blank (and within
- /// a sane length); `domain` must look like a bare domain
- /// ("acme.com" — no scheme, path, `@`, or whitespace) and must not
- /// be a generic email provider domain (gmail.com etc. — a company
- /// keyed on one would swallow every contact on that provider).
- /// Rejections surface as [`CrmError::InvalidRequest`].
- ///
- /// Like populate, ensures `crm_domain_directory` has an entry for
- /// the domain (resolving via the
- /// [`crate::domain::company_metadata_resolver::CompanyMetadataResolver`]
- /// on a miss, or leaving it pending for
- /// [`CrmServiceImpl::enrich_pending_domains`] when the binary has no
- /// resolver) so the company still picks up icon/description
- /// enrichment; the user's `name` is stored on `crm_companies.custom_name`
- /// (never in the shared directory — it's global across teams) and
- /// overrides the directory name on every read path.
- ///
- /// Returns [`CrmError::CrmDisabledForTeam`] when the team-level
- /// killswitch is off and [`CrmError::CompanyAlreadyExistsForTeam`]
- /// when the team already tracks the domain. See
- /// [`crate::domain::companies_repo::CompaniesRepository::create_company_for_team`].
+ /// Domain enrichment runs only when a domain is supplied. The display name
+ /// remains team-scoped. The team CRM killswitch is enforced for both paths.
fn create_company(
&self,
access: &CrmTeamReceipt<MemberTeamRole>,
name: &str,
- domain: &str,
+ domain: Option<&str>,
) -> impl Future<Output = Result<CrmCompanyWithContacts, CrmError>> + Send;
- /// Manually creates a contact under the company addressed by
- /// `access`, with a display `name` and `email` — the user-driven
- /// counterpart of populate's automatic contact creation. Any team
- /// member who can see the company may add one; the receipt's role
- /// decides whether a hidden company is reachable (and the new
- /// contact inherits the company's `hidden`).
- ///
- /// Validates first: `name` must be non-blank (within a sane
- /// length); `email` must be a plausible `local@domain` address.
- /// Rejections surface as [`CrmError::InvalidRequest`]. The email's
- /// domain must additionally be one of the company's domains —
- /// enforced in the repository against the company's `crm_domains`
- /// set ([`CrmError::ContactEmailDomainMismatch`] otherwise).
- ///
- /// Returns [`CrmError::CrmDisabledForTeam`] when the team-level
- /// killswitch is off and
- /// [`CrmError::ContactAlreadyExistsForCompany`] when the company
- /// already tracks the email. See
- /// [`crate::domain::companies_repo::CompaniesRepository::create_contact_for_company`].
+ /// Manually creates a named contact under an authorized company. The email
+ /// is validated and normalized, but need not match any company domain:
+ /// this is an explicit association, separate from automatic inference.
+ /// The contact inherits company visibility; team CRM must be enabled.
+ /// A duplicate email in the same company returns
+ /// [`CrmError::ContactAlreadyExistsForCompany`].
fn create_contact(
&self,
access: &CrmCompanyReceipt<ViewAccessLevel>,
@@ -374,7 +341,8 @@ pub trait CrmService: Clone + Send + Sync + 'static {
/// receipt keeps the lookup scoped to an authorized team; the caller's
/// role decides whether hidden contacts and hidden parent companies are
/// visible. The email is validated and normalized before it crosses the
- /// repository port.
+ /// repository port. Multiple visible matches are an actionable error;
+ /// callers must choose a contact ID.
fn get_contact_by_email(
&self,
access: &CrmTeamReceipt<MemberTeamRole>,
@@ -474,9 +442,8 @@ fn validate_display_name(raw: &str) -> Result<&str, CrmError> {
/// Validates and normalizes a user-supplied contact email: trims,
/// lowercases, and requires a `local@domain` shape whose domain passes
-/// the same bare-domain check as company domains. Shape-only — the
-/// company-domain match is enforced in the repository, where the
-/// company's `crm_domains` set lives.
+/// the same bare-domain shape check as company domains. Generic providers
+/// are valid contact addresses; explicit links do not infer an employer.
fn normalize_contact_email(raw: &str) -> Result<String, CrmError> {
let email = raw.trim().to_ascii_lowercase();
if email.is_empty() {
@@ -826,37 +793,31 @@ where
.await
}
- #[tracing::instrument(skip(self, access), err)]
+ #[tracing::instrument(skip_all, fields(team_id = %access.team_id()), err)]
async fn create_company(
&self,
access: &CrmTeamReceipt<MemberTeamRole>,
name: &str,
- domain: &str,
+ domain: Option<&str>,
) -> Result<CrmCompanyWithContacts, CrmError> {
let name = validate_display_name(name)?;
- let domain = normalize_company_domain(domain)?;
-
- // Same guard populate applies: companies are keyed by domain,
- // so a generic provider domain would swallow every contact on
- // that provider.
- if is_generic_email_domain(&domain) {
- return Err(CrmError::InvalidRequest(
- "generic email provider domains cannot be added as crm companies".into(),
- ));
- }
+ let domain = domain.map(normalize_company_domain).transpose()?;
- // Mirror populate: ensure the directory has an entry for the
- // domain so icon/description enrichment resolves. The user's
- // name never goes here — the directory is global across teams;
- // it lands on `crm_companies.custom_name` in the repo instead.
- self.ensure_domain_directory_entry(&domain).await?;
+ if let Some(domain) = &domain {
+ if is_generic_email_domain(domain) {
+ return Err(CrmError::InvalidRequest(
+ "generic email provider domains cannot be added as crm companies; omit the domain to create a company by name".into(),
+ ));
+ }
+ self.ensure_domain_directory_entry(domain).await?;
+ }
self.companies_repository
- .create_company_for_team(&access.team_id(), &domain, name, Utc::now())
+ .create_company_for_team(&access.team_id(), domain.as_deref(), name, Utc::now())
.await
}
- #[tracing::instrument(skip(self, access), err)]
+ #[tracing::instrument(skip_all, fields(team_id = %access.team_id()), err)]
async fn create_contact(
&self,
access: &CrmCompanyReceipt<ViewAccessLevel>,
@@ -1072,9 +1033,9 @@ where
}
/// Logs by cause rather than with `err`: callers look up whatever address
- /// they were given, so one that is not an email is theirs to fix, while a
- /// repository failure stays at ERROR.
- #[tracing::instrument(skip(self, access))]
+ /// they were given, so an invalid or ambiguous address is theirs to fix,
+ /// while a storage failure stays at ERROR.
+ #[tracing::instrument(skip_all, fields(team_id = %access.team_id()))]
async fn get_contact_by_email(
&self,
access: &CrmTeamReceipt<MemberTeamRole>,
@@ -1085,7 +1046,10 @@ where
self.companies_repository
.get_contact_by_email_for_team(&access.team_id(), &email, access.include_hidden())
.await
- .inspect_err(|error| tracing::error!(error = %error))
+ .inspect_err(|error| match error {
+ CrmError::InvalidRequest(_) => tracing::info!(error = %error),
+ _ => tracing::error!(error = %error),
+ })
}
#[tracing::instrument(skip(self, access), err)]
@@ -1246,7 +1210,7 @@ impl CrmService for NoOpCrmService {
&self,
_access: &CrmTeamReceipt<MemberTeamRole>,
_name: &str,
- _domain: &str,
+ _domain: Option<&str>,
) -> Result<CrmCompanyWithContacts, CrmError> {
unimplemented!("NoOpCrmService.create_company")
}
diff --git a/crates/crm/src/domain/service/test.rs b/crates/crm/src/domain/service/test.rs
index 423d1c145a..7d0c7d20cd 100644
--- a/crates/crm/src/domain/service/test.rs
+++ b/crates/crm/src/domain/service/test.rs
@@ -95,7 +95,7 @@ impl CompaniesRepository for StubRepo {
async fn create_company_for_team(
&self,
_team_id: &uuid::Uuid,
- _domain: &str,
+ _domain: Option<&str>,
_name: &str,
_now: DateTime<Utc>,
) -> Result<CrmCompanyWithContacts, CrmError> {
@@ -645,7 +645,7 @@ async fn create_company_rejects_blank_name() {
let access = receipt_with_role(TeamRole::Member);
for name in ["", " ", "\t\n"] {
let err = service()
- .create_company(&access, name, "acme.com")
+ .create_company(&access, name, Some("acme.com"))
.await
.unwrap_err();
assert!(matches!(err, CrmError::InvalidRequest(_)), "name {name:?}");
@@ -657,7 +657,7 @@ async fn create_company_rejects_overlong_name() {
let access = receipt_with_role(TeamRole::Member);
let name = "x".repeat(201);
let err = service()
- .create_company(&access, &name, "acme.com")
+ .create_company(&access, &name, Some("acme.com"))
.await
.unwrap_err();
assert!(matches!(err, CrmError::InvalidRequest(_)));
@@ -679,7 +679,7 @@ async fn create_company_rejects_malformed_domains() {
"acme .com",
] {
let err = service()
- .create_company(&access, "Acme", domain)
+ .create_company(&access, "Acme", Some(domain))
.await
.unwrap_err();
assert!(
@@ -694,7 +694,7 @@ async fn create_company_rejects_generic_email_domains() {
let access = receipt_with_role(TeamRole::Member);
for domain in ["gmail.com", "Yahoo.com", "outlook.com"] {
let err = service()
- .create_company(&access, "Acme", domain)
+ .create_company(&access, "Acme", Some(domain))
.await
.unwrap_err();
assert!(
diff --git a/crates/crm/src/inbound/axum_extractors/test.rs b/crates/crm/src/inbound/axum_extractors/test.rs
index 55a98fde27..d5ebd18652 100644
--- a/crates/crm/src/inbound/axum_extractors/test.rs
+++ b/crates/crm/src/inbound/axum_extractors/test.rs
@@ -306,7 +306,7 @@ impl CrmService for FakeCrmService {
&self,
_access: &CrmTeamReceipt<MemberTeamRole>,
_name: &str,
- _domain: &str,
+ _domain: Option<&str>,
) -> Result<CrmCompanyWithContacts, CrmError> {
panic!("unexpected create_company call")
}
diff --git a/crates/crm/src/inbound/axum_router.rs b/crates/crm/src/inbound/axum_router.rs
index 0d15279e61..6540ba7e05 100644
--- a/crates/crm/src/inbound/axum_router.rs
+++ b/crates/crm/src/inbound/axum_router.rs
@@ -251,12 +251,6 @@ impl IntoResponse for CrmError {
message: "a crm contact with this email already exists for the company".into(),
}),
),
- CrmError::ContactEmailDomainMismatch => (
- StatusCode::BAD_REQUEST,
- Json(ErrorResponse {
- message: "contact email domain must match one of the company's domains".into(),
- }),
- ),
CrmError::CrmDisabledForTeam => (
StatusCode::FORBIDDEN,
Json(ErrorResponse {
diff --git a/crates/crm/src/inbound/axum_router/create_company.rs b/crates/crm/src/inbound/axum_router/create_company.rs
index 7d1e8b1ff8..7ac884027e 100644
--- a/crates/crm/src/inbound/axum_router/create_company.rs
+++ b/crates/crm/src/inbound/axum_router/create_company.rs
@@ -18,10 +18,11 @@ pub struct CreateCrmCompanyRequest {
/// Display name for the company. Team-scoped: overrides the
/// domain-directory name on every read path.
pub name: String,
- /// The company's email domain, e.g. "acme.com". Must be a bare
+ /// Optional company domain, e.g. "acme.com". Omit for a name-only
+ /// company. When supplied, must be a bare
/// domain (no scheme, path, or email) and not a generic email
/// provider domain.
- pub domain: String,
+ pub domain: Option<String>,
}
/// Manually create a CRM company for the caller's team. Any team member
@@ -57,7 +58,7 @@ pub async fn handler<
let receipt = CrmTeamReceipt::from_team_receipt(access.entity_access_receipt)?;
let record = state
.service
- .create_company(&receipt, &req.name, &req.domain)
+ .create_company(&receipt, &req.name, req.domain.as_deref())
.await?;
Ok(Json(record.into()))
}
diff --git a/crates/crm/src/inbound/axum_router/create_contact.rs b/crates/crm/src/inbound/axum_router/create_contact.rs
index dc68196f4f..38b4055bfa 100644
--- a/crates/crm/src/inbound/axum_router/create_contact.rs
+++ b/crates/crm/src/inbound/axum_router/create_contact.rs
@@ -21,8 +21,8 @@ use super::{CrmRouterState, list_company_contacts::CrmContactResponse};
pub struct CreateCrmContactRequest {
/// Display name for the contact.
pub name: String,
- /// The contact's email address, e.g. "[email protected]". Its domain
- /// must be one of the company's domains (400 otherwise).
+ /// The contact's email address, including personal email providers.
+ /// It need not match a company domain.
pub email: String,
}
@@ -30,7 +30,6 @@ pub struct CreateCrmContactRequest {
/// [`CrmCompanyAccessLevelExtractor`]: the caller must be on the team
/// that owns the company (hidden companies are reachable for
/// admin/owner only, and the new contact then inherits `hidden`). The
-/// email's domain must be one of the company's domains (400), the
/// company must not already track the email (409), and the team's CRM
/// killswitch must be on (403).
#[utoipa::path(
diff --git a/crates/crm/src/inbound/axum_router/get_contact_by_email.rs b/crates/crm/src/inbound/axum_router/get_contact_by_email.rs
index 1a0124f246..5249c543f0 100644
--- a/crates/crm/src/inbound/axum_router/get_contact_by_email.rs
+++ b/crates/crm/src/inbound/axum_router/get_contact_by_email.rs
@@ -30,7 +30,8 @@ pub struct GetContactByEmailResponse {
/// Look up a CRM contact by email in the caller's team. Returns a null
/// `contact` when no visible contact exists. Any team member may resolve a
/// visible contact; admin/owner callers may also resolve hidden contacts and
-/// contacts under hidden companies.
+/// contacts under hidden companies. Returns 400 when several visible contacts
+/// match; callers must choose an explicit contact ID instead.
#[utoipa::path(
get,
path = "/crm/contacts/by-email",
@@ -42,12 +43,12 @@ pub struct GetContactByEmailResponse {
body = GetContactByEmailResponse,
description = "The matching contact, or a null contact when none is visible."
),
- (status = 400, body = ErrorResponse),
+ (status = 400, body = ErrorResponse, description = "Invalid email or multiple visible contacts match; choose a contact ID."),
(status = 401, body = ErrorResponse),
(status = 500, body = ErrorResponse),
),
)]
-#[tracing::instrument(skip_all, err(level = Level::DEBUG), fields(email = %params.email))]
+#[tracing::instrument(skip_all, err(level = Level::DEBUG))]
pub async fn handler<
C: CrmService,
St,
diff --git a/crates/crm/src/inbound/toolset.rs b/crates/crm/src/inbound/toolset.rs
index 09286efc4a..01aebd897f 100644
--- a/crates/crm/src/inbound/toolset.rs
+++ b/crates/crm/src/inbound/toolset.rs
@@ -480,9 +480,6 @@ pub(crate) fn crm_error_description(err: &CrmError) -> String {
CrmError::ContactAlreadyExistsForCompany => {
"the company already has a contact with that email".to_string()
}
- CrmError::ContactEmailDomainMismatch => {
- "the contact's email domain must be one of the company's domains".to_string()
- }
CrmError::StageEditRoleRequired(role) => format!(
"editing deal stages requires the {} team role",
role.as_db_str()
diff --git a/crates/crm/src/inbound/toolset/create_company.rs b/crates/crm/src/inbound/toolset/create_company.rs
index a3e3ac3a03..95d88f1e34 100644
--- a/crates/crm/src/inbound/toolset/create_company.rs
+++ b/crates/crm/src/inbound/toolset/create_company.rs
@@ -31,17 +31,17 @@ pub struct CreateCompanyResponse {
#[serde(rename_all = "camelCase")]
#[schemars(
title = "CreateCompany",
- description = "Add a company to the user's team CRM by name and web domain, as New Company in the CRM does. Companies a team emails are usually added automatically, so check ListCompanies first. Set its stage, owner, and other properties afterwards with SetEntityProperty (entity type company)."
+ description = "Add a company to the user's team CRM by name and optional web domain, as New Company in the CRM does. Companies a team emails are usually added automatically, so check ListCompanies first. Set its stage, owner, and other properties afterwards with SetEntityProperty (entity type company)."
)]
pub struct CreateCompany {
/// Display name.
#[schemars(description = "The company's display name, e.g. \"Acme\".")]
pub name: String,
- /// Primary domain.
+ /// Optional primary domain.
#[schemars(
- description = "The company's web domain, e.g. \"acme.com\" — no scheme or path. Contacts are matched to the company by this domain."
+ description = "Optional company web domain; omit when unknown. For example, \"acme.com\" — no scheme or path. Contacts are matched to the company by this domain."
)]
- pub domain: String,
+ pub domain: Option<String>,
}
impl ToolAnnotated for CreateCompany {
@@ -67,7 +67,7 @@ where
caller_team_receipt(&*service_context.entity_access_service, &request_context).await?;
let created = service_context
.service
- .create_company(&team, self.name.trim(), self.domain.trim())
+ .create_company(&team, self.name.trim(), self.domain.as_deref())
.await
.map_err(crm_error)?;
diff --git a/crates/crm/src/inbound/toolset/create_contact.rs b/crates/crm/src/inbound/toolset/create_contact.rs
index 3a43bb1960..6efc6a1d24 100644
--- a/crates/crm/src/inbound/toolset/create_contact.rs
+++ b/crates/crm/src/inbound/toolset/create_contact.rs
@@ -32,7 +32,7 @@ pub struct CreateContactResponse {
#[serde(rename_all = "camelCase")]
#[schemars(
title = "CreateContact",
- description = "Add a contact person to a company in the user's team CRM, as Add Contact on a company does. The email's domain must be one of the company's domains. Find the company with ListCompanies, or add it first with CreateCompany."
+ description = "Add a contact person to a company in the user's team CRM, as Add Contact on a company does. Personal email and addresses with a different domain are accepted; selecting a company is an explicit association. Find the company with ListCompanies, or add it first with CreateCompany."
)]
pub struct CreateContact {
/// Company to add the contact to.
diff --git a/crates/crm/src/inbound/toolset/test.rs b/crates/crm/src/inbound/toolset/test.rs
index 81a41d6452..a1eda9c8bf 100644
--- a/crates/crm/src/inbound/toolset/test.rs
+++ b/crates/crm/src/inbound/toolset/test.rs
@@ -19,7 +19,6 @@ fn creation_conflicts_explain_what_to_change() {
CrmError::ContactAlreadyExistsForCompany,
"already has a contact",
),
- (CrmError::ContactEmailDomainMismatch, "company's domains"),
(CrmError::CrmDisabledForTeam, "turned off"),
] {
let description = crm_error(error).description;
diff --git a/crates/crm/src/outbound/companies_repo.rs b/crates/crm/src/outbound/companies_repo.rs
index 79b1006c17..22367d58a3 100644
--- a/crates/crm/src/outbound/companies_repo.rs
+++ b/crates/crm/src/outbound/companies_repo.rs
@@ -127,25 +127,39 @@ impl CompaniesRepositoryImpl {
.map_err(|e| CrmError::StorageLayerError(e.into()))
}
- /// Team killswitch, read inside the tx (after the advisory lock) so
- /// a concurrent disable+purge can't race past us. Missing row =
- /// default false.
+ /// Keep the parent team alive before locking its settings, so team deletion
+ /// cannot deadlock with a later company insert's foreign-key check. The
+ /// shared settings lock serializes writers with disable+purge while allowing
+ /// other writers through. Acquire these after any domain advisory lock and
+ /// before company/contact rows. Missing parent or settings means disabled.
async fn team_crm_enabled(
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
team_id: &uuid::Uuid,
) -> Result<bool, CrmError> {
- sqlx::query_scalar!(
+ let team = sqlx::query_scalar!(
+ r#"SELECT id FROM team WHERE id = $1 FOR KEY SHARE"#,
+ team_id,
+ )
+ .fetch_optional(&mut **tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+ if team.is_none() {
+ return Ok(false);
+ }
+
+ let enabled = sqlx::query_scalar!(
r#"
- SELECT COALESCE(
- (SELECT crm_enabled FROM team_crm_settings WHERE team_id = $1),
- FALSE
- ) AS "crm_enabled!"
+ SELECT crm_enabled
+ FROM team_crm_settings
+ WHERE team_id = $1
+ FOR SHARE
"#,
team_id,
)
- .fetch_one(&mut **tx)
+ .fetch_optional(&mut **tx)
.await
- .map_err(|e| CrmError::StorageLayerError(e.into()))
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+ Ok(enabled.unwrap_or(false))
}
/// Look up the company owning `(team, lower(domain))`. Returns
@@ -281,23 +295,22 @@ impl CompaniesRepositoryImpl {
Ok(())
}
- /// Insert a `crm_companies` row (+ its `crm_domains` row) for
- /// `(team, normalized_domain)`, seeding the interaction columns from
+ /// Insert a company and, when supplied, its domain, seeding interaction columns from
/// the caller's known range. `custom_name` is the team-scoped
/// display-name override (manual creation); populate passes `None`.
/// `manually_created` stamps user-created rows so the depopulate
- /// orphan cleanup keeps them. The caller must hold the
- /// per-`(team, domain)` advisory lock.
+ /// orphan cleanup keeps them. When a domain is supplied, the caller must
+ /// hold the per-`(team, domain)` advisory lock.
///
/// Returns `(company_id, created)`. The domain insert carries a
/// defensive ON CONFLICT — the advisory lock should prevent it, but
/// if it fires we'd orphan the company we just inserted, so we
/// recover by deleting it and returning the winner's id with
/// `created = false`.
- async fn insert_company_with_domain(
+ async fn insert_company(
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
team_id: &uuid::Uuid,
- normalized_domain: &str,
+ normalized_domain: Option<&str>,
custom_name: Option<&str>,
manually_created: bool,
first_at: DateTime<Utc>,
@@ -306,8 +319,8 @@ impl CompaniesRepositoryImpl {
let new_company = sqlx::query!(
r#"
INSERT INTO crm_companies
- (team_id, custom_name, manually_created, first_interaction, last_interaction)
- VALUES ($1, $2, $3, $4, $5)
+ (id, team_id, custom_name, manually_created, first_interaction, last_interaction)
+ VALUES ($6, $1, $2, $3, $4, $5)
RETURNING id
"#,
team_id,
@@ -315,11 +328,16 @@ impl CompaniesRepositoryImpl {
manually_created,
first_at,
last_at,
+ uuid::Uuid::now_v7(),
)
.fetch_one(&mut **tx)
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
+ let Some(normalized_domain) = normalized_domain else {
+ return Ok((new_company.id, true));
+ };
+
let domain_insert = sqlx::query!(
r#"
INSERT INTO crm_domains (company_id, team_id, domain)
@@ -468,10 +486,10 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
// range so backfilled mail keeps accurate timestamps.
// No custom_name: backfill companies resolve their
// display name from `crm_domain_directory`.
- let (id, created) = Self::insert_company_with_domain(
+ let (id, created) = Self::insert_company(
&mut tx,
team_id,
- &normalized_domain,
+ Some(&normalized_domain),
None,
false,
first_at,
@@ -555,15 +573,15 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
Ok(())
}
- #[tracing::instrument(skip(self), err)]
+ #[tracing::instrument(skip_all, fields(%team_id), err)]
async fn create_company_for_team(
&self,
team_id: &uuid::Uuid,
- domain: &str,
+ domain: Option<&str>,
name: &str,
now: DateTime<Utc>,
) -> Result<CrmCompanyWithContacts, CrmError> {
- let normalized_domain = domain.to_ascii_lowercase();
+ let normalized_domain = domain.map(str::to_ascii_lowercase);
let mut tx = self
.pool
@@ -571,20 +589,18 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
- // Same lock populate/depopulate take, so a concurrent populate
- // for the domain can't slip a row in between our existence
- // check and insert.
- Self::lock_team_domain(&mut tx, team_id, &normalized_domain).await?;
+ if let Some(domain) = &normalized_domain {
+ Self::lock_team_domain(&mut tx, team_id, domain).await?;
+ }
- // Manual creation surfaces the killswitch instead of silently
- // no-oping like populate: the caller expects a company back.
if !Self::team_crm_enabled(&mut tx, team_id).await? {
return Err(CrmError::CrmDisabledForTeam);
}
- if Self::find_company_by_domain(&mut tx, team_id, &normalized_domain)
- .await?
- .is_some()
+ if let Some(domain) = &normalized_domain
+ && Self::find_company_by_domain(&mut tx, team_id, domain)
+ .await?
+ .is_some()
{
return Err(CrmError::CompanyAlreadyExistsForTeam);
}
@@ -592,10 +608,10 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
// No email history yet: seed both interaction endpoints from
// `now`; future populates merge real timestamps via
// LEAST/GREATEST.
- let (company_id, created) = Self::insert_company_with_domain(
+ let (company_id, created) = Self::insert_company(
&mut tx,
team_id,
- &normalized_domain,
+ normalized_domain.as_deref(),
Some(name),
true,
now,
@@ -622,7 +638,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
})
}
- #[tracing::instrument(skip(self), err)]
+ #[tracing::instrument(skip_all, fields(%team_id, %company_id), err)]
async fn create_contact_for_company(
&self,
team_id: &uuid::Uuid,
@@ -670,31 +686,6 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
return Err(CrmError::CompanyNotFoundForTeam);
};
- // The contact must live on one of the company's domains —
- // contacts are keyed by email under a domain-keyed company, and
- // a foreign-domain contact would never receive populate
- // updates (its domain resolves to a different company).
- let Some((_, email_domain)) = normalized_email.split_once('@') else {
- return Err(CrmError::InvalidRequest("email must contain an '@'".into()));
- };
- let domain_matches = sqlx::query_scalar!(
- r#"
- SELECT EXISTS (
- SELECT 1 FROM crm_domains
- WHERE company_id = $1 AND LOWER(domain) = $2
- ) AS "exists!"
- "#,
- company_id,
- email_domain,
- )
- .fetch_one(&mut *tx)
- .await
- .map_err(|e| CrmError::StorageLayerError(e.into()))?;
-
- if !domain_matches {
- return Err(CrmError::ContactEmailDomainMismatch);
- }
-
// New contacts inherit the company's `hidden` (matches
// populate). `manually_created = TRUE` shields the row from the
// depopulate orphan cleanup — it has no sources by
@@ -1585,12 +1576,10 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
let address_statuses: Vec<CrmAddressStatus> = if addresses.is_empty() {
Vec::new()
} else {
- // Hash-join via derived table (avoids LATERAL per-row).
- // At most one row per (team, email) by virtue of
- // crm_contacts UNIQUE(company_id, email) +
- // crm_domains UNIQUE(team_id, lower(domain)).
- // ORDER BY input.ord preserves input order
- // (contract on `CrmScopePrecheck.addresses`).
+ // Explicit contacts can repeat an email under different companies.
+ // Collapse the requested addresses within this team, with any
+ // hidden/disabled association retaining its opt-out. Preserve one
+ // result per input, including repeated inputs, in caller order.
sqlx::query!(
r#"
SELECT
@@ -1602,13 +1591,14 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
FROM UNNEST($2::text[]) WITH ORDINALITY AS input(address, ord)
LEFT JOIN (
SELECT
- ct.email AS email,
- ct.hidden AS contact_hidden,
- c.hidden AS company_hidden,
- c.email_sync AS email_sync
+ ct.email AS email,
+ BOOL_OR(ct.hidden) AS contact_hidden,
+ BOOL_OR(c.hidden) AS company_hidden,
+ BOOL_AND(c.email_sync) AS email_sync
FROM crm_contacts ct
JOIN crm_companies c ON c.id = ct.company_id
- WHERE c.team_id = $1
+ WHERE c.team_id = $1 AND ct.email = ANY($2::text[])
+ GROUP BY ct.email
) m ON m.email = input.address
ORDER BY input.ord
"#,
@@ -1902,7 +1892,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.collect())
}
- #[tracing::instrument(skip(self), err)]
+ #[tracing::instrument(skip_all, fields(%team_id), err)]
async fn get_contact_by_email_for_team(
&self,
team_id: &uuid::Uuid,
@@ -1912,7 +1902,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
// Contacts are normalized to lowercase on every write path, so
// lowercasing the input preserves use of crm_contacts_email_idx. Team
// scope and hidden-row semantics mirror get_contact_for_team.
- let row = sqlx::query!(
+ let rows = sqlx::query!(
r#"
SELECT
ct.id,
@@ -1929,18 +1919,23 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
WHERE ct.email = LOWER($1)
AND co.team_id = $2
AND ($3 OR (ct.hidden = FALSE AND co.hidden = FALSE))
- ORDER BY ct.id DESC
- LIMIT 1
+ LIMIT 2
"#,
email,
team_id,
include_hidden,
)
- .fetch_optional(&self.pool)
+ .fetch_all(&self.pool)
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
- Ok(row.map(|row| CrmContact {
+ if rows.len() > 1 {
+ return Err(CrmError::InvalidRequest(
+ "Multiple contacts use this email. Select a contact by ID instead.".into(),
+ ));
+ }
+
+ Ok(rows.into_iter().next().map(|row| CrmContact {
id: row.id,
company_id: row.company_id,
email: row.email,
diff --git a/crates/crm/src/outbound/companies_repo/test.rs b/crates/crm/src/outbound/companies_repo/test.rs
index d6898c06b7..d5bfe7576e 100644
--- a/crates/crm/src/outbound/companies_repo/test.rs
+++ b/crates/crm/src/outbound/companies_repo/test.rs
@@ -25,4 +25,5 @@ mod set_company_name;
mod set_contact_hidden;
mod set_contact_name;
mod set_email_sync;
+mod team_crm_enabled;
mod team_settings;
diff --git a/crates/crm/src/outbound/companies_repo/test/create_company.rs b/crates/crm/src/outbound/companies_repo/test/create_company.rs
index 35f625123d..aff2aceb9c 100644
--- a/crates/crm/src/outbound/companies_repo/test/create_company.rs
+++ b/crates/crm/src/outbound/companies_repo/test/create_company.rs
@@ -16,7 +16,7 @@ async fn create_company_inserts_company_and_domain(pool: PgPool) -> anyhow::Resu
let repo = CompaniesRepositoryImpl::new(pool.clone());
let now = Utc::now();
let record = repo
- .create_company_for_team(&team_id, "Acme.COM", "Acme", now)
+ .create_company_for_team(&team_id, Some("Acme.COM"), "Acme", now)
.await?;
assert_eq!(record.name.as_deref(), Some("Acme"));
@@ -65,7 +65,7 @@ async fn create_company_name_overrides_directory_name(pool: PgPool) -> anyhow::R
let repo = CompaniesRepositoryImpl::new(pool.clone());
let record = repo
- .create_company_for_team(&team_id, "acme.com", "Acme (ours)", Utc::now())
+ .create_company_for_team(&team_id, Some("acme.com"), "Acme (ours)", Utc::now())
.await?;
assert_eq!(record.name.as_deref(), Some("Acme (ours)"));
@@ -87,7 +87,7 @@ async fn create_company_rejects_duplicate_domain(pool: PgPool) -> anyhow::Result
let repo = CompaniesRepositoryImpl::new(pool.clone());
// Case-insensitive: "ACME.com" collides with "acme.com".
let err = repo
- .create_company_for_team(&team_id, "ACME.com", "Acme", Utc::now())
+ .create_company_for_team(&team_id, Some("ACME.com"), "Acme", Utc::now())
.await
.unwrap_err();
assert!(matches!(err, CrmError::CompanyAlreadyExistsForTeam));
@@ -111,7 +111,7 @@ async fn create_company_allows_same_domain_on_another_team(pool: PgPool) -> anyh
let repo = CompaniesRepositoryImpl::new(pool.clone());
let record = repo
- .create_company_for_team(&team_b, "acme.com", "Acme", Utc::now())
+ .create_company_for_team(&team_b, Some("acme.com"), "Acme", Utc::now())
.await?;
assert_eq!(record.company.team_id, team_b);
Ok(())
@@ -125,7 +125,7 @@ async fn create_company_requires_crm_enabled(pool: PgPool) -> anyhow::Result<()>
let repo = CompaniesRepositoryImpl::new(pool.clone());
let err = repo
- .create_company_for_team(&team_id, "acme.com", "Acme", Utc::now())
+ .create_company_for_team(&team_id, Some("acme.com"), "Acme", Utc::now())
.await
.unwrap_err();
assert!(matches!(err, CrmError::CrmDisabledForTeam));
@@ -147,7 +147,7 @@ async fn populate_reuses_manually_created_company(pool: PgPool) -> anyhow::Resul
let repo = CompaniesRepositoryImpl::new(pool.clone());
let created = repo
- .create_company_for_team(&team_id, "acme.com", "Acme", Utc::now())
+ .create_company_for_team(&team_id, Some("acme.com"), "Acme", Utc::now())
.await?;
// A later populate for the same domain attaches its contact to the
@@ -194,7 +194,7 @@ async fn soup_listing_uses_name_override(pool: PgPool) -> anyhow::Result<()> {
let repo = CompaniesRepositoryImpl::new(pool.clone());
let created = repo
- .create_company_for_team(&team_id, "acme.com", "Acme (ours)", Utc::now())
+ .create_company_for_team(&team_id, Some("acme.com"), "Acme (ours)", Utc::now())
.await?;
let listed = repo
@@ -213,3 +213,77 @@ async fn soup_listing_uses_name_override(pool: PgPool) -> anyhow::Result<()> {
assert_eq!(listed[0].name.as_deref(), Some("Acme (ours)"));
Ok(())
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn name_only_company_accepts_personal_email_without_inference(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ use crate::domain::auth::CrmTeamReceipt;
+ use crate::domain::service::{CrmService, CrmServiceImpl};
+ use crate::outbound::no_op_resolver::NoOpCompanyMetadataResolver;
+ use entity_access::domain::models::MemberTeamRole;
+
+ let team_id = Uuid::now_v7();
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
+ enable_crm_for_team(&pool, team_id).await?;
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ let service = CrmServiceImpl::new(repo.clone(), NoOpCompanyMetadataResolver);
+ let access = CrmTeamReceipt::<MemberTeamRole>::dangerously_internal(team_id);
+ let company = service.create_company(&access, " Acme ", None).await?;
+ assert_eq!(company.name.as_deref(), Some("Acme"));
+ assert!(company.company.domains.is_empty());
+ assert!(company.description.is_none());
+
+ let contact = repo
+ .create_contact_for_company(
+ &team_id,
+ &company.company.id,
+ "Jane",
+ Utc::now(),
+ false,
+ )
+ .await?;
+ let loaded = repo
+ .get_company_for_team(&team_id, &company.company.id, false)
+ .await?
+ .unwrap();
+ assert_eq!(loaded.contacts[0].id, contact.id);
+ assert!(loaded.company.domains.is_empty());
+ assert_eq!(
+ sqlx::query_scalar!("SELECT COUNT(*) FROM crm_domain_directory")
+ .fetch_one(&pool)
+ .await?,
+ Some(0)
+ );
+ assert_eq!(
+ sqlx::query_scalar!("SELECT COUNT(*) FROM crm_contact_sources")
+ .fetch_one(&pool)
+ .await?,
+ Some(0)
+ );
+
+ // Names are labels, not identity: distinct companies may have the same name.
+ let other = service.create_company(&access, "Acme", None).await?;
+ assert_ne!(other.company.id, company.company.id);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn name_only_company_requires_crm_enabled(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ let error = repo
+ .create_company_for_team(&team_id, None, "Acme", Utc::now())
+ .await
+ .unwrap_err();
+ assert!(matches!(error, CrmError::CrmDisabledForTeam));
+ assert_eq!(
+ sqlx::query_scalar!("SELECT COUNT(*) FROM crm_companies")
+ .fetch_one(&pool)
+ .await?,
+ Some(0)
+ );
+ Ok(())
+}
diff --git a/crates/crm/src/outbound/companies_repo/test/create_contact.rs b/crates/crm/src/outbound/companies_repo/test/create_contact.rs
index 55bd9c0834..348ace1883 100644
--- a/crates/crm/src/outbound/companies_repo/test/create_contact.rs
+++ b/crates/crm/src/outbound/companies_repo/test/create_contact.rs
@@ -80,7 +80,7 @@ async fn create_contact_rejects_duplicate_email(pool: PgPool) -> anyhow::Result<
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn create_contact_rejects_mismatched_domain(pool: PgPool) -> anyhow::Result<()> {
+async fn create_contact_accepts_explicit_cross_domain_links(pool: PgPool) -> anyhow::Result<()> {
let team_id = Uuid::now_v7();
seed_team(&pool, team_id, "macro|[email protected]").await?;
enable_crm_for_team(&pool, team_id).await?;
@@ -88,16 +88,13 @@ async fn create_contact_rejects_mismatched_domain(pool: PgPool) -> anyhow::Resul
let repo = CompaniesRepositoryImpl::new(pool.clone());
- let err = repo
+ let contact = repo
.create_contact_for_company(&team_id, &company_id, email, "Jane", Utc::now(), false)
- .await
- .unwrap_err();
- assert!(
- matches!(err, CrmError::ContactEmailDomainMismatch),
- "email {email:?}"
- );
+ .await?;
+ assert_eq!(contact.email, email);
+ assert_eq!(contact.company_id, company_id);
}
- assert_eq!(count_contacts(&pool, company_id).await?, 0);
+ assert_eq!(count_contacts(&pool, company_id).await?, 3);
Ok(())
}
@@ -292,7 +289,7 @@ async fn manual_rows_survive_link_teardown(pool: PgPool) -> anyhow::Result<()> {
// A fully manual company (no contacts) and a derived company with a
// populated contact + a manual contact side by side.
let manual_company = repo
- .create_company_for_team(&team_id, "manual.com", "Manual Co", Utc::now())
+ .create_company_for_team(&team_id, Some("manual.com"), "Manual Co", Utc::now())
.await?;
let derived_company = insert_company(&pool, team_id, true, &["acme.com"]).await?;
insert_contact_with_source(&pool, derived_company, "[email protected]", link_id).await?;
@@ -324,3 +321,50 @@ async fn manual_rows_survive_link_teardown(pool: PgPool) -> anyhow::Result<()> {
let _ = manual_company;
Ok(())
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn shared_email_preserves_every_company_opt_out(pool: PgPool) -> anyhow::Result<()> {
+ let team = Uuid::now_v7();
+ seed_team(&pool, team, "macro|[email protected]").await?;
+ enable_crm_for_team(&pool, team).await?;
+ let enabled = insert_company(&pool, team, true, &["acme.com"]).await?;
+ let disabled = insert_company(&pool, team, false, &["other.com"]).await?;
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ for company in [enabled, disabled] {
+ repo.create_contact_for_company(
+ &team,
+ &company,
+ "Jane",
+ Utc::now(),
+ false,
+ )
+ .await?;
+ }
+ let inputs = vec![
+ "[email protected]".to_string(),
+ "[email protected]".to_string(),
+ "[email protected]".to_string(),
+ ];
+ let before = repo.crm_scope_precheck(&team, &[], &inputs).await?;
+ assert_eq!(before.addresses.len(), inputs.len());
+ assert_eq!(
+ before
+ .addresses
+ .iter()
+ .map(|row| &row.address)
+ .collect::<Vec<_>>(),
+ inputs.iter().collect::<Vec<_>>()
+ );
+ assert!(before.addresses[0].exists);
+ assert!(!before.addresses[0].email_sync);
+ assert!(!before.addresses[1].exists);
+ assert!(!before.addresses[2].email_sync);
+ repo.set_company_hidden(&team, &disabled, true).await?;
+ let after = repo.crm_scope_precheck(&team, &[], &inputs).await?;
+ assert_eq!(after.addresses.len(), inputs.len());
+ assert!(after.addresses[0].contact_hidden);
+ assert!(after.addresses[0].company_hidden);
+ assert!(!after.addresses[0].email_sync);
+ Ok(())
+}
diff --git a/crates/crm/src/outbound/companies_repo/test/domain_directory.rs b/crates/crm/src/outbound/companies_repo/test/domain_directory.rs
index 88839d7f38..8d6bcabc4b 100644
--- a/crates/crm/src/outbound/companies_repo/test/domain_directory.rs
+++ b/crates/crm/src/outbound/companies_repo/test/domain_directory.rs
@@ -144,7 +144,7 @@ async fn manual_company_is_enriched_later_and_keeps_team_names(pool: PgPool) ->
.create_company(
&CrmTeamReceipt::<MemberTeamRole>::dangerously_internal(team_a),
"Acme (ours)",
- "acme.com",
+ Some("acme.com"),
)
.await?;
let unnamed = insert_company(&pool, team_b, true, &["acme.com"]).await?;
diff --git a/crates/crm/src/outbound/companies_repo/test/get_contact_by_email_for_team.rs b/crates/crm/src/outbound/companies_repo/test/get_contact_by_email_for_team.rs
index c121e1c742..7f7bb1ddf6 100644
--- a/crates/crm/src/outbound/companies_repo/test/get_contact_by_email_for_team.rs
+++ b/crates/crm/src/outbound/companies_repo/test/get_contact_by_email_for_team.rs
@@ -1,10 +1,72 @@
use super::helpers::*;
use crate::domain::companies_repo::*;
+use crate::domain::model::CrmError;
use crate::outbound::companies_repo::*;
+use chrono::Utc;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use sqlx::PgPool;
use uuid::Uuid;
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn email_lookup_requires_an_unambiguous_visible_contact(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
+ enable_crm_for_team(&pool, team_id).await?;
+ let first_company = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+ let second_company = insert_company(&pool, team_id, true, &["other.com"]).await?;
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let first = repo
+ .create_contact_for_company(
+ &team_id,
+ &first_company,
+ "Jane",
+ Utc::now(),
+ false,
+ )
+ .await?;
+ let second = repo
+ .create_contact_for_company(
+ &team_id,
+ &second_company,
+ "Jane",
+ Utc::now(),
+ false,
+ )
+ .await?;
+
+ assert!(matches!(
+ repo.get_contact_by_email_for_team(&team_id, "[email protected]", false).await,
+ Err(CrmError::InvalidRequest(message)) if message.contains("Select a contact by ID")
+ ));
+
+ repo.set_contact_hidden(&team_id, &second.id, true).await?;
+ assert_eq!(
+ repo.get_contact_by_email_for_team(&team_id, "[email protected]", false)
+ .await?
+ .unwrap()
+ .id,
+ first.id
+ );
+ assert!(matches!(
+ repo.get_contact_by_email_for_team(&team_id, "[email protected]", true)
+ .await,
+ Err(CrmError::InvalidRequest(_))
+ ));
+ repo.set_contact_hidden(&team_id, &second.id, false).await?;
+ repo.set_company_hidden(&team_id, &second_company, true)
+ .await?;
+ assert_eq!(
+ repo.get_contact_by_email_for_team(&team_id, "[email protected]", false)
+ .await?
+ .unwrap()
+ .id,
+ first.id
+ );
+ Ok(())
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn get_contact_by_email_returns_team_contact_case_insensitively(
pool: PgPool,
diff --git a/crates/crm/src/outbound/companies_repo/test/team_crm_enabled.rs b/crates/crm/src/outbound/companies_repo/test/team_crm_enabled.rs
new file mode 100644
index 0000000000..6597b5c9ea
--- /dev/null
+++ b/crates/crm/src/outbound/companies_repo/test/team_crm_enabled.rs
@@ -0,0 +1,169 @@
+use super::helpers::{enable_crm_for_team, seed_team};
+use crate::domain::companies_repo::CompaniesRepository;
+use crate::domain::model::CrmError;
+use crate::outbound::companies_repo::CompaniesRepositoryImpl;
+use chrono::Utc;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::PgPool;
+use uuid::Uuid;
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn writer_protects_parent_and_settings_until_commit(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
+ enable_crm_for_team(&pool, team_id).await?;
+
+ let mut writer = pool.begin().await?;
+ assert!(CompaniesRepositoryImpl::team_crm_enabled(&mut writer, &team_id).await?);
+ let parent_error = sqlx::query!(
+ "SELECT id FROM team WHERE id = $1 FOR UPDATE NOWAIT",
+ team_id,
+ )
+ .fetch_one(&pool)
+ .await
+ .expect_err("team deletion must wait before cascading to settings");
+ assert_eq!(
+ parent_error
+ .as_database_error()
+ .and_then(|error| error.code())
+ .as_deref(),
+ Some("55P03")
+ );
+
+ let now = Utc::now();
+ let (company_id, created) = CompaniesRepositoryImpl::insert_company(
+ &mut writer,
+ &team_id,
+ None,
+ Some("Acme"),
+ true,
+ now,
+ now,
+ )
+ .await?;
+ assert!(created);
+
+ // Other writers can share the settings lock while this write is uncommitted.
+ assert!(
+ sqlx::query_scalar!(
+ "SELECT crm_enabled FROM team_crm_settings WHERE team_id = $1 FOR SHARE NOWAIT",
+ team_id,
+ )
+ .fetch_one(&pool)
+ .await?
+ );
+
+ // Disable updates a non-key settings column; KEY SHARE would not protect it.
+ let settings_error = sqlx::query!(
+ "SELECT team_id FROM team_crm_settings WHERE team_id = $1 FOR NO KEY UPDATE NOWAIT",
+ team_id,
+ )
+ .fetch_one(&pool)
+ .await
+ .expect_err("disable must wait for the writer's settings lock");
+ assert_eq!(
+ settings_error
+ .as_database_error()
+ .and_then(|error| error.code())
+ .as_deref(),
+ Some("55P03")
+ );
+
+ writer.commit().await?;
+
+ // Once creation commits, disable can flip the flag and purge that company.
+ let mut disable = pool.begin().await?;
+ sqlx::query!(
+ "UPDATE team_crm_settings SET crm_enabled = FALSE WHERE team_id = $1",
+ team_id,
+ )
+ .execute(&mut *disable)
+ .await?;
+ let purged = sqlx::query!("DELETE FROM crm_companies WHERE team_id = $1", team_id)
+ .execute(&mut *disable)
+ .await?;
+ assert_eq!(purged.rows_affected(), 1);
+ disable.commit().await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ assert!(
+ repo.get_company_for_team(&team_id, &company_id, true)
+ .await?
+ .is_none()
+ );
+ assert!(matches!(
+ repo.create_company_for_team(&team_id, None, "Acme", now)
+ .await,
+ Err(CrmError::CrmDisabledForTeam)
+ ));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn creation_observes_concurrent_disable(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
+ enable_crm_for_team(&pool, team_id).await?;
+ let mut disable = pool.begin().await?;
+ sqlx::query!(
+ "UPDATE team_crm_settings SET crm_enabled = FALSE WHERE team_id = $1",
+ team_id,
+ )
+ .execute(&mut *disable)
+ .await?;
+ sqlx::query!("DELETE FROM crm_companies WHERE team_id = $1", team_id)
+ .execute(&mut *disable)
+ .await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ let (creation, committed) = tokio::join!(
+ repo.create_company_for_team(&team_id, None, "Acme", Utc::now()),
+ disable.commit(),
+ );
+ committed?;
+ assert!(matches!(creation, Err(CrmError::CrmDisabledForTeam)));
+ assert_eq!(
+ sqlx::query_scalar!(
+ "SELECT COUNT(*) FROM crm_companies WHERE team_id = $1",
+ team_id
+ )
+ .fetch_one(&pool)
+ .await?,
+ Some(0)
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn creation_observes_concurrent_team_deletion(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
+ enable_crm_for_team(&pool, team_id).await?;
+ let mut deletion = pool.begin().await?;
+ sqlx::query!("DELETE FROM team WHERE id = $1", team_id)
+ .execute(&mut *deletion)
+ .await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let (creation, committed) = tokio::join!(
+ repo.create_company_for_team(&team_id, None, "Acme", Utc::now()),
+ deletion.commit(),
+ );
+ committed?;
+ assert!(matches!(creation, Err(CrmError::CrmDisabledForTeam)));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn missing_parent_or_settings_is_disabled(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let mut missing_parent = pool.begin().await?;
+ assert!(!CompaniesRepositoryImpl::team_crm_enabled(&mut missing_parent, &team_id).await?);
+ missing_parent.rollback().await?;
+
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
+ let mut missing_settings = pool.begin().await?;
+ assert!(!CompaniesRepositoryImpl::team_crm_enabled(&mut missing_settings, &team_id).await?);
+ missing_settings.rollback().await?;
+ Ok(())
+}
diff --git a/crates/soup/src/domain/service/tests/crm_association.rs b/crates/soup/src/domain/service/tests/crm_association.rs
index 78784545c9..a8e35c93be 100644
--- a/crates/soup/src/domain/service/tests/crm_association.rs
+++ b/crates/soup/src/domain/service/tests/crm_association.rs
@@ -111,7 +111,7 @@ impl CrmService for FakeCrm {
&self,
_access: &CrmTeamReceipt<MemberTeamRole>,
_name: &str,
- _domain: &str,
+ _domain: Option<&str>,
) -> Result<CrmCompanyWithContacts, CrmError> {
unimplemented!("FakeCrm.create_company")
}
diff --git a/docs/agent-guide/crm.md b/docs/agent-guide/crm.md
index 88bdd7a544..904a2a24b0 100644
--- a/docs/agent-guide/crm.md
+++ b/docs/agent-guide/crm.md
@@ -123,9 +123,11 @@ email on the server after a short typing pause, so results include contacts not
yet scrolled into view. The desktop header has the title, shared **New** menu,
and expandable Search; choose **Contact** from New. On touch, **New contact**
is unchanged. The contact dialog asks for a company through a **Choose a company** pill (searchable by name
-or domain, from the up to 500 most relevant companies with a domain) and fixes
-the email to that company's primary domain; **Add contact** on a company's Team
-tab skips the company pill. The company, contact and pipeline dialogs share the
+or domain, from the up to 500 most relevant companies, including name-only
+companies). Enter a full email address; personal addresses and different domains
+are accepted. **Add contact** on a company's Team tab skips the company pill.
+**New company** requires a name; its domain is optional. If supplied, it must be
+a company domain, not a personal email provider. The company, contact and pipeline dialogs share the
task/project composer layout: name on the first row beside **Close**, details
below, and a **Create …** button that also submits on Command-Enter.
@@ -216,8 +218,9 @@ fills 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. Existing contact-domain requirements, email-sync and
-database gates, recipients, and task associations still apply. With company email
+New call, or New database. Add contact is available once the company is loaded,
+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
sync off, New email stays visible but disabled; New company must not replace it.
Keyboard focus and
higher-priority composers suppress the floating action; leaving the section
@@ -393,7 +396,12 @@ the table's own cell editors (unset ones read **Empty**). The body scrolls while
the footer stays pinned with **Cancel** (Esc) and **Add deal**. Select
fields can create a new option. Choosing **Add company “…”** creates the company
with the row: a searched domain fills the domain and the name. **Add contact “…”**
-works the same way, and a new contact's email must use a company's domain.
+works the same way. A new company may omit its domain. A new contact accepts a
+full email address and an explicit company choice, including a name-only company.
+An email-domain match offers **Use suggested company**; accept it or select a
+different company before submitting. Editing the email keeps that explicit choice.
+Focusing the suggestion reveals its full name; Enter accepts it without submitting
+the form, and closes the tooltip without a browser error.
**Add deal** stays disabled until a record is chosen, and Command-Enter submits.
The form makes one row with every value set. A board lane's **New record** opens
the same dialog with the lane's stage filled in. The table's blank row at the
@@ -419,6 +427,11 @@ adds only what is missing; several rows for one new record add separate entries
(deals), as an export of such a pipeline lists them. Relation and non-person entity columns are skipped,
and a value that does not fit its column is left empty.
+Agent CSV imports report ambiguous contact emails as unresolved records with an
+actionable reason and continue the valid rows. They never create another contact
+for an ambiguous email; select the intended contact by ID when adding it to the
+pipeline. Storage and authorization failures during lookup still fail the import.
+
CRM lists are currently disabled by `enableCrmLists` (default `false`). The sidebar
Lists section, list editor, and company membership controls only mount when enabled.
Existing list data is preserved; a restored list view returns to All companies while
diff --git a/docs/design/crm-contact-creation.md b/docs/design/crm-contact-creation.md
new file mode 100644
index 0000000000..ba61c102c9
--- /dev/null
+++ b/docs/design/crm-contact-creation.md
@@ -0,0 +1,91 @@
+# CRM contact creation: staged delivery
+
+The first delivery allows named companies without a domain and manual contacts
+whose email domain differs from the company. It preserves the current team-owned
+records, IDs, visibility checks and email consent behavior. The broader
+company-independent contact model is still open; this change does not deliver
+phone-only contacts or one contact linked to several companies.
+
+## Current implementation decisions
+
+| Entry point | Decision | Behavior |
+| --- | --- | --- |
+| Company UI, pipeline form, HTTP, CreateCompany tool | Change | Name required; domain optional. An omitted/null domain creates no domain or enrichment entry. A supplied empty/invalid domain is an actionable validation error. |
+| Manual contact UI, pipeline form, HTTP, CreateContact tool | Change | Name, full email and explicit company required. Personal email and mismatched domains are accepted. A domain match can suggest a company in the pipeline form. |
+| Duplicate company domain | Keep | Team-scoped case-insensitive conflict. Company names are labels and may repeat. |
+| Duplicate contact email | Keep for this stage | Unique within the company; duplicates return conflict. No silent merge or cross-team lookup. |
+| CSV company import | Keep | Domain remains its matching key; name-only import needs a durable identifier contract. |
+| CSV contact import | Keep for this stage | Existing contacts are found by email; missing contacts use domain inference. Personal-address creation through import remains follow-on work. |
+| Email-only contact lookup in imports and pipeline actions | Change | Multiple visible matches produce an ambiguity error requiring an explicit contact ID; never choose a company arbitrarily. Hidden and cross-team records do not participate in a member's lookup. |
+| Email sync and backfill | Keep | Existing domain inference, provider exclusions, self-domain checks, sources and consent gates. Explicit creation does not manufacture mailbox-source rows. |
+| Ownership and visibility | Keep | Team membership and company receipt authorize creation; hidden companies remain restricted and contacts inherit hidden state. |
+| Company domains | Keep | Storage supports multiple domains; this stage does not add domain editing or primary selection. |
+
+`POST /crm/companies` accepts `{"name":"Acme"}` or
+`{"name":"Acme","domain":"acme.com"}`. A contact created with
+`POST /crm/companies/{id}/contacts` may use
+`{"name":"Jane","email":"[email protected]"}` with either company.
+The create API remains an insert, not an idempotent import/upsert API; callers
+must retain a successful response instead of retrying a confirmed create.
+
+The company Emails view and automatic call association remain domain-based;
+use the contact's Emails view for an explicitly attached off-domain address.
+Address prechecks aggregate repeated emails within the team, preserving any
+hidden or disabled association rather than letting a second company bypass it.
+The existing People listing still displays one representative per email; each
+company's contact list retains its own records. Email-only API and agent lookups
+surface ambiguity errors. The current UI CSV importer counts failed lookups as
+skipped rows, so per-row error reporting and ID-based recovery remain part of
+the import redesign. Agent CSV imports report ambiguous emails as unresolved
+records with the lookup's reason and continue importing valid rows. Refused
+lookups never create a company or contact; storage and authorization failures
+during lookup still fail the import.
+
+Existing IDs, pipeline rows, custom properties, files, tasks, calls, discussions
+and grants are untouched. There is no schema or data migration. Rollback is an
+application rollback: existing name-only companies remain readable, although
+older creation forms cannot add contacts to them. Cross-domain manual contacts
+remain readable and retain the manual-creation protection against sync cleanup.
+
+## Remaining implementation sequence
+
+1. **Identity and ownership contract** — contact worker with the CRM triage and
+ consent owners. The agreed pilot model is stable UUID identity with deduplication
+ within each personal/team ownership scope. Matching identifiers across teams
+ must not merge records or reveal private records. Email normalization trims
+ and lowercases without stripping plus tags or dots. Aliases, shared and
+ recycled addresses need explicit conflict/merge decisions; email is not a
+ proof of personhood. The ownership model is decided; the conflict-resolution
+ and migration details still need implementation.
+2. **Additive independent records and associations** — contact worker, coordinated
+ with company merge. Give contacts independent ownership; support optional
+ email, phone and zero/one/many explicit company links. Preserve IDs and source
+ provenance. Introduce durable merge redirects before deduplicating legacy
+ records. Serialize create/find/link and give imports durable idempotency keys.
+ Backfill existing links without deleting contacts or rewriting references.
+3. **Authorization and capture** — contact and consent owners. Personal records
+ must remain private until explicitly shared; linking must authorize both ends
+ and must not widen email access. Migrate the current parent-company checks in
+ entity access, message parents, properties, associations, and cleanup before
+ enabling independent records. Company unlink/delete must retain contacts.
+4. **Unified UI/API/tools/import editing** — contact worker. Select an existing
+ visible contact before creation, expose aliases/phone and explicit links,
+ reuse properties/database storage for imported fields, and add domain
+ management with an explicit primary. Company merge owns its survivor,
+ conflicts, domain union and durable redirects; do not auto-merge by name.
+5. **Pilot and verification** — the launch owner decides scope after migration and
+ permission tests. Initially exercise manual team-owned creation only; broad
+ personal-contact capture remains off this change. Verify repeat/concurrent
+ imports, phone-only then email-added records, cross-team isolation, link and
+ unlink, references and rollback before expanding the pilot. Use a rolling
+ migration with compatible writers, then reader cutover; remove old columns
+ only after deployment. Roll back readers/writers, never erase new user data.
+
+The GQL backfill worker continues against main's existing contact APIs; this
+stage adds no dependency to that work. Consent/exclusions and company merging
+remain separate coordinated deliveries. No external implementation is assumed.
+
+No hands-on reference CRM comparison or p50/p95 benchmark has been completed. Measure
+create/find/link/import clicks, required fields, errors and recovery, plus open
+and save latency on small and realistic datasets before claiming parity. Search
+work and search performance measurement remain outside this non-search change.
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CreateCrmCompanyRequest.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CreateCrmCompanyRequest.md
index 36c7dda02b..7b7e0db26a 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CreateCrmCompanyRequest.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CreateCrmCompanyRequest.md
@@ -1,6 +1,6 @@
# Type Alias: CreateCrmCompanyRequest
-> **CreateCrmCompanyRequest** = \{ `domain`: `string`; `name`: `string`; \}
+> **CreateCrmCompanyRequest** = \{ `domain?`: `string` \| `null`; `name`: `string`; \}
Request body for `POST /crm/companies`.
@@ -8,5 +8,5 @@ Request body for `POST /crm/companies`.
| Property | Type | Description |
| ------ | ------ | ------ |
-| <a id="property-domain"></a> `domain` | `string` | The company's email domain, e.g. "acme.com". Must be a bare domain (no scheme, path, or email) and not a generic email provider domain. |
+| <a id="property-domain"></a> `domain?` | `string` \| `null` | Optional company domain, e.g. "acme.com". Omit for a name-only company. When supplied, must be a bare domain (no scheme, path, or email) and not a generic email provider domain. |
| <a id="property-name"></a> `name` | `string` | Display name for the company. Team-scoped: overrides the domain-directory name on every read path. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CreateCrmContactRequest.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CreateCrmContactRequest.md
index 577c45c064..90a48c913c 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CreateCrmContactRequest.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CreateCrmContactRequest.md
@@ -8,5 +8,5 @@ Request body for `POST /crm/companies/{company_id}/contacts`.
| Property | Type | Description |
| ------ | ------ | ------ |
-| <a id="property-email"></a> `email` | `string` | The contact's email address, e.g. "[email protected]". Its domain must be one of the company's domains (400 otherwise). |
+| <a id="property-email"></a> `email` | `string` | The contact's email address, including personal email providers. It need not match a company domain. |
| <a id="property-name"></a> `name` | `string` | Display name for the contact. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/GetContactByEmailErrors.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/GetContactByEmailErrors.md
index dc56115c35..313108c62a 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/GetContactByEmailErrors.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/GetContactByEmailErrors.md
@@ -4,8 +4,8 @@
## Properties
-| Property | Type |
-| ------ | ------ |
-| <a id="property-400"></a> `400` | [`ErrorResponse`](ErrorResponse.md) |
-| <a id="property-401"></a> `401` | [`ErrorResponse`](ErrorResponse.md) |
-| <a id="property-500"></a> `500` | [`ErrorResponse`](ErrorResponse.md) |
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-400"></a> `400` | [`ErrorResponse`](ErrorResponse.md) | Invalid email or multiple visible contacts match; choose a contact ID. |
+| <a id="property-401"></a> `401` | [`ErrorResponse`](ErrorResponse.md) | - |
+| <a id="property-500"></a> `500` | [`ErrorResponse`](ErrorResponse.md) | - |
diff --git a/packages/sdk/generated/storage/sdk.gen.ts b/packages/sdk/generated/storage/sdk.gen.ts
index b0113eeba5..38cfcd4c44 100644
--- a/packages/sdk/generated/storage/sdk.gen.ts
+++ b/packages/sdk/generated/storage/sdk.gen.ts
@@ -1014,7 +1014,6 @@ export class Sdk extends HeyApiClient {
* [`CrmCompanyAccessLevelExtractor`]: the caller must be on the team
* that owns the company (hidden companies are reachable for
* admin/owner only, and the new contact then inherits `hidden`). The
- * email's domain must be one of the company's domains (400), the
* company must not already track the email (409), and the team's CRM
* killswitch must be on (403).
*/
@@ -1094,7 +1093,8 @@ export class Sdk extends HeyApiClient {
* Look up a CRM contact by email in the caller's team. Returns a null
* `contact` when no visible contact exists. Any team member may resolve a
* visible contact; admin/owner callers may also resolve hidden contacts and
- * contacts under hidden companies.
+ * contacts under hidden companies. Returns 400 when several visible contacts
+ * match; callers must choose an explicit contact ID instead.
*/
public getContactByEmail<ThrowOnError extends boolean = false>(options: Options<GetContactByEmailData, ThrowOnError>): RequestResult<GetContactByEmailResponses, GetContactByEmailErrors, ThrowOnError> {
return (options.client ?? this.client).get<GetContactByEmailResponses, GetContactByEmailErrors, ThrowOnError>({ url: '/crm/contacts/by-email', ...options });
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index 98e8c8665d..daae71759f 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -4091,11 +4091,12 @@ export type CreateChannelScopedBotResponse = {
*/
export type CreateCrmCompanyRequest = {
/**
- * The company's email domain, e.g. "acme.com". Must be a bare
+ * Optional company domain, e.g. "acme.com". Omit for a name-only
+ * company. When supplied, must be a bare
* domain (no scheme, path, or email) and not a generic email
* provider domain.
*/
- domain: string;
+ domain?: string | null;
/**
* Display name for the company. Team-scoped: overrides the
* domain-directory name on every read path.
@@ -4108,8 +4109,8 @@ export type CreateCrmCompanyRequest = {
*/
export type CreateCrmContactRequest = {
/**
- * The contact's email address, e.g. "[email protected]". Its domain
- * must be one of the company's domains (400 otherwise).
+ * The contact's email address, including personal email providers.
+ * It need not match a company domain.
*/
email: string;
/**
@@ -19445,6 +19446,9 @@ export type GetContactByEmailData = {
};
export type GetContactByEmailErrors = {
+ /**
+ * Invalid email or multiple visible contacts match; choose a contact ID.
+ */
400: ErrorResponse;
401: ErrorResponse;
500: ErrorResponse;
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 46d9b03c14..f717973739 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -5848,7 +5848,7 @@
},
"post": {
"tags": ["crm::inbound::axum_router::create_contact"],
- "summary": "Manually create a contact under a CRM company. Access is enforced by\n[`CrmCompanyAccessLevelExtractor`]: the caller must be on the team\nthat owns the company (hidden companies are reachable for\nadmin/owner only, and the new contact then inherits `hidden`). The\nemail's domain must be one of the company's domains (400), the\ncompany must not already track the email (409), and the team's CRM\nkillswitch must be on (403).",
+ "summary": "Manually create a contact under a CRM company. Access is enforced by\n[`CrmCompanyAccessLevelExtractor`]: the caller must be on the team\nthat owns the company (hidden companies are reachable for\nadmin/owner only, and the new contact then inherits `hidden`). The\ncompany must not already track the email (409), and the team's CRM\nkillswitch must be on (403).",
"operationId": "create_crm_contact",
"parameters": [
{
@@ -6222,7 +6222,7 @@
"/crm/contacts/by-email": {
"get": {
"tags": ["crm::inbound::axum_router::get_contact_by_email"],
- "summary": "Look up a CRM contact by email in the caller's team. Returns a null\n`contact` when no visible contact exists. Any team member may resolve a\nvisible contact; admin/owner callers may also resolve hidden contacts and\ncontacts under hidden companies.",
+ "summary": "Look up a CRM contact by email in the caller's team. Returns a null\n`contact` when no visible contact exists. Any team member may resolve a\nvisible contact; admin/owner callers may also resolve hidden contacts and\ncontacts under hidden companies. Returns 400 when several visible contacts\nmatch; callers must choose an explicit contact ID instead.",
"operationId": "get_contact_by_email",
"parameters": [
{
@@ -6247,7 +6247,7 @@
}
},
"400": {
- "description": "",
+ "description": "Invalid email or multiple visible contacts match; choose a contact ID.",
"content": {
"application/json": {
"schema": {
@@ -25808,11 +25808,11 @@
"CreateCrmCompanyRequest": {
"type": "object",
"description": "Request body for `POST /crm/companies`.",
- "required": ["name", "domain"],
+ "required": ["name"],
"properties": {
"domain": {
- "type": "string",
- "description": "The company's email domain, e.g. \"acme.com\". Must be a bare\ndomain (no scheme, path, or email) and not a generic email\nprovider domain."
+ "type": ["string", "null"],
+ "description": "Optional company domain, e.g. \"acme.com\". Omit for a name-only\ncompany. When supplied, must be a bare\ndomain (no scheme, path, or email) and not a generic email\nprovider domain."
},
"name": {
"type": "string",
@@ -25827,7 +25827,7 @@
"properties": {
"email": {
"type": "string",
- "description": "The contact's email address, e.g. \"[email protected]\". Its domain\nmust be one of the company's domains (400 otherwise)."
+ "description": "The contact's email address, including personal email providers.\nIt need not match a company domain."
},
"name": {
"type": "string",