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): manual company and contact creation (#5084)

Evan Hutnik49e4c28c24ee
diff --git a/.sqlx/query-036fca567f0d90c18fe528869a2e734700b1978cdf1a62bcefcb3a9bad3b6eb5.json b/.sqlx/query-036fca567f0d90c18fe528869a2e734700b1978cdf1a62bcefcb3a9bad3b6eb5.json
deleted file mode 100644
index c3bae2d564..0000000000
--- a/.sqlx/query-036fca567f0d90c18fe528869a2e734700b1978cdf1a62bcefcb3a9bad3b6eb5.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE crm_companies\n SET updated_at = now(),\n first_interaction = CASE\n WHEN $4 THEN LEAST(first_interaction, $2)\n ELSE first_interaction\n END,\n last_interaction = GREATEST(last_interaction, $3)\n WHERE id = $1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Timestamptz",
- "Timestamptz",
- "Bool"
- ]
- },
- "nullable": []
- },
- "hash": "036fca567f0d90c18fe528869a2e734700b1978cdf1a62bcefcb3a9bad3b6eb5"
-}
diff --git a/.sqlx/query-0a0d1e426efa290af0aa47a9431ddb17d4058669432c0411b9f66c2eb21d7fd6.json b/.sqlx/query-0a0d1e426efa290af0aa47a9431ddb17d4058669432c0411b9f66c2eb21d7fd6.json
new file mode 100644
index 0000000000..0a5ddc4cf1
--- /dev/null
+++ b/.sqlx/query-0a0d1e426efa290af0aa47a9431ddb17d4058669432c0411b9f66c2eb21d7fd6.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM crm_contacts ct\n USING crm_companies co\n WHERE ct.company_id = co.id\n AND co.team_id = $1\n AND ct.manually_created = FALSE\n AND NOT EXISTS (\n SELECT 1 FROM crm_contact_sources WHERE contact_id = ct.id\n )\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "0a0d1e426efa290af0aa47a9431ddb17d4058669432c0411b9f66c2eb21d7fd6"
+}
diff --git a/.sqlx/query-26398b17eb12140d0e4230aeb5d98b7852f9cc7d698f1dc196d52de587efbaca.json b/.sqlx/query-26398b17eb12140d0e4230aeb5d98b7852f9cc7d698f1dc196d52de587efbaca.json
new file mode 100644
index 0000000000..2fb96f7583
--- /dev/null
+++ b/.sqlx/query-26398b17eb12140d0e4230aeb5d98b7852f9cc7d698f1dc196d52de587efbaca.json
@@ -0,0 +1,74 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO crm_contacts\n (company_id, email, name, first_interaction, last_interaction, hidden, manually_created)\n VALUES ($1, $2, $3, $4, $4, $5, TRUE)\n ON CONFLICT (company_id, email) DO NOTHING\n RETURNING id, company_id, email, name, hidden,\n first_interaction, last_interaction, created_at, updated_at\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "company_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "email",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "hidden",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 5,
+ "name": "first_interaction",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "last_interaction",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Timestamptz",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "26398b17eb12140d0e4230aeb5d98b7852f9cc7d698f1dc196d52de587efbaca"
+}
diff --git a/.sqlx/query-ac1221f53b3482f947f70affe1fa95f778b5cc841f3a08c8d406752da8d25be3.json b/.sqlx/query-2662705c4eb542940f99bd6e5f820694917a2b516b79b8f3d36386dd317524b2.json
similarity index 75%
rename from .sqlx/query-ac1221f53b3482f947f70affe1fa95f778b5cc841f3a08c8d406752da8d25be3.json
rename to .sqlx/query-2662705c4eb542940f99bd6e5f820694917a2b516b79b8f3d36386dd317524b2.json
index 418264801b..3643342097 100644
--- a/.sqlx/query-ac1221f53b3482f947f70affe1fa95f778b5cc841f3a08c8d406752da8d25be3.json
+++ b/.sqlx/query-2662705c4eb542940f99bd6e5f820694917a2b516b79b8f3d36386dd317524b2.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n c.id AS \"company_id!\",\n c.team_id AS \"company_team_id!\",\n c.email_sync AS \"company_email_sync!\",\n c.hidden AS \"company_hidden!\",\n c.first_interaction AS \"company_created_at!\",\n c.last_interaction AS \"company_updated_at!\",\n d.id AS \"domain_id?\",\n d.domain AS \"domain?\",\n d.created_at AS \"domain_created_at?\",\n dd.name AS \"dir_name?\",\n dd.description AS \"dir_description?\"\n FROM crm_companies c\n LEFT JOIN crm_domains d ON d.company_id = c.id\n LEFT JOIN crm_domain_directory dd\n ON LOWER(dd.domain) = LOWER(d.domain)\n WHERE c.team_id = $1\n AND c.id = ANY($2)\n AND ($3 OR c.hidden = FALSE)\n ORDER BY c.last_interaction DESC, c.id DESC, d.created_at ASC NULLS LAST\n ",
+ "query": "\n SELECT\n c.id AS \"company_id!\",\n c.team_id AS \"company_team_id!\",\n c.email_sync AS \"company_email_sync!\",\n c.hidden AS \"company_hidden!\",\n c.first_interaction AS \"company_created_at!\",\n c.last_interaction AS \"company_updated_at!\",\n d.id AS \"domain_id?\",\n d.domain AS \"domain?\",\n d.created_at AS \"domain_created_at?\",\n COALESCE(c.custom_name, dd.name) AS \"display_name?\",\n dd.description AS \"dir_description?\"\n FROM crm_companies c\n LEFT JOIN crm_domains d ON d.company_id = c.id\n LEFT JOIN crm_domain_directory dd\n ON LOWER(dd.domain) = LOWER(d.domain)\n WHERE c.team_id = $1\n AND c.id = ANY($2)\n AND ($3 OR c.hidden = FALSE)\n ORDER BY c.last_interaction DESC, c.id DESC, d.created_at ASC NULLS LAST\n ",
"describe": {
"columns": [
{
@@ -50,7 +50,7 @@
},
{
"ordinal": 9,
- "name": "dir_name?",
+ "name": "display_name?",
"type_info": "Text"
},
{
@@ -76,9 +76,9 @@
false,
false,
false,
- true,
+ null,
true
]
},
- "hash": "ac1221f53b3482f947f70affe1fa95f778b5cc841f3a08c8d406752da8d25be3"
+ "hash": "2662705c4eb542940f99bd6e5f820694917a2b516b79b8f3d36386dd317524b2"
}
diff --git a/.sqlx/query-2b4e211df88210fe46696e0ecae18ca5b07e78b947651531711226366eb0a608.json b/.sqlx/query-2b4e211df88210fe46696e0ecae18ca5b07e78b947651531711226366eb0a608.json
new file mode 100644
index 0000000000..533aa0fb1a
--- /dev/null
+++ b/.sqlx/query-2b4e211df88210fe46696e0ecae18ca5b07e78b947651531711226366eb0a608.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO crm_domains (company_id, team_id, domain)\n VALUES ($1, $2, $3)\n ON CONFLICT (team_id, LOWER(domain)) DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "2b4e211df88210fe46696e0ecae18ca5b07e78b947651531711226366eb0a608"
+}
diff --git a/.sqlx/query-32ea0d9e282c8a36933988baf3f661f68d583c36123629e7cb939cde4aa76827.json b/.sqlx/query-32ea0d9e282c8a36933988baf3f661f68d583c36123629e7cb939cde4aa76827.json
new file mode 100644
index 0000000000..be474c93e9
--- /dev/null
+++ b/.sqlx/query-32ea0d9e282c8a36933988baf3f661f68d583c36123629e7cb939cde4aa76827.json
@@ -0,0 +1,48 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH matched AS (\n SELECT c.id, c.custom_name, c.last_interaction AS updated_at\n FROM crm_companies c\n WHERE c.team_id = $1\n AND (\n (c.hidden = FALSE AND ($2::bool IS NULL OR $2 = FALSE))\n OR (c.hidden = TRUE AND $2 = TRUE AND $9)\n )\n AND (cardinality($3::uuid[]) = 0 OR c.id = ANY($3))\n AND (\n c.custom_name ILIKE $4\n OR EXISTS (\n SELECT 1\n FROM crm_domains d\n LEFT JOIN crm_domain_directory dd\n ON LOWER(dd.domain) = LOWER(d.domain)\n WHERE d.company_id = c.id\n AND (d.domain ILIKE $4 OR dd.name ILIKE $4)\n )\n )\n AND ($7::timestamptz IS NULL OR (c.last_interaction, c.id) < ($7, $8))\n ORDER BY c.last_interaction DESC, c.id DESC\n LIMIT $5\n ),\n primary_domain AS (\n SELECT DISTINCT ON (d.company_id)\n d.company_id,\n COALESCE(dd.name, d.domain) AS display_name\n FROM crm_domains d\n LEFT JOIN crm_domain_directory dd\n ON LOWER(dd.domain) = LOWER(d.domain)\n WHERE d.company_id IN (SELECT id FROM matched)\n ORDER BY d.company_id, d.created_at ASC NULLS LAST\n )\n SELECT\n m.id AS \"id!\",\n COALESCE(m.custom_name, pd.display_name, '') AS \"name!\",\n regexp_replace(\n COALESCE(m.custom_name, pd.display_name, ''),\n $6, '<macro_em>\\1</macro_em>', 'gi'\n ) AS \"name_highlighted!\",\n m.updated_at AS \"updated_at!\"\n FROM matched m\n LEFT JOIN primary_domain pd ON pd.company_id = m.id\n ORDER BY m.updated_at DESC, m.id DESC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "name!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "name_highlighted!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "updated_at!",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Bool",
+ "UuidArray",
+ "Text",
+ "Int8",
+ "Text",
+ "Timestamptz",
+ "Uuid",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ false,
+ null,
+ null,
+ false
+ ]
+ },
+ "hash": "32ea0d9e282c8a36933988baf3f661f68d583c36123629e7cb939cde4aa76827"
+}
diff --git a/.sqlx/query-361c3d6e5a9549af7dd9042a088005f8da9e6128de27e65a9bb69e780615bf4c.json b/.sqlx/query-361c3d6e5a9549af7dd9042a088005f8da9e6128de27e65a9bb69e780615bf4c.json
deleted file mode 100644
index 48c07f8426..0000000000
--- a/.sqlx/query-361c3d6e5a9549af7dd9042a088005f8da9e6128de27e65a9bb69e780615bf4c.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO crm_domains (company_id, team_id, domain)\n VALUES ($1, $2, $3)\n ON CONFLICT (team_id, LOWER(domain)) DO NOTHING\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Uuid",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "361c3d6e5a9549af7dd9042a088005f8da9e6128de27e65a9bb69e780615bf4c"
-}
diff --git a/.sqlx/query-498922bc53b7001639cdf5cd616196003efb82cd3df8a6eec296df1b22d08464.json b/.sqlx/query-498922bc53b7001639cdf5cd616196003efb82cd3df8a6eec296df1b22d08464.json
new file mode 100644
index 0000000000..36039f5223
--- /dev/null
+++ b/.sqlx/query-498922bc53b7001639cdf5cd616196003efb82cd3df8a6eec296df1b22d08464.json
@@ -0,0 +1,48 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n ct.id AS contact_id,\n ct.manually_created AS \"contact_manually_created!\",\n co.id AS company_id,\n co.email_sync AS \"email_sync!\",\n co.manually_created AS \"company_manually_created!\"\n FROM crm_contacts ct\n JOIN crm_companies co ON co.id = ct.company_id\n JOIN crm_domains d ON d.company_id = co.id\n WHERE co.team_id = $1\n AND LOWER(ct.email) = $2\n AND LOWER(d.domain) = $3\n LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "contact_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "contact_manually_created!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 2,
+ "name": "company_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "email_sync!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 4,
+ "name": "company_manually_created!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "498922bc53b7001639cdf5cd616196003efb82cd3df8a6eec296df1b22d08464"
+}
diff --git a/.sqlx/query-61d663d08e05ea919df584b273c67e2d99c3981222a87e823892706e4b9354ac.json b/.sqlx/query-61d663d08e05ea919df584b273c67e2d99c3981222a87e823892706e4b9354ac.json
deleted file mode 100644
index a25b42db28..0000000000
--- a/.sqlx/query-61d663d08e05ea919df584b273c67e2d99c3981222a87e823892706e4b9354ac.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE crm_companies\n SET updated_at = now(),\n first_interaction = CASE\n WHEN $4 THEN LEAST(first_interaction, $2)\n ELSE first_interaction\n END,\n last_interaction = GREATEST(last_interaction, $3)\n WHERE id = $1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Timestamptz",
- "Timestamptz",
- "Bool"
- ]
- },
- "nullable": []
- },
- "hash": "61d663d08e05ea919df584b273c67e2d99c3981222a87e823892706e4b9354ac"
-}
diff --git a/.sqlx/query-654e58c390f6a8935cd310d596202b9b2036019140bb0da9d2f033cdba2289f3.json b/.sqlx/query-654e58c390f6a8935cd310d596202b9b2036019140bb0da9d2f033cdba2289f3.json
deleted file mode 100644
index 4b5337dcfa..0000000000
--- a/.sqlx/query-654e58c390f6a8935cd310d596202b9b2036019140bb0da9d2f033cdba2289f3.json
+++ /dev/null
@@ -1,36 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n ct.id AS contact_id,\n co.id AS company_id,\n co.email_sync AS \"email_sync!\"\n FROM crm_contacts ct\n JOIN crm_companies co ON co.id = ct.company_id\n JOIN crm_domains d ON d.company_id = co.id\n WHERE co.team_id = $1\n AND LOWER(ct.email) = $2\n AND LOWER(d.domain) = $3\n LIMIT 1\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "contact_id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "company_id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 2,
- "name": "email_sync!",
- "type_info": "Bool"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text"
- ]
- },
- "nullable": [
- false,
- false,
- false
- ]
- },
- "hash": "654e58c390f6a8935cd310d596202b9b2036019140bb0da9d2f033cdba2289f3"
-}
diff --git a/.sqlx/query-8b7c148e88c11c3a2ba484c8ada918bf6497d8ec2339d9173904a7532b2b0052.json b/.sqlx/query-6ff5862768e6227fed0049fd64199828a2a27a8b64542b91b82db0930fc079f4.json
similarity index 52%
rename from .sqlx/query-8b7c148e88c11c3a2ba484c8ada918bf6497d8ec2339d9173904a7532b2b0052.json
rename to .sqlx/query-6ff5862768e6227fed0049fd64199828a2a27a8b64542b91b82db0930fc079f4.json
index 46fe53d17b..d24b449631 100644
--- a/.sqlx/query-8b7c148e88c11c3a2ba484c8ada918bf6497d8ec2339d9173904a7532b2b0052.json
+++ b/.sqlx/query-6ff5862768e6227fed0049fd64199828a2a27a8b64542b91b82db0930fc079f4.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n DELETE FROM crm_companies co\n WHERE co.team_id = $1\n AND co.email_sync = TRUE\n AND NOT EXISTS (\n SELECT 1 FROM crm_contacts WHERE company_id = co.id\n )\n ",
+ "query": "\n DELETE FROM crm_companies co\n WHERE co.team_id = $1\n AND co.email_sync = TRUE\n AND co.manually_created = FALSE\n AND NOT EXISTS (\n SELECT 1 FROM crm_contacts WHERE company_id = co.id\n )\n ",
"describe": {
"columns": [],
"parameters": {
@@ -10,5 +10,5 @@
},
"nullable": []
},
- "hash": "8b7c148e88c11c3a2ba484c8ada918bf6497d8ec2339d9173904a7532b2b0052"
+ "hash": "6ff5862768e6227fed0049fd64199828a2a27a8b64542b91b82db0930fc079f4"
}
diff --git a/.sqlx/query-745780ca3e0e26284050ac92cd3c90f9a796ec770c53cbee32660ed867c138a4.json b/.sqlx/query-745780ca3e0e26284050ac92cd3c90f9a796ec770c53cbee32660ed867c138a4.json
deleted file mode 100644
index 12c74e21a2..0000000000
--- a/.sqlx/query-745780ca3e0e26284050ac92cd3c90f9a796ec770c53cbee32660ed867c138a4.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT c.id\n FROM crm_companies c\n JOIN crm_domains d ON d.company_id = c.id\n WHERE c.team_id = $1\n AND LOWER(d.domain) = $2\n LIMIT 1\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "745780ca3e0e26284050ac92cd3c90f9a796ec770c53cbee32660ed867c138a4"
-}
diff --git a/.sqlx/query-8f27aa55aa502bac325c84ab62c854ede412158bf7ca13b931b56636431c71ff.json b/.sqlx/query-8f27aa55aa502bac325c84ab62c854ede412158bf7ca13b931b56636431c71ff.json
new file mode 100644
index 0000000000..9dc3d05273
--- /dev/null
+++ b/.sqlx/query-8f27aa55aa502bac325c84ab62c854ede412158bf7ca13b931b56636431c71ff.json
@@ -0,0 +1,26 @@
+{
+ "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 ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Bool",
+ "Timestamptz",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "8f27aa55aa502bac325c84ab62c854ede412158bf7ca13b931b56636431c71ff"
+}
diff --git a/.sqlx/query-900c8fabc7e2cdb1ae391b922275ccccb2db888110190ea01bfdda510b808dd1.json b/.sqlx/query-900c8fabc7e2cdb1ae391b922275ccccb2db888110190ea01bfdda510b808dd1.json
new file mode 100644
index 0000000000..e91a229be0
--- /dev/null
+++ b/.sqlx/query-900c8fabc7e2cdb1ae391b922275ccccb2db888110190ea01bfdda510b808dd1.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT hidden\n FROM crm_companies\n WHERE id = $1\n AND team_id = $2\n AND ($3 OR hidden = FALSE)\n FOR UPDATE\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "hidden",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "900c8fabc7e2cdb1ae391b922275ccccb2db888110190ea01bfdda510b808dd1"
+}
diff --git a/.sqlx/query-9d46745c3514bf518340dd31f909163c257890c5008bfbdb5db4d2b7aa01ac35.json b/.sqlx/query-9d46745c3514bf518340dd31f909163c257890c5008bfbdb5db4d2b7aa01ac35.json
new file mode 100644
index 0000000000..8fd31b5c8a
--- /dev/null
+++ b/.sqlx/query-9d46745c3514bf518340dd31f909163c257890c5008bfbdb5db4d2b7aa01ac35.json
@@ -0,0 +1,95 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH limited_companies AS (\n SELECT\n c.id,\n c.team_id,\n c.custom_name,\n c.email_sync,\n c.hidden,\n c.first_interaction,\n c.last_interaction\n FROM crm_companies c\n LEFT JOIN \"UserHistory\" uh\n ON uh.\"itemId\" = c.id::text\n AND uh.\"itemType\" = 'crm_company'\n AND uh.\"userId\" = $8\n WHERE c.team_id = $1\n AND c.hidden = COALESCE($5::bool, FALSE)\n AND EXISTS (\n SELECT 1 FROM team_crm_settings tcs\n WHERE tcs.team_id = $1 AND tcs.crm_enabled\n )\n AND (cardinality($2::uuid[]) = 0 OR c.id = ANY($2::uuid[]))\n -- Keyset seek (NULL = first page): keep only rows that\n -- sort strictly after the cursor.\n AND (\n $6::timestamptz IS NULL\n OR (\n CASE $4\n WHEN 'created_at' THEN c.first_interaction\n WHEN 'viewed_at' THEN uh.\"updatedAt\"\n WHEN 'viewed_updated'\n THEN COALESCE(uh.\"updatedAt\", c.last_interaction)\n ELSE c.last_interaction\n END,\n c.id::text\n ) < ($6, $7)\n )\n ORDER BY\n CASE $4\n WHEN 'created_at' THEN c.first_interaction\n WHEN 'viewed_at' THEN uh.\"updatedAt\"\n WHEN 'viewed_updated'\n THEN COALESCE(uh.\"updatedAt\", c.last_interaction)\n ELSE c.last_interaction\n END DESC NULLS LAST,\n c.id DESC\n LIMIT $3\n )\n SELECT\n lc.id AS \"company_id!\",\n lc.team_id AS \"company_team_id!\",\n lc.email_sync AS \"company_email_sync!\",\n lc.hidden AS \"company_hidden!\",\n lc.first_interaction AS \"company_created_at!\",\n lc.last_interaction AS \"company_updated_at!\",\n d.id AS \"domain_id?\",\n d.domain AS \"domain?\",\n d.created_at AS \"domain_created_at?\",\n COALESCE(lc.custom_name, dd.name) AS \"display_name?\",\n dd.description AS \"dir_description?\",\n uh.\"updatedAt\"::timestamptz AS \"viewed_at?\"\n FROM limited_companies lc\n LEFT JOIN \"UserHistory\" uh\n ON uh.\"itemId\" = lc.id::text\n AND uh.\"itemType\" = 'crm_company'\n AND uh.\"userId\" = $8\n LEFT JOIN crm_domains d ON d.company_id = lc.id\n LEFT JOIN crm_domain_directory dd\n ON LOWER(dd.domain) = LOWER(d.domain)\n ORDER BY\n CASE $4\n WHEN 'created_at' THEN lc.first_interaction\n WHEN 'viewed_at' THEN uh.\"updatedAt\"\n WHEN 'viewed_updated'\n THEN COALESCE(uh.\"updatedAt\", lc.last_interaction)\n ELSE lc.last_interaction\n END DESC NULLS LAST,\n lc.id DESC,\n d.created_at ASC NULLS LAST\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "company_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "company_team_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "company_email_sync!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 3,
+ "name": "company_hidden!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 4,
+ "name": "company_created_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "company_updated_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "domain_id?",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 7,
+ "name": "domain?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "domain_created_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "display_name?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "dir_description?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 11,
+ "name": "viewed_at?",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "UuidArray",
+ "Int8",
+ "Text",
+ "Bool",
+ "Timestamptz",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ null,
+ true,
+ null
+ ]
+ },
+ "hash": "9d46745c3514bf518340dd31f909163c257890c5008bfbdb5db4d2b7aa01ac35"
+}
diff --git a/.sqlx/query-9f1042f72a5c1a5137fbb9cbaee798f5df26e8da3fa98c5afec3cb8d130ab293.json b/.sqlx/query-9f1042f72a5c1a5137fbb9cbaee798f5df26e8da3fa98c5afec3cb8d130ab293.json
new file mode 100644
index 0000000000..fe312dd6eb
--- /dev/null
+++ b/.sqlx/query-9f1042f72a5c1a5137fbb9cbaee798f5df26e8da3fa98c5afec3cb8d130ab293.json
@@ -0,0 +1,23 @@
+{
+ "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-a10bb7f95f88136b0bdf505b0338c8a87045ca5aa3d85cefbba8111c65892870.json b/.sqlx/query-a10bb7f95f88136b0bdf505b0338c8a87045ca5aa3d85cefbba8111c65892870.json
deleted file mode 100644
index 49be80e7ce..0000000000
--- a/.sqlx/query-a10bb7f95f88136b0bdf505b0338c8a87045ca5aa3d85cefbba8111c65892870.json
+++ /dev/null
@@ -1,24 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO crm_companies (team_id, first_interaction, last_interaction)\n VALUES ($1, $2, $3)\n RETURNING id\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Timestamptz",
- "Timestamptz"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "a10bb7f95f88136b0bdf505b0338c8a87045ca5aa3d85cefbba8111c65892870"
-}
diff --git a/.sqlx/query-bab2c7e9807103ec8ece1edcdc8e357dc50be7a4d634f45990b772eb0824a35d.json b/.sqlx/query-bab2c7e9807103ec8ece1edcdc8e357dc50be7a4d634f45990b772eb0824a35d.json
deleted file mode 100644
index 73f58e81b1..0000000000
--- a/.sqlx/query-bab2c7e9807103ec8ece1edcdc8e357dc50be7a4d634f45990b772eb0824a35d.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n DELETE FROM crm_contacts ct\n USING crm_companies co\n WHERE ct.company_id = co.id\n AND co.team_id = $1\n AND NOT EXISTS (\n SELECT 1 FROM crm_contact_sources WHERE contact_id = ct.id\n )\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "bab2c7e9807103ec8ece1edcdc8e357dc50be7a4d634f45990b772eb0824a35d"
-}
diff --git a/.sqlx/query-bda762ae77abbaf4dd6bee0379ef2ae7c653c1ba79aa26e6681b15cee6dc7f88.json b/.sqlx/query-bda762ae77abbaf4dd6bee0379ef2ae7c653c1ba79aa26e6681b15cee6dc7f88.json
new file mode 100644
index 0000000000..efdab7e89d
--- /dev/null
+++ b/.sqlx/query-bda762ae77abbaf4dd6bee0379ef2ae7c653c1ba79aa26e6681b15cee6dc7f88.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT c.id\n FROM crm_companies c\n JOIN crm_domains d ON d.company_id = c.id\n WHERE c.team_id = $1\n AND LOWER(d.domain) = $2\n LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "bda762ae77abbaf4dd6bee0379ef2ae7c653c1ba79aa26e6681b15cee6dc7f88"
+}
diff --git a/.sqlx/query-c7c058fd3acdc93e77a805b28b844150503f955a91339be026f8b68f65092adb.json b/.sqlx/query-da0dbddbc6fa69a1d86ab3187781c5ea5ad8d7e43d340506daa74d04f29ea6da.json
similarity index 76%
rename from .sqlx/query-c7c058fd3acdc93e77a805b28b844150503f955a91339be026f8b68f65092adb.json
rename to .sqlx/query-da0dbddbc6fa69a1d86ab3187781c5ea5ad8d7e43d340506daa74d04f29ea6da.json
index b25657bb43..411acd7cb1 100644
--- a/.sqlx/query-c7c058fd3acdc93e77a805b28b844150503f955a91339be026f8b68f65092adb.json
+++ b/.sqlx/query-da0dbddbc6fa69a1d86ab3187781c5ea5ad8d7e43d340506daa74d04f29ea6da.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n c.id AS \"company_id!\",\n c.team_id AS \"company_team_id!\",\n c.email_sync AS \"company_email_sync!\",\n c.hidden AS \"company_hidden!\",\n c.first_interaction AS \"company_created_at!\",\n c.last_interaction AS \"company_updated_at!\",\n d.id AS \"domain_id?\",\n d.domain AS \"domain?\",\n d.created_at AS \"domain_created_at?\",\n dd.name AS \"dir_name?\",\n dd.description AS \"dir_description?\"\n FROM crm_companies c\n LEFT JOIN crm_domains d ON d.company_id = c.id\n LEFT JOIN crm_domain_directory dd\n ON LOWER(dd.domain) = LOWER(d.domain)\n WHERE c.id = $1\n AND c.team_id = $2\n AND ($3 OR c.hidden = FALSE)\n ORDER BY d.created_at ASC NULLS LAST\n ",
+ "query": "\n SELECT\n c.id AS \"company_id!\",\n c.team_id AS \"company_team_id!\",\n c.email_sync AS \"company_email_sync!\",\n c.hidden AS \"company_hidden!\",\n c.first_interaction AS \"company_created_at!\",\n c.last_interaction AS \"company_updated_at!\",\n d.id AS \"domain_id?\",\n d.domain AS \"domain?\",\n d.created_at AS \"domain_created_at?\",\n COALESCE(c.custom_name, dd.name) AS \"display_name?\",\n dd.description AS \"dir_description?\"\n FROM crm_companies c\n LEFT JOIN crm_domains d ON d.company_id = c.id\n LEFT JOIN crm_domain_directory dd\n ON LOWER(dd.domain) = LOWER(d.domain)\n WHERE c.id = $1\n AND c.team_id = $2\n AND ($3 OR c.hidden = FALSE)\n ORDER BY d.created_at ASC NULLS LAST\n ",
"describe": {
"columns": [
{
@@ -50,7 +50,7 @@
},
{
"ordinal": 9,
- "name": "dir_name?",
+ "name": "display_name?",
"type_info": "Text"
},
{
@@ -76,9 +76,9 @@
false,
false,
false,
- true,
+ null,
true
]
},
- "hash": "c7c058fd3acdc93e77a805b28b844150503f955a91339be026f8b68f65092adb"
+ "hash": "da0dbddbc6fa69a1d86ab3187781c5ea5ad8d7e43d340506daa74d04f29ea6da"
}
diff --git a/.sqlx/query-e3cbccf7e62eaa5d655b12fbf32d181f2bb79b25ac3c2300e2eab17c912697af.json b/.sqlx/query-e3cbccf7e62eaa5d655b12fbf32d181f2bb79b25ac3c2300e2eab17c912697af.json
deleted file mode 100644
index be2165bfbe..0000000000
--- a/.sqlx/query-e3cbccf7e62eaa5d655b12fbf32d181f2bb79b25ac3c2300e2eab17c912697af.json
+++ /dev/null
@@ -1,95 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH limited_companies AS (\n SELECT\n c.id,\n c.team_id,\n c.email_sync,\n c.hidden,\n c.first_interaction,\n c.last_interaction\n FROM crm_companies c\n LEFT JOIN \"UserHistory\" uh\n ON uh.\"itemId\" = c.id::text\n AND uh.\"itemType\" = 'crm_company'\n AND uh.\"userId\" = $8\n WHERE c.team_id = $1\n AND c.hidden = COALESCE($5::bool, FALSE)\n AND EXISTS (\n SELECT 1 FROM team_crm_settings tcs\n WHERE tcs.team_id = $1 AND tcs.crm_enabled\n )\n AND (cardinality($2::uuid[]) = 0 OR c.id = ANY($2::uuid[]))\n -- Keyset seek (NULL = first page): keep only rows that\n -- sort strictly after the cursor.\n AND (\n $6::timestamptz IS NULL\n OR (\n CASE $4\n WHEN 'created_at' THEN c.first_interaction\n WHEN 'viewed_at' THEN uh.\"updatedAt\"\n WHEN 'viewed_updated'\n THEN COALESCE(uh.\"updatedAt\", c.last_interaction)\n ELSE c.last_interaction\n END,\n c.id::text\n ) < ($6, $7)\n )\n ORDER BY\n CASE $4\n WHEN 'created_at' THEN c.first_interaction\n WHEN 'viewed_at' THEN uh.\"updatedAt\"\n WHEN 'viewed_updated'\n THEN COALESCE(uh.\"updatedAt\", c.last_interaction)\n ELSE c.last_interaction\n END DESC NULLS LAST,\n c.id DESC\n LIMIT $3\n )\n SELECT\n lc.id AS \"company_id!\",\n lc.team_id AS \"company_team_id!\",\n lc.email_sync AS \"company_email_sync!\",\n lc.hidden AS \"company_hidden!\",\n lc.first_interaction AS \"company_created_at!\",\n lc.last_interaction AS \"company_updated_at!\",\n d.id AS \"domain_id?\",\n d.domain AS \"domain?\",\n d.created_at AS \"domain_created_at?\",\n dd.name AS \"dir_name?\",\n dd.description AS \"dir_description?\",\n uh.\"updatedAt\"::timestamptz AS \"viewed_at?\"\n FROM limited_companies lc\n LEFT JOIN \"UserHistory\" uh\n ON uh.\"itemId\" = lc.id::text\n AND uh.\"itemType\" = 'crm_company'\n AND uh.\"userId\" = $8\n LEFT JOIN crm_domains d ON d.company_id = lc.id\n LEFT JOIN crm_domain_directory dd\n ON LOWER(dd.domain) = LOWER(d.domain)\n ORDER BY\n CASE $4\n WHEN 'created_at' THEN lc.first_interaction\n WHEN 'viewed_at' THEN uh.\"updatedAt\"\n WHEN 'viewed_updated'\n THEN COALESCE(uh.\"updatedAt\", lc.last_interaction)\n ELSE lc.last_interaction\n END DESC NULLS LAST,\n lc.id DESC,\n d.created_at ASC NULLS LAST\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "company_id!",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "company_team_id!",
- "type_info": "Uuid"
- },
- {
- "ordinal": 2,
- "name": "company_email_sync!",
- "type_info": "Bool"
- },
- {
- "ordinal": 3,
- "name": "company_hidden!",
- "type_info": "Bool"
- },
- {
- "ordinal": 4,
- "name": "company_created_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 5,
- "name": "company_updated_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 6,
- "name": "domain_id?",
- "type_info": "Uuid"
- },
- {
- "ordinal": 7,
- "name": "domain?",
- "type_info": "Text"
- },
- {
- "ordinal": 8,
- "name": "domain_created_at?",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 9,
- "name": "dir_name?",
- "type_info": "Text"
- },
- {
- "ordinal": 10,
- "name": "dir_description?",
- "type_info": "Text"
- },
- {
- "ordinal": 11,
- "name": "viewed_at?",
- "type_info": "Timestamptz"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "UuidArray",
- "Int8",
- "Text",
- "Bool",
- "Timestamptz",
- "Text",
- "Text"
- ]
- },
- "nullable": [
- false,
- false,
- false,
- false,
- false,
- false,
- false,
- false,
- false,
- true,
- true,
- null
- ]
- },
- "hash": "e3cbccf7e62eaa5d655b12fbf32d181f2bb79b25ac3c2300e2eab17c912697af"
-}
diff --git a/.sqlx/query-e63fd5c15b6e5327aecb2524ee304fcd25df705766b08c6fd8d39d10cacfb33e.json b/.sqlx/query-e63fd5c15b6e5327aecb2524ee304fcd25df705766b08c6fd8d39d10cacfb33e.json
deleted file mode 100644
index 982ccd411b..0000000000
--- a/.sqlx/query-e63fd5c15b6e5327aecb2524ee304fcd25df705766b08c6fd8d39d10cacfb33e.json
+++ /dev/null
@@ -1,48 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH matched AS (\n SELECT c.id, c.last_interaction AS updated_at\n FROM crm_companies c\n WHERE c.team_id = $1\n AND (\n (c.hidden = FALSE AND ($2::bool IS NULL OR $2 = FALSE))\n OR (c.hidden = TRUE AND $2 = TRUE AND $9)\n )\n AND (cardinality($3::uuid[]) = 0 OR c.id = ANY($3))\n AND EXISTS (\n SELECT 1\n FROM crm_domains d\n LEFT JOIN crm_domain_directory dd\n ON LOWER(dd.domain) = LOWER(d.domain)\n WHERE d.company_id = c.id\n AND (d.domain ILIKE $4 OR dd.name ILIKE $4)\n )\n AND ($7::timestamptz IS NULL OR (c.last_interaction, c.id) < ($7, $8))\n ORDER BY c.last_interaction DESC, c.id DESC\n LIMIT $5\n ),\n primary_domain AS (\n SELECT DISTINCT ON (d.company_id)\n d.company_id,\n COALESCE(dd.name, d.domain) AS display_name\n FROM crm_domains d\n LEFT JOIN crm_domain_directory dd\n ON LOWER(dd.domain) = LOWER(d.domain)\n WHERE d.company_id IN (SELECT id FROM matched)\n ORDER BY d.company_id, d.created_at ASC NULLS LAST\n )\n SELECT\n m.id AS \"id!\",\n COALESCE(pd.display_name, '') AS \"name!\",\n regexp_replace(\n COALESCE(pd.display_name, ''),\n $6, '<macro_em>\\1</macro_em>', 'gi'\n ) AS \"name_highlighted!\",\n m.updated_at AS \"updated_at!\"\n FROM matched m\n LEFT JOIN primary_domain pd ON pd.company_id = m.id\n ORDER BY m.updated_at DESC, m.id DESC\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id!",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "name!",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "name_highlighted!",
- "type_info": "Text"
- },
- {
- "ordinal": 3,
- "name": "updated_at!",
- "type_info": "Timestamptz"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Bool",
- "UuidArray",
- "Text",
- "Int8",
- "Text",
- "Timestamptz",
- "Uuid",
- "Bool"
- ]
- },
- "nullable": [
- false,
- null,
- null,
- false
- ]
- },
- "hash": "e63fd5c15b6e5327aecb2524ee304fcd25df705766b08c6fd8d39d10cacfb33e"
-}
diff --git a/.sqlx/query-fb1aa4fea5c67c6700be226e8f3798f577fc4320540abb817276838b77d3c397.json b/.sqlx/query-fb1aa4fea5c67c6700be226e8f3798f577fc4320540abb817276838b77d3c397.json
new file mode 100644
index 0000000000..ed0d6c596e
--- /dev/null
+++ b/.sqlx/query-fb1aa4fea5c67c6700be226e8f3798f577fc4320540abb817276838b77d3c397.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE crm_companies\n SET updated_at = now(),\n first_interaction = CASE\n WHEN $4 THEN LEAST(first_interaction, $2)\n ELSE first_interaction\n END,\n last_interaction = GREATEST(last_interaction, $3)\n WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz",
+ "Timestamptz",
+ "Bool"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "fb1aa4fea5c67c6700be226e8f3798f577fc4320540abb817276838b77d3c397"
+}
diff --git a/apps/web/src/components/app/Layout.tsx b/apps/web/src/components/app/Layout.tsx
index d15e78d303..e8feddedd7 100644
--- a/apps/web/src/components/app/Layout.tsx
+++ b/apps/web/src/components/app/Layout.tsx
@@ -15,6 +15,8 @@ import {
setCreateMenuOpen,
} from '@app/features/command/Launcher';
import { MobileSearchOuter } from '@app/features/command/mobile/MobileSearch';
+import { CreateCompanyModal } from '@app/features/companies/CreateCompanyModal';
+import { CreateContactModal } from '@app/features/companies/CreateContactModal';
import { DevStatusBar } from '@app/features/devtools/DevStatusBar';
import { GlobalBulkEditEntityModal } from '@app/features/entity/bulk-edit/BulkEditEntityModal';
import {
@@ -387,6 +389,8 @@ function LayoutInner(props: RouteSectionProps) {
<IosShareSheet />
<MacroMcpSetupModal />
<CreateChannelModal />
+ <CreateCompanyModal />
+ <CreateContactModal />
<Show when={isAddInboxDialogOpen()}>
<AddInboxDialog />
</Show>
diff --git a/apps/web/src/components/app/side-panel/SidePanel.tsx b/apps/web/src/components/app/side-panel/SidePanel.tsx
index 354c791bea..015bc82116 100644
--- a/apps/web/src/components/app/side-panel/SidePanel.tsx
+++ b/apps/web/src/components/app/side-panel/SidePanel.tsx
@@ -313,6 +313,12 @@ function Section(
defaultOpen?: boolean;
/** Render order — lower numbers appear first. */
order?: number;
+ /**
+ * Optional controls rendered at the right edge of the header row,
+ * outside the collapse trigger — clicking them doesn't toggle the
+ * section.
+ */
+ actions?: JSX.Element;
}>
) {
const ctx = useContext(SidePanelContext);
@@ -329,11 +335,14 @@ function Section(
component: () => (
<Accordion.Item value={props.id}>
<Panel depth={2} style={{ height: 'auto' }} class="rounded-xl">
- <Accordion.Header class="group">
- <Accordion.Trigger class="px-2 py-3 flex w-full items-center gap-2 text-xs hover:underline">
+ <Accordion.Header class="group flex items-center">
+ <Accordion.Trigger class="px-2 py-3 flex flex-1 min-w-0 items-center gap-2 text-xs hover:underline">
<CaretRight class="size-3 text-ink-muted transition-transform duration-90 group-data-expanded:rotate-90" />
<span>{props.title}</span>
</Accordion.Trigger>
+ <Show when={props.actions}>
+ <div class="shrink-0 pr-2">{props.actions}</div>
+ </Show>
</Accordion.Header>
<Accordion.Content class="group/content overflow-hidden data-expanded:animate-accordion-down data-closed:animate-accordion-up">
<Suspense fallback={<Loading />}>
diff --git a/apps/web/src/features/companies/Company/Company.tsx b/apps/web/src/features/companies/Company/Company.tsx
index 5b4bb8e771..387298f939 100644
--- a/apps/web/src/features/companies/Company/Company.tsx
+++ b/apps/web/src/features/companies/Company/Company.tsx
@@ -1,5 +1,8 @@
+import { openCreateContactModal } from '@app/features/companies/CreateContactModal';
import { SidePanel } from '@components/app/side-panel';
+import PlusIcon from '@phosphor/plus.svg';
import { useCompanyQuery } from '@queries/crm/companies';
+import { Button } from '@ui';
import { CompanyContactsSection } from './CompanyContactsSection';
import { CompanyDiscussionSection } from './CompanyDiscussionSection';
import { CompanyEmailsSection } from './CompanyEmailsSection';
@@ -48,6 +51,23 @@ export function Company(props: { companyId: string }) {
title="Contacts"
order={20}
defaultOpen
+ actions={
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ label="Add contact"
+ tooltip="Add contact"
+ // Contact emails are pinned to the company's primary domain;
+ // disabled until the company (and its domains) has loaded.
+ disabled={!company()?.domains[0]}
+ onClick={() => {
+ const domain = company()?.domains[0]?.domain;
+ if (domain) openCreateContactModal(props.companyId, domain);
+ }}
+ >
+ <PlusIcon class="size-3.5" />
+ </Button>
+ }
>
<CompanyContactsSection company={company()} contacts={contacts()} />
</SidePanel.Section>
diff --git a/apps/web/src/features/companies/CreateCompanyModal.tsx b/apps/web/src/features/companies/CreateCompanyModal.tsx
new file mode 100644
index 0000000000..b06525cd49
--- /dev/null
+++ b/apps/web/src/features/companies/CreateCompanyModal.tsx
@@ -0,0 +1,197 @@
+import { useSplitLayout } from '@components/app/split-layout/layout';
+import { useFocusLock } from '@core/util/createControlledOpenSignal';
+import { ThrownResultError } from '@core/util/result';
+import BuildingsIcon from '@phosphor/buildings.svg';
+import XIcon from '@phosphor/x.svg';
+import { useCreateCompanyMutation } from '@queries/crm/companies';
+import { Button, Dialog, Panel } from '@ui';
+import { createMemo, createSignal, Show } from 'solid-js';
+
+const [createCompanyModalOpen, setCreateCompanyModalOpen] = createSignal(false);
+const createCompanyModalFocusLock = useFocusLock('create-company');
+
+export function openCreateCompanyModal() {
+ createCompanyModalFocusLock.acquire();
+ setCreateCompanyModalOpen(true);
+}
+
+// Light client-side check for a bare domain like "acme.com"; the server
+// enforces the real rules (no scheme/path/@, not a generic email provider).
+const DOMAIN_PATTERN = /^[a-z0-9][a-z0-9.-]*\.[a-z]{2,}$/i;
+
+function createErrorMessage(cause: unknown): string {
+ if (cause instanceof ThrownResultError) {
+ if (cause.errors.some((e) => e.code === 'CONFLICT')) {
+ return 'A company with this domain already exists.';
+ }
+ if (cause.errors.some((e) => e.code === 'FORBIDDEN')) {
+ return "CRM isn't enabled for your team.";
+ }
+ }
+ return 'Failed to create company. Try again.';
+}
+
+export function CreateCompanyModal() {
+ const { replaceOrInsertSplit } = useSplitLayout();
+ const createCompanyMutation = useCreateCompanyMutation();
+ const [name, setName] = createSignal('');
+ const [domain, setDomain] = createSignal('');
+ const [error, setError] = createSignal<string>();
+ const companyName = createMemo(() => name().trim());
+ const companyDomain = createMemo(() => domain().trim().toLowerCase());
+ const canSubmit = createMemo(
+ () =>
+ companyName().length > 0 &&
+ companyDomain().length > 0 &&
+ !createCompanyMutation.isPending
+ );
+
+ function reset() {
+ setName('');
+ setDomain('');
+ setError(undefined);
+ }
+
+ function resetAndClose() {
+ createCompanyModalFocusLock.release();
+ reset();
+ setCreateCompanyModalOpen(false);
+ }
+
+ function close() {
+ if (createCompanyMutation.isPending) return;
+ resetAndClose();
+ }
+
+ async function handleSubmit(event: SubmitEvent) {
+ event.preventDefault();
+ if (!companyName()) {
+ setError('Enter a company name');
+ return;
+ }
+ if (!DOMAIN_PATTERN.test(companyDomain())) {
+ setError('Enter a valid domain like acme.com');
+ return;
+ }
+
+ setError(undefined);
+ try {
+ const { id } = await createCompanyMutation.mutateAsync({
+ name: companyName(),
+ domain: companyDomain(),
+ });
+ resetAndClose();
+ replaceOrInsertSplit({ type: 'company', id });
+ } catch (cause) {
+ console.error('Failed to create company', cause);
+ setError(createErrorMessage(cause));
+ }
+ }
+
+ return (
+ <Dialog
+ open={createCompanyModalOpen()}
+ onOpenChange={(open) => !open && close()}
+ class="w-120"
+ >
+ <Panel depth={2} class="rounded-xl *:max-h-[75vh]">
+ <Panel.Body>
+ <form class="flex flex-col gap-4 p-4" onSubmit={handleSubmit}>
+ <div class="flex items-center gap-1">
+ <div class="flex-1" />
+ <Dialog.CloseButton
+ as={Button}
+ size="icon-sm"
+ label="Close"
+ tabIndex={-1}
+ disabled={createCompanyMutation.isPending}
+ >
+ <XIcon />
+ </Dialog.CloseButton>
+ </div>
+
+ <div class="flex flex-col gap-4">
+ <div class="flex items-center gap-2 px-2">
+ <Dialog.Title class="sr-only">Create a company</Dialog.Title>
+ <label for="new-company-name" class="sr-only">
+ Name
+ </label>
+ <BuildingsIcon
+ aria-hidden="true"
+ class="size-5 shrink-0 text-ink-placeholder"
+ />
+ <input
+ id="new-company-name"
+ type="text"
+ value={name()}
+ onInput={(event) => {
+ setName(event.currentTarget.value);
+ setError(undefined);
+ }}
+ placeholder="Company name"
+ autocomplete="off"
+ data-1p-ignore
+ aria-invalid={error() === 'Enter a company name'}
+ class="h-10 w-full border-none bg-transparent px-0 text-xl font-medium text-ink outline-none placeholder:text-ink-placeholder focus:ring-0"
+ />
+ </div>
+
+ <div class="flex flex-col gap-2 px-2">
+ <label
+ for="new-company-domain"
+ class="text-xs font-medium text-ink-muted"
+ >
+ Domain
+ </label>
+ <input
+ id="new-company-domain"
+ type="text"
+ value={domain()}
+ onInput={(event) => {
+ setDomain(event.currentTarget.value);
+ setError(undefined);
+ }}
+ placeholder="acme.com"
+ autocomplete="off"
+ spellcheck={false}
+ data-1p-ignore
+ aria-invalid={
+ error() === 'Enter a valid domain like acme.com'
+ }
+ class="h-9 w-full rounded-lg border border-edge-muted bg-transparent px-3 text-sm text-ink outline-none placeholder:text-ink-placeholder focus:border-edge"
+ />
+ <span class="text-xs text-ink-extra-muted">
+ Emails with this domain will be linked to the company.
+ </span>
+ </div>
+ </div>
+
+ <Show when={error()}>
+ {(message) => (
+ <div class="border-y border-edge-muted p-2">
+ <div class="px-3 py-2 text-sm text-failure-ink" role="alert">
+ {message()}
+ </div>
+ </div>
+ )}
+ </Show>
+
+ <div class="flex shrink-0 items-end justify-end gap-2">
+ <Button
+ type="submit"
+ variant={canSubmit() ? 'active' : 'ghost'}
+ depth={3}
+ class="rounded-lg border-0"
+ disabled={!canSubmit()}
+ >
+ {createCompanyMutation.isPending
+ ? 'Creating…'
+ : 'Create Company'}
+ </Button>
+ </div>
+ </form>
+ </Panel.Body>
+ </Panel>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/features/companies/CreateContactModal.tsx b/apps/web/src/features/companies/CreateContactModal.tsx
new file mode 100644
index 0000000000..317c516ebf
--- /dev/null
+++ b/apps/web/src/features/companies/CreateContactModal.tsx
@@ -0,0 +1,220 @@
+import { useSplitLayout } from '@components/app/split-layout/layout';
+import { useFocusLock } from '@core/util/createControlledOpenSignal';
+import { ThrownResultError } from '@core/util/result';
+import UserPlusIcon from '@phosphor/user-plus.svg';
+import XIcon from '@phosphor/x.svg';
+import { useCreateContactMutation } from '@queries/crm/companies';
+import { Button, Dialog, Panel } from '@ui';
+import { createMemo, createSignal, Show } from 'solid-js';
+
+// The company (and its domain, which fixes the email suffix) the modal
+// creates a contact under; undefined = closed.
+const [createContactTarget, setCreateContactTarget] = createSignal<
+ { companyId: string; domain: string } | undefined
+>();
+const createContactModalFocusLock = useFocusLock('create-contact');
+
+/**
+ * `domain` is the company domain contact emails are pinned to — the
+ * modal renders it as a fixed "@domain" suffix and the backend rejects
+ * any other domain.
+ */
+export function openCreateContactModal(companyId: string, domain: string) {
+ createContactModalFocusLock.acquire();
+ setCreateContactTarget({ companyId, domain });
+}
+
+// The part before the @: non-empty, no whitespace or a second @.
+const LOCAL_PART_PATTERN = /^[^\s@]+$/;
+
+function createErrorMessage(cause: unknown): string {
+ if (cause instanceof ThrownResultError) {
+ if (cause.errors.some((e) => e.code === 'CONFLICT')) {
+ return 'A contact with this email already exists.';
+ }
+ if (cause.errors.some((e) => e.code === 'FORBIDDEN')) {
+ return "CRM isn't enabled for your team.";
+ }
+ }
+ return 'Failed to create contact. Try again.';
+}
+
+export function CreateContactModal() {
+ const { replaceOrInsertSplit } = useSplitLayout();
+ const createContactMutation = useCreateContactMutation();
+ const [name, setName] = createSignal('');
+ const [localPart, setLocalPart] = createSignal('');
+ const [error, setError] = createSignal<string>();
+ const contactName = createMemo(() => name().trim());
+ const emailLocalPart = createMemo(() => localPart().trim().toLowerCase());
+ const canSubmit = createMemo(
+ () =>
+ contactName().length > 0 &&
+ emailLocalPart().length > 0 &&
+ !createContactMutation.isPending
+ );
+
+ function reset() {
+ setName('');
+ setLocalPart('');
+ setError(undefined);
+ }
+
+ function resetAndClose() {
+ createContactModalFocusLock.release();
+ reset();
+ setCreateContactTarget(undefined);
+ }
+
+ function close() {
+ if (createContactMutation.isPending) return;
+ 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 = createContactTarget()?.domain;
+ const suffix = domain ? `@${domain}` : undefined;
+ setLocalPart(
+ suffix && value.toLowerCase().endsWith(suffix)
+ ? value.slice(0, -suffix.length)
+ : value
+ );
+ setError(undefined);
+ }
+
+ async function handleSubmit(event: SubmitEvent) {
+ event.preventDefault();
+ const target = createContactTarget();
+ if (!target) return;
+ if (!contactName()) {
+ setError('Enter a name');
+ return;
+ }
+ if (!LOCAL_PART_PATTERN.test(emailLocalPart())) {
+ setError('Enter the part of the email before the @');
+ return;
+ }
+
+ setError(undefined);
+ try {
+ const { id } = await createContactMutation.mutateAsync({
+ companyId: target.companyId,
+ name: contactName(),
+ email: `${emailLocalPart()}@${target.domain}`,
+ });
+ resetAndClose();
+ replaceOrInsertSplit({ type: 'contact', id });
+ } catch (cause) {
+ console.error('Failed to create contact', cause);
+ setError(createErrorMessage(cause));
+ }
+ }
+
+ return (
+ <Dialog
+ open={createContactTarget() !== undefined}
+ onOpenChange={(open) => !open && close()}
+ class="w-120"
+ >
+ <Panel depth={2} class="rounded-xl *:max-h-[75vh]">
+ <Panel.Body>
+ <form class="flex flex-col gap-4 p-4" onSubmit={handleSubmit}>
+ <div class="flex items-center gap-1">
+ <div class="flex-1" />
+ <Dialog.CloseButton
+ as={Button}
+ size="icon-sm"
+ label="Close"
+ tabIndex={-1}
+ disabled={createContactMutation.isPending}
+ >
+ <XIcon />
+ </Dialog.CloseButton>
+ </div>
+
+ <div class="flex flex-col gap-4">
+ <div class="flex items-center gap-2 px-2">
+ <Dialog.Title class="sr-only">Add a contact</Dialog.Title>
+ <label for="new-contact-name" class="sr-only">
+ Name
+ </label>
+ <UserPlusIcon
+ aria-hidden="true"
+ class="size-5 shrink-0 text-ink-placeholder"
+ />
+ <input
+ id="new-contact-name"
+ type="text"
+ value={name()}
+ onInput={(event) => {
+ setName(event.currentTarget.value);
+ setError(undefined);
+ }}
+ placeholder="Contact name"
+ autocomplete="off"
+ data-1p-ignore
+ aria-invalid={error() === 'Enter a name'}
+ class="h-10 w-full border-none bg-transparent px-0 text-xl font-medium text-ink outline-none placeholder:text-ink-placeholder focus:ring-0"
+ />
+ </div>
+
+ <div class="flex flex-col gap-2 px-2">
+ <label
+ for="new-contact-email"
+ class="text-xs font-medium text-ink-muted"
+ >
+ Email
+ </label>
+ <div class="flex h-9 w-full items-center rounded-lg border border-edge-muted focus-within:border-edge">
+ <input
+ id="new-contact-email"
+ type="text"
+ value={localPart()}
+ onInput={(event) =>
+ handleLocalPartInput(event.currentTarget.value)
+ }
+ placeholder="jane"
+ autocomplete="off"
+ spellcheck={false}
+ data-1p-ignore
+ aria-invalid={
+ error() === 'Enter the part of the email before the @'
+ }
+ class="h-full min-w-0 flex-1 border-none bg-transparent pl-3 text-sm text-ink outline-none placeholder:text-ink-placeholder focus:ring-0"
+ />
+ <span class="shrink-0 select-none pr-3 pl-0.5 text-sm text-ink-placeholder">
+ @{createContactTarget()?.domain}
+ </span>
+ </div>
+ </div>
+ </div>
+
+ <Show when={error()}>
+ {(message) => (
+ <div class="border-y border-edge-muted p-2">
+ <div class="px-3 py-2 text-sm text-failure-ink" role="alert">
+ {message()}
+ </div>
+ </div>
+ )}
+ </Show>
+
+ <div class="flex shrink-0 items-end justify-end gap-2">
+ <Button
+ type="submit"
+ variant={canSubmit() ? 'active' : 'ghost'}
+ depth={3}
+ class="rounded-lg border-0"
+ disabled={!canSubmit()}
+ >
+ {createContactMutation.isPending ? 'Adding…' : 'Add Contact'}
+ </Button>
+ </div>
+ </form>
+ </Panel.Body>
+ </Panel>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsx b/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsx
index 2698a8464d..614b0cdf99 100644
--- a/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsx
+++ b/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsx
@@ -3,6 +3,7 @@ import {
CREATABLE_BLOCKS,
runCreateAction,
} from '@app/features/command/Launcher';
+import { openCreateCompanyModal } from '@app/features/companies/CreateCompanyModal';
import { useHandleFileUpload } from '@app/util/handleFileUpload';
import { openNewChannelModal } from '@channel/CreateChannelModal';
import { CollapsibleHeaderItem } from '@components/app/split-layout/components/CollapsibleHeaderItem';
@@ -14,6 +15,7 @@ import {
openFilePicker,
openFolderPicker,
} from '@core/util/upload';
+import BuildingsIcon from '@phosphor/buildings.svg';
import ChevronDownIcon from '@phosphor/caret-down.svg';
import PlusCircleIcon from '@phosphor/plus-circle.svg';
import UploadIcon from '@phosphor/upload-simple.svg';
@@ -34,7 +36,12 @@ const VIEW_CREATE_BLOCKNAMES: Partial<
};
type CreateOption = {
- id: BlockName | BlockAlias | 'import-file' | 'import-folder';
+ id:
+ | BlockName
+ | BlockAlias
+ | 'import-file'
+ | 'import-folder'
+ | 'create-company';
label: string;
};
@@ -46,6 +53,12 @@ const IMPORT_FOLDER_OPTION: CreateOption = {
id: 'import-folder',
label: 'Import folder',
};
+// Companies aren't blocks, so the Customers view gets a bespoke option
+// that opens the create-company modal instead of a create action.
+const CREATE_COMPANY_OPTION: CreateOption = {
+ id: 'create-company',
+ label: 'Company',
+};
/**
* Fallback labels for blocks that shouldn't appear in the global launcher
@@ -60,6 +73,7 @@ const VIEW_ONLY_BLOCK_LABELS: Partial<Record<BlockName | BlockAlias, string>> =
const VIEW_CREATE_LABELS: Partial<Record<ListView, string>> = {
agents: 'Agent',
channels: 'Channel',
+ companies: 'Company',
documents: 'New',
folders: 'Folder',
mail: 'Email',
@@ -82,22 +96,28 @@ function getViewCreateOptions(view: ListView): CreateOption[] {
if (view === 'folders') {
options.push(IMPORT_FOLDER_OPTION);
}
+ if (view === 'companies') {
+ options.push(CREATE_COMPANY_OPTION);
+ }
return options;
}
-function CreateOptionIcon(props: {
- id: BlockName | BlockAlias | 'import-file' | 'import-folder';
-}) {
+function CreateOptionIcon(props: { id: CreateOption['id'] }) {
return (
<Show
when={props.id !== 'import-file' && props.id !== 'import-folder'}
fallback={<UploadIcon class="size-3.5" />}
>
- <EntityIcon
- targetType={props.id as BlockName}
- size="xs"
- class="mobile:size-6"
- />
+ <Show
+ when={props.id !== 'create-company'}
+ fallback={<BuildingsIcon class="size-3.5" />}
+ >
+ <EntityIcon
+ targetType={props.id as BlockName}
+ size="xs"
+ class="mobile:size-6"
+ />
+ </Show>
</Show>
);
}
@@ -128,6 +148,10 @@ export const SoupViewCreateButton = () => {
openNewChannelModal();
return;
}
+ if (option.id === 'create-company') {
+ openCreateCompanyModal();
+ return;
+ }
if (option.id === 'import-file') {
openFilePicker({ multiple: true }, async (files) => {
await handleFileUpload(files, false);
diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-mobile-create-button.tsx b/apps/web/src/features/next-soup/soup-view/soup-view-mobile-create-button.tsx
index 0c10f6dfcf..466d12b521 100644
--- a/apps/web/src/features/next-soup/soup-view/soup-view-mobile-create-button.tsx
+++ b/apps/web/src/features/next-soup/soup-view/soup-view-mobile-create-button.tsx
@@ -3,11 +3,13 @@ import {
runCreateAction,
setCreateMenuOpen,
} from '@app/features/command/Launcher';
+import { openCreateCompanyModal } from '@app/features/companies/CreateCompanyModal';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { openNewChannelModal } from '@channel/CreateChannelModal';
import { hapticImpact } from '@core/mobile/haptics';
import { ICON_ANIMATION_DURATION_MS } from '@icon/animation';
import { AnimatedChannelIcon } from '@icon/wide-channel';
+import { AnimatedCompanyIcon } from '@icon/wide-company';
import { AnimatedEmailIcon } from '@icon/wide-email';
import { AnimatedPlusIcon } from '@icon/wide-plus';
import { AnimatedStarIcon } from '@icon/wide-star';
@@ -37,6 +39,7 @@ const VIEW_CREATE_ICONS: Partial<Record<ListView, IconComponent>> = {
documents: AnimatedPlusIcon,
tasks: AnimatedTaskIcon,
channels: AnimatedChannelIcon,
+ companies: AnimatedCompanyIcon,
inbox: AnimatedPlusIcon,
};
@@ -66,6 +69,9 @@ export function SoupViewMobileCreateButton(props: {
channels: () => {
openNewChannelModal();
},
+ companies: () => {
+ openCreateCompanyModal();
+ },
};
const createAction = createMemo(() => {
diff --git a/apps/web/src/features/next-soup/soup-view/soup-view.tsx b/apps/web/src/features/next-soup/soup-view/soup-view.tsx
index 53fa78f13a..ba81f52896 100644
--- a/apps/web/src/features/next-soup/soup-view/soup-view.tsx
+++ b/apps/web/src/features/next-soup/soup-view/soup-view.tsx
@@ -703,20 +703,20 @@ export const SoupView = (props: SoupViewProps) => {
<SplitHeaderRight>
<Show
when={
- !narrowSearchExpanded() && isComponentListView('companies')
+ !narrowSearchExpanded() &&
+ !isComponentListView('search') &&
+ props.showCreateButton !== false
}
>
- <CompanyViewsMenu />
- <CompanyDisplayMenu />
+ <SoupViewCreateButton />
</Show>
<Show
when={
- !narrowSearchExpanded() &&
- !isComponentListView('search') &&
- props.showCreateButton !== false
+ !narrowSearchExpanded() && isComponentListView('companies')
}
>
- <SoupViewCreateButton />
+ <CompanyViewsMenu />
+ <CompanyDisplayMenu />
</Show>
<Show when={narrowSearchExpanded()}>
<Layer depth={2}>
diff --git a/apps/web/src/lib/queries/crm/companies.ts b/apps/web/src/lib/queries/crm/companies.ts
index 3ffc5b052a..b2ee466463 100644
--- a/apps/web/src/lib/queries/crm/companies.ts
+++ b/apps/web/src/lib/queries/crm/companies.ts
@@ -124,6 +124,57 @@ function wipeCompanyEmailCache(companyId: string): void {
});
}
+/**
+ * Manually creates a CRM company via `POST /crm/companies` (a team-scoped
+ * display name + one 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,
+ * 400 on a malformed/generic-provider domain.
+ */
+export function useCreateCompanyMutation() {
+ return useMutation(() => ({
+ mutationFn: ({ name, domain }: { name: string; domain: string }) =>
+ throwOnErr(() => storageServiceClient.createCompany({ name, domain })),
+ onSuccess: (data) => {
+ queryClient.setQueryData(crmKeys.company(data.id).queryKey, data);
+ return queryClient.invalidateQueries({ queryKey: soupKeys._def });
+ },
+ }));
+}
+
+/**
+ * Manually creates a contact under a company via
+ * `POST /crm/companies/{id}/contacts` (a display name + email). Invalidates
+ * the company detail query (contacts arrive embedded there) and soup so
+ * contact listings refresh. Server-side failures worth surfacing: 409 when
+ * the company already tracks the email, 404 when the company isn't
+ * visible to the caller, 403 when CRM is disabled for the team.
+ */
+export function useCreateContactMutation() {
+ return useMutation(() => ({
+ mutationFn: ({
+ companyId,
+ name,
+ email,
+ }: {
+ companyId: string;
+ name: string;
+ email: string;
+ }) =>
+ throwOnErr(() =>
+ storageServiceClient.createContact({ companyId, name, email })
+ ),
+ onSuccess: (_data, { companyId }) =>
+ Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: crmKeys.company(companyId).queryKey,
+ }),
+ queryClient.invalidateQueries({ queryKey: soupKeys._def }),
+ ]),
+ }));
+}
+
/**
* Toggles `crm_companies.hidden` via `PUT /crm/companies/{id}/hidden`. Hiding
* also disables `email_sync` and soft-hides the company's contacts; un-hide
diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.ts
index 7080138da6..917ab3c58e 100644
--- a/apps/web/src/lib/service-clients/service-storage/client.ts
+++ b/apps/web/src/lib/service-clients/service-storage/client.ts
@@ -75,6 +75,8 @@ import type { CreateChannelScopedBotRequest } from './generated/schemas/createCh
import type { CreateChannelScopedBotResponse } from './generated/schemas/createChannelScopedBotResponse';
import type { CreateCommentResponse } from './generated/schemas/createCommentResponse';
import type { CreateCrmCommentRequest } from './generated/schemas/createCrmCommentRequest';
+import type { CreateCrmCompanyRequest } from './generated/schemas/createCrmCompanyRequest';
+import type { CreateCrmContactRequest } from './generated/schemas/createCrmContactRequest';
import type { CreateDocument200 as CreateDocumentResponse } from './generated/schemas/createDocument200';
import type { CreateDocumentRequest } from './generated/schemas/createDocumentRequest';
import type { CreateEntityMentionRequest } from './generated/schemas/createEntityMentionRequest';
@@ -2279,6 +2281,12 @@ export const storageServiceClient = {
})
).map((result) => result.data);
},
+ async createCompany(body: CreateCrmCompanyRequest) {
+ return await dssFetch<CrmCompanyResponse>('/crm/companies', {
+ method: 'POST',
+ body: JSON.stringify(body),
+ });
+ },
async getCompany({ companyId }: { companyId: string }) {
return await dssFetch<CrmCompanyResponse>(`/crm/companies/${companyId}`, {
method: 'GET',
@@ -2290,6 +2298,18 @@ export const storageServiceClient = {
{ method: 'GET' }
);
},
+ async createContact({
+ companyId,
+ ...body
+ }: { companyId: string } & CreateCrmContactRequest) {
+ return await dssFetch<CrmContactResponse>(
+ `/crm/companies/${companyId}/contacts`,
+ {
+ method: 'POST',
+ body: JSON.stringify(body),
+ }
+ );
+ },
async getContact({ contactId }: { contactId: string }) {
return await dssFetch<CrmContactResponse>(`/crm/contacts/${contactId}`, {
method: 'GET',
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
new file mode 100644
index 0000000000..f71ddef792
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createCrmCompanyRequest.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Request body for `POST /crm/companies`.
+ */
+export interface CreateCrmCompanyRequest {
+ /** 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. */
+ domain: string;
+ /** 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/createCrmContactRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createCrmContactRequest.ts
new file mode 100644
index 0000000000..de6b525b62
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createCrmContactRequest.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * 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). */
+ 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 bd9c09d297..599d3b9698 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
@@ -263,6 +263,8 @@ export * from './createCommentResponseAllOf';
export * from './createCommentResponseAllOfAnchor';
export * from './createCrmCommentRequest';
export * from './createCrmCommentRequestThreadId';
+export * from './createCrmCompanyRequest';
+export * from './createCrmContactRequest';
export * from './createDocument200';
export * from './createDocument200DataOneOf';
export * from './createDocument200DataOneOfAllOf';
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 cdb2ef45d7..957baf39be 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
@@ -3175,6 +3175,121 @@ export const createCrmCommentResponse = zod
'A [`CrmThread`] with its comments nested under it — the unit the\nfrontend renders.'
);
+/**
+ * @summary Manually create a CRM company for the caller's team. Any team member
+may create one. The domain must not already be tracked by the team
+(409), and the team's CRM killswitch must be on (403). Returns the
+created company in the same shape as `GET /crm/companies/{id}` (its
+contact list is empty until emails populate it).
+ */
+export const createCrmCompanyBody = zod
+ .object({
+ domain: zod
+ .string()
+ .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.'
+ ),
+ name: zod
+ .string()
+ .describe(
+ 'Display name for the company. Team-scoped: overrides the\ndomain-directory name on every read path.'
+ ),
+ })
+ .describe('Request body for `POST \/crm\/companies`.');
+
+export const createCrmCompanyResponse = zod
+ .object({
+ contacts: zod
+ .array(
+ zod
+ .object({
+ companyId: zod
+ .uuid()
+ .describe('The id of the company the contact belongs to.'),
+ createdAt: zod.iso
+ .datetime({})
+ .describe('When the contact record was created.'),
+ email: zod.string().describe("The contact's email address."),
+ firstInteraction: zod.iso
+ .datetime({})
+ .describe('Earliest known interaction with this contact.'),
+ hidden: zod
+ .boolean()
+ .describe(
+ 'Whether the contact is hidden from CRM listings for the\nrequesting team. Non-admin viewers never see `hidden = true`\nrows (the endpoint filters them out); admin\/owner callers see\nhidden contacts so they can render the right toggle state.'
+ ),
+ id: zod.uuid().describe('The id of the contact record.'),
+ lastInteraction: zod.iso
+ .datetime({})
+ .describe('Most recent known interaction with this contact.'),
+ name: zod
+ .string()
+ .nullish()
+ .describe('Display name observed for the contact, if any.'),
+ updatedAt: zod.iso
+ .datetime({})
+ .describe('When the contact record was last updated.'),
+ })
+ .describe(
+ 'A CRM contact as returned by `GET \/crm\/companies\/{company_id}\/contacts`.'
+ )
+ )
+ .describe(
+ 'Contacts attached to this company. Hidden contacts are filtered\nout for non-admin viewers.'
+ ),
+ createdAt: zod.iso
+ .datetime({})
+ .describe('Earliest known interaction with this company.'),
+ description: zod
+ .string()
+ .nullish()
+ .describe(
+ "Display description from the primary domain's directory entry."
+ ),
+ domains: zod
+ .array(
+ zod
+ .object({
+ companyId: zod
+ .uuid()
+ .describe('The id of the company the domain belongs to.'),
+ createdAt: zod.iso
+ .datetime({})
+ .describe('When the domain record was created.'),
+ domain: zod.string().describe('The domain (e.g. \"acme.com\").'),
+ id: zod.uuid().describe('The id of the domain record.'),
+ })
+ .describe('A CRM domain associated with a company.')
+ )
+ .describe(
+ 'All domains associated with this company, ordered by creation\ntime ascending (primary first).'
+ ),
+ emailSync: zod
+ .boolean()
+ .describe('Whether email sync is enabled for this company.'),
+ hidden: zod
+ .boolean()
+ .describe(
+ 'Whether the company is hidden from CRM listings for the\nrequesting team. Non-admin viewers never see `hidden = true`\nrows (the endpoint 404s for them); admin\/owner callers see\nhidden companies so they can render the right toggle state.'
+ ),
+ id: zod.uuid().describe('The id of the company.'),
+ name: zod
+ .string()
+ .nullish()
+ .describe(
+ "Display name from the primary domain's directory entry, or\n`None` when unresolved."
+ ),
+ teamId: zod
+ .uuid()
+ .describe('The id of the team that owns this company record.'),
+ updatedAt: zod.iso
+ .datetime({})
+ .describe('Most recent known interaction with this company.'),
+ })
+ .describe(
+ "A CRM company as returned by `GET \/crm\/companies\/{company_id}`.\nMirrors the soup-listed `crmCompany` shape (`name` \/ `description`\nresolved from the primary domain's `crm_domain_directory` entry) and\nembeds the company's contacts so the panel can render in a single\nrequest."
+ );
+
/**
* @summary Fetch a single CRM company by id, hydrated with its domains, the
primary domain's directory display metadata (name + description),
@@ -3328,6 +3443,65 @@ export const listCompanyContactsResponse = zod.array(
listCompanyContactsResponseItem
);
+/**
+ * @summary Manually create a contact under a CRM company. Access is enforced by
+[`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).
+ */
+export const createCrmContactParams = zod.object({
+ company_id: zod.uuid().describe('The CRM company to add the contact to'),
+});
+
+export const createCrmContactBody = zod
+ .object({
+ 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).'
+ ),
+ name: zod.string().describe('Display name for the contact.'),
+ })
+ .describe(
+ 'Request body for `POST \/crm\/companies\/{company_id}\/contacts`.'
+ );
+
+export const createCrmContactResponse = zod
+ .object({
+ companyId: zod
+ .uuid()
+ .describe('The id of the company the contact belongs to.'),
+ createdAt: zod.iso
+ .datetime({})
+ .describe('When the contact record was created.'),
+ email: zod.string().describe("The contact's email address."),
+ firstInteraction: zod.iso
+ .datetime({})
+ .describe('Earliest known interaction with this contact.'),
+ hidden: zod
+ .boolean()
+ .describe(
+ 'Whether the contact is hidden from CRM listings for the\nrequesting team. Non-admin viewers never see `hidden = true`\nrows (the endpoint filters them out); admin\/owner callers see\nhidden contacts so they can render the right toggle state.'
+ ),
+ id: zod.uuid().describe('The id of the contact record.'),
+ lastInteraction: zod.iso
+ .datetime({})
+ .describe('Most recent known interaction with this contact.'),
+ name: zod
+ .string()
+ .nullish()
+ .describe('Display name observed for the contact, if any.'),
+ updatedAt: zod.iso
+ .datetime({})
+ .describe('When the contact record was last updated.'),
+ })
+ .describe(
+ 'A CRM contact as returned by `GET \/crm\/companies\/{company_id}\/contacts`.'
+ );
+
/**
* @summary Toggle `email_sync` on a CRM company. Purely a visibility flag —
it gates whether team members can see each other's emails with
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 ec942458b7..26d6434bf1 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -4237,6 +4237,85 @@
}
}
},
+ "/crm/companies": {
+ "post": {
+ "tags": ["crm::inbound::axum_router::create_company"],
+ "summary": "Manually create a CRM company for the caller's team. Any team member\nmay create one. The domain must not already be tracked by the team\n(409), and the team's CRM killswitch must be on (403). Returns the\ncreated company in the same shape as `GET /crm/companies/{id}` (its\ncontact list is empty until emails populate it).",
+ "operationId": "create_crm_company",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateCrmCompanyRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CrmCompanyResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/crm/companies/{company_id}": {
"get": {
"tags": ["crm::inbound::axum_router::get_company"],
@@ -4360,6 +4439,105 @@
}
}
}
+ },
+ "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).",
+ "operationId": "create_crm_contact",
+ "parameters": [
+ {
+ "name": "company_id",
+ "in": "path",
+ "description": "The CRM company to add the contact to",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateCrmContactRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CrmContactResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
}
},
"/crm/companies/{company_id}/email-sync": {
@@ -12579,6 +12757,36 @@
}
}
},
+ "CreateCrmCompanyRequest": {
+ "type": "object",
+ "description": "Request body for `POST /crm/companies`.",
+ "required": ["name", "domain"],
+ "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."
+ },
+ "name": {
+ "type": "string",
+ "description": "Display name for the company. Team-scoped: overrides the\ndomain-directory name on every read path."
+ }
+ }
+ },
+ "CreateCrmContactRequest": {
+ "type": "object",
+ "description": "Request body for `POST /crm/companies/{company_id}/contacts`.",
+ "required": ["name", "email"],
+ "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)."
+ },
+ "name": {
+ "type": "string",
+ "description": "Display name for the contact."
+ }
+ }
+ },
"CreateDocumentRequest": {
"type": "object",
"required": ["sha", "documentName"],
diff --git a/crates/crm/src/domain/companies_repo.rs b/crates/crm/src/domain/companies_repo.rs
index c8ef3349ad..770b4b5e09 100644
--- a/crates/crm/src/domain/companies_repo.rs
+++ b/crates/crm/src/domain/companies_repo.rs
@@ -133,6 +133,92 @@ 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
+ fn create_company_for_team(
+ &self,
+ team_id: &uuid::Uuid,
+ domain: &str,
+ name: &str,
+ now: DateTime<Utc>,
+ ) -> impl Future<Output = Result<CrmCompanyWithContacts, CrmError>> + Send;
+
+ /// Manually creates a contact under `company_id` (scoped to
+ /// `team_id`) with a display `name` and `email`. In a single
+ /// transaction:
+ ///
+ /// 1. Reads the team killswitch; returns
+ /// [`CrmError::CrmDisabledForTeam`] when off.
+ /// 2. Locks the company row (`FOR UPDATE`, serializing with the
+ /// hide/un-hide contact cascade) and scopes it to `team_id`.
+ /// 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
+ /// current `hidden` (an admin adding a contact to a hidden
+ /// company gets a hidden contact, matching populate's
+ /// inheritance). Returns
+ /// [`CrmError::ContactAlreadyExistsForCompany`] when the company
+ /// already has a contact for the email.
+ ///
+ /// `email` is normalized to lowercase before storage. Both
+ /// interaction endpoints seed from `now`; later populates for the
+ /// same `(company, email)` merge real timestamps via LEAST/GREATEST
+ /// and keep the manual `name` (first non-NULL name wins).
+ ///
+ /// The row is stamped `manually_created = TRUE` so the depopulate
+ /// orphan cleanup ([`depopulate_contact`] /
+ /// [`depopulate_link_in_team`]) never deletes it — manual contacts
+ /// have no `crm_contact_sources` rows and would otherwise be
+ /// indistinguishable from derived-data orphans.
+ ///
+ /// [`depopulate_contact`]: CompaniesRepository::depopulate_contact
+ /// [`depopulate_link_in_team`]: CompaniesRepository::depopulate_link_in_team
+ fn create_contact_for_company(
+ &self,
+ team_id: &uuid::Uuid,
+ company_id: &uuid::Uuid,
+ email: &str,
+ name: &str,
+ now: DateTime<Utc>,
+ include_hidden: bool,
+ ) -> impl Future<Output = Result<CrmContact, CrmError>> + Send;
+
/// Read the cached [`DomainMetadata`] for `domain` from
/// `crm_domain_directory`, if any. `domain` is matched
/// case-insensitively. Returns `Ok(None)` when no row exists for
@@ -178,7 +264,13 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
/// in a "default sync = true" state.
///
/// Source and contact rows are derived data and are always cleaned
- /// up regardless of the company's `email_sync`.
+ /// up regardless of the company's `email_sync` — except rows with
+ /// `manually_created = TRUE` (user-created via
+ /// [`create_contact_for_company`] / [`create_company_for_team`]),
+ /// which are never deleted by this teardown.
+ ///
+ /// [`create_contact_for_company`]: CompaniesRepository::create_contact_for_company
+ /// [`create_company_for_team`]: CompaniesRepository::create_company_for_team
///
/// The whole cascade runs in a single transaction that begins by
/// acquiring the same advisory lock [`populate_contact`] takes (key
diff --git a/crates/crm/src/domain/model.rs b/crates/crm/src/domain/model.rs
index 077aba067b..2385cfaef0 100644
--- a/crates/crm/src/domain/model.rs
+++ b/crates/crm/src/domain/model.rs
@@ -11,7 +11,9 @@ use serde_json::Value;
pub struct CrmCompanyForSoup {
/// The underlying company record.
pub company: CrmCompany,
- /// Display name from the primary domain's directory entry.
+ /// Display name: the team-scoped `crm_companies.custom_name` override when
+ /// set (manual creation), otherwise the primary domain's directory
+ /// entry.
pub name: Option<String>,
/// Display description from the primary domain's directory entry.
pub description: Option<String>,
@@ -31,7 +33,9 @@ pub struct CrmCompanyForSoup {
pub struct CrmCompanyWithContacts {
/// The underlying company record (with domains pre-populated).
pub company: CrmCompany,
- /// Display name from the primary domain's directory entry.
+ /// Display name: the team-scoped `crm_companies.custom_name` override when
+ /// set (manual creation), otherwise the primary domain's directory
+ /// entry.
pub name: Option<String>,
/// Display description from the primary domain's directory entry.
pub description: Option<String>,
@@ -45,8 +49,10 @@ pub struct CrmCompanyWithContacts {
/// considered to belong to the same external party.
///
/// Company display metadata (name, description, icon) lives in
-/// `crm_domain_directory` keyed by domain, not on `crm_companies` —
-/// look it up via [`DomainMetadata`] when needed.
+/// `crm_domain_directory` keyed by domain — look it up via
+/// [`DomainMetadata`] when needed. Manually created companies may
+/// additionally carry a team-scoped `crm_companies.custom_name` override that
+/// read paths COALESCE over the directory name.
#[derive(Debug, Clone, serde::Serialize)]
pub struct CrmCompany {
/// The id of the company
@@ -362,6 +368,18 @@ pub enum CrmError {
/// re-enable `email_sync` on a hidden company.
#[error("crm company is hidden")]
CompanyHidden,
+ /// The team already tracks a company for the requested domain.
+ #[error("a crm company already exists for this domain")]
+ CompanyAlreadyExistsForTeam,
+ /// 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,
/// Entity access receipt did not contain a valid team UUID.
#[error("invalid team id in entity access receipt")]
InvalidTeamId,
diff --git a/crates/crm/src/domain/service.rs b/crates/crm/src/domain/service.rs
index c308122f57..e08ecc2124 100644
--- a/crates/crm/src/domain/service.rs
+++ b/crates/crm/src/domain/service.rs
@@ -135,6 +135,64 @@ 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).
+ ///
+ /// 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) 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`].
+ fn create_company(
+ &self,
+ access: &CrmTeamReceipt<MemberTeamRole>,
+ name: &str,
+ domain: &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`].
+ fn create_contact(
+ &self,
+ access: &CrmCompanyReceipt<ViewAccessLevel>,
+ name: &str,
+ email: &str,
+ ) -> impl Future<Output = Result<CrmContact, CrmError>> + Send;
+
/// Toggle `email_sync` for the company addressed by `access`. Purely
/// a visibility/permission flag — populate continues to write CRM
/// rows regardless. See
@@ -304,6 +362,81 @@ pub trait CrmService: Clone + Send + Sync + 'static {
) -> impl Future<Output = Result<CrmTeamSettings, CrmError>> + Send;
}
+/// Maximum accepted length (in chars) for a manually specified display
+/// name (company or contact).
+const MAX_DISPLAY_NAME_CHARS: usize = 200;
+
+/// Maximum accepted length for a domain (RFC 1035 limit).
+const MAX_DOMAIN_CHARS: usize = 253;
+
+/// Maximum accepted length for a contact email (RFC 3696 errata limit).
+const MAX_EMAIL_CHARS: usize = 320;
+
+/// Validates a user-supplied display name: trims whitespace; must be
+/// non-blank and within [`MAX_DISPLAY_NAME_CHARS`].
+fn validate_display_name(raw: &str) -> Result<&str, CrmError> {
+ let name = raw.trim();
+ if name.is_empty() {
+ return Err(CrmError::InvalidRequest("name must not be empty".into()));
+ }
+ if name.chars().count() > MAX_DISPLAY_NAME_CHARS {
+ return Err(CrmError::InvalidRequest("name is too long".into()));
+ }
+ Ok(name)
+}
+
+/// 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.
+fn normalize_contact_email(raw: &str) -> Result<String, CrmError> {
+ let email = raw.trim().to_ascii_lowercase();
+ if email.is_empty() {
+ return Err(CrmError::InvalidRequest("email must not be empty".into()));
+ }
+ if email.len() > MAX_EMAIL_CHARS {
+ return Err(CrmError::InvalidRequest("email is too long".into()));
+ }
+ let invalid =
+ || CrmError::InvalidRequest("email must be a valid address like [email protected]".into());
+ let Some((local, domain)) = email.split_once('@') else {
+ return Err(invalid());
+ };
+ if local.is_empty() || local.chars().any(|c| c.is_whitespace()) {
+ return Err(invalid());
+ }
+ let domain = normalize_company_domain(domain).map_err(|_| invalid())?;
+ Ok(format!("{local}@{domain}"))
+}
+
+/// Validates and normalizes a user-supplied company domain: trims
+/// whitespace and trailing dots, then lowercases. Rejects anything that
+/// isn't a bare domain like "acme.com" (schemes, paths, emails, ports).
+fn normalize_company_domain(raw: &str) -> Result<String, CrmError> {
+ let domain = raw.trim().trim_end_matches('.').to_ascii_lowercase();
+ if domain.is_empty() {
+ return Err(CrmError::InvalidRequest("domain must not be empty".into()));
+ }
+ if domain.len() > MAX_DOMAIN_CHARS {
+ return Err(CrmError::InvalidRequest("domain is too long".into()));
+ }
+ if domain
+ .chars()
+ .any(|c| c.is_whitespace() || matches!(c, '@' | '/' | ':' | '?' | '#'))
+ {
+ return Err(CrmError::InvalidRequest(
+ "domain must be a bare domain like acme.com (no scheme, path, or email)".into(),
+ ));
+ }
+ if !domain.contains('.') || domain.starts_with('.') || domain.contains("..") {
+ return Err(CrmError::InvalidRequest(
+ "domain must be a valid domain like acme.com".into(),
+ ));
+ }
+ Ok(domain)
+}
+
/// Implementation of [`CrmService`] backed by a [`CompaniesRepository`]
/// and a [`CompanyMetadataResolver`].
#[derive(Debug)]
@@ -490,6 +623,71 @@ where
.await
}
+ #[tracing::instrument(skip(self, access), err)]
+ async fn create_company(
+ &self,
+ access: &CrmTeamReceipt<MemberTeamRole>,
+ name: &str,
+ domain: &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(),
+ ));
+ }
+
+ // 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.
+ if self
+ .companies_repository
+ .lookup_domain_metadata(&domain)
+ .await?
+ .is_none()
+ {
+ let metadata = self.metadata_resolver.resolve(&domain).await;
+ self.companies_repository
+ .upsert_domain_metadata(&domain, &metadata)
+ .await?;
+ }
+
+ self.companies_repository
+ .create_company_for_team(&access.team_id(), &domain, name, Utc::now())
+ .await
+ }
+
+ #[tracing::instrument(skip(self, access), err)]
+ async fn create_contact(
+ &self,
+ access: &CrmCompanyReceipt<ViewAccessLevel>,
+ name: &str,
+ email: &str,
+ ) -> Result<CrmContact, CrmError> {
+ let name = validate_display_name(name)?;
+ let email = normalize_contact_email(email)?;
+
+ let team_id = access.team_id();
+ let company_id = access.company_id()?;
+ let include_hidden = access.include_hidden();
+ self.companies_repository
+ .create_contact_for_company(
+ &team_id,
+ &company_id,
+ &email,
+ name,
+ Utc::now(),
+ include_hidden,
+ )
+ .await
+ }
+
#[tracing::instrument(skip(self, access), err)]
async fn set_email_sync(
&self,
@@ -795,6 +993,24 @@ impl CrmService for NoOpCrmService {
unimplemented!("NoOpCrmService.get_team_id_for_user")
}
+ async fn create_company(
+ &self,
+ _access: &CrmTeamReceipt<MemberTeamRole>,
+ _name: &str,
+ _domain: &str,
+ ) -> Result<CrmCompanyWithContacts, CrmError> {
+ unimplemented!("NoOpCrmService.create_company")
+ }
+
+ async fn create_contact(
+ &self,
+ _access: &CrmCompanyReceipt<ViewAccessLevel>,
+ _name: &str,
+ _email: &str,
+ ) -> Result<CrmContact, CrmError> {
+ unimplemented!("NoOpCrmService.create_contact")
+ }
+
async fn set_email_sync(
&self,
_access: &CrmCompanyReceipt<EditAccessLevel>,
diff --git a/crates/crm/src/domain/service/test.rs b/crates/crm/src/domain/service/test.rs
index 50a16f34e7..920dcf7f9c 100644
--- a/crates/crm/src/domain/service/test.rs
+++ b/crates/crm/src/domain/service/test.rs
@@ -31,6 +31,28 @@ impl CompaniesRepository for StubRepo {
unimplemented!()
}
+ async fn create_company_for_team(
+ &self,
+ _team_id: &uuid::Uuid,
+ _domain: &str,
+ _name: &str,
+ _now: DateTime<Utc>,
+ ) -> Result<CrmCompanyWithContacts, CrmError> {
+ unimplemented!()
+ }
+
+ async fn create_contact_for_company(
+ &self,
+ _team_id: &uuid::Uuid,
+ _company_id: &uuid::Uuid,
+ _email: &str,
+ _name: &str,
+ _now: DateTime<Utc>,
+ _include_hidden: bool,
+ ) -> Result<CrmContact, CrmError> {
+ unimplemented!()
+ }
+
async fn lookup_domain_metadata(
&self,
_domain: &str,
@@ -319,3 +341,109 @@ async fn team_views_must_be_an_array() {
.unwrap_err();
assert!(matches!(err, CrmError::InvalidRequest(_)));
}
+
+#[tokio::test]
+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")
+ .await
+ .unwrap_err();
+ assert!(matches!(err, CrmError::InvalidRequest(_)), "name {name:?}");
+ }
+}
+
+#[tokio::test]
+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")
+ .await
+ .unwrap_err();
+ assert!(matches!(err, CrmError::InvalidRequest(_)));
+}
+
+#[tokio::test]
+async fn create_company_rejects_malformed_domains() {
+ let access = receipt_with_role(TeamRole::Member);
+ for domain in [
+ "",
+ " ",
+ "acme",
+ ".acme.com",
+ "acme..com",
+ "https://acme.com",
+ "acme.com/about",
+ "acme.com:8080",
+ "acme .com",
+ ] {
+ let err = service()
+ .create_company(&access, "Acme", domain)
+ .await
+ .unwrap_err();
+ assert!(
+ matches!(err, CrmError::InvalidRequest(_)),
+ "domain {domain:?}"
+ );
+ }
+}
+
+#[tokio::test]
+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)
+ .await
+ .unwrap_err();
+ assert!(
+ matches!(err, CrmError::InvalidRequest(_)),
+ "domain {domain:?}"
+ );
+ }
+}
+
+fn company_receipt() -> CrmCompanyReceipt<ViewAccessLevel> {
+ CrmCompanyReceipt::dangerously_internal(uuid::Uuid::now_v7(), uuid::Uuid::now_v7())
+}
+
+#[tokio::test]
+async fn create_contact_rejects_blank_name() {
+ let access = company_receipt();
+ for name in ["", " ", "\t\n"] {
+ let err = service()
+ .create_contact(&access, name, "[email protected]")
+ .await
+ .unwrap_err();
+ assert!(matches!(err, CrmError::InvalidRequest(_)), "name {name:?}");
+ }
+}
+
+#[tokio::test]
+async fn create_contact_rejects_malformed_emails() {
+ let access = company_receipt();
+ for email in [
+ "",
+ " ",
+ "jane",
+ "jane@",
+ "@acme.com",
+ "jane@acme",
+ "jane@ac me.com",
+ "jane@@acme.com",
+ ] {
+ let err = service()
+ .create_contact(&access, "Jane", email)
+ .await
+ .unwrap_err();
+ assert!(
+ matches!(err, CrmError::InvalidRequest(_)),
+ "email {email:?}"
+ );
+ }
+}
diff --git a/crates/crm/src/inbound/axum_extractors/test.rs b/crates/crm/src/inbound/axum_extractors/test.rs
index 98e8287e2b..c1fc83e561 100644
--- a/crates/crm/src/inbound/axum_extractors/test.rs
+++ b/crates/crm/src/inbound/axum_extractors/test.rs
@@ -281,6 +281,24 @@ impl CrmService for FakeCrmService {
panic!("unexpected get_team_id_for_user call")
}
+ async fn create_company(
+ &self,
+ _access: &CrmTeamReceipt<MemberTeamRole>,
+ _name: &str,
+ _domain: &str,
+ ) -> Result<CrmCompanyWithContacts, CrmError> {
+ panic!("unexpected create_company call")
+ }
+
+ async fn create_contact(
+ &self,
+ _access: &CrmCompanyReceipt<ViewAccessLevel>,
+ _name: &str,
+ _email: &str,
+ ) -> Result<CrmContact, CrmError> {
+ panic!("unexpected create_contact call")
+ }
+
async fn set_email_sync(
&self,
_access: &CrmCompanyReceipt<EditAccessLevel>,
diff --git a/crates/crm/src/inbound/axum_router/create_company.rs b/crates/crm/src/inbound/axum_router/create_company.rs
new file mode 100644
index 0000000000..5e0d2a724f
--- /dev/null
+++ b/crates/crm/src/inbound/axum_router/create_company.rs
@@ -0,0 +1,58 @@
+use axum::{Json, extract::State};
+use entity_access::{
+ domain::{models::MemberTeamRole, ports::EntityAccessService},
+ inbound::axum_extractors::MacroUserTeamExtractorV2,
+};
+use macro_authorization::MacroAuthorizationService;
+use model_error_response::ErrorResponse;
+use serde::Deserialize;
+use utoipa::ToSchema;
+
+use crate::domain::{auth::CrmTeamReceipt, model::CrmError, service::CrmService};
+
+use super::{CrmRouterState, get_company::CrmCompanyResponse};
+
+/// Request body for `POST /crm/companies`.
+#[derive(Debug, Deserialize, ToSchema)]
+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
+ /// domain (no scheme, path, or email) and not a generic email
+ /// provider domain.
+ pub domain: String,
+}
+
+/// Manually create a CRM company for the caller's team. Any team member
+/// may create one. The domain must not already be tracked by the team
+/// (409), and the team's CRM killswitch must be on (403). Returns the
+/// created company in the same shape as `GET /crm/companies/{id}` (its
+/// contact list is empty until emails populate it).
+#[utoipa::path(
+ post,
+ path = "/crm/companies",
+ operation_id = "create_crm_company",
+ request_body = CreateCrmCompanyRequest,
+ responses(
+ (status = 200, body = CrmCompanyResponse),
+ (status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 403, body = ErrorResponse),
+ (status = 409, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ ),
+)]
+#[tracing::instrument(skip_all, err)]
+pub async fn handler<C: CrmService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
+ access: MacroUserTeamExtractorV2<MemberTeamRole, Eas, Auth>,
+ State(state): State<CrmRouterState<C, Eas, Auth>>,
+ Json(req): Json<CreateCrmCompanyRequest>,
+) -> Result<Json<CrmCompanyResponse>, CrmError> {
+ let receipt = CrmTeamReceipt::from_team_receipt(access.entity_access_receipt)?;
+ let record = state
+ .service
+ .create_company(&receipt, &req.name, &req.domain)
+ .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
new file mode 100644
index 0000000000..b87b2a600f
--- /dev/null
+++ b/crates/crm/src/inbound/axum_router/create_contact.rs
@@ -0,0 +1,66 @@
+use axum::{
+ Json,
+ extract::{Path, State},
+};
+use entity_access::domain::{models::ViewAccessLevel, ports::EntityAccessService};
+use macro_authorization::MacroAuthorizationService;
+use model_error_response::ErrorResponse;
+use serde::Deserialize;
+use utoipa::ToSchema;
+use uuid::Uuid;
+
+use crate::{
+ domain::{model::CrmError, service::CrmService},
+ inbound::axum_extractors::CrmCompanyAccessLevelExtractor,
+};
+
+use super::{CrmRouterState, list_company_contacts::CrmContactResponse};
+
+/// Request body for `POST /crm/companies/{company_id}/contacts`.
+#[derive(Debug, Deserialize, ToSchema)]
+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).
+ pub email: String,
+}
+
+/// Manually create a contact under a CRM company. Access is enforced by
+/// [`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(
+ post,
+ path = "/crm/companies/{company_id}/contacts",
+ operation_id = "create_crm_contact",
+ params(
+ ("company_id" = Uuid, Path, description = "The CRM company to add the contact to"),
+ ),
+ request_body = CreateCrmContactRequest,
+ responses(
+ (status = 200, body = CrmContactResponse),
+ (status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 403, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 409, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ ),
+)]
+#[tracing::instrument(skip_all, err, fields(company_id = %company_id))]
+pub async fn handler<C: CrmService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
+ access: CrmCompanyAccessLevelExtractor<ViewAccessLevel, Eas, Auth>,
+ State(state): State<CrmRouterState<C, Eas, Auth>>,
+ Path(company_id): Path<Uuid>,
+ Json(req): Json<CreateCrmContactRequest>,
+) -> Result<Json<CrmContactResponse>, CrmError> {
+ let contact = state
+ .service
+ .create_contact(&access.receipt, &req.name, &req.email)
+ .await?;
+ Ok(Json(contact.into()))
+}
diff --git a/crates/crm/src/inbound/axum_router/mod.rs b/crates/crm/src/inbound/axum_router/mod.rs
index a84fec1808..69183d2eb8 100644
--- a/crates/crm/src/inbound/axum_router/mod.rs
+++ b/crates/crm/src/inbound/axum_router/mod.rs
@@ -20,6 +20,12 @@ pub mod get_contact;
/// Fetch a single CRM company by id, hydrated with domains and contacts.
pub mod get_company;
+/// Manually create a CRM company (name + domain) for the caller's team.
+pub mod create_company;
+
+/// Manually create a contact (name + email) under a CRM company.
+pub mod create_contact;
+
/// Comment threads on a `crm_companies` / `crm_contacts` row.
pub mod comments;
@@ -34,7 +40,7 @@ use axum::{
extract::FromRef,
http::StatusCode,
response::{IntoResponse, Response},
- routing::{get, patch, put},
+ routing::{get, patch, post, put},
};
use entity_access::domain::ports::EntityAccessService;
use macro_authorization::{MacroAuthorizationService, MacroAuthorizationState};
@@ -106,6 +112,7 @@ where
S: Send + Sync + 'static,
{
Router::new()
+ .route("/companies", post(create_company::handler::<C, Eas, Auth>))
.route(
"/companies/{company_id}/email-sync",
put(set_email_sync::handler::<C, Eas, Auth>),
@@ -120,7 +127,8 @@ where
)
.route(
"/companies/{company_id}/contacts",
- get(list_company_contacts::handler::<C, Eas, Auth>),
+ get(list_company_contacts::handler::<C, Eas, Auth>)
+ .post(create_contact::handler::<C, Eas, Auth>),
)
.route(
"/contacts/{contact_id}",
@@ -207,6 +215,30 @@ impl IntoResponse for CrmError {
message: "crm company is hidden; un-hide before enabling email sync".into(),
}),
),
+ CrmError::CompanyAlreadyExistsForTeam => (
+ StatusCode::CONFLICT,
+ Json(ErrorResponse {
+ message: "a crm company already exists for this domain".into(),
+ }),
+ ),
+ CrmError::ContactAlreadyExistsForCompany => (
+ StatusCode::CONFLICT,
+ Json(ErrorResponse {
+ 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 {
+ message: "crm is not enabled for this team".into(),
+ }),
+ ),
CrmError::InvalidTeamId | CrmError::StorageLayerError(_) => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
diff --git a/crates/crm/src/outbound/companies_repo.rs b/crates/crm/src/outbound/companies_repo.rs
index 825abd6441..d80ffbbcfc 100644
--- a/crates/crm/src/outbound/companies_repo.rs
+++ b/crates/crm/src/outbound/companies_repo.rs
@@ -56,16 +56,186 @@ impl CompaniesRepositoryImpl {
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
for domain in domains {
- sqlx::query!(
- r#"SELECT pg_advisory_xact_lock(hashtextextended($1, 0))"#,
- format!("{team_id}:{domain}"),
- )
+ Self::lock_team_domain(tx, team_id, &domain).await?;
+ }
+
+ Ok(())
+ }
+
+ /// Take the per-`(team, lower(domain))` advisory lock that
+ /// serializes populate / depopulate / manual create for one domain.
+ /// `normalized_domain` must already be lowercased.
+ async fn lock_team_domain(
+ tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
+ team_id: &uuid::Uuid,
+ normalized_domain: &str,
+ ) -> Result<(), CrmError> {
+ sqlx::query!(
+ r#"SELECT pg_advisory_xact_lock(hashtextextended($1, 0))"#,
+ format!("{team_id}:{normalized_domain}"),
+ )
+ .execute(&mut **tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+ Ok(())
+ }
+
+ /// Team killswitch, read inside the tx (after the advisory lock) so
+ /// a concurrent disable+purge can't race past us. Missing row =
+ /// default false.
+ async fn team_crm_enabled(
+ tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
+ team_id: &uuid::Uuid,
+ ) -> Result<bool, CrmError> {
+ sqlx::query_scalar!(
+ r#"
+ SELECT COALESCE(
+ (SELECT crm_enabled FROM team_crm_settings WHERE team_id = $1),
+ FALSE
+ ) AS "crm_enabled!"
+ "#,
+ team_id,
+ )
+ .fetch_one(&mut **tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))
+ }
+
+ /// Look up the company owning `(team, lower(domain))`. Returns
+ /// `(id, hidden)`; `hidden` is read so new contacts can inherit it.
+ async fn find_company_by_domain(
+ tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
+ team_id: &uuid::Uuid,
+ normalized_domain: &str,
+ ) -> Result<Option<(uuid::Uuid, bool)>, CrmError> {
+ let row = sqlx::query!(
+ r#"
+ SELECT c.id, c.hidden
+ FROM crm_companies c
+ JOIN crm_domains d ON d.company_id = c.id
+ WHERE c.team_id = $1
+ AND LOWER(d.domain) = $2
+ LIMIT 1
+ "#,
+ team_id,
+ normalized_domain,
+ )
+ .fetch_optional(&mut **tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+ Ok(row.map(|r| (r.id, r.hidden)))
+ }
+
+ /// Merge an interaction range into a company row.
+ /// `last_interaction` always bumps via GREATEST; `first_interaction`
+ /// only LEAST-merges on `is_sent = true` — received-direction
+ /// populates must not pull the anchor backwards.
+ async fn merge_company_interactions(
+ tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
+ company_id: &uuid::Uuid,
+ first_at: DateTime<Utc>,
+ last_at: DateTime<Utc>,
+ is_sent: bool,
+ ) -> Result<(), CrmError> {
+ sqlx::query!(
+ r#"UPDATE crm_companies
+ SET updated_at = now(),
+ first_interaction = CASE
+ WHEN $4 THEN LEAST(first_interaction, $2)
+ ELSE first_interaction
+ END,
+ last_interaction = GREATEST(last_interaction, $3)
+ WHERE id = $1"#,
+ company_id,
+ first_at,
+ last_at,
+ is_sent,
+ )
+ .execute(&mut **tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+ Ok(())
+ }
+
+ /// Insert a `crm_companies` row (+ its `crm_domains` row) for
+ /// `(team, normalized_domain)`, seeding the 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.
+ ///
+ /// 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(
+ tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
+ team_id: &uuid::Uuid,
+ normalized_domain: &str,
+ custom_name: Option<&str>,
+ manually_created: bool,
+ first_at: DateTime<Utc>,
+ last_at: DateTime<Utc>,
+ ) -> Result<(uuid::Uuid, bool), CrmError> {
+ 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)
+ RETURNING id
+ "#,
+ team_id,
+ custom_name,
+ manually_created,
+ first_at,
+ last_at,
+ )
+ .fetch_one(&mut **tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ let domain_insert = sqlx::query!(
+ r#"
+ INSERT INTO crm_domains (company_id, team_id, domain)
+ VALUES ($1, $2, $3)
+ ON CONFLICT (team_id, LOWER(domain)) DO NOTHING
+ "#,
+ new_company.id,
+ team_id,
+ normalized_domain,
+ )
+ .execute(&mut **tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ if domain_insert.rows_affected() > 0 {
+ return Ok((new_company.id, true));
+ }
+
+ sqlx::query!(r#"DELETE FROM crm_companies WHERE id = $1"#, new_company.id,)
.execute(&mut **tx)
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
- }
- Ok(())
+ let winner = sqlx::query_scalar!(
+ r#"
+ SELECT c.id
+ FROM crm_companies c
+ JOIN crm_domains d ON d.company_id = c.id
+ WHERE c.team_id = $1
+ AND LOWER(d.domain) = $2
+ LIMIT 1
+ "#,
+ team_id,
+ normalized_domain,
+ )
+ .fetch_one(&mut **tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ Ok((winner, false))
}
/// Resolve a comment's author, but only when the comment resolves to a
@@ -137,31 +307,9 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
// Serialize on (team, lower(domain)): the unique constraint on
// crm_domains catches the race only after an orphan crm_companies
// row was already inserted by the loser.
- sqlx::query!(
- r#"SELECT pg_advisory_xact_lock(hashtextextended($1, 0))"#,
- format!("{team_id}:{normalized_domain}"),
- )
- .execute(&mut *tx)
- .await
- .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+ Self::lock_team_domain(&mut tx, team_id, &normalized_domain).await?;
- // Team killswitch. Read inside the tx (after the lock) so a
- // concurrent disable+purge can't race past us. Missing row =
- // default false.
- let team_crm_enabled = sqlx::query_scalar!(
- r#"
- SELECT COALESCE(
- (SELECT crm_enabled FROM team_crm_settings WHERE team_id = $1),
- FALSE
- ) AS "crm_enabled!"
- "#,
- team_id,
- )
- .fetch_one(&mut *tx)
- .await
- .map_err(|e| CrmError::StorageLayerError(e.into()))?;
-
- if !team_crm_enabled {
+ if !Self::team_crm_enabled(&mut tx, team_id).await? {
tx.commit()
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
@@ -169,55 +317,19 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
}
// Look up the existing company row (by team + lowercased
- // domain). `email_sync` is read solely so the caller's
- // visibility/permission gates can later check it; populate
- // itself runs regardless. Hide is the only opt-out that
- // affects what gets written (and even then only via the
- // `hidden` cascade onto new contacts, not by skipping the
- // write entirely).
- let existing = sqlx::query!(
- r#"
- SELECT c.id, c.hidden
- FROM crm_companies c
- JOIN crm_domains d ON d.company_id = c.id
- WHERE c.team_id = $1
- AND LOWER(d.domain) = $2
- LIMIT 1
- "#,
- team_id,
- normalized_domain,
- )
- .fetch_optional(&mut *tx)
- .await
- .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+ // domain). Populate runs regardless of `email_sync` — that flag
+ // is a read-side gate. Hide is the only opt-out that affects
+ // what gets written (and even then only via the `hidden`
+ // cascade onto new contacts, not by skipping the write
+ // entirely).
+ let existing = Self::find_company_by_domain(&mut tx, team_id, &normalized_domain).await?;
// Track the company's current hidden state alongside its id so
// new contacts inherit it on INSERT.
let (company_id, company_hidden) = match existing {
- Some(row) => {
- // `last_interaction` always bumps via GREATEST.
- // `first_interaction` only LEAST-merges on is_sent=true:
- // received-direction populates must not pull the anchor
- // backwards.
- sqlx::query!(
- r#"UPDATE crm_companies
- SET updated_at = now(),
- first_interaction = CASE
- WHEN $4 THEN LEAST(first_interaction, $2)
- ELSE first_interaction
- END,
- last_interaction = GREATEST(last_interaction, $3)
- WHERE id = $1"#,
- row.id,
- first_at,
- last_at,
- is_sent,
- )
- .execute(&mut *tx)
- .await
- .map_err(|e| CrmError::StorageLayerError(e.into()))?;
-
- (row.id, row.hidden)
+ Some((id, hidden)) => {
+ Self::merge_company_interactions(&mut tx, &id, first_at, last_at, is_sent).await?;
+ (id, hidden)
}
None if !is_sent => {
// Received-direction never creates a company row.
@@ -229,93 +341,37 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
None => {
// Seed interaction columns from the producer's known
// range so backfilled mail keeps accurate timestamps.
- let new_company = sqlx::query!(
- r#"
- INSERT INTO crm_companies (team_id, first_interaction, last_interaction)
- VALUES ($1, $2, $3)
- RETURNING id
- "#,
+ // No custom_name: backfill companies resolve their
+ // display name from `crm_domain_directory`.
+ let (id, created) = Self::insert_company_with_domain(
+ &mut tx,
team_id,
+ &normalized_domain,
+ None,
+ false,
first_at,
last_at,
)
- .fetch_one(&mut *tx)
- .await
- .map_err(|e| CrmError::StorageLayerError(e.into()))?;
-
- // Defensive ON CONFLICT — the advisory lock should
- // prevent it, but if it fires we'd orphan the company
- // we just inserted, so we recover via rows_affected.
- let domain_insert = sqlx::query!(
- r#"
- INSERT INTO crm_domains (company_id, team_id, domain)
- VALUES ($1, $2, $3)
- ON CONFLICT (team_id, LOWER(domain)) DO NOTHING
- "#,
- new_company.id,
- team_id,
- normalized_domain,
- )
- .execute(&mut *tx)
- .await
- .map_err(|e| CrmError::StorageLayerError(e.into()))?;
-
- if domain_insert.rows_affected() == 0 {
- let existing_company_id = sqlx::query_scalar!(
- r#"
- SELECT c.id
- FROM crm_companies c
- JOIN crm_domains d ON d.company_id = c.id
- WHERE c.team_id = $1
- AND LOWER(d.domain) = $2
- LIMIT 1
- "#,
- team_id,
- normalized_domain,
- )
- .fetch_one(&mut *tx)
- .await
- .map_err(|e| CrmError::StorageLayerError(e.into()))?;
-
- // is_sent is true here (the !is_sent arm exited);
- // CASE kept for symmetry with the regular path.
- sqlx::query!(
- r#"UPDATE crm_companies
- SET updated_at = now(),
- first_interaction = CASE
- WHEN $4 THEN LEAST(first_interaction, $2)
- ELSE first_interaction
- END,
- last_interaction = GREATEST(last_interaction, $3)
- WHERE id = $1"#,
- existing_company_id,
- first_at,
- last_at,
- is_sent,
- )
- .execute(&mut *tx)
- .await
- .map_err(|e| CrmError::StorageLayerError(e.into()))?;
-
- sqlx::query!(r#"DELETE FROM crm_companies WHERE id = $1"#, new_company.id,)
- .execute(&mut *tx)
- .await
- .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+ .await?;
- // Race winner is already visible (no hide cascade ran
- // since insertion); read its current hidden defensively.
+ if created {
+ // Fresh company — defaults to hidden = FALSE.
+ (id, false)
+ } else {
+ // Lost the defensive domain race: merge our range
+ // into the winner and read its current hidden
+ // defensively (it's freshly inserted, so no hide
+ // cascade can have run — but cheap to check).
+ Self::merge_company_interactions(&mut tx, &id, first_at, last_at, is_sent)
+ .await?;
let winner_hidden = sqlx::query_scalar!(
r#"SELECT hidden FROM crm_companies WHERE id = $1"#,
- existing_company_id,
+ id,
)
.fetch_one(&mut *tx)
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
-
- (existing_company_id, winner_hidden)
- } else {
- // Fresh company — defaults to hidden = FALSE.
- (new_company.id, false)
+ (id, winner_hidden)
}
}
};
@@ -374,6 +430,192 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
Ok(())
}
+ #[tracing::instrument(skip(self), err)]
+ async fn create_company_for_team(
+ &self,
+ team_id: &uuid::Uuid,
+ domain: &str,
+ name: &str,
+ now: DateTime<Utc>,
+ ) -> Result<CrmCompanyWithContacts, CrmError> {
+ let normalized_domain = domain.to_ascii_lowercase();
+
+ let mut tx = self
+ .pool
+ .begin()
+ .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?;
+
+ // 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()
+ {
+ return Err(CrmError::CompanyAlreadyExistsForTeam);
+ }
+
+ // 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(
+ &mut tx,
+ team_id,
+ &normalized_domain,
+ Some(name),
+ true,
+ now,
+ now,
+ )
+ .await?;
+ if !created {
+ // Unreachable while we hold the advisory lock; defensive.
+ return Err(CrmError::CompanyAlreadyExistsForTeam);
+ }
+
+ tx.commit()
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ // Hydrate through the shared read path so domains + directory
+ // metadata resolve identically to the GET endpoint.
+ self.get_company_for_team(team_id, &company_id, true)
+ .await?
+ .ok_or_else(|| {
+ CrmError::StorageLayerError(anyhow::anyhow!(
+ "created crm company vanished before hydration"
+ ))
+ })
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn create_contact_for_company(
+ &self,
+ team_id: &uuid::Uuid,
+ company_id: &uuid::Uuid,
+ email: &str,
+ name: &str,
+ now: DateTime<Utc>,
+ include_hidden: bool,
+ ) -> Result<CrmContact, CrmError> {
+ let normalized_email = email.to_ascii_lowercase();
+
+ let mut tx = self
+ .pool
+ .begin()
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ if !Self::team_crm_enabled(&mut tx, team_id).await? {
+ return Err(CrmError::CrmDisabledForTeam);
+ }
+
+ // Scope + authorize on the company row. FOR UPDATE serializes
+ // with the hide/un-hide contact cascade so the inherited
+ // `hidden` can't go stale between this read and our insert.
+ // Hidden companies are unreachable for members
+ // (`include_hidden = false`) — same 404 semantics as the reads.
+ let company = sqlx::query!(
+ r#"
+ SELECT hidden
+ FROM crm_companies
+ WHERE id = $1
+ AND team_id = $2
+ AND ($3 OR hidden = FALSE)
+ FOR UPDATE
+ "#,
+ company_id,
+ team_id,
+ include_hidden,
+ )
+ .fetch_optional(&mut *tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ let Some(company) = company else {
+ 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
+ // construction. No interaction history yet: both endpoints
+ // seed from `now`; later populates merge via LEAST/GREATEST
+ // and keep the manual name (first non-NULL wins).
+ let row = sqlx::query!(
+ r#"
+ INSERT INTO crm_contacts
+ (company_id, email, name, first_interaction, last_interaction, hidden, manually_created)
+ VALUES ($1, $2, $3, $4, $4, $5, TRUE)
+ ON CONFLICT (company_id, email) DO NOTHING
+ RETURNING id, company_id, email, name, hidden,
+ first_interaction, last_interaction, created_at, updated_at
+ "#,
+ company_id,
+ normalized_email,
+ name,
+ now,
+ company.hidden,
+ )
+ .fetch_optional(&mut *tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ let Some(row) = row else {
+ return Err(CrmError::ContactAlreadyExistsForCompany);
+ };
+
+ tx.commit()
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ Ok(CrmContact {
+ id: row.id,
+ company_id: row.company_id,
+ email: row.email,
+ name: row.name,
+ hidden: row.hidden,
+ first_interaction: row.first_interaction,
+ last_interaction: row.last_interaction,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ })
+ }
+
#[tracing::instrument(skip(self), err)]
async fn depopulate_contact(
&self,
@@ -406,8 +648,10 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
r#"
SELECT
ct.id AS contact_id,
+ ct.manually_created AS "contact_manually_created!",
co.id AS company_id,
- co.email_sync AS "email_sync!"
+ co.email_sync AS "email_sync!",
+ co.manually_created AS "company_manually_created!"
FROM crm_contacts ct
JOIN crm_companies co ON co.id = ct.company_id
JOIN crm_domains d ON d.company_id = co.id
@@ -443,8 +687,18 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
- // 2. Keep the contact iff any other link in the team still
- // references it.
+ // 2. Manually created contacts are user data, not derived —
+ // never torn down (they have no sources by construction, so
+ // the orphan check below would always condemn them).
+ if row.contact_manually_created {
+ tx.commit()
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+ return Ok(());
+ }
+
+ // Otherwise keep the contact iff any other link in the team
+ // still references it.
let other_sources = sqlx::query_scalar!(
r#"
SELECT EXISTS(
@@ -471,7 +725,9 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
// 3. Keep killswitched companies — dropping would erase the
// opt-out and a future populate would recreate as enabled.
- if !row.email_sync {
+ // Manually created companies are likewise user data and
+ // survive teardown even when empty.
+ if !row.email_sync || row.company_manually_created {
tx.commit()
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
@@ -540,13 +796,15 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
// 2. Drop every contact in this team that no longer has any
- // source.
+ // source. Manually created contacts have no sources by
+ // construction — they're user data and survive teardown.
sqlx::query!(
r#"
DELETE FROM crm_contacts ct
USING crm_companies co
WHERE ct.company_id = co.id
AND co.team_id = $1
+ AND ct.manually_created = FALSE
AND NOT EXISTS (
SELECT 1 FROM crm_contact_sources WHERE contact_id = ct.id
)
@@ -557,13 +815,16 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
- // 3. Drop orphan non-killswitched companies. crm_domains
- // cascades via FK.
+ // 3. Drop orphan non-killswitched companies. Manually created
+ // companies survive even when empty — they're user data,
+ // not derived from the departing link. crm_domains cascades
+ // via FK.
sqlx::query!(
r#"
DELETE FROM crm_companies co
WHERE co.team_id = $1
AND co.email_sync = TRUE
+ AND co.manually_created = FALSE
AND NOT EXISTS (
SELECT 1 FROM crm_contacts WHERE company_id = co.id
)
@@ -1093,6 +1354,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
SELECT
c.id,
c.team_id,
+ c.custom_name,
c.email_sync,
c.hidden,
c.first_interaction,
@@ -1145,7 +1407,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
d.id AS "domain_id?",
d.domain AS "domain?",
d.created_at AS "domain_created_at?",
- dd.name AS "dir_name?",
+ COALESCE(lc.custom_name, dd.name) AS "display_name?",
dd.description AS "dir_description?",
uh."updatedAt"::timestamptz AS "viewed_at?"
FROM limited_companies lc
@@ -1196,7 +1458,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
updated_at: row.company_updated_at,
domains: Vec::new(),
},
- name: row.dir_name,
+ name: row.display_name,
description: row.dir_description,
viewed_at: row.viewed_at,
});
@@ -1371,7 +1633,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
d.id AS "domain_id?",
d.domain AS "domain?",
d.created_at AS "domain_created_at?",
- dd.name AS "dir_name?",
+ COALESCE(c.custom_name, dd.name) AS "display_name?",
dd.description AS "dir_description?"
FROM crm_companies c
LEFT JOIN crm_domains d ON d.company_id = c.id
@@ -1395,9 +1657,11 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
return Ok(None);
};
- // Directory name/description come from the primary domain's row
- // (which is the first row by `created_at ASC` per the ORDER BY).
- let name = first.dir_name.clone();
+ // Display name is the team-scoped override when set, otherwise
+ // the primary domain's directory name (first row by
+ // `created_at ASC` per the ORDER BY). Description comes from
+ // the directory.
+ let name = first.display_name.clone();
let description = first.dir_description.clone();
let mut company = CrmCompany {
diff --git a/crates/crm/src/outbound/companies_repo/test.rs b/crates/crm/src/outbound/companies_repo/test.rs
index da5bc57586..9efcad8e67 100644
--- a/crates/crm/src/outbound/companies_repo/test.rs
+++ b/crates/crm/src/outbound/companies_repo/test.rs
@@ -7,6 +7,8 @@
mod helpers;
mod comments;
+mod create_company;
+mod create_contact;
mod get_company_for_team;
mod get_contact_for_team;
mod list_companies_for_soup;
diff --git a/crates/crm/src/outbound/companies_repo/test/create_company.rs b/crates/crm/src/outbound/companies_repo/test/create_company.rs
new file mode 100644
index 0000000000..35f625123d
--- /dev/null
+++ b/crates/crm/src/outbound/companies_repo/test/create_company.rs
@@ -0,0 +1,215 @@
+use super::helpers::*;
+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 create_company_inserts_company_and_domain(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 repo = CompaniesRepositoryImpl::new(pool.clone());
+ let now = Utc::now();
+ let record = repo
+ .create_company_for_team(&team_id, "Acme.COM", "Acme", now)
+ .await?;
+
+ assert_eq!(record.name.as_deref(), Some("Acme"));
+ assert_eq!(record.company.team_id, team_id);
+ assert!(!record.company.hidden);
+ assert!(record.company.email_sync);
+ assert!(record.contacts.is_empty());
+ // Domain is stored lowercased.
+ assert_eq!(record.company.domains.len(), 1);
+ assert_eq!(record.company.domains[0].domain, "acme.com");
+ // Interaction endpoints are both seeded from `now` (compare at
+ // microsecond precision — Postgres truncates nanoseconds).
+ assert_eq!(
+ record.company.created_at.timestamp_micros(),
+ now.timestamp_micros()
+ );
+ assert_eq!(
+ record.company.updated_at.timestamp_micros(),
+ now.timestamp_micros()
+ );
+
+ assert_eq!(
+ count_companies_for_domain(&pool, team_id, "acme.com").await?,
+ 1
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_company_name_overrides_directory_name(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?;
+
+ // Directory already resolved a different (global) name for the
+ // domain; the team-scoped override must win.
+ sqlx::query(
+ r#"INSERT INTO crm_domain_directory (domain, name, description)
+ VALUES ($1, $2, $3)"#,
+ )
+ .bind("acme.com")
+ .bind("Acme Inc. (directory)")
+ .bind("Maker of rocket-powered roller skates.")
+ .execute(&pool)
+ .await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ let record = repo
+ .create_company_for_team(&team_id, "acme.com", "Acme (ours)", Utc::now())
+ .await?;
+
+ assert_eq!(record.name.as_deref(), Some("Acme (ours)"));
+ // Description still comes from the directory.
+ assert_eq!(
+ record.description.as_deref(),
+ Some("Maker of rocket-powered roller skates.")
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_company_rejects_duplicate_domain(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?;
+ insert_company(&pool, team_id, true, &["acme.com"]).await?;
+
+ 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())
+ .await
+ .unwrap_err();
+ assert!(matches!(err, CrmError::CompanyAlreadyExistsForTeam));
+
+ assert_eq!(
+ count_companies_for_domain(&pool, team_id, "acme.com").await?,
+ 1
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_company_allows_same_domain_on_another_team(pool: PgPool) -> anyhow::Result<()> {
+ let team_a = Uuid::now_v7();
+ let team_b = Uuid::now_v7();
+ seed_team(&pool, team_a, "macro|[email protected]").await?;
+ seed_team(&pool, team_b, "macro|[email protected]").await?;
+ enable_crm_for_team(&pool, team_a).await?;
+ enable_crm_for_team(&pool, team_b).await?;
+ insert_company(&pool, team_a, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ let record = repo
+ .create_company_for_team(&team_b, "acme.com", "Acme", Utc::now())
+ .await?;
+ assert_eq!(record.company.team_id, team_b);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_company_requires_crm_enabled(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
+ // No team_crm_settings row: killswitch defaults to off.
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ let err = repo
+ .create_company_for_team(&team_id, "acme.com", "Acme", Utc::now())
+ .await
+ .unwrap_err();
+ assert!(matches!(err, CrmError::CrmDisabledForTeam));
+
+ assert_eq!(
+ count_companies_for_domain(&pool, team_id, "acme.com").await?,
+ 0
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn populate_reuses_manually_created_company(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner = "macro|[email protected]";
+ seed_team(&pool, team_id, owner).await?;
+ enable_crm_for_team(&pool, team_id).await?;
+ let link_id = insert_email_link(&pool, owner, "[email protected]").await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ let created = repo
+ .create_company_for_team(&team_id, "acme.com", "Acme", Utc::now())
+ .await?;
+
+ // A later populate for the same domain attaches its contact to the
+ // manually created company instead of inserting a second one.
+ let now = Utc::now();
+ repo.populate_contact(
+ &team_id,
+ &link_id,
+ "acme.com",
+ Some("Jane"),
+ now,
+ now,
+ true,
+ )
+ .await?;
+
+ assert_eq!(
+ count_companies_for_domain(&pool, team_id, "acme.com").await?,
+ 1
+ );
+ assert_eq!(count_contacts(&pool, created.company.id).await?, 1);
+
+ // The manual name override survives the populate.
+ let record = repo
+ .get_company_for_team(&team_id, &created.company.id, false)
+ .await?
+ .expect("company should be returned");
+ assert_eq!(record.name.as_deref(), Some("Acme"));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn soup_listing_uses_name_override(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?;
+
+ sqlx::query(r#"INSERT INTO crm_domain_directory (domain, name) VALUES ($1, $2)"#)
+ .bind("acme.com")
+ .bind("Acme Inc. (directory)")
+ .execute(&pool)
+ .await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ let created = repo
+ .create_company_for_team(&team_id, "acme.com", "Acme (ours)", Utc::now())
+ .await?;
+
+ let listed = repo
+ .list_companies_for_soup(
+ &team_id,
+ &[],
+ None,
+ crate::domain::companies_repo::CrmCompanyListSort::UpdatedAt,
+ None,
+ 10,
+ )
+ .await?;
+ assert_eq!(listed.len(), 1);
+ assert_eq!(listed[0].company.id, created.company.id);
+ assert_eq!(listed[0].name.as_deref(), Some("Acme (ours)"));
+ 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
new file mode 100644
index 0000000000..7ed1830c98
--- /dev/null
+++ b/crates/crm/src/outbound/companies_repo/test/create_contact.rs
@@ -0,0 +1,321 @@
+use super::helpers::*;
+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 create_contact_inserts_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 company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ let now = Utc::now();
+ let contact = repo
+ .create_contact_for_company(&team_id, &company_id, "[email protected]", "Jane", now, false)
+ .await?;
+
+ // Email is stored lowercased; the contact starts visible and both
+ // interaction endpoints seed from `now`.
+ assert_eq!(contact.email, "[email protected]");
+ assert_eq!(contact.name.as_deref(), Some("Jane"));
+ assert_eq!(contact.company_id, company_id);
+ assert!(!contact.hidden);
+ assert_eq!(
+ contact.first_interaction.timestamp_micros(),
+ now.timestamp_micros()
+ );
+ assert_eq!(
+ contact.last_interaction.timestamp_micros(),
+ now.timestamp_micros()
+ );
+
+ let listed = repo
+ .list_contacts_for_company(&team_id, &company_id, false)
+ .await?;
+ assert_eq!(listed.len(), 1);
+ assert_eq!(listed[0].id, contact.id);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_contact_rejects_duplicate_email(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 company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ repo.create_contact_for_company(
+ &team_id,
+ &company_id,
+ "Jane",
+ Utc::now(),
+ false,
+ )
+ .await?;
+
+ // Case-insensitive: normalization lowercases before the insert.
+ let err = repo
+ .create_contact_for_company(
+ &team_id,
+ &company_id,
+ "Jane 2",
+ Utc::now(),
+ false,
+ )
+ .await
+ .unwrap_err();
+ assert!(matches!(err, CrmError::ContactAlreadyExistsForCompany));
+
+ assert_eq!(count_contacts(&pool, company_id).await?, 1);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_contact_rejects_mismatched_domain(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 company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ let err = repo
+ .create_contact_for_company(&team_id, &company_id, email, "Jane", Utc::now(), false)
+ .await
+ .unwrap_err();
+ assert!(
+ matches!(err, CrmError::ContactEmailDomainMismatch),
+ "email {email:?}"
+ );
+ }
+ assert_eq!(count_contacts(&pool, company_id).await?, 0);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_contact_accepts_any_company_domain(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?;
+ // Multi-domain company: any of its domains is a valid email domain,
+ // matched case-insensitively.
+ let company_id = insert_company(&pool, team_id, true, &["acme.com", "Acme.io"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ repo.create_contact_for_company(
+ &team_id,
+ &company_id,
+ "Jane",
+ Utc::now(),
+ false,
+ )
+ .await?;
+ repo.create_contact_for_company(
+ &team_id,
+ &company_id,
+ "Jane",
+ Utc::now(),
+ false,
+ )
+ .await?;
+ assert_eq!(count_contacts(&pool, company_id).await?, 2);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_contact_cross_team_company_not_found(pool: PgPool) -> anyhow::Result<()> {
+ let team_a = Uuid::now_v7();
+ let team_b = Uuid::now_v7();
+ seed_team(&pool, team_a, "macro|[email protected]").await?;
+ seed_team(&pool, team_b, "macro|[email protected]").await?;
+ enable_crm_for_team(&pool, team_a).await?;
+ enable_crm_for_team(&pool, team_b).await?;
+ let company_id = insert_company(&pool, team_a, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ let err = repo
+ .create_contact_for_company(
+ &team_b,
+ &company_id,
+ "Jane",
+ Utc::now(),
+ true,
+ )
+ .await
+ .unwrap_err();
+ assert!(matches!(err, CrmError::CompanyNotFoundForTeam));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_contact_hidden_company_semantics(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 company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ repo.set_company_hidden(&team_id, &company_id, true).await?;
+
+ // Members can't reach a hidden company.
+ let err = repo
+ .create_contact_for_company(
+ &team_id,
+ &company_id,
+ "Jane",
+ Utc::now(),
+ false,
+ )
+ .await
+ .unwrap_err();
+ assert!(matches!(err, CrmError::CompanyNotFoundForTeam));
+
+ // Admin/owner can, and the new contact inherits `hidden`.
+ let contact = repo
+ .create_contact_for_company(
+ &team_id,
+ &company_id,
+ "Jane",
+ Utc::now(),
+ true,
+ )
+ .await?;
+ assert!(contact.hidden);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_contact_requires_crm_enabled(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
+ // Company exists but no team_crm_settings row: killswitch off.
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ let err = repo
+ .create_contact_for_company(
+ &team_id,
+ &company_id,
+ "Jane",
+ Utc::now(),
+ false,
+ )
+ .await
+ .unwrap_err();
+ assert!(matches!(err, CrmError::CrmDisabledForTeam));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn populate_merges_into_manual_contact(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner = "macro|[email protected]";
+ seed_team(&pool, team_id, owner).await?;
+ enable_crm_for_team(&pool, team_id).await?;
+ let link_id = insert_email_link(&pool, owner, "[email protected]").await?;
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ let contact = repo
+ .create_contact_for_company(
+ &team_id,
+ &company_id,
+ "Jane",
+ Utc::now(),
+ false,
+ )
+ .await?;
+
+ // A populate for the same email upserts onto the manual row: the
+ // manual name wins (first non-NULL), no second contact appears.
+ let now = Utc::now();
+ repo.populate_contact(
+ &team_id,
+ &link_id,
+ "acme.com",
+ Some("Jane Doe (observed)"),
+ now,
+ now,
+ true,
+ )
+ .await?;
+
+ assert_eq!(count_contacts(&pool, company_id).await?, 1);
+ let listed = repo
+ .list_contacts_for_company(&team_id, &company_id, false)
+ .await?;
+ assert_eq!(listed[0].id, contact.id);
+ assert_eq!(listed[0].name.as_deref(), Some("Jane"));
+
+ // The populate attached a source row; tearing that link down again
+ // must keep the manual contact (manually_created shields it from
+ // the no-sources orphan cleanup).
+ repo.depopulate_contact(&team_id, &link_id, "acme.com", "[email protected]")
+ .await?;
+ assert_eq!(count_contacts(&pool, company_id).await?, 1);
+ assert_eq!(count_sources_for_company(&pool, company_id).await?, 0);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn manual_rows_survive_link_teardown(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner = "macro|[email protected]";
+ seed_team(&pool, team_id, owner).await?;
+ enable_crm_for_team(&pool, team_id).await?;
+ let link_id = insert_email_link(&pool, owner, "[email protected]").await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+
+ // 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())
+ .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?;
+ let manual_contact = repo
+ .create_contact_for_company(
+ &team_id,
+ &derived_company,
+ "Jane",
+ Utc::now(),
+ false,
+ )
+ .await?;
+
+ repo.depopulate_link_in_team(&team_id, &link_id).await?;
+
+ // The populated contact (last source dropped) is gone; the manual
+ // contact keeps its company alive; the empty manual company also
+ // survives.
+ let listed = repo
+ .list_contacts_for_company(&team_id, &derived_company, false)
+ .await?;
+ assert_eq!(listed.len(), 1);
+ assert_eq!(listed[0].id, manual_contact.id);
+ assert_eq!(
+ count_companies_for_domain(&pool, team_id, "manual.com").await?,
+ 1
+ );
+ let _ = manual_company;
+ Ok(())
+}
diff --git a/crates/crm/src/outbound/search_repo.rs b/crates/crm/src/outbound/search_repo.rs
index a03be76268..c42c0f4a6c 100644
--- a/crates/crm/src/outbound/search_repo.rs
+++ b/crates/crm/src/outbound/search_repo.rs
@@ -71,17 +71,19 @@ impl CrmSearchRepository for CrmSearchRepositoryImpl {
let cursor_ts = cursor.map(|c| c.last_updated_at);
let cursor_id = cursor.map(|c| c.last_id);
- // Company names live in `crm_domain_directory` (keyed by domain),
- // not on `crm_companies` — so we match over both the domain string
- // and the directory name, and resolve the display name from the
- // company's primary (earliest-created) domain, mirroring
- // `list_companies_for_soup`. `$2` (hidden) defaults to visible-only
- // when NULL. The keyset guard ($7/$8) seeks past the previous page
- // under the `(updated_at DESC, id DESC)` sort; NULL = first page.
+ // Display names resolve as: the team-scoped
+ // `crm_companies.custom_name` override (manual creation) when
+ // set, otherwise the primary
+ // (earliest-created) domain's `crm_domain_directory` name,
+ // mirroring `list_companies_for_soup` — so we match over the
+ // override, the domain string, and the directory name. `$2`
+ // (hidden) defaults to visible-only when NULL. The keyset guard
+ // ($7/$8) seeks past the previous page under the
+ // `(updated_at DESC, id DESC)` sort; NULL = first page.
let rows = sqlx::query!(
r#"
WITH matched AS (
- SELECT c.id, c.last_interaction AS updated_at
+ SELECT c.id, c.custom_name, c.last_interaction AS updated_at
FROM crm_companies c
WHERE c.team_id = $1
AND (
@@ -89,13 +91,16 @@ impl CrmSearchRepository for CrmSearchRepositoryImpl {
OR (c.hidden = TRUE AND $2 = TRUE AND $9)
)
AND (cardinality($3::uuid[]) = 0 OR c.id = ANY($3))
- AND EXISTS (
- SELECT 1
- FROM crm_domains d
- LEFT JOIN crm_domain_directory dd
- ON LOWER(dd.domain) = LOWER(d.domain)
- WHERE d.company_id = c.id
- AND (d.domain ILIKE $4 OR dd.name ILIKE $4)
+ AND (
+ c.custom_name ILIKE $4
+ OR EXISTS (
+ SELECT 1
+ FROM crm_domains d
+ LEFT JOIN crm_domain_directory dd
+ ON LOWER(dd.domain) = LOWER(d.domain)
+ WHERE d.company_id = c.id
+ AND (d.domain ILIKE $4 OR dd.name ILIKE $4)
+ )
)
AND ($7::timestamptz IS NULL OR (c.last_interaction, c.id) < ($7, $8))
ORDER BY c.last_interaction DESC, c.id DESC
@@ -113,9 +118,9 @@ impl CrmSearchRepository for CrmSearchRepositoryImpl {
)
SELECT
m.id AS "id!",
- COALESCE(pd.display_name, '') AS "name!",
+ COALESCE(m.custom_name, pd.display_name, '') AS "name!",
regexp_replace(
- COALESCE(pd.display_name, ''),
+ COALESCE(m.custom_name, pd.display_name, ''),
$6, '<macro_em>\1</macro_em>', 'gi'
) AS "name_highlighted!",
m.updated_at AS "updated_at!"
@@ -175,7 +180,7 @@ impl CrmSearchRepository for CrmSearchRepositoryImpl {
d.id AS "domain_id?",
d.domain AS "domain?",
d.created_at AS "domain_created_at?",
- dd.name AS "dir_name?",
+ COALESCE(c.custom_name, dd.name) AS "display_name?",
dd.description AS "dir_description?"
FROM crm_companies c
LEFT JOIN crm_domains d ON d.company_id = c.id
@@ -210,7 +215,7 @@ impl CrmSearchRepository for CrmSearchRepositoryImpl {
updated_at: row.company_updated_at,
domains: Vec::new(),
},
- name: row.dir_name,
+ name: row.display_name,
description: row.dir_description,
// Search results aren't resolved against per-user view
// history; the soup listing path supplies viewed_at.
diff --git a/crates/macro_db_client/migrations/20260721185457_crm_company_name.sql b/crates/macro_db_client/migrations/20260721185457_crm_company_name.sql
new file mode 100644
index 0000000000..9481b5699e
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260721185457_crm_company_name.sql
@@ -0,0 +1,9 @@
+-- Team-scoped display-name override for manually created CRM companies.
+-- NULL means "resolve from crm_domain_directory" (the pre-existing
+-- behavior for backfill-created companies); reads COALESCE this column
+-- over the directory name. A `name` column existed originally and was
+-- dropped in 20260521120000_crm_domain_directory; this one is named
+-- custom_name to make the override semantics explicit — user-typed
+-- names must stay scoped to the owning team and cannot live in the
+-- global directory.
+ALTER TABLE crm_companies ADD COLUMN IF NOT EXISTS custom_name TEXT;
diff --git a/crates/macro_db_client/migrations/20260722132833_crm_manually_created.sql b/crates/macro_db_client/migrations/20260722132833_crm_manually_created.sql
new file mode 100644
index 0000000000..96c56a3034
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260722132833_crm_manually_created.sql
@@ -0,0 +1,7 @@
+-- Provenance marker for user-created CRM rows. The depopulate paths
+-- treat contacts without crm_contact_sources rows (and companies
+-- without contacts) as derived-data orphans and delete them on link
+-- teardown; manually created rows have no sources by construction and
+-- must survive that cleanup.
+ALTER TABLE crm_companies ADD COLUMN IF NOT EXISTS manually_created BOOLEAN NOT NULL DEFAULT FALSE;
+ALTER TABLE crm_contacts ADD COLUMN IF NOT EXISTS manually_created BOOLEAN NOT NULL DEFAULT FALSE;
diff --git a/services/document_storage_service/src/api/swagger.rs b/services/document_storage_service/src/api/swagger.rs
index b38d6c7ea3..0c59eedfb9 100644
--- a/services/document_storage_service/src/api/swagger.rs
+++ b/services/document_storage_service/src/api/swagger.rs
@@ -324,6 +324,8 @@ use utoipa::OpenApi;
crm::inbound::axum_router::list_company_contacts::handler,
crm::inbound::axum_router::get_contact::handler,
crm::inbound::axum_router::get_company::handler,
+ crm::inbound::axum_router::create_company::handler,
+ crm::inbound::axum_router::create_contact::handler,
crm::inbound::axum_router::comments::list_handler,
crm::inbound::axum_router::comments::create_handler,
crm::inbound::axum_router::comments::edit_handler,
@@ -605,6 +607,8 @@ use utoipa::OpenApi;
crm::inbound::axum_router::list_company_contacts::CrmContactResponse,
crm::inbound::axum_router::get_company::CrmCompanyResponse,
crm::inbound::axum_router::get_company::CrmDomainResponse,
+ crm::inbound::axum_router::create_company::CreateCrmCompanyRequest,
+ crm::inbound::axum_router::create_contact::CreateCrmContactRequest,
crm::inbound::axum_router::comments::CreateCrmCommentRequest,
crm::inbound::axum_router::comments::EditCrmCommentRequest,
crm::domain::comment::CrmCommentEntityType,