Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(crm): get_company endpoint + viewed_updated soup sort (#3746)
Evan Hutnik4d0643418b3d
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyResponse.ts b/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyResponse.tsnew file mode 100644index 0000000000..b7c17b5153--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyResponse.ts@@ -0,0 +1,47 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++import type { CrmCompanyResponseDescription } from './crmCompanyResponseDescription';+import type { CrmCompanyResponseName } from './crmCompanyResponseName';+import type { CrmContactResponse } from './crmContactResponse';+import type { CrmDomainResponse } from './crmDomainResponse';++/**+ * A CRM company as returned by `GET /crm/companies/{company_id}`.+Mirrors the soup-listed `crmCompany` shape (`name` / `description`+resolved from the primary domain's `crm_domain_directory` entry) and+embeds the company's contacts so the panel can render in a single+request.+ */+export interface CrmCompanyResponse {+ /** Contacts attached to this company. Hidden contacts are filtered+out for non-admin viewers. */+ contacts: CrmContactResponse[];+ /** Earliest known interaction with this company. */+ createdAt: string;+ /** Display description from the primary domain's directory entry. */+ description?: CrmCompanyResponseDescription;+ /** All domains associated with this company, ordered by creation+time ascending (primary first). */+ domains: CrmDomainResponse[];+ /** Whether email sync is enabled for this company. */+ emailSync: boolean;+ /** Whether the company is hidden from CRM listings for the+requesting team. Non-admin viewers never see `hidden = true`+rows (the endpoint 404s for them); admin/owner callers see+hidden companies so they can render the right toggle state. */+ hidden: boolean;+ /** The id of the company. */+ id: string;+ /** Display name from the primary domain's directory entry, or+`None` when unresolved. */+ name?: CrmCompanyResponseName;+ /** The id of the team that owns this company record. */+ teamId: string;+ /** Most recent known interaction with this company. */+ updatedAt: string;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyResponseDescription.ts b/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyResponseDescription.tsnew file mode 100644index 0000000000..5d0ada2a2d--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyResponseDescription.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Display description from the primary domain's directory entry.+ */+export type CrmCompanyResponseDescription = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyResponseName.ts b/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyResponseName.tsnew file mode 100644index 0000000000..93d7aba9d5--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyResponseName.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Display name from the primary domain's directory entry, or+`None` when unresolved.+ */+export type CrmCompanyResponseName = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/crmDomainResponse.ts b/js/app/packages/service-clients/service-storage/generated/schemas/crmDomainResponse.tsnew file mode 100644index 0000000000..913e590a51--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/crmDomainResponse.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * A CRM domain associated with a company.+ */+export interface CrmDomainResponse {+ /** The id of the company the domain belongs to. */+ companyId: string;+ /** When the domain record was created. */+ createdAt: string;+ /** The domain (e.g. "acme.com"). */+ domain: string;+ /** The id of the domain record. */+ id: string;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.tsindex 6de20572a7..571ca647f9 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts@@ -270,8 +270,12 @@ export * from './crmCommentSender';export * from './crmCommentThread';export * from './crmCompanyFilters';export * from './crmCompanyFiltersHidden';+export * from './crmCompanyResponse';+export * from './crmCompanyResponseDescription';+export * from './crmCompanyResponseName';export * from './crmContactResponse';export * from './crmContactResponseName';+export * from './crmDomainResponse';export * from './crmThread';export * from './crmThreadDeletedAt';export * from './customSpeakerAssignment';diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex 753c14baf9..decb4d81b6 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -2903,6 +2903,112 @@ export const createCrmCommentResponse = zod'A [`CrmThread`] with its comments nested under it — the unit the\nfrontend renders.');+/**+ * @summary Fetch a single CRM company by id, hydrated with its domains, the+primary domain's directory display metadata (name + description),+and the company's contacts. Access is enforced by+[`CrmCompanyAccessLevelExtractor`]: the user must be on the team+that owns the company, and hidden companies are invisible to plain+members. Admin/owner callers see hidden companies and contacts so+they can render the right unhide UI.+ */+export const getCompanyParams = zod.object({+ company_id: zod.uuid().describe('The CRM company to fetch'),+});++export const getCompanyResponse = 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 List the contacts of a CRM company. Access is enforced by[`CrmCompanyAccessLevelExtractor`]: the user must be on the team thatdiff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 16c5689cb7..738ba5ac78 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -3733,6 +3733,67 @@}}},+ "/crm/companies/{company_id}": {+ "get": {+ "tags": ["crm::inbound::axum_router::get_company"],+ "summary": "Fetch a single CRM company by id, hydrated with its domains, the\nprimary domain's directory display metadata (name + description),\nand the company's contacts. Access is enforced by\n[`CrmCompanyAccessLevelExtractor`]: the user must be on the team\nthat owns the company, and hidden companies are invisible to plain\nmembers. Admin/owner callers see hidden companies and contacts so\nthey can render the right unhide UI.",+ "operationId": "get_company",+ "parameters": [+ {+ "name": "company_id",+ "in": "path",+ "description": "The CRM company to fetch",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CrmCompanyResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/crm/companies/{company_id}/contacts": {"get": {"tags": ["crm::inbound::axum_router::list_company_contacts"],@@ -10931,6 +10992,72 @@}}},+ "CrmCompanyResponse": {+ "type": "object",+ "description": "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.",+ "required": [+ "id",+ "teamId",+ "emailSync",+ "hidden",+ "createdAt",+ "updatedAt",+ "domains",+ "contacts"+ ],+ "properties": {+ "contacts": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/CrmContactResponse"+ },+ "description": "Contacts attached to this company. Hidden contacts are filtered\nout for non-admin viewers."+ },+ "createdAt": {+ "type": "string",+ "format": "date-time",+ "description": "Earliest known interaction with this company."+ },+ "description": {+ "type": ["string", "null"],+ "description": "Display description from the primary domain's directory entry."+ },+ "domains": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/CrmDomainResponse"+ },+ "description": "All domains associated with this company, ordered by creation\ntime ascending (primary first)."+ },+ "emailSync": {+ "type": "boolean",+ "description": "Whether email sync is enabled for this company."+ },+ "hidden": {+ "type": "boolean",+ "description": "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": {+ "type": "string",+ "format": "uuid",+ "description": "The id of the company."+ },+ "name": {+ "type": ["string", "null"],+ "description": "Display name from the primary domain's directory entry, or\n`None` when unresolved."+ },+ "teamId": {+ "type": "string",+ "format": "uuid",+ "description": "The id of the team that owns this company record."+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time",+ "description": "Most recent known interaction with this company."+ }+ }+ },"CrmContactResponse": {"type": "object","description": "A CRM contact as returned by `GET /crm/companies/{company_id}/contacts`.",@@ -10989,6 +11116,32 @@}}},+ "CrmDomainResponse": {+ "type": "object",+ "description": "A CRM domain associated with a company.",+ "required": ["id", "companyId", "domain", "createdAt"],+ "properties": {+ "companyId": {+ "type": "string",+ "format": "uuid",+ "description": "The id of the company the domain belongs to."+ },+ "createdAt": {+ "type": "string",+ "format": "date-time",+ "description": "When the domain record was created."+ },+ "domain": {+ "type": "string",+ "description": "The domain (e.g. \"acme.com\")."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "The id of the domain record."+ }+ }+ },"CrmThread": {"type": "object","description": "A CRM comment thread: the parent record one or more comments hang off.",diff --git a/rust/cloud-storage/.sqlx/query-2b84b8b3f8249a00c5fdc077b6450804a38baa96682f5c6dc8bb95dddf25d037.json b/rust/cloud-storage/.sqlx/query-2b84b8b3f8249a00c5fdc077b6450804a38baa96682f5c6dc8bb95dddf25d037.jsondeleted file mode 100644index 93646d814b..0000000000--- a/rust/cloud-storage/.sqlx/query-2b84b8b3f8249a00c5fdc077b6450804a38baa96682f5c6dc8bb95dddf25d037.json+++ /dev/null@@ -1,40 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT id, company_id, domain, created_at\n FROM crm_domains\n WHERE company_id = $1\n ORDER BY created_at ASC\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "company_id",- "type_info": "Uuid"- },- {- "ordinal": 2,- "name": "domain",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "created_at",- "type_info": "Timestamptz"- }- ],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": [- false,- false,- false,- false- ]- },- "hash": "2b84b8b3f8249a00c5fdc077b6450804a38baa96682f5c6dc8bb95dddf25d037"-}diff --git a/rust/cloud-storage/.sqlx/query-3f084390f0f997762642796059a56b37dc19270a95b8e12e9e86d53824562037.json b/rust/cloud-storage/.sqlx/query-3f084390f0f997762642796059a56b37dc19270a95b8e12e9e86d53824562037.jsondeleted file mode 100644index bb4b2dee3f..0000000000--- a/rust/cloud-storage/.sqlx/query-3f084390f0f997762642796059a56b37dc19270a95b8e12e9e86d53824562037.json+++ /dev/null@@ -1,53 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT c.id, c.team_id, c.email_sync, c.hidden, c.created_at, c.updated_at\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"- },- {- "ordinal": 1,- "name": "team_id",- "type_info": "Uuid"- },- {- "ordinal": 2,- "name": "email_sync",- "type_info": "Bool"- },- {- "ordinal": 3,- "name": "hidden",- "type_info": "Bool"- },- {- "ordinal": 4,- "name": "created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 5,- "name": "updated_at",- "type_info": "Timestamptz"- }- ],- "parameters": {- "Left": [- "Uuid",- "Text"- ]- },- "nullable": [- false,- false,- false,- false,- false,- false- ]- },- "hash": "3f084390f0f997762642796059a56b37dc19270a95b8e12e9e86d53824562037"-}diff --git a/rust/cloud-storage/.sqlx/query-42a235c2075b26c57bb8da489f7bb3e128b612caacf68635ea29ec275cd14aae.json b/rust/cloud-storage/.sqlx/query-42a235c2075b26c57bb8da489f7bb3e128b612caacf68635ea29ec275cd14aae.jsonnew file mode 100644index 0000000000..10fa4557ee--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-42a235c2075b26c57bb8da489f7bb3e128b612caacf68635ea29ec275cd14aae.json@@ -0,0 +1,89 @@+{+ "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 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"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "UuidArray",+ "Int8",+ "Text",+ "Bool",+ "Timestamptz",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ true,+ true+ ]+ },+ "hash": "42a235c2075b26c57bb8da489f7bb3e128b612caacf68635ea29ec275cd14aae"+}diff --git a/rust/cloud-storage/.sqlx/query-694440e1141a1afea892f03c2397da3f899bd4ca4ad3adc60c1c7babcd39faad.json b/rust/cloud-storage/.sqlx/query-694440e1141a1afea892f03c2397da3f899bd4ca4ad3adc60c1c7babcd39faad.jsondeleted file mode 100644index fa83ca1fa5..0000000000--- a/rust/cloud-storage/.sqlx/query-694440e1141a1afea892f03c2397da3f899bd4ca4ad3adc60c1c7babcd39faad.json+++ /dev/null@@ -1,88 +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 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 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 ELSE c.last_interaction\n END DESC,\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 FROM limited_companies lc\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 ELSE lc.last_interaction\n END DESC,\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"- }- ],- "parameters": {- "Left": [- "Uuid",- "UuidArray",- "Int8",- "Text",- "Bool",- "Timestamptz",- "Text"- ]- },- "nullable": [- false,- false,- false,- false,- false,- false,- false,- false,- false,- true,- true- ]- },- "hash": "694440e1141a1afea892f03c2397da3f899bd4ca4ad3adc60c1c7babcd39faad"-}diff --git a/rust/cloud-storage/.sqlx/query-c7c058fd3acdc93e77a805b28b844150503f955a91339be026f8b68f65092adb.json b/rust/cloud-storage/.sqlx/query-c7c058fd3acdc93e77a805b28b844150503f955a91339be026f8b68f65092adb.jsonnew file mode 100644index 0000000000..b25657bb43--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-c7c058fd3acdc93e77a805b28b844150503f955a91339be026f8b68f65092adb.json@@ -0,0 +1,84 @@+{+ "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 ",+ "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"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Bool"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ true,+ true+ ]+ },+ "hash": "c7c058fd3acdc93e77a805b28b844150503f955a91339be026f8b68f65092adb"+}diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rsindex 102fe09bf0..7cd169fa49 100644--- a/rust/cloud-storage/ai_tools/src/tool_context.rs+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs@@ -41,10 +41,10 @@ pub type ToolFrecencyService = frecency::domain::services::FrecencyQueryServiceI/// Type alias for the CRM service implementation used by tools.///-/// Tools only read CRM rows (e.g. `get_company_by_domain`); the populate-/// path runs in the email-service pubsub worker. The no-op resolver-/// keeps reqwest/scraper out of the tool binary at the cost of a silent-/// negative cache if populate is ever invoked here.+/// Tools only read CRM rows; the populate path runs in the email-service+/// pubsub worker. The no-op resolver keeps reqwest/scraper out of the+/// tool binary at the cost of a silent negative cache if populate is+/// ever invoked here.pub type ToolCrmService = crm::domain::service::CrmServiceImpl<crm::outbound::companies_repo::CompaniesRepositoryImpl,crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,diff --git a/rust/cloud-storage/crm/src/domain/companies_repo.rs b/rust/cloud-storage/crm/src/domain/companies_repo.rsindex 03c463d4c5..e9a1da402a 100644--- a/rust/cloud-storage/crm/src/domain/companies_repo.rs+++ b/rust/cloud-storage/crm/src/domain/companies_repo.rs@@ -4,19 +4,31 @@ use crate::domain::comment::{CrmComment, CrmCommentEntityType, CrmCommentThread, DeleteCrmCommentResult,};use crate::domain::model::{- CrmCompany, CrmCompanyForSoup, CrmContact, CrmError, CrmScopePrecheck, DomainMetadata,+ CrmCompanyForSoup, CrmCompanyWithContacts, CrmContact, CrmError, CrmScopePrecheck,+ DomainMetadata,};use chrono::{DateTime, Utc};use serde_json::Value;-/// Sort order for [`CompaniesRepository::list_companies_for_soup`].-/// Both variants tiebreak on `id DESC` for deterministic pagination.+/// Sort order for [`CompaniesRepository::list_companies_for_soup`]. All+/// variants tiebreak on `id DESC` for deterministic pagination. The two+/// `Viewed*` variants require a `user_id` (the `UserHistory` join is+/// per-user); rows the user has never opened sort to NULL (`ViewedAt`+/// drops them to the bottom; `ViewedUpdated` falls back to+/// `last_interaction`).#[derive(Debug, Clone, Copy)]pub enum CrmCompanyListSort {/// Sort by `crm_companies.last_interaction` DESC.UpdatedAt,/// Sort by `crm_companies.first_interaction` DESC.CreatedAt,+ /// Sort by the user's `UserHistory."updatedAt"` DESC (when this user+ /// last opened the company). Unviewed rows sort to NULL (bottom).+ ViewedAt,+ /// Sort by `COALESCE(UserHistory."updatedAt", last_interaction)` DESC+ /// — recently viewed bubble up, with a graceful fallback to+ /// activity recency for unviewed rows.+ ViewedUpdated,}/// Keyset cursor for [`CompaniesRepository::list_companies_for_soup`].@@ -24,8 +36,11 @@ pub enum CrmCompanyListSort {/// so the next page seeks strictly past it. `None` = first page.#[derive(Debug, Clone, Copy)]pub struct CrmCompanySoupCursor {- /// Sort timestamp of the previous page's last row —- /// `first_interaction`/`last_interaction` per [`CrmCompanyListSort`].+ /// Sort timestamp of the previous page's last row, expressed in the+ /// sort method's units: `first_interaction` for `CreatedAt`,+ /// `last_interaction` for `UpdatedAt`, `UserHistory."updatedAt"` for+ /// `ViewedAt`, and `COALESCE(uh."updatedAt", last_interaction)` for+ /// `ViewedUpdated`.pub last_sort_ts: DateTime<Utc>,/// Id of the previous page's last row; tiebreaks equal timestamps.pub last_id: uuid::Uuid,@@ -34,16 +49,6 @@ pub struct CrmCompanySoupCursor {/// The CompaniesRepository defines persistence operations for CRM/// companies and their associated domains.pub trait CompaniesRepository: Clone + Send + Sync + 'static {- /// Fetches the company for the given team that has `domain` registered- /// against it, hydrated with the full list of domains belonging to that- /// company. Returns `Ok(None)` when no company in the team has the- /// domain registered. Domain matching is case-insensitive.- fn get_company_by_domain(- &self,- team_id: &uuid::Uuid,- domain: &str,- ) -> impl Future<Output = Result<Option<CrmCompany>, CrmError>> + Send;-/// Idempotently records that `email` (which lives on `domain`) was seen/// from the mailbox identified by `link_id`, for the team `team_id`./// Performs the company/domain/contact/contact_source upserts in a single@@ -327,10 +332,18 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {/// this method (soup's axum router does this). Empty `company_ids`/// = all rows matching the `hidden` filter; non-empty = whitelist./// `cursor` seeks strictly past the previous soup page's last row- /// (`None` = first page). Both sort orders tiebreak on `id DESC`.+ /// (`None` = first page). All sort orders tiebreak on `id DESC`.+ ///+ /// `user_id` scopes the per-user `UserHistory` join used by the+ /// `Viewed*` sort variants. Pass the requesting user's id verbatim+ /// (as stored in `team_user.user_id` / `UserHistory."userId"`);+ /// internal callers without a user can pass an empty string —+ /// `Viewed*` sorts then collapse to NULL (no viewed-at signal).+ #[allow(clippy::too_many_arguments)]fn list_companies_for_soup(&self,team_id: &uuid::Uuid,+ user_id: &str,company_ids: &[uuid::Uuid],hidden: Option<bool>,sort: CrmCompanyListSort,@@ -370,6 +383,23 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {include_hidden: bool,) -> impl Future<Output = Result<Option<CrmContact>, CrmError>> + Send;+ /// Fetches a single CRM company by id, scoped to `team_id`,+ /// hydrated with all domains (ordered by `created_at ASC` —+ /// primary first), the primary domain's `crm_domain_directory`+ /// display metadata (name + description), and the company's full+ /// contact list (subject to `include_hidden`). Returns `Ok(None)`+ /// when the company doesn't exist, belongs to a different team,+ /// or — for non-admin viewers (`include_hidden = false`) — the+ /// company is hidden. With `include_hidden = true` (admin/owner)+ /// every owned company is reachable. The handler converts `None`+ /// into a 404 [`CrmError::CompanyNotFoundForTeam`].+ fn get_company_for_team(+ &self,+ team_id: &uuid::Uuid,+ company_id: &uuid::Uuid,+ include_hidden: bool,+ ) -> impl Future<Output = Result<Option<CrmCompanyWithContacts>, CrmError>> + Send;+/// Create a CRM comment. With `thread_id = None` a new thread is opened/// on `(entity_type, entity_id)` and the comment becomes its root; with/// `Some`, the comment is appended to that existing thread (whosediff --git a/rust/cloud-storage/crm/src/domain/model.rs b/rust/cloud-storage/crm/src/domain/model.rsindex 4acbc6ed3a..1e3f6cebc8 100644--- a/rust/cloud-storage/crm/src/domain/model.rs+++ b/rust/cloud-storage/crm/src/domain/model.rs@@ -17,6 +17,24 @@ pub struct CrmCompanyForSoup {pub description: Option<String>,}+/// A [`CrmCompany`] bundled with its directory display metadata+/// (same as [`CrmCompanyForSoup`]) plus its full contact list — the+/// shape returned by `GET /crm/companies/{company_id}`. Lets the FE+/// hydrate the company panel in a single round trip instead of+/// composing a soup call with a follow-up contacts call.+#[derive(Debug, Clone)]+pub struct CrmCompanyWithContacts {+ /// The underlying company record (with domains pre-populated).+ pub company: CrmCompany,+ /// Display name from the primary domain's directory entry.+ pub name: Option<String>,+ /// Display description from the primary domain's directory entry.+ pub description: Option<String>,+ /// Contacts attached to this company, subject to the caller's+ /// `include_hidden` flag (non-admins get only visible contacts).+ pub contacts: Vec<CrmContact>,+}+/// A known external company tracked by a team (CRM-style record). A company/// aggregates one or more email domains and individual contacts that are/// considered to belong to the same external party.diff --git a/rust/cloud-storage/crm/src/domain/service.rs b/rust/cloud-storage/crm/src/domain/service.rsindex 4cc9a4b49a..abc51f576a 100644--- a/rust/cloud-storage/crm/src/domain/service.rs+++ b/rust/cloud-storage/crm/src/domain/service.rs@@ -5,7 +5,7 @@ use crate::domain::{companies_repo::{CompaniesRepository, CrmCompanyListSort, CrmCompanySoupCursor},company_metadata_resolver::CompanyMetadataResolver,generic_email_domains::is_generic_email_domain,- model::{CrmCompany, CrmCompanyForSoup, CrmContact, CrmError, CrmScopePrecheck},+ model::{CrmCompanyForSoup, CrmCompanyWithContacts, CrmContact, CrmError, CrmScopePrecheck},};use chrono::{DateTime, Utc};use serde_json::Value;@@ -13,15 +13,6 @@ use serde_json::Value;/// The CrmService exposes operations over CRM records (companies, their/// domains and contacts).pub trait CrmService: Clone + Send + Sync + 'static {- /// Fetches the company for the given team that has `domain` registered- /// against it, hydrated with all of the company's domains. Returns- /// `Ok(None)` when no company in the team has that domain.- fn get_company_by_domain(- &self,- team_id: &uuid::Uuid,- domain: &str,- ) -> impl Future<Output = Result<Option<CrmCompany>, CrmError>> + Send;-/// Idempotently records that `email` was seen from the mailbox/// identified by `link_id`, for the team `team_id`. Upserts/// `crm_companies` (+ `crm_domains`), `crm_contacts`, and@@ -183,11 +174,15 @@ pub trait CrmService: Clone + Send + Sync + 'static {addresses: &[String],) -> impl Future<Output = Result<CrmScopePrecheck, CrmError>> + Send;- /// List the team's CRM companies for the soup feed. See+ /// List the team's CRM companies for the soup feed. `user_id` is+ /// required by the `Viewed*` sort variants (per-user+ /// `UserHistory` join); see/// [`CompaniesRepository::list_companies_for_soup`].+ #[allow(clippy::too_many_arguments)]fn list_companies_for_soup(&self,team_id: &uuid::Uuid,+ user_id: &str,company_ids: &[uuid::Uuid],hidden: Option<bool>,sort: CrmCompanyListSort,@@ -220,6 +215,19 @@ pub trait CrmService: Clone + Send + Sync + 'static {include_hidden: bool,) -> impl Future<Output = Result<Option<CrmContact>, CrmError>> + Send;+ /// Fetch a single CRM company by id, scoped to `team_id`, hydrated+ /// with all domains, the primary domain's directory metadata, and+ /// the company's full contact list. `include_hidden = false` hides+ /// companies whose `hidden` flag is set and filters hidden contacts;+ /// `true` (admin/owner) reveals every owned company and contact.+ /// See [`CompaniesRepository::get_company_for_team`].+ fn get_company_for_team(+ &self,+ team_id: &uuid::Uuid,+ company_id: &uuid::Uuid,+ include_hidden: bool,+ ) -> impl Future<Output = Result<Option<CrmCompanyWithContacts>, CrmError>> + Send;+/// Create a comment on a CRM company or contact, optionally as a reply/// to an existing thread. See/// [`CompaniesRepository::create_crm_comment`]. Authorization (team@@ -332,17 +340,6 @@ whereCR: CompaniesRepository,R: CompanyMetadataResolver,{- #[tracing::instrument(skip(self), err)]- async fn get_company_by_domain(- &self,- team_id: &uuid::Uuid,- domain: &str,- ) -> Result<Option<CrmCompany>, CrmError> {- self.companies_repository- .get_company_by_domain(team_id, domain)- .await- }-#[tracing::instrument(skip(self), err)]#[allow(clippy::too_many_arguments)]async fn populate_contact(@@ -530,9 +527,11 @@ where}#[tracing::instrument(skip(self), err)]+ #[allow(clippy::too_many_arguments)]async fn list_companies_for_soup(&self,team_id: &uuid::Uuid,+ user_id: &str,company_ids: &[uuid::Uuid],hidden: Option<bool>,sort: CrmCompanyListSort,@@ -540,7 +539,7 @@ wherelimit: i64,) -> Result<Vec<CrmCompanyForSoup>, CrmError> {self.companies_repository- .list_companies_for_soup(team_id, company_ids, hidden, sort, cursor, limit)+ .list_companies_for_soup(team_id, user_id, company_ids, hidden, sort, cursor, limit).await}@@ -568,6 +567,18 @@ where.await}+ #[tracing::instrument(skip(self), err)]+ async fn get_company_for_team(+ &self,+ team_id: &uuid::Uuid,+ company_id: &uuid::Uuid,+ include_hidden: bool,+ ) -> Result<Option<CrmCompanyWithContacts>, CrmError> {+ self.companies_repository+ .get_company_for_team(team_id, company_id, include_hidden)+ .await+ }+#[tracing::instrument(skip(self, thread_metadata, text, metadata), err)]#[allow(clippy::too_many_arguments)]async fn create_crm_comment(@@ -654,14 +665,6 @@ wherepub struct NoOpCrmService;impl CrmService for NoOpCrmService {- async fn get_company_by_domain(- &self,- _team_id: &uuid::Uuid,- _domain: &str,- ) -> Result<Option<CrmCompany>, CrmError> {- unimplemented!("NoOpCrmService.get_company_by_domain")- }-async fn populate_contact(&self,_team_id: &uuid::Uuid,@@ -733,9 +736,11 @@ impl CrmService for NoOpCrmService {unimplemented!("NoOpCrmService.crm_scope_precheck")}+ #[allow(clippy::too_many_arguments)]async fn list_companies_for_soup(&self,_team_id: &uuid::Uuid,+ _user_id: &str,_company_ids: &[uuid::Uuid],_hidden: Option<bool>,_sort: CrmCompanyListSort,@@ -763,6 +768,15 @@ impl CrmService for NoOpCrmService {Ok(None)}+ async fn get_company_for_team(+ &self,+ _team_id: &uuid::Uuid,+ _company_id: &uuid::Uuid,+ _include_hidden: bool,+ ) -> Result<Option<CrmCompanyWithContacts>, CrmError> {+ Ok(None)+ }+#[allow(clippy::too_many_arguments)]async fn create_crm_comment(&self,diff --git a/rust/cloud-storage/crm/src/inbound/axum_router/get_company.rs b/rust/cloud-storage/crm/src/inbound/axum_router/get_company.rsnew file mode 100644index 0000000000..a6085b587d--- /dev/null+++ b/rust/cloud-storage/crm/src/inbound/axum_router/get_company.rs@@ -0,0 +1,148 @@+use axum::{+ Json,+ extract::{Path, State},+};+use chrono::{DateTime, Utc};+use entity_access::{+ domain::{+ models::{AccessLevel, ViewAccessLevel},+ ports::EntityAccessService,+ },+ inbound::axum_extractors::CrmCompanyAccessLevelExtractor,+};+use model_error_response::ErrorResponse;+use serde::Serialize;+use utoipa::ToSchema;+use uuid::Uuid;++use crate::domain::{+ model::{CrmCompanyWithContacts, CrmDomain, CrmError},+ service::CrmService,+};++use super::{CrmRouterState, list_company_contacts::CrmContactResponse};++/// A CRM domain associated with a company.+#[derive(Debug, Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct CrmDomainResponse {+ /// The id of the domain record.+ pub id: Uuid,+ /// The id of the company the domain belongs to.+ pub company_id: Uuid,+ /// The domain (e.g. "acme.com").+ pub domain: String,+ /// When the domain record was created.+ pub created_at: DateTime<Utc>,+}++impl From<CrmDomain> for CrmDomainResponse {+ fn from(d: CrmDomain) -> Self {+ Self {+ id: d.id,+ company_id: d.company_id,+ domain: d.domain,+ created_at: d.created_at,+ }+ }+}++/// A CRM company as returned by `GET /crm/companies/{company_id}`.+/// Mirrors the soup-listed `crmCompany` shape (`name` / `description`+/// resolved from the primary domain's `crm_domain_directory` entry) and+/// embeds the company's contacts so the panel can render in a single+/// request.+#[derive(Debug, Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct CrmCompanyResponse {+ /// The id of the company.+ pub id: Uuid,+ /// The id of the team that owns this company record.+ pub team_id: Uuid,+ /// Display name from the primary domain's directory entry, or+ /// `None` when unresolved.+ pub name: Option<String>,+ /// Display description from the primary domain's directory entry.+ pub description: Option<String>,+ /// Whether email sync is enabled for this company.+ pub email_sync: bool,+ /// Whether the company is hidden from CRM listings for the+ /// requesting team. Non-admin viewers never see `hidden = true`+ /// rows (the endpoint 404s for them); admin/owner callers see+ /// hidden companies so they can render the right toggle state.+ pub hidden: bool,+ /// Earliest known interaction with this company.+ pub created_at: DateTime<Utc>,+ /// Most recent known interaction with this company.+ pub updated_at: DateTime<Utc>,+ /// All domains associated with this company, ordered by creation+ /// time ascending (primary first).+ pub domains: Vec<CrmDomainResponse>,+ /// Contacts attached to this company. Hidden contacts are filtered+ /// out for non-admin viewers.+ pub contacts: Vec<CrmContactResponse>,+}++impl From<CrmCompanyWithContacts> for CrmCompanyResponse {+ fn from(record: CrmCompanyWithContacts) -> Self {+ let CrmCompanyWithContacts {+ company,+ name,+ description,+ contacts,+ } = record;+ Self {+ id: company.id,+ team_id: company.team_id,+ name,+ description,+ email_sync: company.email_sync,+ hidden: company.hidden,+ created_at: company.created_at,+ updated_at: company.updated_at,+ domains: company.domains.into_iter().map(Into::into).collect(),+ contacts: contacts.into_iter().map(Into::into).collect(),+ }+ }+}++/// Fetch a single CRM company by id, hydrated with its domains, the+/// primary domain's directory display metadata (name + description),+/// and the company's contacts. Access is enforced by+/// [`CrmCompanyAccessLevelExtractor`]: the user must be on the team+/// that owns the company, and hidden companies are invisible to plain+/// members. Admin/owner callers see hidden companies and contacts so+/// they can render the right unhide UI.+#[utoipa::path(+ get,+ path = "/crm/companies/{company_id}",+ operation_id = "get_company",+ params(+ ("company_id" = Uuid, Path, description = "The CRM company to fetch"),+ ),+ responses(+ (status = 200, body = CrmCompanyResponse),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ ),+)]+#[tracing::instrument(skip_all, err, fields(company_id = %company_id))]+pub async fn handler<C: CrmService, Eas: EntityAccessService>(+ access: CrmCompanyAccessLevelExtractor<ViewAccessLevel, Eas>,+ State(state): State<CrmRouterState<C, Eas>>,+ Path(company_id): Path<Uuid>,+) -> Result<Json<CrmCompanyResponse>, CrmError> {+ let include_hidden = access+ .entity_access_receipt+ .entity_permission()+ .allows_access_level(AccessLevel::Edit);++ let record = state+ .service+ .get_company_for_team(&access.team_id, &company_id, include_hidden)+ .await?+ .ok_or(CrmError::CompanyNotFoundForTeam)?;++ Ok(Json(record.into()))+}diff --git a/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs b/rust/cloud-storage/crm/src/inbound/axum_router/mod.rsindex c6b52f0643..6bb915de3b 100644--- a/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs+++ b/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs@@ -9,12 +9,17 @@ pub mod set_company_hidden;/// Toggle the `hidden` flag on a `crm_contacts` row.pub mod set_contact_hidden;-/// List the non-hidden contacts of a `crm_companies` row.+/// List contacts of a `crm_companies` row. Role-aware: members see+/// visible contacts only; admin/owner see hidden contacts too.pub mod list_company_contacts;-/// Fetch a single non-hidden CRM contact by id.+/// Fetch a single CRM contact by id. Role-aware: members 404 on hidden+/// rows; admin/owner reach hidden contacts (and hidden parent companies).pub mod get_contact;+/// Fetch a single CRM company by id, hydrated with domains and contacts.+pub mod get_company;+/// Comment threads on a `crm_companies` / `crm_contacts` row.pub mod comments;@@ -93,6 +98,10 @@ where"/companies/{company_id}/hidden",put(set_company_hidden::handler::<C, Eas>),)+ .route(+ "/companies/{company_id}",+ get(get_company::handler::<C, Eas>),+ ).route("/companies/{company_id}/contacts",get(list_company_contacts::handler::<C, Eas>),diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo.rs b/rust/cloud-storage/crm/src/outbound/companies_repo.rsindex bf35fecd58..fb808f11b9 100644--- a/rust/cloud-storage/crm/src/outbound/companies_repo.rs+++ b/rust/cloud-storage/crm/src/outbound/companies_repo.rs@@ -9,8 +9,8 @@ use crate::domain::{},companies_repo::{CompaniesRepository, CrmCompanyListSort, CrmCompanySoupCursor},model::{- CrmAddressStatus, CrmCompany, CrmCompanyForSoup, CrmContact, CrmDomain, CrmDomainStatus,- CrmError, CrmScopePrecheck, DomainMetadata,+ CrmAddressStatus, CrmCompany, CrmCompanyForSoup, CrmCompanyWithContacts, CrmContact,+ CrmDomain, CrmDomainStatus, CrmError, CrmScopePrecheck, DomainMetadata,},};use chrono::{DateTime, Utc};@@ -69,66 +69,6 @@ impl CompaniesRepositoryImpl {}impl CompaniesRepository for CompaniesRepositoryImpl {- #[tracing::instrument(skip(self), err)]- async fn get_company_by_domain(- &self,- team_id: &uuid::Uuid,- domain: &str,- ) -> Result<Option<CrmCompany>, CrmError> {- let normalized_domain = domain.to_ascii_lowercase();-- let company = sqlx::query!(- r#"- SELECT c.id, c.team_id, c.email_sync, c.hidden, c.created_at, c.updated_at- 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(&self.pool)- .await- .map_err(|e| CrmError::StorageLayerError(e.into()))?;-- let Some(company) = company else {- return Ok(None);- };-- let domains = sqlx::query!(- r#"- SELECT id, company_id, domain, created_at- FROM crm_domains- WHERE company_id = $1- ORDER BY created_at ASC- "#,- company.id,- )- .fetch_all(&self.pool)- .await- .map_err(|e| CrmError::StorageLayerError(e.into()))?- .into_iter()- .map(|row| CrmDomain {- id: row.id,- company_id: row.company_id,- domain: row.domain,- created_at: row.created_at,- })- .collect();-- Ok(Some(CrmCompany {- id: company.id,- team_id: company.team_id,- email_sync: company.email_sync,- hidden: company.hidden,- created_at: company.created_at,- updated_at: company.updated_at,- domains,- }))- }-#[tracing::instrument(skip(self), err)]#[allow(clippy::too_many_arguments)]async fn populate_contact(@@ -1068,9 +1008,11 @@ impl CompaniesRepository for CompaniesRepositoryImpl {}#[tracing::instrument(skip(self), err)]+ #[allow(clippy::too_many_arguments)]async fn list_companies_for_soup(&self,team_id: &uuid::Uuid,+ user_id: &str,company_ids: &[uuid::Uuid],hidden: Option<bool>,sort: CrmCompanyListSort,@@ -1080,6 +1022,8 @@ impl CompaniesRepository for CompaniesRepositoryImpl {let sort_method_str = match sort {CrmCompanyListSort::UpdatedAt => "updated_at",CrmCompanyListSort::CreatedAt => "created_at",+ CrmCompanyListSort::ViewedAt => "viewed_at",+ CrmCompanyListSort::ViewedUpdated => "viewed_updated",};// Keyset seek past the previous soup page's last row. Compared as// (sort_ts, id::text) to match the main soup query's tiebreak in@@ -1092,7 +1036,10 @@ impl CompaniesRepository for CompaniesRepositoryImpl {// so rows arrive contiguous per company with the primary// domain first. Sort columns are `first_interaction` /// `last_interaction` from populate_contact (both NOT NULL —- // see the `crm_interaction_timestamps` migration).+ // see the `crm_interaction_timestamps` migration). `Viewed*`+ // variants join `UserHistory` per-user — same shape as the+ // soup repo's `viewed_at` / `viewed_updated` sorts for+ // docs/chats/projects (see pg_soup_repo/expanded/by_cursor.rs).//// `$5` (`hidden`) defaults to visible-only when `NULL`; the// admin/owner role check for `Some(true)` is enforced upstream@@ -1108,6 +1055,10 @@ impl CompaniesRepository for CompaniesRepositoryImpl {c.first_interaction,c.last_interactionFROM crm_companies c+ LEFT JOIN "UserHistory" uh+ ON uh."itemId" = c.id::text+ AND uh."itemType" = 'crm_company'+ AND uh."userId" = $8WHERE c.team_id = $1AND c.hidden = COALESCE($5::bool, FALSE)AND EXISTS (@@ -1122,6 +1073,9 @@ impl CompaniesRepository for CompaniesRepositoryImpl {OR (CASE $4WHEN 'created_at' THEN c.first_interaction+ WHEN 'viewed_at' THEN uh."updatedAt"+ WHEN 'viewed_updated'+ THEN COALESCE(uh."updatedAt", c.last_interaction)ELSE c.last_interactionEND,c.id::text@@ -1130,8 +1084,11 @@ impl CompaniesRepository for CompaniesRepositoryImpl {ORDER BYCASE $4WHEN 'created_at' THEN c.first_interaction+ WHEN 'viewed_at' THEN uh."updatedAt"+ WHEN 'viewed_updated'+ THEN COALESCE(uh."updatedAt", c.last_interaction)ELSE c.last_interaction- END DESC,+ END DESC NULLS LAST,c.id DESCLIMIT $3)@@ -1148,14 +1105,21 @@ impl CompaniesRepository for CompaniesRepositoryImpl {dd.name AS "dir_name?",dd.description AS "dir_description?"FROM limited_companies lc+ LEFT JOIN "UserHistory" uh+ ON uh."itemId" = lc.id::text+ AND uh."itemType" = 'crm_company'+ AND uh."userId" = $8LEFT JOIN crm_domains d ON d.company_id = lc.idLEFT JOIN crm_domain_directory ddON LOWER(dd.domain) = LOWER(d.domain)ORDER BYCASE $4WHEN 'created_at' THEN lc.first_interaction+ WHEN 'viewed_at' THEN uh."updatedAt"+ WHEN 'viewed_updated'+ THEN COALESCE(uh."updatedAt", lc.last_interaction)ELSE lc.last_interaction- END DESC,+ END DESC NULLS LAST,lc.id DESC,d.created_at ASC NULLS LAST"#,@@ -1166,6 +1130,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {hidden,cursor_ts,cursor_id,+ user_id,).fetch_all(&self.pool).await@@ -1335,6 +1300,100 @@ impl CompaniesRepository for CompaniesRepositoryImpl {}))}+ #[tracing::instrument(skip(self), err)]+ async fn get_company_for_team(+ &self,+ team_id: &uuid::Uuid,+ company_id: &uuid::Uuid,+ include_hidden: bool,+ ) -> Result<Option<CrmCompanyWithContacts>, CrmError> {+ // Mirrors `list_companies_for_soup`'s domain + directory join shape+ // but scoped to a single id. Domains arrive ordered by their+ // `created_at` so the first row carries the "primary" domain and+ // its `crm_domain_directory` row contributes name/description.+ // First-interaction / last-interaction are aliased into the+ // CrmCompany.created_at / updated_at slots — same convention as+ // the soup listing.+ let rows = sqlx::query!(+ r#"+ SELECT+ c.id AS "company_id!",+ c.team_id AS "company_team_id!",+ c.email_sync AS "company_email_sync!",+ c.hidden AS "company_hidden!",+ c.first_interaction AS "company_created_at!",+ c.last_interaction AS "company_updated_at!",+ d.id AS "domain_id?",+ d.domain AS "domain?",+ d.created_at AS "domain_created_at?",+ dd.name AS "dir_name?",+ dd.description AS "dir_description?"+ FROM crm_companies c+ LEFT JOIN crm_domains d ON d.company_id = c.id+ LEFT JOIN crm_domain_directory dd+ ON LOWER(dd.domain) = LOWER(d.domain)+ WHERE c.id = $1+ AND c.team_id = $2+ AND ($3 OR c.hidden = FALSE)+ ORDER BY d.created_at ASC NULLS LAST+ "#,+ company_id,+ team_id,+ include_hidden,+ )+ .fetch_all(&self.pool)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ let mut iter = rows.into_iter();+ let Some(first) = iter.next() else {+ 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();+ let description = first.dir_description.clone();++ let mut company = CrmCompany {+ id: first.company_id,+ team_id: first.company_team_id,+ email_sync: first.company_email_sync,+ hidden: first.company_hidden,+ created_at: first.company_created_at,+ updated_at: first.company_updated_at,+ domains: Vec::new(),+ };++ for row in std::iter::once(first).chain(iter) {+ if let (Some(id), Some(domain), Some(created_at)) =+ (row.domain_id, row.domain, row.domain_created_at)+ {+ company.domains.push(CrmDomain {+ id,+ company_id: company.id,+ domain,+ created_at,+ });+ }+ }++ // Fetch contacts via the existing list method so the hidden+ // semantics stay in one place. Issued only after the company+ // resolves so cross-team or hidden 404s short-circuit before+ // a second round trip.+ let contacts = self+ .list_contacts_for_company(team_id, company_id, include_hidden)+ .await?;++ Ok(Some(CrmCompanyWithContacts {+ company,+ name,+ description,+ contacts,+ }))+ }+#[tracing::instrument(skip(self, thread_metadata, text, metadata), err, fields(entity_id = %entity_id))]#[allow(clippy::too_many_arguments)]async fn create_crm_comment(diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs b/rust/cloud-storage/crm/src/outbound/companies_repo/test.rsindex 49ed520139..463cb2ee93 100644--- a/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs@@ -1,3280 +1,17 @@-use super::*;-use crate::domain::comment::CrmCommentEntityType;-use crate::domain::service::{CrmService, CrmServiceImpl};-use crate::outbound::no_op_resolver::NoOpCompanyMetadataResolver;-use macro_db_migrator::MACRO_DB_MIGRATIONS;-use sqlx::PgPool;-use uuid::Uuid;--async fn seed_team(pool: &PgPool, team_id: Uuid, owner_id: &str) -> sqlx::Result<()> {- let macro_user_id = Uuid::now_v7();-- sqlx::query(- r#"INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, $2, $3, $4)"#,- )- .bind(macro_user_id)- .bind(owner_id)- .bind(format!("{owner_id}@test.com"))- .bind(format!("stripe_{macro_user_id}"))- .execute(pool)- .await?;-- sqlx::query(r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $2, $3)"#)- .bind(owner_id)- .bind(format!("{owner_id}@test.com"))- .bind(macro_user_id)- .execute(pool)- .await?;-- sqlx::query(r#"INSERT INTO team (id, name, owner_id) VALUES ($1, $2, $3)"#)- .bind(team_id)- .bind("test team")- .bind(owner_id)- .execute(pool)- .await?;-- Ok(())-}--async fn insert_company(- pool: &PgPool,- team_id: Uuid,- email_sync: bool,- domains: &[&str],-) -> sqlx::Result<Uuid> {- let company_id = Uuid::now_v7();-- sqlx::query(- r#"INSERT INTO crm_companies (id, team_id, email_sync, first_interaction, last_interaction)- VALUES ($1, $2, $3, now(), now())"#,- )- .bind(company_id)- .bind(team_id)- .bind(email_sync)- .execute(pool)- .await?;-- for domain in domains {- sqlx::query(r#"INSERT INTO crm_domains (company_id, team_id, domain) VALUES ($1, $2, $3)"#)- .bind(company_id)- .bind(team_id)- .bind(*domain)- .execute(pool)- .await?;- }-- Ok(company_id)-}--async fn insert_email_link(pool: &PgPool, owner_id: &str, email: &str) -> sqlx::Result<Uuid> {- let link_id = Uuid::now_v7();- sqlx::query(- r#"INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider)- VALUES ($1, $2, $3, $4, 'GMAIL')"#,- )- .bind(link_id)- .bind(owner_id)- .bind(format!("fa_{link_id}"))- .bind(email)- .execute(pool)- .await?;- Ok(link_id)-}--async fn insert_contact_with_source(- pool: &PgPool,- company_id: Uuid,- email: &str,- link_id: Uuid,-) -> sqlx::Result<Uuid> {- let contact_id = Uuid::now_v7();- sqlx::query(- r#"INSERT INTO crm_contacts (id, company_id, email, first_interaction, last_interaction)- VALUES ($1, $2, $3, now(), now())"#,- )- .bind(contact_id)- .bind(company_id)- .bind(email)- .execute(pool)- .await?;- sqlx::query(r#"INSERT INTO crm_contact_sources (contact_id, link_id) VALUES ($1, $2)"#)- .bind(contact_id)- .bind(link_id)- .execute(pool)- .await?;- Ok(contact_id)-}--async fn count_contacts(pool: &PgPool, company_id: Uuid) -> sqlx::Result<i64> {- let (count,): (i64,) =- sqlx::query_as(r#"SELECT COUNT(*) FROM crm_contacts WHERE company_id = $1"#)- .bind(company_id)- .fetch_one(pool)- .await?;- Ok(count)-}--async fn count_sources_for_company(pool: &PgPool, company_id: Uuid) -> sqlx::Result<i64> {- let (count,): (i64,) = sqlx::query_as(- r#"SELECT COUNT(*) FROM crm_contact_sources cs- JOIN crm_contacts ct ON ct.id = cs.contact_id- WHERE ct.company_id = $1"#,- )- .bind(company_id)- .fetch_one(pool)- .await?;- Ok(count)-}--async fn fetch_email_sync(pool: &PgPool, company_id: Uuid) -> sqlx::Result<Option<bool>> {- let row: Option<(bool,)> =- sqlx::query_as(r#"SELECT email_sync FROM crm_companies WHERE id = $1"#)- .bind(company_id)- .fetch_optional(pool)- .await?;- Ok(row.map(|(s,)| s))-}--async fn fetch_company_hidden(pool: &PgPool, company_id: Uuid) -> sqlx::Result<Option<bool>> {- let row: Option<(bool,)> = sqlx::query_as(r#"SELECT hidden FROM crm_companies WHERE id = $1"#)- .bind(company_id)- .fetch_optional(pool)- .await?;- Ok(row.map(|(h,)| h))-}--async fn fetch_contact_hidden(pool: &PgPool, contact_id: Uuid) -> sqlx::Result<Option<bool>> {- let row: Option<(bool,)> = sqlx::query_as(r#"SELECT hidden FROM crm_contacts WHERE id = $1"#)- .bind(contact_id)- .fetch_optional(pool)- .await?;- Ok(row.map(|(h,)| h))-}--async fn fetch_company_updated_at(- pool: &PgPool,- company_id: Uuid,-) -> sqlx::Result<Option<chrono::DateTime<chrono::Utc>>> {- let row: Option<(chrono::DateTime<chrono::Utc>,)> =- sqlx::query_as(r#"SELECT updated_at FROM crm_companies WHERE id = $1"#)- .bind(company_id)- .fetch_optional(pool)- .await?;- Ok(row.map(|(updated_at,)| updated_at))-}--async fn fetch_contact_updated_at(- pool: &PgPool,- contact_id: Uuid,-) -> sqlx::Result<Option<chrono::DateTime<chrono::Utc>>> {- let row: Option<(chrono::DateTime<chrono::Utc>,)> =- sqlx::query_as(r#"SELECT updated_at FROM crm_contacts WHERE id = $1"#)- .bind(contact_id)- .fetch_optional(pool)- .await?;- Ok(row.map(|(updated_at,)| updated_at))-}--async fn fetch_company_interactions(- pool: &PgPool,- company_id: Uuid,-) -> sqlx::Result<Option<(chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>)>> {- sqlx::query_as(r#"SELECT first_interaction, last_interaction FROM crm_companies WHERE id = $1"#)- .bind(company_id)- .fetch_optional(pool)- .await-}--async fn fetch_contact_interactions(- pool: &PgPool,- contact_id: Uuid,-) -> sqlx::Result<Option<(chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>)>> {- sqlx::query_as(r#"SELECT first_interaction, last_interaction FROM crm_contacts WHERE id = $1"#)- .bind(contact_id)- .fetch_optional(pool)- .await-}--async fn fetch_company_for_domain(- pool: &PgPool,- team_id: Uuid,- domain: &str,-) -> sqlx::Result<Option<Uuid>> {- let row: Option<(Uuid,)> = sqlx::query_as(- 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) = LOWER($2)- LIMIT 1"#,- )- .bind(team_id)- .bind(domain)- .fetch_optional(pool)- .await?;- Ok(row.map(|(id,)| id))-}--async fn fetch_contact_id(- pool: &PgPool,- company_id: Uuid,- email: &str,-) -> sqlx::Result<Option<Uuid>> {- let row: Option<(Uuid,)> = sqlx::query_as(- r#"SELECT id FROM crm_contacts WHERE company_id = $1 AND LOWER(email) = LOWER($2) LIMIT 1"#,- )- .bind(company_id)- .bind(email)- .fetch_optional(pool)- .await?;- Ok(row.map(|(id,)| id))-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn returns_none_when_no_company_for_domain(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- seed_team(&pool, team_id, "macro|[email protected]").await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo.get_company_by_domain(&team_id, "missing.com").await?;-- assert!(result.is_none());- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn returns_company_with_all_domains_when_match(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- seed_team(&pool, team_id, "macro|[email protected]").await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com", "acme.io"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let company = repo- .get_company_by_domain(&team_id, "acme.com")- .await?- .expect("company should be returned");-- assert_eq!(company.id, company_id);- assert_eq!(company.team_id, team_id);- assert!(company.email_sync);-- let mut domains: Vec<_> = company.domains.iter().map(|d| d.domain.as_str()).collect();- domains.sort();- assert_eq!(domains, vec!["acme.com", "acme.io"]);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn domain_lookup_is_case_insensitive(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- seed_team(&pool, team_id, "macro|[email protected]").await?;- insert_company(&pool, team_id, true, &["acme.com"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool);-- assert!(- repo.get_company_by_domain(&team_id, "ACME.COM")- .await?- .is_some()- );- assert!(- repo.get_company_by_domain(&team_id, "Acme.Com")- .await?- .is_some()- );- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn does_not_return_companies_from_other_teams(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?;- insert_company(&pool, team_a, true, &["acme.com"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo.get_company_by_domain(&team_b, "acme.com").await?;-- assert!(result.is_none());- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn returns_company_when_email_sync_is_false(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- seed_team(&pool, team_id, "macro|[email protected]").await?;- insert_company(&pool, team_id, false, &["acme.com"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let company = repo- .get_company_by_domain(&team_id, "acme.com")- .await?- .expect("company should be returned");-- assert!(!company.email_sync);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn set_email_sync_disable_preserves_contacts_and_sources(pool: PgPool) -> anyhow::Result<()> {- // Disabling email_sync only affects read-side visibility /- // permission checks — it must not touch existing contacts.- // Populate continues to write while sync is off; visibility is- // controlled by `hidden`. Teams that want to drop contacts should- // hide the company.- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;- let alice = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;- let bob = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;-- let repo = CompaniesRepositoryImpl::new(pool.clone());- repo.set_email_sync(&team_id, &company_id, false).await?;-- assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));- // Contacts + sources stay put; their hidden state is untouched.- assert_eq!(count_contacts(&pool, company_id).await?, 2);- assert_eq!(count_sources_for_company(&pool, company_id).await?, 2);- assert_eq!(fetch_contact_hidden(&pool, alice).await?, Some(false));- assert_eq!(fetch_contact_hidden(&pool, bob).await?, Some(false));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn set_email_sync_enable_preserves_contacts(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- // Start disabled with a lingering contact — re-enabling must NOT touch it.- let company_id = insert_company(&pool, team_id, false, &["acme.com"]).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;- insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;-- let repo = CompaniesRepositoryImpl::new(pool.clone());- repo.set_email_sync(&team_id, &company_id, true).await?;-- assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(true));- assert_eq!(count_contacts(&pool, company_id).await?, 1);- assert_eq!(count_sources_for_company(&pool, company_id).await?, 1);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn set_email_sync_returns_not_found_for_unknown_company(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- seed_team(&pool, team_id, "macro|[email protected]").await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo.set_email_sync(&team_id, &Uuid::now_v7(), false).await;-- assert!(matches!(- result,- Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)- ));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn set_email_sync_isolates_companies_across_teams(pool: PgPool) -> anyhow::Result<()> {- let team_a = Uuid::now_v7();- let team_b = Uuid::now_v7();- let owner_a = "macro|[email protected]";- let owner_b = "macro|[email protected]";- seed_team(&pool, team_a, owner_a).await?;- seed_team(&pool, team_b, owner_b).await?;- let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;- let link_a = insert_email_link(&pool, owner_a, "[email protected]").await?;- insert_contact_with_source(&pool, company_a, "[email protected]", link_a).await?;-- let repo = CompaniesRepositoryImpl::new(pool.clone());- // team_b mutating team_a's company must fail without touching the row.- let result = repo.set_email_sync(&team_b, &company_a, false).await;- assert!(matches!(- result,- Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)- ));-- assert_eq!(fetch_email_sync(&pool, company_a).await?, Some(true));- assert_eq!(count_contacts(&pool, company_a).await?, 1);- assert_eq!(count_sources_for_company(&pool, company_a).await?, 1);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn set_email_sync_disable_handles_multi_domain_company(pool: PgPool) -> anyhow::Result<()> {- // Multi-domain companies lock each (team, domain) on disable; the- // flag flips but contacts/sources/domains are preserved.- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- let company_id =- insert_company(&pool, team_id, true, &["acme.com", "acme.io", "acme.co"]).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;- insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;- insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;-- let repo = CompaniesRepositoryImpl::new(pool.clone());- repo.set_email_sync(&team_id, &company_id, false).await?;-- assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));- assert_eq!(count_contacts(&pool, company_id).await?, 2);- assert_eq!(count_sources_for_company(&pool, company_id).await?, 2);- // Company + its domain rows survive the disable so future populates short-circuit.- let (domain_count,): (i64,) =- sqlx::query_as(r#"SELECT COUNT(*) FROM crm_domains WHERE company_id = $1"#)- .bind(company_id)- .fetch_one(&pool)- .await?;- assert_eq!(domain_count, 3);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn set_company_hidden_toggles_flag(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- seed_team(&pool, team_id, "macro|[email protected]").await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;-- assert_eq!(fetch_company_hidden(&pool, company_id).await?, Some(false));-- let repo = CompaniesRepositoryImpl::new(pool.clone());- repo.set_company_hidden(&team_id, &company_id, true).await?;- assert_eq!(fetch_company_hidden(&pool, company_id).await?, Some(true));-- repo.set_company_hidden(&team_id, &company_id, false)- .await?;- assert_eq!(fetch_company_hidden(&pool, company_id).await?, Some(false));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn set_company_hidden_returns_not_found_for_unknown_company(- pool: PgPool,-) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- seed_team(&pool, team_id, "macro|[email protected]").await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .set_company_hidden(&team_id, &Uuid::now_v7(), true)- .await;-- assert!(matches!(- result,- Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)- ));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn set_company_hidden_isolates_companies_across_teams(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?;- let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool.clone());- let result = repo.set_company_hidden(&team_b, &company_a, true).await;- assert!(matches!(- result,- Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)- ));- assert_eq!(fetch_company_hidden(&pool, company_a).await?, Some(false));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn set_contact_hidden_toggles_flag(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;- let contact_id =- insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;-- assert_eq!(fetch_contact_hidden(&pool, contact_id).await?, Some(false));-- let repo = CompaniesRepositoryImpl::new(pool.clone());- repo.set_contact_hidden(&team_id, &contact_id, true).await?;- assert_eq!(fetch_contact_hidden(&pool, contact_id).await?, Some(true));-- repo.set_contact_hidden(&team_id, &contact_id, false)- .await?;- assert_eq!(fetch_contact_hidden(&pool, contact_id).await?, Some(false));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn set_contact_hidden_returns_not_found_for_unknown_contact(- pool: PgPool,-) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- seed_team(&pool, team_id, "macro|[email protected]").await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .set_contact_hidden(&team_id, &Uuid::now_v7(), true)- .await;-- assert!(matches!(- result,- Err(crate::domain::model::CrmError::ContactNotFoundForTeam)- ));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn set_email_sync_enable_refuses_hidden_company(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- let company_id = insert_company(&pool, team_id, false, &["acme.com"]).await?;- sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)- .bind(company_id)- .execute(&pool)- .await?;-- let repo = CompaniesRepositoryImpl::new(pool.clone());- let result = repo.set_email_sync(&team_id, &company_id, true).await;-- assert!(matches!(- result,- Err(crate::domain::model::CrmError::CompanyHidden)- ));- // State must be unchanged.- assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));- assert_eq!(fetch_company_hidden(&pool, company_id).await?, Some(true));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn set_email_sync_disable_allowed_on_hidden_company(pool: PgPool) -> anyhow::Result<()> {- // Disabling sync on an already-hidden, already-disabled company is- // a no-op-shaped call but must not error — the hidden check only- // fires on the enable path.- let team_id = Uuid::now_v7();- seed_team(&pool, team_id, "macro|[email protected]").await?;- let company_id = insert_company(&pool, team_id, false, &["acme.com"]).await?;- sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)- .bind(company_id)- .execute(&pool)- .await?;-- let repo = CompaniesRepositoryImpl::new(pool.clone());- repo.set_email_sync(&team_id, &company_id, false).await?;-- assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));- assert_eq!(fetch_company_hidden(&pool, company_id).await?, Some(true));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn service_set_company_hidden_true_soft_hides_contacts_and_disables_email_sync(- pool: PgPool,-) -> anyhow::Result<()> {- // Hide flips the company flag, forces email_sync = false, and- // cascades hidden = TRUE onto every contact. Contact rows AND- // contact_sources are preserved so un-hide can restore them.- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;- let alice = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;- let bob = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;-- let service = CrmServiceImpl::new(- CompaniesRepositoryImpl::new(pool.clone()),- NoOpCompanyMetadataResolver,- );- service- .set_company_hidden(&team_id, &company_id, true)- .await?;-- assert_eq!(fetch_company_hidden(&pool, company_id).await?, Some(true));- assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));- // Contacts and sources preserved; both contacts now hidden.- assert_eq!(count_contacts(&pool, company_id).await?, 2);- assert_eq!(count_sources_for_company(&pool, company_id).await?, 2);- assert_eq!(fetch_contact_hidden(&pool, alice).await?, Some(true));- assert_eq!(fetch_contact_hidden(&pool, bob).await?, Some(true));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn set_company_hidden_false_cascades_contacts_visible(pool: PgPool) -> anyhow::Result<()> {- // After un-hide, every contact under the company becomes visible —- // including ones an admin previously hid individually. Cascade- // overwrites individual hide state by design.- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;- let alice = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;- let bob = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;-- let repo = CompaniesRepositoryImpl::new(pool.clone());- // Individually hide `alice` before any company-level toggling.- repo.set_contact_hidden(&team_id, &alice, true).await?;- // Then hide the whole company (cascades `bob` to hidden too).- repo.set_company_hidden(&team_id, &company_id, true).await?;- assert_eq!(fetch_contact_hidden(&pool, alice).await?, Some(true));- assert_eq!(fetch_contact_hidden(&pool, bob).await?, Some(true));-- // Un-hide cascades EVERY contact back to visible, blowing away- // alice's individual hide too.- repo.set_company_hidden(&team_id, &company_id, false)- .await?;-- assert_eq!(fetch_company_hidden(&pool, company_id).await?, Some(false));- assert_eq!(fetch_contact_hidden(&pool, alice).await?, Some(false));- assert_eq!(fetch_contact_hidden(&pool, bob).await?, Some(false));- // Un-hide does NOT re-enable email_sync; that's a separate action.- assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn service_set_company_hidden_false_does_not_re_enable_email_sync(- pool: PgPool,-) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- seed_team(&pool, team_id, "macro|[email protected]").await?;- // Start with hidden=true (via service, which also flipped sync off) then un-hide.- let company_id = insert_company(&pool, team_id, false, &["acme.com"]).await?;- sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)- .bind(company_id)- .execute(&pool)- .await?;-- let service = CrmServiceImpl::new(- CompaniesRepositoryImpl::new(pool.clone()),- NoOpCompanyMetadataResolver,- );- service- .set_company_hidden(&team_id, &company_id, false)- .await?;-- assert_eq!(fetch_company_hidden(&pool, company_id).await?, Some(false));- // Un-hiding leaves email_sync alone — caller must re-enable it explicitly.- assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn set_contact_hidden_isolates_contacts_across_teams(pool: PgPool) -> anyhow::Result<()> {- let team_a = Uuid::now_v7();- let team_b = Uuid::now_v7();- let owner_a = "macro|[email protected]";- let owner_b = "macro|[email protected]";- seed_team(&pool, team_a, owner_a).await?;- seed_team(&pool, team_b, owner_b).await?;- let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;- let link_a = insert_email_link(&pool, owner_a, "[email protected]").await?;- let contact_a = insert_contact_with_source(&pool, company_a, "[email protected]", link_a).await?;-- let repo = CompaniesRepositoryImpl::new(pool.clone());- // team_b mutating team_a's contact must fail without touching the row.- let result = repo.set_contact_hidden(&team_b, &contact_a, true).await;- assert!(matches!(- result,- Err(crate::domain::model::CrmError::ContactNotFoundForTeam)- ));-- assert_eq!(fetch_contact_hidden(&pool, contact_a).await?, Some(false));- Ok(())-}--async fn enable_crm_for_team(pool: &PgPool, team_id: Uuid) -> sqlx::Result<()> {- sqlx::query(- r#"INSERT INTO team_crm_settings (team_id, crm_enabled) VALUES ($1, TRUE)- ON CONFLICT (team_id) DO UPDATE SET crm_enabled = TRUE"#,- )- .bind(team_id)- .execute(pool)- .await?;- Ok(())-}--async fn count_companies_for_domain(- pool: &PgPool,- team_id: Uuid,- domain: &str,-) -> sqlx::Result<i64> {- let (count,): (i64,) = sqlx::query_as(- r#"SELECT COUNT(*) FROM crm_companies c- JOIN crm_domains d ON d.company_id = c.id- WHERE c.team_id = $1 AND LOWER(d.domain) = LOWER($2)"#,- )- .bind(team_id)- .bind(domain)- .fetch_one(pool)- .await?;- Ok(count)-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn service_populate_contact_skips_when_domain_matches_user_domain(- pool: PgPool,-) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- enable_crm_for_team(&pool, team_id).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;-- let service = CrmServiceImpl::new(- CompaniesRepositoryImpl::new(pool.clone()),- NoOpCompanyMetadataResolver,- );-- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- None,- chrono::Utc::now(),- chrono::Utc::now(),- true,- )- .await?;-- assert_eq!(- count_companies_for_domain(&pool, team_id, "macro.com").await?,- 0,- "contact on the user's own domain must not create a CRM row"- );- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn service_populate_contact_same_domain_check_is_case_insensitive(- pool: PgPool,-) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- enable_crm_for_team(&pool, team_id).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;-- let service = CrmServiceImpl::new(- CompaniesRepositoryImpl::new(pool.clone()),- NoOpCompanyMetadataResolver,- );-- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- None,- chrono::Utc::now(),- chrono::Utc::now(),- true,- )- .await?;-- assert_eq!(- count_companies_for_domain(&pool, team_id, "macro.com").await?,- 0- );- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn service_populate_contact_refreshes_existing_company_and_contact_updated_at(- pool: PgPool,-) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- enable_crm_for_team(&pool, team_id).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;-- let old_updated_at: chrono::DateTime<chrono::Utc> =- sqlx::query_scalar(r#"SELECT now() - INTERVAL '1 hour'"#)- .fetch_one(&pool)- .await?;-- let company_id = Uuid::now_v7();- sqlx::query(- r#"INSERT INTO crm_companies (id, team_id, email_sync, updated_at, first_interaction, last_interaction)- VALUES ($1, $2, TRUE, $3, $3, $3)"#,- )- .bind(company_id)- .bind(team_id)- .bind(old_updated_at)- .execute(&pool)- .await?;-- sqlx::query(r#"INSERT INTO crm_domains (company_id, team_id, domain) VALUES ($1, $2, $3)"#)- .bind(company_id)- .bind(team_id)- .bind("acme.com")- .execute(&pool)- .await?;-- let contact_id = Uuid::now_v7();- sqlx::query(- r#"INSERT INTO crm_contacts (id, company_id, email, updated_at, first_interaction, last_interaction)- VALUES ($1, $2, $3, $4, $4, $4)"#,- )- .bind(contact_id)- .bind(company_id)- .bind("[email protected]")- .bind(old_updated_at)- .execute(&pool)- .await?;-- sqlx::query(r#"INSERT INTO crm_contact_sources (contact_id, link_id) VALUES ($1, $2)"#)- .bind(contact_id)- .bind(link_id)- .execute(&pool)- .await?;-- let service = CrmServiceImpl::new(- CompaniesRepositoryImpl::new(pool.clone()),- NoOpCompanyMetadataResolver,- );-- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- Some("Alice"),- chrono::Utc::now(),- chrono::Utc::now(),- true,- )- .await?;-- let company_updated_at = fetch_company_updated_at(&pool, company_id)- .await?- .expect("company should still exist");- let contact_updated_at = fetch_contact_updated_at(&pool, contact_id)- .await?- .expect("contact should still exist");-- assert!(company_updated_at > old_updated_at);- assert!(contact_updated_at > old_updated_at);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn service_populate_contact_writes_when_domain_differs(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- enable_crm_for_team(&pool, team_id).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;-- let service = CrmServiceImpl::new(- CompaniesRepositoryImpl::new(pool.clone()),- NoOpCompanyMetadataResolver,- );-- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- None,- chrono::Utc::now(),- chrono::Utc::now(),- true,- )- .await?;-- assert_eq!(- count_companies_for_domain(&pool, team_id, "acme.com").await?,- 1- );- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn precheck_reports_killswitch_off_when_settings_missing(pool: PgPool) -> anyhow::Result<()> {- let team = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team, owner).await?;- // intentionally no team_crm_settings row-- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .crm_scope_precheck(&team, &["acme.com".to_string()], &[])- .await?;- // Killswitch off short-circuits: the email service rejects with- // CrmDisabledForTeam regardless of per-input state, so the probes- // are skipped and per-input rows come back empty.- assert!(!result.crm_enabled);- assert!(result.domains.is_empty());- assert!(result.addresses.is_empty());- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn precheck_resolves_domain_with_company_state(pool: PgPool) -> anyhow::Result<()> {- let team = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team, owner).await?;- enable_crm_for_team(&pool, team).await?;- insert_company(&pool, team, true, &["acme.com"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .crm_scope_precheck(- &team,- &["acme.com".to_string(), "missing.com".to_string()],- &[],- )- .await?;- assert!(result.crm_enabled);- assert_eq!(result.domains.len(), 2);-- let acme = result- .domains- .iter()- .find(|d| d.domain == "acme.com")- .unwrap();- assert!(acme.exists);- assert!(!acme.company_hidden);- assert!(acme.email_sync);-- let missing = result- .domains- .iter()- .find(|d| d.domain == "missing.com")- .unwrap();- assert!(!missing.exists);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn precheck_reports_hidden_and_email_sync_disabled_companies(- pool: PgPool,-) -> anyhow::Result<()> {- let team = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team, owner).await?;- enable_crm_for_team(&pool, team).await?;- let hidden_co = insert_company(&pool, team, false, &["hidden.com"]).await?;- sqlx::query("UPDATE crm_companies SET hidden = TRUE WHERE id = $1")- .bind(hidden_co)- .execute(&pool)- .await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .crm_scope_precheck(&team, &["hidden.com".to_string()], &[])- .await?;- let d = &result.domains[0];- assert!(d.exists);- assert!(d.company_hidden);- assert!(!d.email_sync);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn precheck_address_resolves_contact_within_team(pool: PgPool) -> anyhow::Result<()> {- let team = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team, owner).await?;- enable_crm_for_team(&pool, team).await?;- let company = insert_company(&pool, team, true, &["acme.com"]).await?;- let link = insert_email_link(&pool, owner, "[email protected]").await?;- insert_contact_with_source(&pool, company, "[email protected]", link).await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .crm_scope_precheck(- &team,- &[],- &["[email protected]".to_string(), "[email protected]".to_string()],- )- .await?;-- let alice = result- .addresses- .iter()- .find(|a| a.address == "[email protected]")- .unwrap();- assert!(alice.exists);- assert!(!alice.contact_hidden);- assert!(!alice.company_hidden);- assert!(alice.email_sync);-- let bob = result- .addresses- .iter()- .find(|a| a.address == "[email protected]")- .unwrap();- assert!(!bob.exists);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn precheck_address_does_not_leak_other_team_contacts(pool: PgPool) -> anyhow::Result<()> {- let team_a = Uuid::now_v7();- let team_b = Uuid::now_v7();- let owner_a = "macro|[email protected]";- let owner_b = "macro|[email protected]";- seed_team(&pool, team_a, owner_a).await?;- seed_team(&pool, team_b, owner_b).await?;- enable_crm_for_team(&pool, team_b).await?;- let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;- let link_a = insert_email_link(&pool, owner_a, "[email protected]").await?;- insert_contact_with_source(&pool, company_a, "[email protected]", link_a).await?;-- // team_b asks about an address that only exists under team_a — must- // report as non-existent, not leak team_a's contact state.- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .crm_scope_precheck(&team_b, &[], &["[email protected]".to_string()])- .await?;- assert!(!result.addresses[0].exists);- Ok(())-}--/// Received-direction populate for an unknown `(team, domain)` is a-/// no-op: only sent-direction may create a new `crm_companies` row.-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn populate_contact_is_sent_false_skips_when_no_company(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- enable_crm_for_team(&pool, team_id).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;-- let service = CrmServiceImpl::new(- CompaniesRepositoryImpl::new(pool.clone()),- NoOpCompanyMetadataResolver,- );-- let now = chrono::Utc::now();- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- None,- now,- now,- false,- )- .await?;-- assert_eq!(- count_companies_for_domain(&pool, team_id, "acme.com").await?,- 0,- "received-direction populate must not create a crm_companies row"- );- Ok(())-}--/// Brand-new company + contact INSERT writes `first_interaction` and-/// `last_interaction` directly from the payload's distinct `first_at` /-/// `last_at` (covers the historical-seed range, e.g. 2020→2024).-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn populate_contact_insert_seeds_first_and_last_from_payload(- pool: PgPool,-) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- enable_crm_for_team(&pool, team_id).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;-- let first: chrono::DateTime<chrono::Utc> = "2020-01-01T00:00:00Z".parse()?;- let last: chrono::DateTime<chrono::Utc> = "2024-06-15T00:00:00Z".parse()?;-- let service = CrmServiceImpl::new(- CompaniesRepositoryImpl::new(pool.clone()),- NoOpCompanyMetadataResolver,- );-- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- None,- first,- last,- true,- )- .await?;-- let company_id = fetch_company_for_domain(&pool, team_id, "acme.com")- .await?- .expect("company should be inserted");- let (company_first, company_last) = fetch_company_interactions(&pool, company_id)- .await?- .expect("company interactions");- assert_eq!(company_first, first);- assert_eq!(company_last, last);-- let contact_id = fetch_contact_id(&pool, company_id, "[email protected]")- .await?- .expect("contact should be inserted");- let (contact_first, contact_last) = fetch_contact_interactions(&pool, contact_id)- .await?- .expect("contact interactions");- assert_eq!(contact_first, first);- assert_eq!(contact_last, last);- Ok(())-}--/// Sent-direction populate against an existing row merges-/// `first_interaction` via `LEAST` (older message pulls it back) and-/// `last_interaction` via `GREATEST` (newer message pushes it forward),-/// on both the company and contact rows.-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn populate_contact_is_sent_true_merges_first_least_and_last_greatest(- pool: PgPool,-) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- enable_crm_for_team(&pool, team_id).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;-- let initial: chrono::DateTime<chrono::Utc> = "2022-06-01T00:00:00Z".parse()?;- let older: chrono::DateTime<chrono::Utc> = "2020-01-01T00:00:00Z".parse()?;- let newer: chrono::DateTime<chrono::Utc> = "2024-12-31T00:00:00Z".parse()?;-- let service = CrmServiceImpl::new(- CompaniesRepositoryImpl::new(pool.clone()),- NoOpCompanyMetadataResolver,- );-- // First populate establishes the row at `initial`.- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- None,- initial,- initial,- true,- )- .await?;-- let company_id = fetch_company_for_domain(&pool, team_id, "acme.com")- .await?- .expect("company");- let contact_id = fetch_contact_id(&pool, company_id, "[email protected]")- .await?- .expect("contact");-- // A backfilled older message should pull first_interaction back via LEAST.- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- None,- older,- older,- true,- )- .await?;-- let (company_first, company_last) = fetch_company_interactions(&pool, company_id)- .await?- .expect("interactions");- assert_eq!(company_first, older);- assert_eq!(company_last, initial);- let (contact_first, contact_last) = fetch_contact_interactions(&pool, contact_id)- .await?- .expect("interactions");- assert_eq!(contact_first, older);- assert_eq!(contact_last, initial);-- // A newer message should push last_interaction forward via GREATEST,- // leaving first_interaction at `older`.- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- None,- newer,- newer,- true,- )- .await?;-- let (company_first, company_last) = fetch_company_interactions(&pool, company_id)- .await?- .expect("interactions");- assert_eq!(company_first, older);- assert_eq!(company_last, newer);- Ok(())-}--/// Received-direction populate against an existing row must not pull-/// `first_interaction` backwards — even with an older timestamp — but-/// still GREATEST-merges `last_interaction` when newer. Asserts both-/// company and contact.-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn populate_contact_is_sent_false_leaves_first_interaction_unchanged(- pool: PgPool,-) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- enable_crm_for_team(&pool, team_id).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;-- let baseline: chrono::DateTime<chrono::Utc> = "2022-06-01T00:00:00Z".parse()?;- let older: chrono::DateTime<chrono::Utc> = "2020-01-01T00:00:00Z".parse()?;- let newer: chrono::DateTime<chrono::Utc> = "2024-12-31T00:00:00Z".parse()?;-- let service = CrmServiceImpl::new(- CompaniesRepositoryImpl::new(pool.clone()),- NoOpCompanyMetadataResolver,- );-- // Sent populate seeds the row at `baseline`.- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- None,- baseline,- baseline,- true,- )- .await?;-- let company_id = fetch_company_for_domain(&pool, team_id, "acme.com")- .await?- .expect("company");- let contact_id = fetch_contact_id(&pool, company_id, "[email protected]")- .await?- .expect("contact");-- // Received populate with an older timestamp must NOT pull- // first_interaction backwards on either row.- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- None,- older,- older,- false,- )- .await?;-- let (company_first, _) = fetch_company_interactions(&pool, company_id)- .await?- .expect("interactions");- assert_eq!(- company_first, baseline,- "received populate must not pull company first_interaction backwards"- );- let (contact_first, _) = fetch_contact_interactions(&pool, contact_id)- .await?- .expect("interactions");- assert_eq!(- contact_first, baseline,- "received populate must not pull contact first_interaction backwards"- );-- // Received populate with a newer timestamp still bumps last_interaction.- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- None,- newer,- newer,- false,- )- .await?;-- let (_, company_last) = fetch_company_interactions(&pool, company_id)- .await?- .expect("interactions");- assert_eq!(company_last, newer);- let (_, contact_last) = fetch_contact_interactions(&pool, contact_id)- .await?- .expect("interactions");- assert_eq!(contact_last, newer);- Ok(())-}--/// Received-direction populate at a known company creates a new-/// `crm_contacts` row (seeded with both timestamps) and a-/// `crm_contact_sources` row — verifying sources now track-/// interactions in both directions.-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn populate_contact_is_sent_false_inserts_contact_at_existing_company(- pool: PgPool,-) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- enable_crm_for_team(&pool, team_id).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;-- let baseline: chrono::DateTime<chrono::Utc> = "2022-06-01T00:00:00Z".parse()?;- let received_at: chrono::DateTime<chrono::Utc> = "2024-09-15T00:00:00Z".parse()?;-- let service = CrmServiceImpl::new(- CompaniesRepositoryImpl::new(pool.clone()),- NoOpCompanyMetadataResolver,- );-- // Sent populate establishes the company via [email protected].- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- None,- baseline,- baseline,- true,- )- .await?;-- let company_id = fetch_company_for_domain(&pool, team_id, "acme.com")- .await?- .expect("company");- assert_eq!(count_contacts(&pool, company_id).await?, 1);-- // Received-direction populate for a *new* address at the same- // company creates a contact row + source row.- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- Some("Bob"),- received_at,- received_at,- false,- )- .await?;-- assert_eq!(- count_contacts(&pool, company_id).await?,- 2,- "received-direction populate must insert a contact under the known company"- );- let bob_id = fetch_contact_id(&pool, company_id, "[email protected]")- .await?- .expect("bob contact");- let (bob_first, bob_last) = fetch_contact_interactions(&pool, bob_id)- .await?- .expect("bob interactions");- assert_eq!(bob_first, received_at);- assert_eq!(bob_last, received_at);- assert_eq!(- count_sources_for_company(&pool, company_id).await?,- 2,- "received-direction populate must write a crm_contact_sources row"- );- Ok(())-}--/// Team-level CRM killswitch (`team_crm_settings.crm_enabled = false`-/// or missing) short-circuits populate in both directions before any-/// rows are written.-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn populate_contact_team_killswitch_off_noops_both_directions(- pool: PgPool,-) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- // Intentionally do NOT enable_crm_for_team — team_crm_settings row is- // missing, which is treated as crm_enabled = false.- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;-- let service = CrmServiceImpl::new(- CompaniesRepositoryImpl::new(pool.clone()),- NoOpCompanyMetadataResolver,- );-- let now = chrono::Utc::now();-- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- None,- now,- now,- true,- )- .await?;- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- None,- now,- now,- false,- )- .await?;-- assert_eq!(- count_companies_for_domain(&pool, team_id, "acme.com").await?,- 0,- "team killswitch must short-circuit both directions"- );- Ok(())-}--/// `email_sync = false` no longer gates populate. The flag is now-/// purely a visibility/permission check consumed at read time-/// (soup, email permissions). Populate updates interaction columns-/// and writes contact / source rows just like it would with-/// `email_sync = true`, so re-enabling sync exposes the full history-/// with zero backfill.-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn populate_contact_runs_regardless_of_email_sync_flag(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- enable_crm_for_team(&pool, team_id).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;-- // Seed a sync-off company. Baseline timestamp parsed from a string- // (no sub-microsecond precision — Postgres `TIMESTAMPTZ` only- // stores micros and `chrono::Utc::now()`'s nanos would get- // silently truncated and break the `assert_eq` below).- let company_id = insert_company(&pool, team_id, false, &["acme.com"]).await?;- let baseline: chrono::DateTime<chrono::Utc> = "2024-01-01T00:00:00Z".parse()?;- sqlx::query(- r#"UPDATE crm_companies- SET first_interaction = $2, last_interaction = $2- WHERE id = $1"#,- )- .bind(company_id)- .bind(baseline)- .execute(&pool)- .await?;-- let service = CrmServiceImpl::new(- CompaniesRepositoryImpl::new(pool.clone()),- NoOpCompanyMetadataResolver,- );-- let later: chrono::DateTime<chrono::Utc> = "2024-01-08T00:00:00Z".parse()?;- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- None,- later,- later,- true,- )- .await?;-- // Company `last_interaction` advances; first_interaction- // LEAST-merges on is_sent=true so it stays at the earlier- // baseline. Contact + source rows land regardless of email_sync.- let (first, last) = fetch_company_interactions(&pool, company_id)- .await?- .expect("company");- assert_eq!(first, baseline);- assert_eq!(last, later);- assert_eq!(count_contacts(&pool, company_id).await?, 1);- assert_eq!(count_sources_for_company(&pool, company_id).await?, 1);- // email_sync itself is unchanged — populate never touches it.- assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));- Ok(())-}--/// Historical-seed-style populate (`first_at != last_at`) against an-/// already-tracked row expands the stored range outward: `first` pulls-/// back via LEAST and `last` pushes forward via GREATEST in the same-/// call.-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn populate_contact_seed_style_range_merges_into_existing(- pool: PgPool,-) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- enable_crm_for_team(&pool, team_id).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;-- let baseline: chrono::DateTime<chrono::Utc> = "2022-06-01T00:00:00Z".parse()?;-- let service = CrmServiceImpl::new(- CompaniesRepositoryImpl::new(pool.clone()),- NoOpCompanyMetadataResolver,- );-- // Establish the rows at `baseline`.- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- None,- baseline,- baseline,- true,- )- .await?;-- let company_id = fetch_company_for_domain(&pool, team_id, "acme.com")- .await?- .expect("company");- let contact_id = fetch_contact_id(&pool, company_id, "[email protected]")- .await?- .expect("contact");-- // Historical-seed-style populate: distinct first_at < last_at,- // is_sent=true, hitting an already-populated contact. Should pull- // first_interaction earlier AND push last_interaction later.- let seed_first: chrono::DateTime<chrono::Utc> = "2010-03-15T00:00:00Z".parse()?;- let seed_last: chrono::DateTime<chrono::Utc> = "2024-12-31T00:00:00Z".parse()?;- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- None,- seed_first,- seed_last,- true,- )- .await?;-- let (company_first, company_last) = fetch_company_interactions(&pool, company_id)- .await?- .expect("interactions");- assert_eq!(company_first, seed_first);- assert_eq!(company_last, seed_last);- let (contact_first, contact_last) = fetch_contact_interactions(&pool, contact_id)- .await?- .expect("interactions");- assert_eq!(contact_first, seed_first);- assert_eq!(contact_last, seed_last);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn email_sync_disable_then_re_enable_preserves_full_history_with_no_backfill(- pool: PgPool,-) -> anyhow::Result<()> {- // Regression: the whole point of decoupling populate from- // email_sync. While sync is OFF, new emails arriving for this- // company must still write CRM rows. Re-enabling sync must surface- // the complete history without any explicit backfill step.- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- enable_crm_for_team(&pool, team_id).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;-- let service = CrmServiceImpl::new(- CompaniesRepositoryImpl::new(pool.clone()),- NoOpCompanyMetadataResolver,- );- let repo = CompaniesRepositoryImpl::new(pool.clone());-- // Phase 1: sync ON. First contact lands normally.- let t1: chrono::DateTime<chrono::Utc> = "2024-01-01T00:00:00Z".parse()?;- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- None,- t1,- t1,- true,- )- .await?;- let company_id = fetch_company_for_domain(&pool, team_id, "acme.com")- .await?- .expect("company");- assert_eq!(count_contacts(&pool, company_id).await?, 1);-- // Phase 2: admin disables sync. Existing data stays put.- repo.set_email_sync(&team_id, &company_id, false).await?;- assert_eq!(count_contacts(&pool, company_id).await?, 1);- assert_eq!(count_sources_for_company(&pool, company_id).await?, 1);-- // Phase 3: a new email arrives during the sync-off window. This- // is the critical assertion — populate must still write the new- // contact + source so there's no gap to backfill later.- let t2: chrono::DateTime<chrono::Utc> = "2024-02-15T00:00:00Z".parse()?;- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- None,- t2,- t2,- true,- )- .await?;- assert_eq!(count_contacts(&pool, company_id).await?, 2);- assert_eq!(count_sources_for_company(&pool, company_id).await?, 2);- assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));-- // Phase 4: admin re-enables sync. No backfill is run — but the- // history written during the off-window is already there.- repo.set_email_sync(&team_id, &company_id, true).await?;- assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(true));- assert_eq!(count_contacts(&pool, company_id).await?, 2);- assert_eq!(count_sources_for_company(&pool, company_id).await?, 2);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn populate_contact_into_hidden_company_inserts_hidden_contact(- pool: PgPool,-) -> anyhow::Result<()> {- // Defensive: new contacts inserted into a hidden company must- // inherit `hidden = TRUE` so a populate-vs-hide race can't sneak a- // visible contact under an otherwise-hidden company. Populate- // doesn't itself gate on `hidden` (it always writes when the- // team-level CRM killswitch is on), so this is the only line of- // defense.- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- enable_crm_for_team(&pool, team_id).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;- sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)- .bind(company_id)- .execute(&pool)- .await?;-- let service = CrmServiceImpl::new(- CompaniesRepositoryImpl::new(pool.clone()),- NoOpCompanyMetadataResolver,- );- let now: chrono::DateTime<chrono::Utc> = "2024-01-15T00:00:00Z".parse()?;- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- None,- now,- now,- true,- )- .await?;-- let alice = fetch_contact_id(&pool, company_id, "[email protected]")- .await?- .expect("alice should have been inserted");- assert_eq!(fetch_contact_hidden(&pool, alice).await?, Some(true));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn populate_contact_upsert_does_not_overwrite_individual_hide(- pool: PgPool,-) -> anyhow::Result<()> {- // Populate upsert (ON CONFLICT path) must preserve a contact's- // existing `hidden` so individual `set_contact_hidden` actions- // survive subsequent email activity.- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- enable_crm_for_team(&pool, team_id).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;-- let service = CrmServiceImpl::new(- CompaniesRepositoryImpl::new(pool.clone()),- NoOpCompanyMetadataResolver,- );- let first_at: chrono::DateTime<chrono::Utc> = "2024-01-01T00:00:00Z".parse()?;- let later: chrono::DateTime<chrono::Utc> = "2024-02-01T00:00:00Z".parse()?;-- // Seed the contact via a normal populate.- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- None,- first_at,- first_at,- true,- )- .await?;- let company_id = fetch_company_for_domain(&pool, team_id, "acme.com")- .await?- .expect("company");- let alice = fetch_contact_id(&pool, company_id, "[email protected]")- .await?- .expect("alice");-- // Admin hides alice individually.- let repo = CompaniesRepositoryImpl::new(pool.clone());- repo.set_contact_hidden(&team_id, &alice, true).await?;- assert_eq!(fetch_contact_hidden(&pool, alice).await?, Some(true));-- // A later populate (new email from alice) must NOT un-hide her.- service- .populate_contact(- &team_id,- &link_id,- "[email protected]",- "[email protected]",- None,- later,- later,- true,- )- .await?;-- assert_eq!(fetch_contact_hidden(&pool, alice).await?, Some(true));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn list_for_soup_returns_empty_when_killswitch_missing(pool: PgPool) -> anyhow::Result<()> {- let team = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team, owner).await?;- // No team_crm_settings row → killswitch defaults to off.- insert_company(&pool, team, true, &["acme.com"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .list_companies_for_soup(&team, &[], None, CrmCompanyListSort::UpdatedAt, None, 100)- .await?;- assert!(- result.is_empty(),- "killswitch missing must short-circuit to empty list even when companies exist"- );- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn list_for_soup_returns_empty_when_killswitch_off(pool: PgPool) -> anyhow::Result<()> {- let team = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team, owner).await?;- sqlx::query(r#"INSERT INTO team_crm_settings (team_id, crm_enabled) VALUES ($1, FALSE)"#)- .bind(team)- .execute(&pool)- .await?;- insert_company(&pool, team, true, &["acme.com"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .list_companies_for_soup(&team, &[], None, CrmCompanyListSort::UpdatedAt, None, 100)- .await?;- assert!(result.is_empty());- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn list_for_soup_excludes_hidden_rows(pool: PgPool) -> anyhow::Result<()> {- let team = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team, owner).await?;- enable_crm_for_team(&pool, team).await?;- let visible = insert_company(&pool, team, true, &["acme.com"]).await?;- let hidden = insert_company(&pool, team, true, &["zeta.com"]).await?;- sqlx::query("UPDATE crm_companies SET hidden = TRUE WHERE id = $1")- .bind(hidden)- .execute(&pool)- .await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .list_companies_for_soup(&team, &[], None, CrmCompanyListSort::UpdatedAt, None, 100)- .await?;- let ids: Vec<Uuid> = result.iter().map(|c| c.company.id).collect();- assert_eq!(ids, vec![visible], "hidden = TRUE rows must not appear");- // The visible row must have its domains hydrated.- assert_eq!(result[0].company.domains.len(), 1);- assert_eq!(result[0].company.domains[0].domain, "acme.com");- // No directory row for acme.com — both display fields should be None.- assert_eq!(result[0].name, None);- assert_eq!(result[0].description, None);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn list_for_soup_returns_hidden_when_hidden_true(pool: PgPool) -> anyhow::Result<()> {- let team = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team, owner).await?;- enable_crm_for_team(&pool, team).await?;- let visible = insert_company(&pool, team, true, &["acme.com"]).await?;- let hidden = insert_company(&pool, team, true, &["zeta.com"]).await?;- sqlx::query("UPDATE crm_companies SET hidden = TRUE WHERE id = $1")- .bind(hidden)- .execute(&pool)- .await?;-- let repo = CompaniesRepositoryImpl::new(pool);-- let hidden_only = repo- .list_companies_for_soup(- &team,- &[],- Some(true),- CrmCompanyListSort::UpdatedAt,- None,- 100,- )- .await?;- let ids: Vec<Uuid> = hidden_only.iter().map(|c| c.company.id).collect();- assert_eq!(- ids,- vec![hidden],- "hidden=Some(true) must return only hidden rows"- );-- let visible_only_explicit = repo- .list_companies_for_soup(- &team,- &[],- Some(false),- CrmCompanyListSort::UpdatedAt,- None,- 100,- )- .await?;- let ids: Vec<Uuid> = visible_only_explicit.iter().map(|c| c.company.id).collect();- assert_eq!(- ids,- vec![visible],- "hidden=Some(false) must behave the same as None (visible only)",- );- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn list_for_soup_hydrates_name_and_description_from_directory(- pool: PgPool,-) -> anyhow::Result<()> {- let team = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team, owner).await?;- enable_crm_for_team(&pool, team).await?;- insert_company(&pool, team, true, &["acme.com", "acmecorp.com"]).await?;- // Directory row only on the primary — secondary must not be picked.- sqlx::query(- r#"INSERT INTO crm_domain_directory (domain, name, description)- VALUES ($1, $2, $3)"#,- )- .bind("acme.com")- .bind("Acme Inc.")- .bind("Maker of rocket-powered roller skates.")- .execute(&pool)- .await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .list_companies_for_soup(&team, &[], None, CrmCompanyListSort::UpdatedAt, None, 100)- .await?;- assert_eq!(result.len(), 1);- assert_eq!(result[0].name.as_deref(), Some("Acme Inc."));- assert_eq!(- result[0].description.as_deref(),- Some("Maker of rocket-powered roller skates.")- );- // Domain order is by created_at ASC; both should be present.- assert_eq!(result[0].company.domains.len(), 2);- assert_eq!(result[0].company.domains[0].domain, "acme.com");- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn list_for_soup_returns_none_for_negative_cache_directory_row(- pool: PgPool,-) -> anyhow::Result<()> {- // Negative-cache directory row (NULL name/description) → soup- // surfaces as None, not Some("").- let team = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team, owner).await?;- enable_crm_for_team(&pool, team).await?;- insert_company(&pool, team, true, &["acme.com"]).await?;- sqlx::query(- r#"INSERT INTO crm_domain_directory (domain, name, description)- VALUES ($1, NULL, NULL)"#,- )- .bind("acme.com")- .execute(&pool)- .await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .list_companies_for_soup(&team, &[], None, CrmCompanyListSort::UpdatedAt, None, 100)- .await?;- assert_eq!(result.len(), 1);- assert_eq!(result[0].name, None);- assert_eq!(result[0].description, None);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn list_for_soup_filters_by_company_ids_when_non_empty(pool: PgPool) -> anyhow::Result<()> {- let team = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team, owner).await?;- enable_crm_for_team(&pool, team).await?;- let wanted = insert_company(&pool, team, true, &["acme.com"]).await?;- let _other = insert_company(&pool, team, true, &["zeta.com"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .list_companies_for_soup(- &team,- &[wanted],- None,- CrmCompanyListSort::UpdatedAt,- None,- 100,- )- .await?;- let ids: Vec<Uuid> = result.iter().map(|c| c.company.id).collect();- assert_eq!(ids, vec![wanted]);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn list_for_soup_does_not_leak_other_team_rows(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 b_only = insert_company(&pool, team_b, true, &["zeta.com"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .list_companies_for_soup(&team_b, &[], None, CrmCompanyListSort::UpdatedAt, None, 100)- .await?;- let ids: Vec<Uuid> = result.iter().map(|c| c.company.id).collect();- assert_eq!(ids, vec![b_only]);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn list_for_soup_paginates_past_cursor(pool: PgPool) -> anyhow::Result<()> {- let team = Uuid::now_v7();- seed_team(&pool, team, "macro|[email protected]").await?;- enable_crm_for_team(&pool, team).await?;-- // Five companies with strictly increasing interaction timestamps.- // Parsed (not `now()`) so they carry no sub-microsecond precision- // that Postgres would truncate out from under the cursor compare.- let mut companies = Vec::new();- for day in 1..=5 {- let domain = format!("c{day}.com");- let id = insert_company(&pool, team, true, &[domain.as_str()]).await?;- let ts: chrono::DateTime<chrono::Utc> = format!("2024-01-0{day}T00:00:00Z").parse()?;- sqlx::query(- r#"UPDATE crm_companies- SET first_interaction = $2, last_interaction = $2- WHERE id = $1"#,- )- .bind(id)- .bind(ts)- .execute(&pool)- .await?;- companies.push(id);- }- // Descending by timestamp → newest (day 5) first.- let expected: Vec<Uuid> = companies.iter().rev().copied().collect();-- let repo = CompaniesRepositoryImpl::new(pool);-- // Walk every page with limit=2, threading the keyset cursor from the- // last row of each page — exactly how the soup paginator drives it.- let mut seen: Vec<Uuid> = Vec::new();- let mut cursor: Option<CrmCompanySoupCursor> = None;- let mut first_page: Vec<Uuid> = Vec::new();- for page_idx in 0..10 {- let page = repo- .list_companies_for_soup(&team, &[], None, CrmCompanyListSort::UpdatedAt, cursor, 2)- .await?;- if page.is_empty() {- break;- }- let page_ids: Vec<Uuid> = page.iter().map(|c| c.company.id).collect();- if page_idx == 0 {- first_page = page_ids.clone();- } else {- // Regression: a follow-up page must not re-serve page one.- // (The pre-fix query ignored the cursor and always did this.)- assert_ne!(- page_ids, first_page,- "cursor did not advance — page {page_idx} repeated the first page"- );- }- let last = page.last().unwrap();- cursor = Some(CrmCompanySoupCursor {- last_sort_ts: last.company.updated_at,- last_id: last.company.id,- });- let exhausted = page.len() < 2;- seen.extend(page_ids);- if exhausted {- break;- }- }-- assert_eq!(- seen, expected,- "pagination must yield every company exactly once in descending interaction order"- );- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn list_for_soup_pagination_breaks_ties_on_id(pool: PgPool) -> anyhow::Result<()> {- let team = Uuid::now_v7();- seed_team(&pool, team, "macro|[email protected]").await?;- enable_crm_for_team(&pool, team).await?;-- // One newest company, then a tied pair, then two older. At limit=2- // the tied pair straddles the page-1/page-2 boundary, so pagination- // must lean on the `id` half of the keyset — a timestamp-only seek- // would skip the second tied row (its ts is not `< cursor_ts`).- let newest: chrono::DateTime<chrono::Utc> = "2024-01-05T00:00:00Z".parse()?;- let tie: chrono::DateTime<chrono::Utc> = "2024-01-04T00:00:00Z".parse()?;- let mid: chrono::DateTime<chrono::Utc> = "2024-01-03T00:00:00Z".parse()?;- let oldest: chrono::DateTime<chrono::Utc> = "2024-01-02T00:00:00Z".parse()?;-- let mut want: Vec<(chrono::DateTime<chrono::Utc>, Uuid)> = Vec::new();- for (idx, ts) in [newest, tie, tie, mid, oldest].into_iter().enumerate() {- let domain = format!("tie{idx}.com");- let id = insert_company(&pool, team, true, &[domain.as_str()]).await?;- sqlx::query(- r#"UPDATE crm_companies- SET first_interaction = $2, last_interaction = $2- WHERE id = $1"#,- )- .bind(id)- .bind(ts)- .execute(&pool)- .await?;- want.push((ts, id));- }- // Expected DB order: last_interaction DESC, then id DESC. Computed- // from the ids actually generated, so it holds regardless of which- // tied row drew the larger uuid.- want.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));- let expected: Vec<Uuid> = want.iter().map(|(_, id)| *id).collect();-- let repo = CompaniesRepositoryImpl::new(pool);- let mut seen: Vec<Uuid> = Vec::new();- let mut cursor: Option<CrmCompanySoupCursor> = None;- for _ in 0..10 {- let page = repo- .list_companies_for_soup(&team, &[], None, CrmCompanyListSort::UpdatedAt, cursor, 2)- .await?;- if page.is_empty() {- break;- }- let last = page.last().unwrap();- cursor = Some(CrmCompanySoupCursor {- last_sort_ts: last.company.updated_at,- last_id: last.company.id,- });- let exhausted = page.len() < 2;- seen.extend(page.iter().map(|c| c.company.id));- if exhausted {- break;- }- }-- assert_eq!(- seen, expected,- "tied timestamps must paginate by id without skipping or repeating across the boundary"- );- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn list_contacts_returns_visible_ordered_alphabetically(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;-- // Named contacts sort by name; a name-less contact sorts by email.- // `anna smith` is lowercased to confirm the sort is case-insensitive.- let zoe = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;- let mike = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;- let carol = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;- sqlx::query(r#"UPDATE crm_contacts SET name = 'Zoe Adams' WHERE id = $1"#)- .bind(zoe)- .execute(&pool)- .await?;- sqlx::query(r#"UPDATE crm_contacts SET name = 'anna smith' WHERE id = $1"#)- .bind(carol)- .execute(&pool)- .await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let contacts = repo- .list_contacts_for_company(&team_id, &company_id, false)- .await?;- let ids: Vec<Uuid> = contacts.iter().map(|c| c.id).collect();- // "anna smith" (carol) < "[email protected]" (mike) < "zoe adams" (zoe)- assert_eq!(ids, vec![carol, mike, zoe]);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn list_contacts_excludes_hidden(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;- let visible = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;- let hidden = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;- sqlx::query(r#"UPDATE crm_contacts SET hidden = TRUE WHERE id = $1"#)- .bind(hidden)- .execute(&pool)- .await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let contacts = repo- .list_contacts_for_company(&team_id, &company_id, false)- .await?;- let ids: Vec<Uuid> = contacts.iter().map(|c| c.id).collect();- assert_eq!(ids, vec![visible]);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn list_contacts_owned_company_with_no_contacts_returns_empty(- pool: PgPool,-) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- seed_team(&pool, team_id, "macro|[email protected]").await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let contacts = repo- .list_contacts_for_company(&team_id, &company_id, false)- .await?;- assert!(contacts.is_empty());- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn list_contacts_unknown_company_returns_not_found(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- seed_team(&pool, team_id, "macro|[email protected]").await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .list_contacts_for_company(&team_id, &Uuid::now_v7(), false)- .await;- assert!(matches!(- result,- Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)- ));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn list_contacts_does_not_leak_across_teams(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?;- let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;- let link_a = insert_email_link(&pool, "macro|[email protected]", "[email protected]").await?;- insert_contact_with_source(&pool, company_a, "[email protected]", link_a).await?;-- // Team B asking for team A's company must 404, not see an empty list.- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .list_contacts_for_company(&team_b, &company_a, false)- .await;- assert!(matches!(- result,- Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)- ));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn get_contact_returns_owned_visible_contact(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;- let contact_id =- insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;- sqlx::query(r#"UPDATE crm_contacts SET name = 'Alice Adams' WHERE id = $1"#)- .bind(contact_id)- .execute(&pool)- .await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let contact = repo- .get_contact_for_team(&team_id, &contact_id, false)- .await?- .expect("contact should be returned");-- assert_eq!(contact.id, contact_id);- assert_eq!(contact.company_id, company_id);- assert_eq!(contact.email, "[email protected]");- assert_eq!(contact.name.as_deref(), Some("Alice Adams"));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn get_contact_returns_none_for_unknown_id(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- seed_team(&pool, team_id, "macro|[email protected]").await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .get_contact_for_team(&team_id, &Uuid::now_v7(), false)- .await?;- assert!(result.is_none());- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn get_contact_does_not_leak_across_teams(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?;- let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;- let link_a = insert_email_link(&pool, "macro|[email protected]", "[email protected]").await?;- let contact_a = insert_contact_with_source(&pool, company_a, "[email protected]", link_a).await?;-- // Team B fetching team A's contact must get None, not the row.- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .get_contact_for_team(&team_b, &contact_a, false)- .await?;- assert!(result.is_none());- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn get_contact_returns_none_for_hidden_contact(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;- let contact_id =- insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;- sqlx::query(r#"UPDATE crm_contacts SET hidden = TRUE WHERE id = $1"#)- .bind(contact_id)- .execute(&pool)- .await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .get_contact_for_team(&team_id, &contact_id, false)- .await?;- assert!(result.is_none());- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn get_contact_returns_none_when_parent_company_is_hidden(- pool: PgPool,-) -> anyhow::Result<()> {- // Defensive: a non-hidden contact whose parent company is hidden- // must not be reachable. In practice `set_company_hidden` tears- // down contacts on hide, but the query enforces the invariant.- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;- let contact_id =- insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;- // Force company hidden directly (bypassing the service cascade)- // to simulate a stale row from a prior buggy code path.- sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)- .bind(company_id)- .execute(&pool)- .await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .get_contact_for_team(&team_id, &contact_id, false)- .await?;- assert!(result.is_none());- Ok(())-}--// ----------------------------------------------------------------------------// Admin-visibility: include_hidden = true reveals hidden contacts /-// hidden parent companies. Mirrors what the read handlers do when the-// user's resolved team role is Admin or Owner.-// -----------------------------------------------------------------------------#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn list_contacts_admin_sees_hidden_contacts(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;- let visible = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;- let hidden = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;- sqlx::query(r#"UPDATE crm_contacts SET hidden = TRUE WHERE id = $1"#)- .bind(hidden)- .execute(&pool)- .await?;-- let repo = CompaniesRepositoryImpl::new(pool);-- // Member: only the visible contact.- let member = repo- .list_contacts_for_company(&team_id, &company_id, false)- .await?;- let member_ids: Vec<Uuid> = member.iter().map(|c| c.id).collect();- assert_eq!(member_ids, vec![visible]);-- // Admin: both contacts; the response carries the hidden flag so the- // admin UI can render the right toggle state.- let admin = repo- .list_contacts_for_company(&team_id, &company_id, true)- .await?;- let admin_ids: Vec<Uuid> = admin.iter().map(|c| c.id).collect();- assert_eq!(admin_ids.len(), 2);- assert!(admin_ids.contains(&visible));- assert!(admin_ids.contains(&hidden));- let hidden_contact = admin.iter().find(|c| c.id == hidden).expect("hidden");- assert!(hidden_contact.hidden);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn list_contacts_admin_reaches_hidden_company(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;- insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;- sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)- .bind(company_id)- .execute(&pool)- .await?;-- let repo = CompaniesRepositoryImpl::new(pool);-- // Member: hidden parent → 404 (CompanyNotFoundForTeam).- let member = repo- .list_contacts_for_company(&team_id, &company_id, false)- .await;- assert!(matches!(- member,- Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)- ));-- // Admin: the hidden company is reachable.- let admin = repo- .list_contacts_for_company(&team_id, &company_id, true)- .await?;- assert_eq!(admin.len(), 1);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn get_contact_admin_sees_hidden_contact(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;- let contact_id =- insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;- sqlx::query(r#"UPDATE crm_contacts SET hidden = TRUE WHERE id = $1"#)- .bind(contact_id)- .execute(&pool)- .await?;-- let repo = CompaniesRepositoryImpl::new(pool);-- // Member: hidden contact → None (404).- assert!(- repo.get_contact_for_team(&team_id, &contact_id, false)- .await?- .is_none()- );-- // Admin: contact is reachable; response carries hidden=true.- let admin = repo- .get_contact_for_team(&team_id, &contact_id, true)- .await?- .expect("admin should see hidden contact");- assert_eq!(admin.id, contact_id);- assert!(admin.hidden);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn get_contact_admin_reaches_contact_under_hidden_company(- pool: PgPool,-) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner_id = "macro|[email protected]";- seed_team(&pool, team_id, owner_id).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;- let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;- let contact_id =- insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;- sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)- .bind(company_id)- .execute(&pool)- .await?;-- let repo = CompaniesRepositoryImpl::new(pool);- assert!(- repo.get_contact_for_team(&team_id, &contact_id, false)- .await?- .is_none()- );- let admin = repo- .get_contact_for_team(&team_id, &contact_id, true)- .await?- .expect("admin should reach a contact under a hidden company");- assert_eq!(admin.id, contact_id);- Ok(())-}--// ----------------------------------------------------------------------------// CRM comment threads-// -----------------------------------------------------------------------------/// Inserts a bare contact under `company_id` (no source row needed for the-/// comment tests).-async fn insert_contact(pool: &PgPool, company_id: Uuid, email: &str) -> sqlx::Result<Uuid> {- let contact_id = Uuid::now_v7();- sqlx::query(- r#"INSERT INTO crm_contacts (id, company_id, email, first_interaction, last_interaction)- VALUES ($1, $2, $3, now(), now())"#,- )- .bind(contact_id)- .bind(company_id)- .bind(email)- .execute(pool)- .await?;- Ok(contact_id)-}--/// Counts live (non-soft-deleted) threads.-async fn count_threads(pool: &PgPool) -> sqlx::Result<i64> {- let (count,): (i64,) =- sqlx::query_as(r#"SELECT COUNT(*) FROM crm_thread WHERE deleted_at IS NULL"#)- .fetch_one(pool)- .await?;- Ok(count)-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn create_crm_comment_opens_thread_on_company(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team_id, owner).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let ct = repo- .create_crm_comment(- &team_id,- CrmCommentEntityType::CrmCompany,- &company_id,- owner,- None,- None,- "first comment",- None,- false,- )- .await?;-- assert_eq!(ct.thread.entity_type, CrmCommentEntityType::CrmCompany);- assert_eq!(ct.thread.entity_id, company_id);- assert_eq!(ct.thread.owner, owner);- assert_eq!(ct.comments.len(), 1);- assert_eq!(ct.comments[0].text, "first comment");- assert_eq!(ct.comments[0].owner, owner);- assert_eq!(ct.comments[0].thread_id, ct.thread.thread_id);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn create_crm_comment_opens_thread_on_contact(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team_id, owner).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;- let contact_id = insert_contact(&pool, company_id, "[email protected]").await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let ct = repo- .create_crm_comment(- &team_id,- CrmCommentEntityType::CrmContact,- &contact_id,- owner,- None,- None,- "hi alice",- None,- false,- )- .await?;-- assert_eq!(ct.thread.entity_type, CrmCommentEntityType::CrmContact);- assert_eq!(ct.thread.entity_id, contact_id);- assert_eq!(ct.comments.len(), 1);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn create_crm_comment_reply_appends_to_thread(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team_id, owner).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool.clone());- let root = repo- .create_crm_comment(- &team_id,- CrmCommentEntityType::CrmCompany,- &company_id,- owner,- None,- None,- "root",- None,- false,- )- .await?;- let thread_id = root.thread.thread_id;-- repo.create_crm_comment(- &team_id,- CrmCommentEntityType::CrmCompany,- &company_id,- owner,- Some(thread_id),- None,- "reply",- None,- false,- )- .await?;-- // One thread, two comments, oldest-first.- let threads = repo- .get_crm_comment_threads(- &team_id,- CrmCommentEntityType::CrmCompany,- &company_id,- false,- )- .await?;- assert_eq!(threads.len(), 1);- assert_eq!(threads[0].thread.thread_id, thread_id);- assert_eq!(threads[0].comments.len(), 2);- assert_eq!(threads[0].comments[0].text, "root");- assert_eq!(threads[0].comments[1].text, "reply");- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn create_crm_comment_unknown_company_404(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team_id, owner).await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .create_crm_comment(- &team_id,- CrmCommentEntityType::CrmCompany,- &Uuid::now_v7(),- owner,- None,- None,- "x",- None,- false,- )- .await;- assert!(matches!(- result,- Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)- ));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn create_crm_comment_cross_team_404(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?;- let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;-- // Team B cannot comment on team A's company.- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .create_crm_comment(- &team_b,- CrmCommentEntityType::CrmCompany,- &company_a,- "macro|[email protected]",- None,- None,- "x",- None,- false,- )- .await;- assert!(matches!(- result,- Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)- ));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn create_crm_comment_reply_to_foreign_thread_404(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team_id, owner).await?;- let company_1 = insert_company(&pool, team_id, true, &["acme.com"]).await?;- let company_2 = insert_company(&pool, team_id, true, &["beta.com"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let root = repo- .create_crm_comment(- &team_id,- CrmCommentEntityType::CrmCompany,- &company_1,- owner,- None,- None,- "root",- None,- false,- )- .await?;-- // Replying with company_1's thread id but addressing company_2 must 404.- let result = repo- .create_crm_comment(- &team_id,- CrmCommentEntityType::CrmCompany,- &company_2,- owner,- Some(root.thread.thread_id),- None,- "reply",- None,- false,- )- .await;- assert!(matches!(- result,- Err(crate::domain::model::CrmError::ThreadNotFound)- ));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn get_crm_comment_threads_empty_for_owned_company(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- seed_team(&pool, team_id, "macro|[email protected]").await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let threads = repo- .get_crm_comment_threads(- &team_id,- CrmCommentEntityType::CrmCompany,- &company_id,- false,- )- .await?;- assert!(threads.is_empty());- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn get_crm_comment_threads_unknown_company_404(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- seed_team(&pool, team_id, "macro|[email protected]").await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let result = repo- .get_crm_comment_threads(- &team_id,- CrmCommentEntityType::CrmCompany,- &Uuid::now_v7(),- false,- )- .await;- assert!(matches!(- result,- Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)- ));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn edit_crm_comment_updates_text(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team_id, owner).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let ct = repo- .create_crm_comment(- &team_id,- CrmCommentEntityType::CrmCompany,- &company_id,- owner,- None,- None,- "before",- None,- false,- )- .await?;- let comment_id = ct.comments[0].comment_id;-- let updated = repo- .edit_crm_comment(&team_id, &comment_id, "after", false)- .await?;- assert_eq!(updated.text, "after");-- let threads = repo- .get_crm_comment_threads(- &team_id,- CrmCommentEntityType::CrmCompany,- &company_id,- false,- )- .await?;- assert_eq!(threads[0].comments[0].text, "after");- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn edit_crm_comment_cross_team_404(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?;- let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let ct = repo- .create_crm_comment(- &team_a,- CrmCommentEntityType::CrmCompany,- &company_a,- "macro|[email protected]",- None,- None,- "secret",- None,- false,- )- .await?;-- let result = repo- .edit_crm_comment(&team_b, &ct.comments[0].comment_id, "hacked", false)- .await;- assert!(matches!(- result,- Err(crate::domain::model::CrmError::CommentNotFound)- ));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn delete_crm_comment_removes_empty_thread(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team_id, owner).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool.clone());- let ct = repo- .create_crm_comment(- &team_id,- CrmCommentEntityType::CrmCompany,- &company_id,- owner,- None,- None,- "only comment",- None,- false,- )- .await?;-- let result = repo- .delete_crm_comment(&team_id, &ct.comments[0].comment_id, false)- .await?;- assert!(result.thread_deleted);- assert_eq!(result.thread_id, ct.thread.thread_id);- assert_eq!(count_threads(&pool).await?, 0);-- let threads = repo- .get_crm_comment_threads(- &team_id,- CrmCommentEntityType::CrmCompany,- &company_id,- false,- )- .await?;- assert!(threads.is_empty());- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn delete_crm_comment_keeps_thread_with_remaining(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team_id, owner).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool.clone());- let root = repo- .create_crm_comment(- &team_id,- CrmCommentEntityType::CrmCompany,- &company_id,- owner,- None,- None,- "root",- None,- false,- )- .await?;- repo.create_crm_comment(- &team_id,- CrmCommentEntityType::CrmCompany,- &company_id,- owner,- Some(root.thread.thread_id),- None,- "reply",- None,- false,- )- .await?;-- // Deleting the root leaves the thread alive with the reply.- let result = repo- .delete_crm_comment(&team_id, &root.comments[0].comment_id, false)- .await?;- assert!(!result.thread_deleted);-- let threads = repo- .get_crm_comment_threads(- &team_id,- CrmCommentEntityType::CrmCompany,- &company_id,- false,- )- .await?;- assert_eq!(threads.len(), 1);- assert_eq!(threads[0].comments.len(), 1);- assert_eq!(threads[0].comments[0].text, "reply");- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn delete_crm_comment_cross_team_404(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?;- let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool);- let ct = repo- .create_crm_comment(- &team_a,- CrmCommentEntityType::CrmCompany,- &company_a,- "macro|[email protected]",- None,- None,- "secret",- None,- false,- )- .await?;-- let result = repo- .delete_crm_comment(&team_b, &ct.comments[0].comment_id, false)- .await;- assert!(matches!(- result,- Err(crate::domain::model::CrmError::CommentNotFound)- ));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn deleting_company_cascades_to_threads(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team_id, owner).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool.clone());- repo.create_crm_comment(- &team_id,- CrmCommentEntityType::CrmCompany,- &company_id,- owner,- None,- None,- "doomed",- None,- false,- )- .await?;- assert_eq!(count_threads(&pool).await?, 1);-- // Hard-deleting the company cascades to its threads (and their comments).- sqlx::query(r#"DELETE FROM crm_companies WHERE id = $1"#)- .bind(company_id)- .execute(&pool)- .await?;- assert_eq!(count_threads(&pool).await?, 0);- Ok(())-}--// ----------------------------------------------------------------------------// Comments: admin-visibility on hidden parent entities-// -----------------------------------------------------------------------------#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn get_crm_comment_threads_admin_sees_hidden_company(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team_id, owner).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool.clone());- // Seed a thread while the company is visible.- repo.create_crm_comment(- &team_id,- CrmCommentEntityType::CrmCompany,- &company_id,- owner,- None,- None,- "hi",- None,- false,- )- .await?;-- // Hide the company.- sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)- .bind(company_id)- .execute(&pool)- .await?;-- // Member: 404 — hidden parent treated as not found.- let member = repo- .get_crm_comment_threads(- &team_id,- CrmCommentEntityType::CrmCompany,- &company_id,- false,- )- .await;- assert!(matches!(- member,- Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)- ));-- // Admin: thread is reachable.- let admin = repo- .get_crm_comment_threads(- &team_id,- CrmCommentEntityType::CrmCompany,- &company_id,- true,- )- .await?;- assert_eq!(admin.len(), 1);- assert_eq!(admin[0].comments.len(), 1);- assert_eq!(admin[0].comments[0].text, "hi");- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn create_crm_comment_blocks_member_on_hidden_entity(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team_id, owner).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;- sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)- .bind(company_id)- .execute(&pool)- .await?;-- let repo = CompaniesRepositoryImpl::new(pool.clone());- // Member: can't write to a hidden parent.- let member = repo- .create_crm_comment(- &team_id,- CrmCommentEntityType::CrmCompany,- &company_id,- owner,- None,- None,- "blocked",- None,- false,- )- .await;- assert!(matches!(- member,- Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)- ));-- // Admin: write succeeds.- let admin = repo- .create_crm_comment(- &team_id,- CrmCommentEntityType::CrmCompany,- &company_id,- owner,- None,- None,- "ok",- None,- true,- )- .await?;- assert_eq!(admin.comments.len(), 1);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn edit_delete_crm_comment_block_member_on_hidden_entity(pool: PgPool) -> anyhow::Result<()> {- let team_id = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team_id, owner).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;-- let repo = CompaniesRepositoryImpl::new(pool.clone());- let thread = repo- .create_crm_comment(- &team_id,- CrmCommentEntityType::CrmCompany,- &company_id,- owner,- None,- None,- "first",- None,- false,- )- .await?;- let comment_id = thread.comments[0].comment_id;-- // Hide the company AFTER the comment was created (so a hidden-parent- // edit/delete is the only thing under test).- sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)- .bind(company_id)- .execute(&pool)- .await?;-- // Member: edit and delete both 404 because the parent is hidden.- assert!(matches!(- repo.edit_crm_comment(&team_id, &comment_id, "edited", false)- .await,- Err(crate::domain::model::CrmError::CommentNotFound)- ));- assert!(matches!(- repo.delete_crm_comment(&team_id, &comment_id, false).await,- Err(crate::domain::model::CrmError::CommentNotFound)- ));-- // Admin: edit succeeds, then delete succeeds.- let edited = repo- .edit_crm_comment(&team_id, &comment_id, "edited by admin", true)- .await?;- assert_eq!(edited.text, "edited by admin");- repo.delete_crm_comment(&team_id, &comment_id, true).await?;- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn crm_comment_visibility_on_hidden_contact_with_visible_company(- pool: PgPool,-) -> anyhow::Result<()> {- // Closes the contact-side dimension of the hide matrix:- // company is visible, but `crm_contacts.hidden = TRUE`. Members- // 404 on every read/write touching the contact; admins reach- // everything. Without this case the `entity_owned_by_team` helper's- // contact arm (which checks BOTH `c.hidden` and `co.hidden`) is- // only exercised end-to-end via the cascade — this pins- // contact-only hide as a first-class state.- let team_id = Uuid::now_v7();- let owner = "macro|[email protected]";- seed_team(&pool, team_id, owner).await?;- let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;- let contact_id = insert_contact(&pool, company_id, "[email protected]").await?;-- let repo = CompaniesRepositoryImpl::new(pool.clone());- // Seed a thread on the contact while it's visible.- let thread = repo- .create_crm_comment(- &team_id,- CrmCommentEntityType::CrmContact,- &contact_id,- owner,- None,- None,- "first",- None,- false,- )- .await?;- let comment_id = thread.comments[0].comment_id;-- // Hide just the contact; parent company stays visible.- sqlx::query(r#"UPDATE crm_contacts SET hidden = TRUE WHERE id = $1"#)- .bind(contact_id)- .execute(&pool)- .await?;-- // Member view: every operation on the now-hidden contact 404s.- let member_list = repo- .get_crm_comment_threads(- &team_id,- CrmCommentEntityType::CrmContact,- &contact_id,- false,- )- .await;- assert!(matches!(- member_list,- Err(crate::domain::model::CrmError::ContactNotFoundForTeam)- ));-- let member_create = repo- .create_crm_comment(- &team_id,- CrmCommentEntityType::CrmContact,- &contact_id,- owner,- None,- None,- "blocked",- None,- false,- )- .await;- assert!(matches!(- member_create,- Err(crate::domain::model::CrmError::ContactNotFoundForTeam)- ));-- assert!(matches!(- repo.edit_crm_comment(&team_id, &comment_id, "edited", false)- .await,- Err(crate::domain::model::CrmError::CommentNotFound)- ));- assert!(matches!(- repo.delete_crm_comment(&team_id, &comment_id, false).await,- Err(crate::domain::model::CrmError::CommentNotFound)- ));-- // Admin view: everything reachable. Thread + comment survive,- // edit + delete succeed in sequence.- let admin_threads = repo- .get_crm_comment_threads(- &team_id,- CrmCommentEntityType::CrmContact,- &contact_id,- true,- )- .await?;- assert_eq!(admin_threads.len(), 1);- assert_eq!(admin_threads[0].comments.len(), 1);-- let edited = repo- .edit_crm_comment(&team_id, &comment_id, "edited by admin", true)- .await?;- assert_eq!(edited.text, "edited by admin");-- repo.delete_crm_comment(&team_id, &comment_id, true).await?;- Ok(())-}+//! Test suite for [`super::CompaniesRepositoryImpl`], split by the+//! function under test. Shared seeding / assertion helpers live in+//! [`helpers`]; each sibling module covers one repo method (or one+//! closely-related cluster of methods, e.g. all CRM comment operations+//! in [`comments`]).++mod helpers;++mod comments;+mod get_company_for_team;+mod get_contact_for_team;+mod list_companies_for_soup;+mod list_contacts_for_company;+mod populate_contact;+mod set_company_hidden;+mod set_contact_hidden;+mod set_email_sync;diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo/test/comments.rs b/rust/cloud-storage/crm/src/outbound/companies_repo/test/comments.rsnew file mode 100644index 0000000000..81b18a30a5--- /dev/null+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test/comments.rs@@ -0,0 +1,758 @@+use super::helpers::*;+use crate::domain::comment::CrmCommentEntityType;+use crate::domain::companies_repo::*;+use crate::outbound::companies_repo::*;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::PgPool;+use uuid::Uuid;++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn create_crm_comment_opens_thread_on_company(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team_id, owner).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let ct = repo+ .create_crm_comment(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_id,+ owner,+ None,+ None,+ "first comment",+ None,+ false,+ )+ .await?;++ assert_eq!(ct.thread.entity_type, CrmCommentEntityType::CrmCompany);+ assert_eq!(ct.thread.entity_id, company_id);+ assert_eq!(ct.thread.owner, owner);+ assert_eq!(ct.comments.len(), 1);+ assert_eq!(ct.comments[0].text, "first comment");+ assert_eq!(ct.comments[0].owner, owner);+ assert_eq!(ct.comments[0].thread_id, ct.thread.thread_id);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn create_crm_comment_opens_thread_on_contact(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team_id, owner).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ let contact_id = insert_contact(&pool, company_id, "[email protected]").await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let ct = repo+ .create_crm_comment(+ &team_id,+ CrmCommentEntityType::CrmContact,+ &contact_id,+ owner,+ None,+ None,+ "hi alice",+ None,+ false,+ )+ .await?;++ assert_eq!(ct.thread.entity_type, CrmCommentEntityType::CrmContact);+ assert_eq!(ct.thread.entity_id, contact_id);+ assert_eq!(ct.comments.len(), 1);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn create_crm_comment_reply_appends_to_thread(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team_id, owner).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ let root = repo+ .create_crm_comment(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_id,+ owner,+ None,+ None,+ "root",+ None,+ false,+ )+ .await?;+ let thread_id = root.thread.thread_id;++ repo.create_crm_comment(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_id,+ owner,+ Some(thread_id),+ None,+ "reply",+ None,+ false,+ )+ .await?;++ // One thread, two comments, oldest-first.+ let threads = repo+ .get_crm_comment_threads(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_id,+ false,+ )+ .await?;+ assert_eq!(threads.len(), 1);+ assert_eq!(threads[0].thread.thread_id, thread_id);+ assert_eq!(threads[0].comments.len(), 2);+ assert_eq!(threads[0].comments[0].text, "root");+ assert_eq!(threads[0].comments[1].text, "reply");+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn create_crm_comment_unknown_company_404(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team_id, owner).await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .create_crm_comment(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &Uuid::now_v7(),+ owner,+ None,+ None,+ "x",+ None,+ false,+ )+ .await;+ assert!(matches!(+ result,+ Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)+ ));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn create_crm_comment_cross_team_404(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?;+ let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;++ // Team B cannot comment on team A's company.+ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .create_crm_comment(+ &team_b,+ CrmCommentEntityType::CrmCompany,+ &company_a,+ "macro|[email protected]",+ None,+ None,+ "x",+ None,+ false,+ )+ .await;+ assert!(matches!(+ result,+ Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)+ ));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn create_crm_comment_reply_to_foreign_thread_404(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team_id, owner).await?;+ let company_1 = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ let company_2 = insert_company(&pool, team_id, true, &["beta.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let root = repo+ .create_crm_comment(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_1,+ owner,+ None,+ None,+ "root",+ None,+ false,+ )+ .await?;++ // Replying with company_1's thread id but addressing company_2 must 404.+ let result = repo+ .create_crm_comment(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_2,+ owner,+ Some(root.thread.thread_id),+ None,+ "reply",+ None,+ false,+ )+ .await;+ assert!(matches!(+ result,+ Err(crate::domain::model::CrmError::ThreadNotFound)+ ));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_crm_comment_threads_empty_for_owned_company(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ seed_team(&pool, team_id, "macro|[email protected]").await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let threads = repo+ .get_crm_comment_threads(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_id,+ false,+ )+ .await?;+ assert!(threads.is_empty());+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_crm_comment_threads_unknown_company_404(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ seed_team(&pool, team_id, "macro|[email protected]").await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .get_crm_comment_threads(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &Uuid::now_v7(),+ false,+ )+ .await;+ assert!(matches!(+ result,+ Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)+ ));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn edit_crm_comment_updates_text(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team_id, owner).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let ct = repo+ .create_crm_comment(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_id,+ owner,+ None,+ None,+ "before",+ None,+ false,+ )+ .await?;+ let comment_id = ct.comments[0].comment_id;++ let updated = repo+ .edit_crm_comment(&team_id, &comment_id, "after", false)+ .await?;+ assert_eq!(updated.text, "after");++ let threads = repo+ .get_crm_comment_threads(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_id,+ false,+ )+ .await?;+ assert_eq!(threads[0].comments[0].text, "after");+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn edit_crm_comment_cross_team_404(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?;+ let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let ct = repo+ .create_crm_comment(+ &team_a,+ CrmCommentEntityType::CrmCompany,+ &company_a,+ "macro|[email protected]",+ None,+ None,+ "secret",+ None,+ false,+ )+ .await?;++ let result = repo+ .edit_crm_comment(&team_b, &ct.comments[0].comment_id, "hacked", false)+ .await;+ assert!(matches!(+ result,+ Err(crate::domain::model::CrmError::CommentNotFound)+ ));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn delete_crm_comment_removes_empty_thread(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team_id, owner).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ let ct = repo+ .create_crm_comment(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_id,+ owner,+ None,+ None,+ "only comment",+ None,+ false,+ )+ .await?;++ let result = repo+ .delete_crm_comment(&team_id, &ct.comments[0].comment_id, false)+ .await?;+ assert!(result.thread_deleted);+ assert_eq!(result.thread_id, ct.thread.thread_id);+ assert_eq!(count_threads(&pool).await?, 0);++ let threads = repo+ .get_crm_comment_threads(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_id,+ false,+ )+ .await?;+ assert!(threads.is_empty());+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn delete_crm_comment_keeps_thread_with_remaining(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team_id, owner).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ let root = repo+ .create_crm_comment(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_id,+ owner,+ None,+ None,+ "root",+ None,+ false,+ )+ .await?;+ repo.create_crm_comment(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_id,+ owner,+ Some(root.thread.thread_id),+ None,+ "reply",+ None,+ false,+ )+ .await?;++ // Deleting the root leaves the thread alive with the reply.+ let result = repo+ .delete_crm_comment(&team_id, &root.comments[0].comment_id, false)+ .await?;+ assert!(!result.thread_deleted);++ let threads = repo+ .get_crm_comment_threads(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_id,+ false,+ )+ .await?;+ assert_eq!(threads.len(), 1);+ assert_eq!(threads[0].comments.len(), 1);+ assert_eq!(threads[0].comments[0].text, "reply");+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn delete_crm_comment_cross_team_404(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?;+ let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let ct = repo+ .create_crm_comment(+ &team_a,+ CrmCommentEntityType::CrmCompany,+ &company_a,+ "macro|[email protected]",+ None,+ None,+ "secret",+ None,+ false,+ )+ .await?;++ let result = repo+ .delete_crm_comment(&team_b, &ct.comments[0].comment_id, false)+ .await;+ assert!(matches!(+ result,+ Err(crate::domain::model::CrmError::CommentNotFound)+ ));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn deleting_company_cascades_to_threads(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team_id, owner).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ repo.create_crm_comment(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_id,+ owner,+ None,+ None,+ "doomed",+ None,+ false,+ )+ .await?;+ assert_eq!(count_threads(&pool).await?, 1);++ // Hard-deleting the company cascades to its threads (and their comments).+ sqlx::query(r#"DELETE FROM crm_companies WHERE id = $1"#)+ .bind(company_id)+ .execute(&pool)+ .await?;+ assert_eq!(count_threads(&pool).await?, 0);+ Ok(())+}++// ---------------------------------------------------------------------------+// Comments: admin-visibility on hidden parent entities+// ---------------------------------------------------------------------------++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_crm_comment_threads_admin_sees_hidden_company(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team_id, owner).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ // Seed a thread while the company is visible.+ repo.create_crm_comment(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_id,+ owner,+ None,+ None,+ "hi",+ None,+ false,+ )+ .await?;++ // Hide the company.+ sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)+ .bind(company_id)+ .execute(&pool)+ .await?;++ // Member: 404 — hidden parent treated as not found.+ let member = repo+ .get_crm_comment_threads(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_id,+ false,+ )+ .await;+ assert!(matches!(+ member,+ Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)+ ));++ // Admin: thread is reachable.+ let admin = repo+ .get_crm_comment_threads(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_id,+ true,+ )+ .await?;+ assert_eq!(admin.len(), 1);+ assert_eq!(admin[0].comments.len(), 1);+ assert_eq!(admin[0].comments[0].text, "hi");+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn create_crm_comment_blocks_member_on_hidden_entity(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team_id, owner).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)+ .bind(company_id)+ .execute(&pool)+ .await?;++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ // Member: can't write to a hidden parent.+ let member = repo+ .create_crm_comment(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_id,+ owner,+ None,+ None,+ "blocked",+ None,+ false,+ )+ .await;+ assert!(matches!(+ member,+ Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)+ ));++ // Admin: write succeeds.+ let admin = repo+ .create_crm_comment(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_id,+ owner,+ None,+ None,+ "ok",+ None,+ true,+ )+ .await?;+ assert_eq!(admin.comments.len(), 1);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn edit_delete_crm_comment_block_member_on_hidden_entity(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team_id, owner).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ let thread = repo+ .create_crm_comment(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_id,+ owner,+ None,+ None,+ "first",+ None,+ false,+ )+ .await?;+ let comment_id = thread.comments[0].comment_id;++ // Hide the company AFTER the comment was created (so a hidden-parent+ // edit/delete is the only thing under test).+ sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)+ .bind(company_id)+ .execute(&pool)+ .await?;++ // Member: edit and delete both 404 because the parent is hidden.+ assert!(matches!(+ repo.edit_crm_comment(&team_id, &comment_id, "edited", false)+ .await,+ Err(crate::domain::model::CrmError::CommentNotFound)+ ));+ assert!(matches!(+ repo.delete_crm_comment(&team_id, &comment_id, false).await,+ Err(crate::domain::model::CrmError::CommentNotFound)+ ));++ // Admin: edit succeeds, then delete succeeds.+ let edited = repo+ .edit_crm_comment(&team_id, &comment_id, "edited by admin", true)+ .await?;+ assert_eq!(edited.text, "edited by admin");+ repo.delete_crm_comment(&team_id, &comment_id, true).await?;+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn crm_comment_visibility_on_hidden_contact_with_visible_company(+ pool: PgPool,+) -> anyhow::Result<()> {+ // Closes the contact-side dimension of the hide matrix:+ // company is visible, but `crm_contacts.hidden = TRUE`. Members+ // 404 on every read/write touching the contact; admins reach+ // everything. Without this case the `entity_owned_by_team` helper's+ // contact arm (which checks BOTH `c.hidden` and `co.hidden`) is+ // only exercised end-to-end via the cascade — this pins+ // contact-only hide as a first-class state.+ let team_id = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team_id, owner).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ let contact_id = insert_contact(&pool, company_id, "[email protected]").await?;++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ // Seed a thread on the contact while it's visible.+ let thread = repo+ .create_crm_comment(+ &team_id,+ CrmCommentEntityType::CrmContact,+ &contact_id,+ owner,+ None,+ None,+ "first",+ None,+ false,+ )+ .await?;+ let comment_id = thread.comments[0].comment_id;++ // Hide just the contact; parent company stays visible.+ sqlx::query(r#"UPDATE crm_contacts SET hidden = TRUE WHERE id = $1"#)+ .bind(contact_id)+ .execute(&pool)+ .await?;++ // Member view: every operation on the now-hidden contact 404s.+ let member_list = repo+ .get_crm_comment_threads(+ &team_id,+ CrmCommentEntityType::CrmContact,+ &contact_id,+ false,+ )+ .await;+ assert!(matches!(+ member_list,+ Err(crate::domain::model::CrmError::ContactNotFoundForTeam)+ ));++ let member_create = repo+ .create_crm_comment(+ &team_id,+ CrmCommentEntityType::CrmContact,+ &contact_id,+ owner,+ None,+ None,+ "blocked",+ None,+ false,+ )+ .await;+ assert!(matches!(+ member_create,+ Err(crate::domain::model::CrmError::ContactNotFoundForTeam)+ ));++ assert!(matches!(+ repo.edit_crm_comment(&team_id, &comment_id, "edited", false)+ .await,+ Err(crate::domain::model::CrmError::CommentNotFound)+ ));+ assert!(matches!(+ repo.delete_crm_comment(&team_id, &comment_id, false).await,+ Err(crate::domain::model::CrmError::CommentNotFound)+ ));++ // Admin view: everything reachable. Thread + comment survive,+ // edit + delete succeed in sequence.+ let admin_threads = repo+ .get_crm_comment_threads(+ &team_id,+ CrmCommentEntityType::CrmContact,+ &contact_id,+ true,+ )+ .await?;+ assert_eq!(admin_threads.len(), 1);+ assert_eq!(admin_threads[0].comments.len(), 1);++ let edited = repo+ .edit_crm_comment(&team_id, &comment_id, "edited by admin", true)+ .await?;+ assert_eq!(edited.text, "edited by admin");++ repo.delete_crm_comment(&team_id, &comment_id, true).await?;+ Ok(())+}diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo/test/get_company_for_team.rs b/rust/cloud-storage/crm/src/outbound/companies_repo/test/get_company_for_team.rsnew file mode 100644index 0000000000..7af4886b75--- /dev/null+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test/get_company_for_team.rs@@ -0,0 +1,247 @@+use super::helpers::*;+use crate::domain::companies_repo::*;+use crate::outbound::companies_repo::*;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::PgPool;+use uuid::Uuid;++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_company_returns_owned_visible_company_with_contacts(+ pool: PgPool,+) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;+ let alice = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;+ let bob = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let record = repo+ .get_company_for_team(&team_id, &company_id, false)+ .await?+ .expect("company should be returned");++ assert_eq!(record.company.id, company_id);+ assert_eq!(record.company.team_id, team_id);+ assert!(record.company.email_sync);+ assert!(!record.company.hidden);+ assert_eq!(record.company.domains.len(), 1);+ assert_eq!(record.company.domains[0].domain, "acme.com");+ // No directory row → display name/description fall through to None.+ assert_eq!(record.name, None);+ assert_eq!(record.description, None);+ // Contacts arrive bundled in.+ let contact_ids: Vec<Uuid> = record.contacts.iter().map(|c| c.id).collect();+ assert_eq!(contact_ids.len(), 2);+ assert!(contact_ids.contains(&alice));+ assert!(contact_ids.contains(&bob));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_company_returns_company_with_no_contacts(pool: PgPool) -> anyhow::Result<()> {+ // A company with zero contacts should still resolve — `contacts` is+ // empty, not the whole record collapsing to None.+ let team_id = Uuid::now_v7();+ seed_team(&pool, team_id, "macro|[email protected]").await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let record = repo+ .get_company_for_team(&team_id, &company_id, false)+ .await?+ .expect("company should be returned");++ assert_eq!(record.company.id, company_id);+ assert!(record.contacts.is_empty());+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_company_returns_none_for_unknown_id(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ seed_team(&pool, team_id, "macro|[email protected]").await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .get_company_for_team(&team_id, &Uuid::now_v7(), false)+ .await?;+ assert!(result.is_none());+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_company_does_not_leak_across_teams(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?;+ let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;++ // Team B fetching team A's company must get None even as admin.+ let repo = CompaniesRepositoryImpl::new(pool);+ assert!(+ repo.get_company_for_team(&team_b, &company_a, false)+ .await?+ .is_none()+ );+ assert!(+ repo.get_company_for_team(&team_b, &company_a, true)+ .await?+ .is_none()+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_company_returns_none_for_hidden_company_member(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ seed_team(&pool, team_id, "macro|[email protected]").await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)+ .bind(company_id)+ .execute(&pool)+ .await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .get_company_for_team(&team_id, &company_id, false)+ .await?;+ assert!(result.is_none());+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_company_admin_sees_hidden_company(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;+ insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;+ sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)+ .bind(company_id)+ .execute(&pool)+ .await?;++ let repo = CompaniesRepositoryImpl::new(pool);++ // Member: hidden → None.+ assert!(+ repo.get_company_for_team(&team_id, &company_id, false)+ .await?+ .is_none()+ );++ // Admin: reachable; response carries hidden = true so the UI can+ // render the right toggle state.+ let admin = repo+ .get_company_for_team(&team_id, &company_id, true)+ .await?+ .expect("admin should see hidden company");+ assert!(admin.company.hidden);+ assert_eq!(admin.contacts.len(), 1);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_company_filters_hidden_contacts_for_member(pool: PgPool) -> anyhow::Result<()> {+ // Company itself is visible; one of its contacts is hidden.+ // Member: contacts list excludes the hidden one. Admin: both.+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;+ let visible = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;+ let hidden = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;+ sqlx::query(r#"UPDATE crm_contacts SET hidden = TRUE WHERE id = $1"#)+ .bind(hidden)+ .execute(&pool)+ .await?;++ let repo = CompaniesRepositoryImpl::new(pool);++ let member = repo+ .get_company_for_team(&team_id, &company_id, false)+ .await?+ .expect("company visible to member");+ let member_contacts: Vec<Uuid> = member.contacts.iter().map(|c| c.id).collect();+ assert_eq!(member_contacts, vec![visible]);++ let admin = repo+ .get_company_for_team(&team_id, &company_id, true)+ .await?+ .expect("company visible to admin");+ let admin_contacts: Vec<Uuid> = admin.contacts.iter().map(|c| c.id).collect();+ assert_eq!(admin_contacts.len(), 2);+ assert!(admin_contacts.contains(&visible));+ assert!(admin_contacts.contains(&hidden));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_company_hydrates_name_and_description_from_primary_domain(+ pool: PgPool,+) -> anyhow::Result<()> {+ // Two domains; directory row only on the primary (earliest-created).+ // The handler returns metadata from the primary, not the secondary.+ let team_id = Uuid::now_v7();+ seed_team(&pool, team_id, "macro|[email protected]").await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com", "acmecorp.com"]).await?;+ sqlx::query(+ r#"INSERT INTO crm_domain_directory (domain, name, description)+ VALUES ($1, $2, $3)"#,+ )+ .bind("acme.com")+ .bind("Acme Inc.")+ .bind("Maker of rocket-powered roller skates.")+ .execute(&pool)+ .await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let record = repo+ .get_company_for_team(&team_id, &company_id, false)+ .await?+ .expect("company should be returned");++ assert_eq!(record.name.as_deref(), Some("Acme Inc."));+ assert_eq!(+ record.description.as_deref(),+ Some("Maker of rocket-powered roller skates.")+ );+ // Domain order is by created_at ASC; primary first.+ assert_eq!(record.company.domains.len(), 2);+ assert_eq!(record.company.domains[0].domain, "acme.com");+ assert_eq!(record.company.domains[1].domain, "acmecorp.com");+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_company_returns_none_for_negative_cache_directory_row(+ pool: PgPool,+) -> anyhow::Result<()> {+ // Negative-cache directory row (NULL name/description) must surface+ // as None on the response, not Some("").+ let team_id = Uuid::now_v7();+ seed_team(&pool, team_id, "macro|[email protected]").await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ sqlx::query(+ r#"INSERT INTO crm_domain_directory (domain, name, description)+ VALUES ($1, NULL, NULL)"#,+ )+ .bind("acme.com")+ .execute(&pool)+ .await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let record = repo+ .get_company_for_team(&team_id, &company_id, false)+ .await?+ .expect("company should be returned");+ assert_eq!(record.name, None);+ assert_eq!(record.description, None);+ Ok(())+}diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo/test/get_contact_for_team.rs b/rust/cloud-storage/crm/src/outbound/companies_repo/test/get_contact_for_team.rsnew file mode 100644index 0000000000..6fadc090ce--- /dev/null+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test/get_contact_for_team.rs@@ -0,0 +1,179 @@+use super::helpers::*;+use crate::domain::companies_repo::*;+use crate::outbound::companies_repo::*;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::PgPool;+use uuid::Uuid;++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_contact_returns_owned_visible_contact(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;+ let contact_id =+ insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;+ sqlx::query(r#"UPDATE crm_contacts SET name = 'Alice Adams' WHERE id = $1"#)+ .bind(contact_id)+ .execute(&pool)+ .await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let contact = repo+ .get_contact_for_team(&team_id, &contact_id, false)+ .await?+ .expect("contact should be returned");++ assert_eq!(contact.id, contact_id);+ assert_eq!(contact.company_id, company_id);+ assert_eq!(contact.email, "[email protected]");+ assert_eq!(contact.name.as_deref(), Some("Alice Adams"));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_contact_returns_none_for_unknown_id(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ seed_team(&pool, team_id, "macro|[email protected]").await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .get_contact_for_team(&team_id, &Uuid::now_v7(), false)+ .await?;+ assert!(result.is_none());+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_contact_does_not_leak_across_teams(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?;+ let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;+ let link_a = insert_email_link(&pool, "macro|[email protected]", "[email protected]").await?;+ let contact_a = insert_contact_with_source(&pool, company_a, "[email protected]", link_a).await?;++ // Team B fetching team A's contact must get None, not the row.+ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .get_contact_for_team(&team_b, &contact_a, false)+ .await?;+ assert!(result.is_none());+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_contact_returns_none_for_hidden_contact(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;+ let contact_id =+ insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;+ sqlx::query(r#"UPDATE crm_contacts SET hidden = TRUE WHERE id = $1"#)+ .bind(contact_id)+ .execute(&pool)+ .await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .get_contact_for_team(&team_id, &contact_id, false)+ .await?;+ assert!(result.is_none());+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_contact_returns_none_when_parent_company_is_hidden(+ pool: PgPool,+) -> anyhow::Result<()> {+ // Defensive: a non-hidden contact whose parent company is hidden+ // must not be reachable. In practice `set_company_hidden` tears+ // down contacts on hide, but the query enforces the invariant.+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;+ let contact_id =+ insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;+ // Force company hidden directly (bypassing the service cascade)+ // to simulate a stale row from a prior buggy code path.+ sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)+ .bind(company_id)+ .execute(&pool)+ .await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .get_contact_for_team(&team_id, &contact_id, false)+ .await?;+ assert!(result.is_none());+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_contact_admin_sees_hidden_contact(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;+ let contact_id =+ insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;+ sqlx::query(r#"UPDATE crm_contacts SET hidden = TRUE WHERE id = $1"#)+ .bind(contact_id)+ .execute(&pool)+ .await?;++ let repo = CompaniesRepositoryImpl::new(pool);++ // Member: hidden contact → None (404).+ assert!(+ repo.get_contact_for_team(&team_id, &contact_id, false)+ .await?+ .is_none()+ );++ // Admin: contact is reachable; response carries hidden=true.+ let admin = repo+ .get_contact_for_team(&team_id, &contact_id, true)+ .await?+ .expect("admin should see hidden contact");+ assert_eq!(admin.id, contact_id);+ assert!(admin.hidden);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_contact_admin_reaches_contact_under_hidden_company(+ pool: PgPool,+) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;+ let contact_id =+ insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;+ sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)+ .bind(company_id)+ .execute(&pool)+ .await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ assert!(+ repo.get_contact_for_team(&team_id, &contact_id, false)+ .await?+ .is_none()+ );+ let admin = repo+ .get_contact_for_team(&team_id, &contact_id, true)+ .await?+ .expect("admin should reach a contact under a hidden company");+ assert_eq!(admin.id, contact_id);+ Ok(())+}diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo/test/helpers.rs b/rust/cloud-storage/crm/src/outbound/companies_repo/test/helpers.rsnew file mode 100644index 0000000000..ecb6e2eb10--- /dev/null+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test/helpers.rs@@ -0,0 +1,298 @@+use sqlx::PgPool;+use uuid::Uuid;++pub(super) async fn seed_team(pool: &PgPool, team_id: Uuid, owner_id: &str) -> sqlx::Result<()> {+ let macro_user_id = Uuid::now_v7();++ sqlx::query(+ r#"INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, $2, $3, $4)"#,+ )+ .bind(macro_user_id)+ .bind(owner_id)+ .bind(owner_id)+ .bind(format!("stripe_{macro_user_id}"))+ .execute(pool)+ .await?;++ sqlx::query(r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $2, $3)"#)+ .bind(owner_id)+ .bind(owner_id)+ .bind(macro_user_id)+ .execute(pool)+ .await?;++ sqlx::query(r#"INSERT INTO team (id, name, owner_id) VALUES ($1, $2, $3)"#)+ .bind(team_id)+ .bind("test team")+ .bind(owner_id)+ .execute(pool)+ .await?;++ Ok(())+}++pub(super) async fn insert_company(+ pool: &PgPool,+ team_id: Uuid,+ email_sync: bool,+ domains: &[&str],+) -> sqlx::Result<Uuid> {+ let company_id = Uuid::now_v7();++ sqlx::query(+ r#"INSERT INTO crm_companies (id, team_id, email_sync, first_interaction, last_interaction)+ VALUES ($1, $2, $3, now(), now())"#,+ )+ .bind(company_id)+ .bind(team_id)+ .bind(email_sync)+ .execute(pool)+ .await?;++ for domain in domains {+ sqlx::query(r#"INSERT INTO crm_domains (company_id, team_id, domain) VALUES ($1, $2, $3)"#)+ .bind(company_id)+ .bind(team_id)+ .bind(*domain)+ .execute(pool)+ .await?;+ }++ Ok(company_id)+}++pub(super) async fn insert_email_link(+ pool: &PgPool,+ owner_id: &str,+ email: &str,+) -> sqlx::Result<Uuid> {+ let link_id = Uuid::now_v7();+ sqlx::query(+ r#"INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider)+ VALUES ($1, $2, $3, $4, 'GMAIL')"#,+ )+ .bind(link_id)+ .bind(owner_id)+ .bind(format!("fa_{link_id}"))+ .bind(email)+ .execute(pool)+ .await?;+ Ok(link_id)+}++pub(super) async fn insert_contact_with_source(+ pool: &PgPool,+ company_id: Uuid,+ email: &str,+ link_id: Uuid,+) -> sqlx::Result<Uuid> {+ let contact_id = Uuid::now_v7();+ sqlx::query(+ r#"INSERT INTO crm_contacts (id, company_id, email, first_interaction, last_interaction)+ VALUES ($1, $2, $3, now(), now())"#,+ )+ .bind(contact_id)+ .bind(company_id)+ .bind(email)+ .execute(pool)+ .await?;+ sqlx::query(r#"INSERT INTO crm_contact_sources (contact_id, link_id) VALUES ($1, $2)"#)+ .bind(contact_id)+ .bind(link_id)+ .execute(pool)+ .await?;+ Ok(contact_id)+}++pub(super) async fn count_contacts(pool: &PgPool, company_id: Uuid) -> sqlx::Result<i64> {+ let (count,): (i64,) =+ sqlx::query_as(r#"SELECT COUNT(*) FROM crm_contacts WHERE company_id = $1"#)+ .bind(company_id)+ .fetch_one(pool)+ .await?;+ Ok(count)+}++pub(super) async fn count_sources_for_company(+ pool: &PgPool,+ company_id: Uuid,+) -> sqlx::Result<i64> {+ let (count,): (i64,) = sqlx::query_as(+ r#"SELECT COUNT(*) FROM crm_contact_sources cs+ JOIN crm_contacts ct ON ct.id = cs.contact_id+ WHERE ct.company_id = $1"#,+ )+ .bind(company_id)+ .fetch_one(pool)+ .await?;+ Ok(count)+}++pub(super) async fn fetch_email_sync(+ pool: &PgPool,+ company_id: Uuid,+) -> sqlx::Result<Option<bool>> {+ let row: Option<(bool,)> =+ sqlx::query_as(r#"SELECT email_sync FROM crm_companies WHERE id = $1"#)+ .bind(company_id)+ .fetch_optional(pool)+ .await?;+ Ok(row.map(|(s,)| s))+}++pub(super) async fn fetch_company_hidden(+ pool: &PgPool,+ company_id: Uuid,+) -> sqlx::Result<Option<bool>> {+ let row: Option<(bool,)> = sqlx::query_as(r#"SELECT hidden FROM crm_companies WHERE id = $1"#)+ .bind(company_id)+ .fetch_optional(pool)+ .await?;+ Ok(row.map(|(h,)| h))+}++pub(super) async fn fetch_contact_hidden(+ pool: &PgPool,+ contact_id: Uuid,+) -> sqlx::Result<Option<bool>> {+ let row: Option<(bool,)> = sqlx::query_as(r#"SELECT hidden FROM crm_contacts WHERE id = $1"#)+ .bind(contact_id)+ .fetch_optional(pool)+ .await?;+ Ok(row.map(|(h,)| h))+}++pub(super) async fn fetch_company_updated_at(+ pool: &PgPool,+ company_id: Uuid,+) -> sqlx::Result<Option<chrono::DateTime<chrono::Utc>>> {+ let row: Option<(chrono::DateTime<chrono::Utc>,)> =+ sqlx::query_as(r#"SELECT updated_at FROM crm_companies WHERE id = $1"#)+ .bind(company_id)+ .fetch_optional(pool)+ .await?;+ Ok(row.map(|(updated_at,)| updated_at))+}++pub(super) async fn fetch_contact_updated_at(+ pool: &PgPool,+ contact_id: Uuid,+) -> sqlx::Result<Option<chrono::DateTime<chrono::Utc>>> {+ let row: Option<(chrono::DateTime<chrono::Utc>,)> =+ sqlx::query_as(r#"SELECT updated_at FROM crm_contacts WHERE id = $1"#)+ .bind(contact_id)+ .fetch_optional(pool)+ .await?;+ Ok(row.map(|(updated_at,)| updated_at))+}++pub(super) async fn fetch_company_interactions(+ pool: &PgPool,+ company_id: Uuid,+) -> sqlx::Result<Option<(chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>)>> {+ sqlx::query_as(r#"SELECT first_interaction, last_interaction FROM crm_companies WHERE id = $1"#)+ .bind(company_id)+ .fetch_optional(pool)+ .await+}++pub(super) async fn fetch_contact_interactions(+ pool: &PgPool,+ contact_id: Uuid,+) -> sqlx::Result<Option<(chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>)>> {+ sqlx::query_as(r#"SELECT first_interaction, last_interaction FROM crm_contacts WHERE id = $1"#)+ .bind(contact_id)+ .fetch_optional(pool)+ .await+}++pub(super) async fn fetch_company_for_domain(+ pool: &PgPool,+ team_id: Uuid,+ domain: &str,+) -> sqlx::Result<Option<Uuid>> {+ let row: Option<(Uuid,)> = sqlx::query_as(+ 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) = LOWER($2)+ LIMIT 1"#,+ )+ .bind(team_id)+ .bind(domain)+ .fetch_optional(pool)+ .await?;+ Ok(row.map(|(id,)| id))+}++pub(super) async fn fetch_contact_id(+ pool: &PgPool,+ company_id: Uuid,+ email: &str,+) -> sqlx::Result<Option<Uuid>> {+ let row: Option<(Uuid,)> = sqlx::query_as(+ r#"SELECT id FROM crm_contacts WHERE company_id = $1 AND LOWER(email) = LOWER($2) LIMIT 1"#,+ )+ .bind(company_id)+ .bind(email)+ .fetch_optional(pool)+ .await?;+ Ok(row.map(|(id,)| id))+}++pub(super) async fn enable_crm_for_team(pool: &PgPool, team_id: Uuid) -> sqlx::Result<()> {+ sqlx::query(+ r#"INSERT INTO team_crm_settings (team_id, crm_enabled) VALUES ($1, TRUE)+ ON CONFLICT (team_id) DO UPDATE SET crm_enabled = TRUE"#,+ )+ .bind(team_id)+ .execute(pool)+ .await?;+ Ok(())+}++pub(super) async fn count_companies_for_domain(+ pool: &PgPool,+ team_id: Uuid,+ domain: &str,+) -> sqlx::Result<i64> {+ let (count,): (i64,) = sqlx::query_as(+ r#"SELECT COUNT(*) FROM crm_companies c+ JOIN crm_domains d ON d.company_id = c.id+ WHERE c.team_id = $1 AND LOWER(d.domain) = LOWER($2)"#,+ )+ .bind(team_id)+ .bind(domain)+ .fetch_one(pool)+ .await?;+ Ok(count)+}++/// Inserts a bare contact under `company_id` (no source row needed for the+/// comment tests).+pub(super) async fn insert_contact(+ pool: &PgPool,+ company_id: Uuid,+ email: &str,+) -> sqlx::Result<Uuid> {+ let contact_id = Uuid::now_v7();+ sqlx::query(+ r#"INSERT INTO crm_contacts (id, company_id, email, first_interaction, last_interaction)+ VALUES ($1, $2, $3, now(), now())"#,+ )+ .bind(contact_id)+ .bind(company_id)+ .bind(email)+ .execute(pool)+ .await?;+ Ok(contact_id)+}++/// Counts live (non-soft-deleted) threads.+pub(super) async fn count_threads(pool: &PgPool) -> sqlx::Result<i64> {+ let (count,): (i64,) =+ sqlx::query_as(r#"SELECT COUNT(*) FROM crm_thread WHERE deleted_at IS NULL"#)+ .fetch_one(pool)+ .await?;+ Ok(count)+}diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo/test/list_companies_for_soup.rs b/rust/cloud-storage/crm/src/outbound/companies_repo/test/list_companies_for_soup.rsnew file mode 100644index 0000000000..b85b12fc5c--- /dev/null+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test/list_companies_for_soup.rs@@ -0,0 +1,437 @@+use super::helpers::*;+use crate::domain::companies_repo::*;+use crate::outbound::companies_repo::*;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::PgPool;+use uuid::Uuid;++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_for_soup_returns_empty_when_killswitch_missing(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team, owner).await?;+ // No team_crm_settings row → killswitch defaults to off.+ insert_company(&pool, team, true, &["acme.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .list_companies_for_soup(+ &team,+ "macro|[email protected]",+ &[],+ None,+ CrmCompanyListSort::UpdatedAt,+ None,+ 100,+ )+ .await?;+ assert!(+ result.is_empty(),+ "killswitch missing must short-circuit to empty list even when companies exist"+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_for_soup_returns_empty_when_killswitch_off(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team, owner).await?;+ sqlx::query(r#"INSERT INTO team_crm_settings (team_id, crm_enabled) VALUES ($1, FALSE)"#)+ .bind(team)+ .execute(&pool)+ .await?;+ insert_company(&pool, team, true, &["acme.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .list_companies_for_soup(+ &team,+ "macro|[email protected]",+ &[],+ None,+ CrmCompanyListSort::UpdatedAt,+ None,+ 100,+ )+ .await?;+ assert!(result.is_empty());+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_for_soup_excludes_hidden_rows(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team, owner).await?;+ enable_crm_for_team(&pool, team).await?;+ let visible = insert_company(&pool, team, true, &["acme.com"]).await?;+ let hidden = insert_company(&pool, team, true, &["zeta.com"]).await?;+ sqlx::query("UPDATE crm_companies SET hidden = TRUE WHERE id = $1")+ .bind(hidden)+ .execute(&pool)+ .await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .list_companies_for_soup(+ &team,+ "macro|[email protected]",+ &[],+ None,+ CrmCompanyListSort::UpdatedAt,+ None,+ 100,+ )+ .await?;+ let ids: Vec<Uuid> = result.iter().map(|c| c.company.id).collect();+ assert_eq!(ids, vec![visible], "hidden = TRUE rows must not appear");+ // The visible row must have its domains hydrated.+ assert_eq!(result[0].company.domains.len(), 1);+ assert_eq!(result[0].company.domains[0].domain, "acme.com");+ // No directory row for acme.com — both display fields should be None.+ assert_eq!(result[0].name, None);+ assert_eq!(result[0].description, None);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_for_soup_returns_hidden_when_hidden_true(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team, owner).await?;+ enable_crm_for_team(&pool, team).await?;+ let visible = insert_company(&pool, team, true, &["acme.com"]).await?;+ let hidden = insert_company(&pool, team, true, &["zeta.com"]).await?;+ sqlx::query("UPDATE crm_companies SET hidden = TRUE WHERE id = $1")+ .bind(hidden)+ .execute(&pool)+ .await?;++ let repo = CompaniesRepositoryImpl::new(pool);++ let hidden_only = repo+ .list_companies_for_soup(+ &team,+ "macro|[email protected]",+ &[],+ Some(true),+ CrmCompanyListSort::UpdatedAt,+ None,+ 100,+ )+ .await?;+ let ids: Vec<Uuid> = hidden_only.iter().map(|c| c.company.id).collect();+ assert_eq!(+ ids,+ vec![hidden],+ "hidden=Some(true) must return only hidden rows"+ );++ let visible_only_explicit = repo+ .list_companies_for_soup(+ &team,+ "macro|[email protected]",+ &[],+ Some(false),+ CrmCompanyListSort::UpdatedAt,+ None,+ 100,+ )+ .await?;+ let ids: Vec<Uuid> = visible_only_explicit.iter().map(|c| c.company.id).collect();+ assert_eq!(+ ids,+ vec![visible],+ "hidden=Some(false) must behave the same as None (visible only)",+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_for_soup_hydrates_name_and_description_from_directory(+ pool: PgPool,+) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team, owner).await?;+ enable_crm_for_team(&pool, team).await?;+ insert_company(&pool, team, true, &["acme.com", "acmecorp.com"]).await?;+ // Directory row only on the primary — secondary must not be picked.+ sqlx::query(+ r#"INSERT INTO crm_domain_directory (domain, name, description)+ VALUES ($1, $2, $3)"#,+ )+ .bind("acme.com")+ .bind("Acme Inc.")+ .bind("Maker of rocket-powered roller skates.")+ .execute(&pool)+ .await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .list_companies_for_soup(+ &team,+ "macro|[email protected]",+ &[],+ None,+ CrmCompanyListSort::UpdatedAt,+ None,+ 100,+ )+ .await?;+ assert_eq!(result.len(), 1);+ assert_eq!(result[0].name.as_deref(), Some("Acme Inc."));+ assert_eq!(+ result[0].description.as_deref(),+ Some("Maker of rocket-powered roller skates.")+ );+ // Domain order is by created_at ASC; both should be present.+ assert_eq!(result[0].company.domains.len(), 2);+ assert_eq!(result[0].company.domains[0].domain, "acme.com");+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_for_soup_returns_none_for_negative_cache_directory_row(+ pool: PgPool,+) -> anyhow::Result<()> {+ // Negative-cache directory row (NULL name/description) → soup+ // surfaces as None, not Some("").+ let team = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team, owner).await?;+ enable_crm_for_team(&pool, team).await?;+ insert_company(&pool, team, true, &["acme.com"]).await?;+ sqlx::query(+ r#"INSERT INTO crm_domain_directory (domain, name, description)+ VALUES ($1, NULL, NULL)"#,+ )+ .bind("acme.com")+ .execute(&pool)+ .await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .list_companies_for_soup(+ &team,+ "macro|[email protected]",+ &[],+ None,+ CrmCompanyListSort::UpdatedAt,+ None,+ 100,+ )+ .await?;+ assert_eq!(result.len(), 1);+ assert_eq!(result[0].name, None);+ assert_eq!(result[0].description, None);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_for_soup_filters_by_company_ids_when_non_empty(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team, owner).await?;+ enable_crm_for_team(&pool, team).await?;+ let wanted = insert_company(&pool, team, true, &["acme.com"]).await?;+ let _other = insert_company(&pool, team, true, &["zeta.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .list_companies_for_soup(+ &team,+ "macro|[email protected]",+ &[wanted],+ None,+ CrmCompanyListSort::UpdatedAt,+ None,+ 100,+ )+ .await?;+ let ids: Vec<Uuid> = result.iter().map(|c| c.company.id).collect();+ assert_eq!(ids, vec![wanted]);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_for_soup_does_not_leak_other_team_rows(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 b_only = insert_company(&pool, team_b, true, &["zeta.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .list_companies_for_soup(+ &team_b,+ "macro|[email protected]",+ &[],+ None,+ CrmCompanyListSort::UpdatedAt,+ None,+ 100,+ )+ .await?;+ let ids: Vec<Uuid> = result.iter().map(|c| c.company.id).collect();+ assert_eq!(ids, vec![b_only]);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_for_soup_paginates_past_cursor(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ enable_crm_for_team(&pool, team).await?;++ // Five companies with strictly increasing interaction timestamps.+ // Parsed (not `now()`) so they carry no sub-microsecond precision+ // that Postgres would truncate out from under the cursor compare.+ let mut companies = Vec::new();+ for day in 1..=5 {+ let domain = format!("c{day}.com");+ let id = insert_company(&pool, team, true, &[domain.as_str()]).await?;+ let ts: chrono::DateTime<chrono::Utc> = format!("2024-01-0{day}T00:00:00Z").parse()?;+ sqlx::query(+ r#"UPDATE crm_companies+ SET first_interaction = $2, last_interaction = $2+ WHERE id = $1"#,+ )+ .bind(id)+ .bind(ts)+ .execute(&pool)+ .await?;+ companies.push(id);+ }+ // Descending by timestamp → newest (day 5) first.+ let expected: Vec<Uuid> = companies.iter().rev().copied().collect();++ let repo = CompaniesRepositoryImpl::new(pool);++ // Walk every page with limit=2, threading the keyset cursor from the+ // last row of each page — exactly how the soup paginator drives it.+ let mut seen: Vec<Uuid> = Vec::new();+ let mut cursor: Option<CrmCompanySoupCursor> = None;+ let mut first_page: Vec<Uuid> = Vec::new();+ for page_idx in 0..10 {+ let page = repo+ .list_companies_for_soup(+ &team,+ "macro|[email protected]",+ &[],+ None,+ CrmCompanyListSort::UpdatedAt,+ cursor,+ 2,+ )+ .await?;+ if page.is_empty() {+ break;+ }+ let page_ids: Vec<Uuid> = page.iter().map(|c| c.company.id).collect();+ if page_idx == 0 {+ first_page = page_ids.clone();+ } else {+ // Regression: a follow-up page must not re-serve page one.+ // (The pre-fix query ignored the cursor and always did this.)+ assert_ne!(+ page_ids, first_page,+ "cursor did not advance — page {page_idx} repeated the first page"+ );+ }+ let last = page.last().unwrap();+ cursor = Some(CrmCompanySoupCursor {+ last_sort_ts: last.company.updated_at,+ last_id: last.company.id,+ });+ let exhausted = page.len() < 2;+ seen.extend(page_ids);+ if exhausted {+ break;+ }+ }++ assert_eq!(+ seen, expected,+ "pagination must yield every company exactly once in descending interaction order"+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_for_soup_pagination_breaks_ties_on_id(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ seed_team(&pool, team, "macro|[email protected]").await?;+ enable_crm_for_team(&pool, team).await?;++ // One newest company, then a tied pair, then two older. At limit=2+ // the tied pair straddles the page-1/page-2 boundary, so pagination+ // must lean on the `id` half of the keyset — a timestamp-only seek+ // would skip the second tied row (its ts is not `< cursor_ts`).+ let newest: chrono::DateTime<chrono::Utc> = "2024-01-05T00:00:00Z".parse()?;+ let tie: chrono::DateTime<chrono::Utc> = "2024-01-04T00:00:00Z".parse()?;+ let mid: chrono::DateTime<chrono::Utc> = "2024-01-03T00:00:00Z".parse()?;+ let oldest: chrono::DateTime<chrono::Utc> = "2024-01-02T00:00:00Z".parse()?;++ let mut want: Vec<(chrono::DateTime<chrono::Utc>, Uuid)> = Vec::new();+ for (idx, ts) in [newest, tie, tie, mid, oldest].into_iter().enumerate() {+ let domain = format!("tie{idx}.com");+ let id = insert_company(&pool, team, true, &[domain.as_str()]).await?;+ sqlx::query(+ r#"UPDATE crm_companies+ SET first_interaction = $2, last_interaction = $2+ WHERE id = $1"#,+ )+ .bind(id)+ .bind(ts)+ .execute(&pool)+ .await?;+ want.push((ts, id));+ }+ // Expected DB order: last_interaction DESC, then id DESC. Computed+ // from the ids actually generated, so it holds regardless of which+ // tied row drew the larger uuid.+ want.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));+ let expected: Vec<Uuid> = want.iter().map(|(_, id)| *id).collect();++ let repo = CompaniesRepositoryImpl::new(pool);+ let mut seen: Vec<Uuid> = Vec::new();+ let mut cursor: Option<CrmCompanySoupCursor> = None;+ for _ in 0..10 {+ let page = repo+ .list_companies_for_soup(+ &team,+ "macro|[email protected]",+ &[],+ None,+ CrmCompanyListSort::UpdatedAt,+ cursor,+ 2,+ )+ .await?;+ if page.is_empty() {+ break;+ }+ let last = page.last().unwrap();+ cursor = Some(CrmCompanySoupCursor {+ last_sort_ts: last.company.updated_at,+ last_id: last.company.id,+ });+ let exhausted = page.len() < 2;+ seen.extend(page.iter().map(|c| c.company.id));+ if exhausted {+ break;+ }+ }++ assert_eq!(+ seen, expected,+ "tied timestamps must paginate by id without skipping or repeating across the boundary"+ );+ Ok(())+}diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo/test/list_contacts_for_company.rs b/rust/cloud-storage/crm/src/outbound/companies_repo/test/list_contacts_for_company.rsnew file mode 100644index 0000000000..09dbace4b4--- /dev/null+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test/list_contacts_for_company.rs@@ -0,0 +1,184 @@+use super::helpers::*;+use crate::domain::companies_repo::*;+use crate::outbound::companies_repo::*;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::PgPool;+use uuid::Uuid;++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_contacts_returns_visible_ordered_alphabetically(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;++ // Named contacts sort by name; a name-less contact sorts by email.+ // `anna smith` is lowercased to confirm the sort is case-insensitive.+ let zoe = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;+ let mike = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;+ let carol = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;+ sqlx::query(r#"UPDATE crm_contacts SET name = 'Zoe Adams' WHERE id = $1"#)+ .bind(zoe)+ .execute(&pool)+ .await?;+ sqlx::query(r#"UPDATE crm_contacts SET name = 'anna smith' WHERE id = $1"#)+ .bind(carol)+ .execute(&pool)+ .await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let contacts = repo+ .list_contacts_for_company(&team_id, &company_id, false)+ .await?;+ let ids: Vec<Uuid> = contacts.iter().map(|c| c.id).collect();+ // "anna smith" (carol) < "[email protected]" (mike) < "zoe adams" (zoe)+ assert_eq!(ids, vec![carol, mike, zoe]);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_contacts_excludes_hidden(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;+ let visible = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;+ let hidden = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;+ sqlx::query(r#"UPDATE crm_contacts SET hidden = TRUE WHERE id = $1"#)+ .bind(hidden)+ .execute(&pool)+ .await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let contacts = repo+ .list_contacts_for_company(&team_id, &company_id, false)+ .await?;+ let ids: Vec<Uuid> = contacts.iter().map(|c| c.id).collect();+ assert_eq!(ids, vec![visible]);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_contacts_owned_company_with_no_contacts_returns_empty(+ pool: PgPool,+) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ seed_team(&pool, team_id, "macro|[email protected]").await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let contacts = repo+ .list_contacts_for_company(&team_id, &company_id, false)+ .await?;+ assert!(contacts.is_empty());+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_contacts_unknown_company_returns_not_found(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ seed_team(&pool, team_id, "macro|[email protected]").await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .list_contacts_for_company(&team_id, &Uuid::now_v7(), false)+ .await;+ assert!(matches!(+ result,+ Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)+ ));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_contacts_does_not_leak_across_teams(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?;+ let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;+ let link_a = insert_email_link(&pool, "macro|[email protected]", "[email protected]").await?;+ insert_contact_with_source(&pool, company_a, "[email protected]", link_a).await?;++ // Team B asking for team A's company must 404, not see an empty list.+ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .list_contacts_for_company(&team_b, &company_a, false)+ .await;+ assert!(matches!(+ result,+ Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)+ ));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_contacts_admin_sees_hidden_contacts(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;+ let visible = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;+ let hidden = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;+ sqlx::query(r#"UPDATE crm_contacts SET hidden = TRUE WHERE id = $1"#)+ .bind(hidden)+ .execute(&pool)+ .await?;++ let repo = CompaniesRepositoryImpl::new(pool);++ // Member: only the visible contact.+ let member = repo+ .list_contacts_for_company(&team_id, &company_id, false)+ .await?;+ let member_ids: Vec<Uuid> = member.iter().map(|c| c.id).collect();+ assert_eq!(member_ids, vec![visible]);++ // Admin: both contacts; the response carries the hidden flag so the+ // admin UI can render the right toggle state.+ let admin = repo+ .list_contacts_for_company(&team_id, &company_id, true)+ .await?;+ let admin_ids: Vec<Uuid> = admin.iter().map(|c| c.id).collect();+ assert_eq!(admin_ids.len(), 2);+ assert!(admin_ids.contains(&visible));+ assert!(admin_ids.contains(&hidden));+ let hidden_contact = admin.iter().find(|c| c.id == hidden).expect("hidden");+ assert!(hidden_contact.hidden);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_contacts_admin_reaches_hidden_company(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;+ insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;+ sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)+ .bind(company_id)+ .execute(&pool)+ .await?;++ let repo = CompaniesRepositoryImpl::new(pool);++ // Member: hidden parent → 404 (CompanyNotFoundForTeam).+ let member = repo+ .list_contacts_for_company(&team_id, &company_id, false)+ .await;+ assert!(matches!(+ member,+ Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)+ ));++ // Admin: the hidden company is reachable.+ let admin = repo+ .list_contacts_for_company(&team_id, &company_id, true)+ .await?;+ assert_eq!(admin.len(), 1);+ Ok(())+}diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo/test/populate_contact.rs b/rust/cloud-storage/crm/src/outbound/companies_repo/test/populate_contact.rsnew file mode 100644index 0000000000..08718efef0--- /dev/null+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test/populate_contact.rs@@ -0,0 +1,1068 @@+use super::helpers::*;+use crate::domain::companies_repo::*;+use crate::domain::service::{CrmService, CrmServiceImpl};+use crate::outbound::companies_repo::*;+use crate::outbound::no_op_resolver::NoOpCompanyMetadataResolver;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::PgPool;+use uuid::Uuid;++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn service_populate_contact_skips_when_domain_matches_user_domain(+ pool: PgPool,+) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ enable_crm_for_team(&pool, team_id).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;++ let service = CrmServiceImpl::new(+ CompaniesRepositoryImpl::new(pool.clone()),+ NoOpCompanyMetadataResolver,+ );++ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ None,+ chrono::Utc::now(),+ chrono::Utc::now(),+ true,+ )+ .await?;++ assert_eq!(+ count_companies_for_domain(&pool, team_id, "macro.com").await?,+ 0,+ "contact on the user's own domain must not create a CRM row"+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn service_populate_contact_same_domain_check_is_case_insensitive(+ pool: PgPool,+) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ enable_crm_for_team(&pool, team_id).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;++ let service = CrmServiceImpl::new(+ CompaniesRepositoryImpl::new(pool.clone()),+ NoOpCompanyMetadataResolver,+ );++ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ None,+ chrono::Utc::now(),+ chrono::Utc::now(),+ true,+ )+ .await?;++ assert_eq!(+ count_companies_for_domain(&pool, team_id, "macro.com").await?,+ 0+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn service_populate_contact_refreshes_existing_company_and_contact_updated_at(+ pool: PgPool,+) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ enable_crm_for_team(&pool, team_id).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;++ let old_updated_at: chrono::DateTime<chrono::Utc> =+ sqlx::query_scalar(r#"SELECT now() - INTERVAL '1 hour'"#)+ .fetch_one(&pool)+ .await?;++ let company_id = Uuid::now_v7();+ sqlx::query(+ r#"INSERT INTO crm_companies (id, team_id, email_sync, updated_at, first_interaction, last_interaction)+ VALUES ($1, $2, TRUE, $3, $3, $3)"#,+ )+ .bind(company_id)+ .bind(team_id)+ .bind(old_updated_at)+ .execute(&pool)+ .await?;++ sqlx::query(r#"INSERT INTO crm_domains (company_id, team_id, domain) VALUES ($1, $2, $3)"#)+ .bind(company_id)+ .bind(team_id)+ .bind("acme.com")+ .execute(&pool)+ .await?;++ let contact_id = Uuid::now_v7();+ sqlx::query(+ r#"INSERT INTO crm_contacts (id, company_id, email, updated_at, first_interaction, last_interaction)+ VALUES ($1, $2, $3, $4, $4, $4)"#,+ )+ .bind(contact_id)+ .bind(company_id)+ .bind("[email protected]")+ .bind(old_updated_at)+ .execute(&pool)+ .await?;++ sqlx::query(r#"INSERT INTO crm_contact_sources (contact_id, link_id) VALUES ($1, $2)"#)+ .bind(contact_id)+ .bind(link_id)+ .execute(&pool)+ .await?;++ let service = CrmServiceImpl::new(+ CompaniesRepositoryImpl::new(pool.clone()),+ NoOpCompanyMetadataResolver,+ );++ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ Some("Alice"),+ chrono::Utc::now(),+ chrono::Utc::now(),+ true,+ )+ .await?;++ let company_updated_at = fetch_company_updated_at(&pool, company_id)+ .await?+ .expect("company should still exist");+ let contact_updated_at = fetch_contact_updated_at(&pool, contact_id)+ .await?+ .expect("contact should still exist");++ assert!(company_updated_at > old_updated_at);+ assert!(contact_updated_at > old_updated_at);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn service_populate_contact_writes_when_domain_differs(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ enable_crm_for_team(&pool, team_id).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;++ let service = CrmServiceImpl::new(+ CompaniesRepositoryImpl::new(pool.clone()),+ NoOpCompanyMetadataResolver,+ );++ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ None,+ chrono::Utc::now(),+ chrono::Utc::now(),+ true,+ )+ .await?;++ assert_eq!(+ count_companies_for_domain(&pool, team_id, "acme.com").await?,+ 1+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn precheck_reports_killswitch_off_when_settings_missing(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team, owner).await?;+ // intentionally no team_crm_settings row++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .crm_scope_precheck(&team, &["acme.com".to_string()], &[])+ .await?;+ // Killswitch off short-circuits: the email service rejects with+ // CrmDisabledForTeam regardless of per-input state, so the probes+ // are skipped and per-input rows come back empty.+ assert!(!result.crm_enabled);+ assert!(result.domains.is_empty());+ assert!(result.addresses.is_empty());+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn precheck_resolves_domain_with_company_state(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team, owner).await?;+ enable_crm_for_team(&pool, team).await?;+ insert_company(&pool, team, true, &["acme.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .crm_scope_precheck(+ &team,+ &["acme.com".to_string(), "missing.com".to_string()],+ &[],+ )+ .await?;+ assert!(result.crm_enabled);+ assert_eq!(result.domains.len(), 2);++ let acme = result+ .domains+ .iter()+ .find(|d| d.domain == "acme.com")+ .unwrap();+ assert!(acme.exists);+ assert!(!acme.company_hidden);+ assert!(acme.email_sync);++ let missing = result+ .domains+ .iter()+ .find(|d| d.domain == "missing.com")+ .unwrap();+ assert!(!missing.exists);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn precheck_reports_hidden_and_email_sync_disabled_companies(+ pool: PgPool,+) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team, owner).await?;+ enable_crm_for_team(&pool, team).await?;+ let hidden_co = insert_company(&pool, team, false, &["hidden.com"]).await?;+ sqlx::query("UPDATE crm_companies SET hidden = TRUE WHERE id = $1")+ .bind(hidden_co)+ .execute(&pool)+ .await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .crm_scope_precheck(&team, &["hidden.com".to_string()], &[])+ .await?;+ let d = &result.domains[0];+ assert!(d.exists);+ assert!(d.company_hidden);+ assert!(!d.email_sync);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn precheck_address_resolves_contact_within_team(pool: PgPool) -> anyhow::Result<()> {+ let team = Uuid::now_v7();+ let owner = "macro|[email protected]";+ seed_team(&pool, team, owner).await?;+ enable_crm_for_team(&pool, team).await?;+ let company = insert_company(&pool, team, true, &["acme.com"]).await?;+ let link = insert_email_link(&pool, owner, "[email protected]").await?;+ insert_contact_with_source(&pool, company, "[email protected]", link).await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .crm_scope_precheck(+ &team,+ &[],+ &["[email protected]".to_string(), "[email protected]".to_string()],+ )+ .await?;++ let alice = result+ .addresses+ .iter()+ .find(|a| a.address == "[email protected]")+ .unwrap();+ assert!(alice.exists);+ assert!(!alice.contact_hidden);+ assert!(!alice.company_hidden);+ assert!(alice.email_sync);++ let bob = result+ .addresses+ .iter()+ .find(|a| a.address == "[email protected]")+ .unwrap();+ assert!(!bob.exists);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn precheck_address_does_not_leak_other_team_contacts(pool: PgPool) -> anyhow::Result<()> {+ let team_a = Uuid::now_v7();+ let team_b = Uuid::now_v7();+ let owner_a = "macro|[email protected]";+ let owner_b = "macro|[email protected]";+ seed_team(&pool, team_a, owner_a).await?;+ seed_team(&pool, team_b, owner_b).await?;+ enable_crm_for_team(&pool, team_b).await?;+ let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;+ let link_a = insert_email_link(&pool, owner_a, "[email protected]").await?;+ insert_contact_with_source(&pool, company_a, "[email protected]", link_a).await?;++ // team_b asks about an address that only exists under team_a — must+ // report as non-existent, not leak team_a's contact state.+ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .crm_scope_precheck(&team_b, &[], &["[email protected]".to_string()])+ .await?;+ assert!(!result.addresses[0].exists);+ Ok(())+}++/// Received-direction populate for an unknown `(team, domain)` is a+/// no-op: only sent-direction may create a new `crm_companies` row.+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn populate_contact_is_sent_false_skips_when_no_company(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ enable_crm_for_team(&pool, team_id).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;++ let service = CrmServiceImpl::new(+ CompaniesRepositoryImpl::new(pool.clone()),+ NoOpCompanyMetadataResolver,+ );++ let now = chrono::Utc::now();+ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ None,+ now,+ now,+ false,+ )+ .await?;++ assert_eq!(+ count_companies_for_domain(&pool, team_id, "acme.com").await?,+ 0,+ "received-direction populate must not create a crm_companies row"+ );+ Ok(())+}++/// Brand-new company + contact INSERT writes `first_interaction` and+/// `last_interaction` directly from the payload's distinct `first_at` /+/// `last_at` (covers the historical-seed range, e.g. 2020→2024).+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn populate_contact_insert_seeds_first_and_last_from_payload(+ pool: PgPool,+) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ enable_crm_for_team(&pool, team_id).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;++ let first: chrono::DateTime<chrono::Utc> = "2020-01-01T00:00:00Z".parse()?;+ let last: chrono::DateTime<chrono::Utc> = "2024-06-15T00:00:00Z".parse()?;++ let service = CrmServiceImpl::new(+ CompaniesRepositoryImpl::new(pool.clone()),+ NoOpCompanyMetadataResolver,+ );++ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ None,+ first,+ last,+ true,+ )+ .await?;++ let company_id = fetch_company_for_domain(&pool, team_id, "acme.com")+ .await?+ .expect("company should be inserted");+ let (company_first, company_last) = fetch_company_interactions(&pool, company_id)+ .await?+ .expect("company interactions");+ assert_eq!(company_first, first);+ assert_eq!(company_last, last);++ let contact_id = fetch_contact_id(&pool, company_id, "[email protected]")+ .await?+ .expect("contact should be inserted");+ let (contact_first, contact_last) = fetch_contact_interactions(&pool, contact_id)+ .await?+ .expect("contact interactions");+ assert_eq!(contact_first, first);+ assert_eq!(contact_last, last);+ Ok(())+}++/// Sent-direction populate against an existing row merges+/// `first_interaction` via `LEAST` (older message pulls it back) and+/// `last_interaction` via `GREATEST` (newer message pushes it forward),+/// on both the company and contact rows.+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn populate_contact_is_sent_true_merges_first_least_and_last_greatest(+ pool: PgPool,+) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ enable_crm_for_team(&pool, team_id).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;++ let initial: chrono::DateTime<chrono::Utc> = "2022-06-01T00:00:00Z".parse()?;+ let older: chrono::DateTime<chrono::Utc> = "2020-01-01T00:00:00Z".parse()?;+ let newer: chrono::DateTime<chrono::Utc> = "2024-12-31T00:00:00Z".parse()?;++ let service = CrmServiceImpl::new(+ CompaniesRepositoryImpl::new(pool.clone()),+ NoOpCompanyMetadataResolver,+ );++ // First populate establishes the row at `initial`.+ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ None,+ initial,+ initial,+ true,+ )+ .await?;++ let company_id = fetch_company_for_domain(&pool, team_id, "acme.com")+ .await?+ .expect("company");+ let contact_id = fetch_contact_id(&pool, company_id, "[email protected]")+ .await?+ .expect("contact");++ // A backfilled older message should pull first_interaction back via LEAST.+ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ None,+ older,+ older,+ true,+ )+ .await?;++ let (company_first, company_last) = fetch_company_interactions(&pool, company_id)+ .await?+ .expect("interactions");+ assert_eq!(company_first, older);+ assert_eq!(company_last, initial);+ let (contact_first, contact_last) = fetch_contact_interactions(&pool, contact_id)+ .await?+ .expect("interactions");+ assert_eq!(contact_first, older);+ assert_eq!(contact_last, initial);++ // A newer message should push last_interaction forward via GREATEST,+ // leaving first_interaction at `older`.+ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ None,+ newer,+ newer,+ true,+ )+ .await?;++ let (company_first, company_last) = fetch_company_interactions(&pool, company_id)+ .await?+ .expect("interactions");+ assert_eq!(company_first, older);+ assert_eq!(company_last, newer);+ Ok(())+}++/// Received-direction populate against an existing row must not pull+/// `first_interaction` backwards — even with an older timestamp — but+/// still GREATEST-merges `last_interaction` when newer. Asserts both+/// company and contact.+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn populate_contact_is_sent_false_leaves_first_interaction_unchanged(+ pool: PgPool,+) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ enable_crm_for_team(&pool, team_id).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;++ let baseline: chrono::DateTime<chrono::Utc> = "2022-06-01T00:00:00Z".parse()?;+ let older: chrono::DateTime<chrono::Utc> = "2020-01-01T00:00:00Z".parse()?;+ let newer: chrono::DateTime<chrono::Utc> = "2024-12-31T00:00:00Z".parse()?;++ let service = CrmServiceImpl::new(+ CompaniesRepositoryImpl::new(pool.clone()),+ NoOpCompanyMetadataResolver,+ );++ // Sent populate seeds the row at `baseline`.+ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ None,+ baseline,+ baseline,+ true,+ )+ .await?;++ let company_id = fetch_company_for_domain(&pool, team_id, "acme.com")+ .await?+ .expect("company");+ let contact_id = fetch_contact_id(&pool, company_id, "[email protected]")+ .await?+ .expect("contact");++ // Received populate with an older timestamp must NOT pull+ // first_interaction backwards on either row.+ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ None,+ older,+ older,+ false,+ )+ .await?;++ let (company_first, _) = fetch_company_interactions(&pool, company_id)+ .await?+ .expect("interactions");+ assert_eq!(+ company_first, baseline,+ "received populate must not pull company first_interaction backwards"+ );+ let (contact_first, _) = fetch_contact_interactions(&pool, contact_id)+ .await?+ .expect("interactions");+ assert_eq!(+ contact_first, baseline,+ "received populate must not pull contact first_interaction backwards"+ );++ // Received populate with a newer timestamp still bumps last_interaction.+ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ None,+ newer,+ newer,+ false,+ )+ .await?;++ let (_, company_last) = fetch_company_interactions(&pool, company_id)+ .await?+ .expect("interactions");+ assert_eq!(company_last, newer);+ let (_, contact_last) = fetch_contact_interactions(&pool, contact_id)+ .await?+ .expect("interactions");+ assert_eq!(contact_last, newer);+ Ok(())+}++/// Received-direction populate at a known company creates a new+/// `crm_contacts` row (seeded with both timestamps) and a+/// `crm_contact_sources` row — verifying sources now track+/// interactions in both directions.+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn populate_contact_is_sent_false_inserts_contact_at_existing_company(+ pool: PgPool,+) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ enable_crm_for_team(&pool, team_id).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;++ let baseline: chrono::DateTime<chrono::Utc> = "2022-06-01T00:00:00Z".parse()?;+ let received_at: chrono::DateTime<chrono::Utc> = "2024-09-15T00:00:00Z".parse()?;++ let service = CrmServiceImpl::new(+ CompaniesRepositoryImpl::new(pool.clone()),+ NoOpCompanyMetadataResolver,+ );++ // Sent populate establishes the company via [email protected].+ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ None,+ baseline,+ baseline,+ true,+ )+ .await?;++ let company_id = fetch_company_for_domain(&pool, team_id, "acme.com")+ .await?+ .expect("company");+ assert_eq!(count_contacts(&pool, company_id).await?, 1);++ // Received-direction populate for a *new* address at the same+ // company creates a contact row + source row.+ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ Some("Bob"),+ received_at,+ received_at,+ false,+ )+ .await?;++ assert_eq!(+ count_contacts(&pool, company_id).await?,+ 2,+ "received-direction populate must insert a contact under the known company"+ );+ let bob_id = fetch_contact_id(&pool, company_id, "[email protected]")+ .await?+ .expect("bob contact");+ let (bob_first, bob_last) = fetch_contact_interactions(&pool, bob_id)+ .await?+ .expect("bob interactions");+ assert_eq!(bob_first, received_at);+ assert_eq!(bob_last, received_at);+ assert_eq!(+ count_sources_for_company(&pool, company_id).await?,+ 2,+ "received-direction populate must write a crm_contact_sources row"+ );+ Ok(())+}++/// Team-level CRM killswitch (`team_crm_settings.crm_enabled = false`+/// or missing) short-circuits populate in both directions before any+/// rows are written.+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn populate_contact_team_killswitch_off_noops_both_directions(+ pool: PgPool,+) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ // Intentionally do NOT enable_crm_for_team — team_crm_settings row is+ // missing, which is treated as crm_enabled = false.+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;++ let service = CrmServiceImpl::new(+ CompaniesRepositoryImpl::new(pool.clone()),+ NoOpCompanyMetadataResolver,+ );++ let now = chrono::Utc::now();++ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ None,+ now,+ now,+ true,+ )+ .await?;+ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ None,+ now,+ now,+ false,+ )+ .await?;++ assert_eq!(+ count_companies_for_domain(&pool, team_id, "acme.com").await?,+ 0,+ "team killswitch must short-circuit both directions"+ );+ Ok(())+}++/// `email_sync = false` no longer gates populate. The flag is now+/// purely a visibility/permission check consumed at read time+/// (soup, email permissions). Populate updates interaction columns+/// and writes contact / source rows just like it would with+/// `email_sync = true`, so re-enabling sync exposes the full history+/// with zero backfill.+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn populate_contact_runs_regardless_of_email_sync_flag(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ enable_crm_for_team(&pool, team_id).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;++ // Seed a sync-off company. Baseline timestamp parsed from a string+ // (no sub-microsecond precision — Postgres `TIMESTAMPTZ` only+ // stores micros and `chrono::Utc::now()`'s nanos would get+ // silently truncated and break the `assert_eq` below).+ let company_id = insert_company(&pool, team_id, false, &["acme.com"]).await?;+ let baseline: chrono::DateTime<chrono::Utc> = "2024-01-01T00:00:00Z".parse()?;+ sqlx::query(+ r#"UPDATE crm_companies+ SET first_interaction = $2, last_interaction = $2+ WHERE id = $1"#,+ )+ .bind(company_id)+ .bind(baseline)+ .execute(&pool)+ .await?;++ let service = CrmServiceImpl::new(+ CompaniesRepositoryImpl::new(pool.clone()),+ NoOpCompanyMetadataResolver,+ );++ let later: chrono::DateTime<chrono::Utc> = "2024-01-08T00:00:00Z".parse()?;+ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ None,+ later,+ later,+ true,+ )+ .await?;++ // Company `last_interaction` advances; first_interaction+ // LEAST-merges on is_sent=true so it stays at the earlier+ // baseline. Contact + source rows land regardless of email_sync.+ let (first, last) = fetch_company_interactions(&pool, company_id)+ .await?+ .expect("company");+ assert_eq!(first, baseline);+ assert_eq!(last, later);+ assert_eq!(count_contacts(&pool, company_id).await?, 1);+ assert_eq!(count_sources_for_company(&pool, company_id).await?, 1);+ // email_sync itself is unchanged — populate never touches it.+ assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));+ Ok(())+}++/// Historical-seed-style populate (`first_at != last_at`) against an+/// already-tracked row expands the stored range outward: `first` pulls+/// back via LEAST and `last` pushes forward via GREATEST in the same+/// call.+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn populate_contact_seed_style_range_merges_into_existing(+ pool: PgPool,+) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ enable_crm_for_team(&pool, team_id).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;++ let baseline: chrono::DateTime<chrono::Utc> = "2022-06-01T00:00:00Z".parse()?;++ let service = CrmServiceImpl::new(+ CompaniesRepositoryImpl::new(pool.clone()),+ NoOpCompanyMetadataResolver,+ );++ // Establish the rows at `baseline`.+ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ None,+ baseline,+ baseline,+ true,+ )+ .await?;++ let company_id = fetch_company_for_domain(&pool, team_id, "acme.com")+ .await?+ .expect("company");+ let contact_id = fetch_contact_id(&pool, company_id, "[email protected]")+ .await?+ .expect("contact");++ // Historical-seed-style populate: distinct first_at < last_at,+ // is_sent=true, hitting an already-populated contact. Should pull+ // first_interaction earlier AND push last_interaction later.+ let seed_first: chrono::DateTime<chrono::Utc> = "2010-03-15T00:00:00Z".parse()?;+ let seed_last: chrono::DateTime<chrono::Utc> = "2024-12-31T00:00:00Z".parse()?;+ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ None,+ seed_first,+ seed_last,+ true,+ )+ .await?;++ let (company_first, company_last) = fetch_company_interactions(&pool, company_id)+ .await?+ .expect("interactions");+ assert_eq!(company_first, seed_first);+ assert_eq!(company_last, seed_last);+ let (contact_first, contact_last) = fetch_contact_interactions(&pool, contact_id)+ .await?+ .expect("interactions");+ assert_eq!(contact_first, seed_first);+ assert_eq!(contact_last, seed_last);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn email_sync_disable_then_re_enable_preserves_full_history_with_no_backfill(+ pool: PgPool,+) -> anyhow::Result<()> {+ // Regression: the whole point of decoupling populate from+ // email_sync. While sync is OFF, new emails arriving for this+ // company must still write CRM rows. Re-enabling sync must surface+ // the complete history without any explicit backfill step.+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ enable_crm_for_team(&pool, team_id).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;++ let service = CrmServiceImpl::new(+ CompaniesRepositoryImpl::new(pool.clone()),+ NoOpCompanyMetadataResolver,+ );+ let repo = CompaniesRepositoryImpl::new(pool.clone());++ // Phase 1: sync ON. First contact lands normally.+ let t1: chrono::DateTime<chrono::Utc> = "2024-01-01T00:00:00Z".parse()?;+ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ None,+ t1,+ t1,+ true,+ )+ .await?;+ let company_id = fetch_company_for_domain(&pool, team_id, "acme.com")+ .await?+ .expect("company");+ assert_eq!(count_contacts(&pool, company_id).await?, 1);++ // Phase 2: admin disables sync. Existing data stays put.+ repo.set_email_sync(&team_id, &company_id, false).await?;+ assert_eq!(count_contacts(&pool, company_id).await?, 1);+ assert_eq!(count_sources_for_company(&pool, company_id).await?, 1);++ // Phase 3: a new email arrives during the sync-off window. This+ // is the critical assertion — populate must still write the new+ // contact + source so there's no gap to backfill later.+ let t2: chrono::DateTime<chrono::Utc> = "2024-02-15T00:00:00Z".parse()?;+ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ None,+ t2,+ t2,+ true,+ )+ .await?;+ assert_eq!(count_contacts(&pool, company_id).await?, 2);+ assert_eq!(count_sources_for_company(&pool, company_id).await?, 2);+ assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));++ // Phase 4: admin re-enables sync. No backfill is run — but the+ // history written during the off-window is already there.+ repo.set_email_sync(&team_id, &company_id, true).await?;+ assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(true));+ assert_eq!(count_contacts(&pool, company_id).await?, 2);+ assert_eq!(count_sources_for_company(&pool, company_id).await?, 2);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn populate_contact_into_hidden_company_inserts_hidden_contact(+ pool: PgPool,+) -> anyhow::Result<()> {+ // Defensive: new contacts inserted into a hidden company must+ // inherit `hidden = TRUE` so a populate-vs-hide race can't sneak a+ // visible contact under an otherwise-hidden company. Populate+ // doesn't itself gate on `hidden` (it always writes when the+ // team-level CRM killswitch is on), so this is the only line of+ // defense.+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ enable_crm_for_team(&pool, team_id).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)+ .bind(company_id)+ .execute(&pool)+ .await?;++ let service = CrmServiceImpl::new(+ CompaniesRepositoryImpl::new(pool.clone()),+ NoOpCompanyMetadataResolver,+ );+ let now: chrono::DateTime<chrono::Utc> = "2024-01-15T00:00:00Z".parse()?;+ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ None,+ now,+ now,+ true,+ )+ .await?;++ let alice = fetch_contact_id(&pool, company_id, "[email protected]")+ .await?+ .expect("alice should have been inserted");+ assert_eq!(fetch_contact_hidden(&pool, alice).await?, Some(true));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn populate_contact_upsert_does_not_overwrite_individual_hide(+ pool: PgPool,+) -> anyhow::Result<()> {+ // Populate upsert (ON CONFLICT path) must preserve a contact's+ // existing `hidden` so individual `set_contact_hidden` actions+ // survive subsequent email activity.+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ enable_crm_for_team(&pool, team_id).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;++ let service = CrmServiceImpl::new(+ CompaniesRepositoryImpl::new(pool.clone()),+ NoOpCompanyMetadataResolver,+ );+ let first_at: chrono::DateTime<chrono::Utc> = "2024-01-01T00:00:00Z".parse()?;+ let later: chrono::DateTime<chrono::Utc> = "2024-02-01T00:00:00Z".parse()?;++ // Seed the contact via a normal populate.+ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ None,+ first_at,+ first_at,+ true,+ )+ .await?;+ let company_id = fetch_company_for_domain(&pool, team_id, "acme.com")+ .await?+ .expect("company");+ let alice = fetch_contact_id(&pool, company_id, "[email protected]")+ .await?+ .expect("alice");++ // Admin hides alice individually.+ let repo = CompaniesRepositoryImpl::new(pool.clone());+ repo.set_contact_hidden(&team_id, &alice, true).await?;+ assert_eq!(fetch_contact_hidden(&pool, alice).await?, Some(true));++ // A later populate (new email from alice) must NOT un-hide her.+ service+ .populate_contact(+ &team_id,+ &link_id,+ "[email protected]",+ "[email protected]",+ None,+ later,+ later,+ true,+ )+ .await?;++ assert_eq!(fetch_contact_hidden(&pool, alice).await?, Some(true));+ Ok(())+}diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo/test/set_company_hidden.rs b/rust/cloud-storage/crm/src/outbound/companies_repo/test/set_company_hidden.rsnew file mode 100644index 0000000000..0ad2877910--- /dev/null+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test/set_company_hidden.rs@@ -0,0 +1,157 @@+use super::helpers::*;+use crate::domain::companies_repo::*;+use crate::domain::service::{CrmService, CrmServiceImpl};+use crate::outbound::companies_repo::*;+use crate::outbound::no_op_resolver::NoOpCompanyMetadataResolver;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::PgPool;+use uuid::Uuid;++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn set_company_hidden_toggles_flag(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ seed_team(&pool, team_id, "macro|[email protected]").await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;++ assert_eq!(fetch_company_hidden(&pool, company_id).await?, Some(false));++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ repo.set_company_hidden(&team_id, &company_id, true).await?;+ assert_eq!(fetch_company_hidden(&pool, company_id).await?, Some(true));++ repo.set_company_hidden(&team_id, &company_id, false)+ .await?;+ assert_eq!(fetch_company_hidden(&pool, company_id).await?, Some(false));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn set_company_hidden_returns_not_found_for_unknown_company(+ pool: PgPool,+) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ seed_team(&pool, team_id, "macro|[email protected]").await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .set_company_hidden(&team_id, &Uuid::now_v7(), true)+ .await;++ assert!(matches!(+ result,+ Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)+ ));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn set_company_hidden_isolates_companies_across_teams(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?;+ let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ let result = repo.set_company_hidden(&team_b, &company_a, true).await;+ assert!(matches!(+ result,+ Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)+ ));+ assert_eq!(fetch_company_hidden(&pool, company_a).await?, Some(false));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn service_set_company_hidden_true_soft_hides_contacts_and_disables_email_sync(+ pool: PgPool,+) -> anyhow::Result<()> {+ // Hide flips the company flag, forces email_sync = false, and+ // cascades hidden = TRUE onto every contact. Contact rows AND+ // contact_sources are preserved so un-hide can restore them.+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;+ let alice = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;+ let bob = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;++ let service = CrmServiceImpl::new(+ CompaniesRepositoryImpl::new(pool.clone()),+ NoOpCompanyMetadataResolver,+ );+ service+ .set_company_hidden(&team_id, &company_id, true)+ .await?;++ assert_eq!(fetch_company_hidden(&pool, company_id).await?, Some(true));+ assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));+ // Contacts and sources preserved; both contacts now hidden.+ assert_eq!(count_contacts(&pool, company_id).await?, 2);+ assert_eq!(count_sources_for_company(&pool, company_id).await?, 2);+ assert_eq!(fetch_contact_hidden(&pool, alice).await?, Some(true));+ assert_eq!(fetch_contact_hidden(&pool, bob).await?, Some(true));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn set_company_hidden_false_cascades_contacts_visible(pool: PgPool) -> anyhow::Result<()> {+ // After un-hide, every contact under the company becomes visible —+ // including ones an admin previously hid individually. Cascade+ // overwrites individual hide state by design.+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;+ let alice = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;+ let bob = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ // Individually hide `alice` before any company-level toggling.+ repo.set_contact_hidden(&team_id, &alice, true).await?;+ // Then hide the whole company (cascades `bob` to hidden too).+ repo.set_company_hidden(&team_id, &company_id, true).await?;+ assert_eq!(fetch_contact_hidden(&pool, alice).await?, Some(true));+ assert_eq!(fetch_contact_hidden(&pool, bob).await?, Some(true));++ // Un-hide cascades EVERY contact back to visible, blowing away+ // alice's individual hide too.+ repo.set_company_hidden(&team_id, &company_id, false)+ .await?;++ assert_eq!(fetch_company_hidden(&pool, company_id).await?, Some(false));+ assert_eq!(fetch_contact_hidden(&pool, alice).await?, Some(false));+ assert_eq!(fetch_contact_hidden(&pool, bob).await?, Some(false));+ // Un-hide does NOT re-enable email_sync; that's a separate action.+ assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn service_set_company_hidden_false_does_not_re_enable_email_sync(+ pool: PgPool,+) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ seed_team(&pool, team_id, "macro|[email protected]").await?;+ // Start with hidden=true (via service, which also flipped sync off) then un-hide.+ let company_id = insert_company(&pool, team_id, false, &["acme.com"]).await?;+ sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)+ .bind(company_id)+ .execute(&pool)+ .await?;++ let service = CrmServiceImpl::new(+ CompaniesRepositoryImpl::new(pool.clone()),+ NoOpCompanyMetadataResolver,+ );+ service+ .set_company_hidden(&team_id, &company_id, false)+ .await?;++ assert_eq!(fetch_company_hidden(&pool, company_id).await?, Some(false));+ // Un-hiding leaves email_sync alone — caller must re-enable it explicitly.+ assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));+ Ok(())+}diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo/test/set_contact_hidden.rs b/rust/cloud-storage/crm/src/outbound/companies_repo/test/set_contact_hidden.rsnew file mode 100644index 0000000000..41b199bb23--- /dev/null+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test/set_contact_hidden.rs@@ -0,0 +1,71 @@+use super::helpers::*;+use crate::domain::companies_repo::*;+use crate::outbound::companies_repo::*;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::PgPool;+use uuid::Uuid;++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn set_contact_hidden_toggles_flag(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;+ let contact_id =+ insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;++ assert_eq!(fetch_contact_hidden(&pool, contact_id).await?, Some(false));++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ repo.set_contact_hidden(&team_id, &contact_id, true).await?;+ assert_eq!(fetch_contact_hidden(&pool, contact_id).await?, Some(true));++ repo.set_contact_hidden(&team_id, &contact_id, false)+ .await?;+ assert_eq!(fetch_contact_hidden(&pool, contact_id).await?, Some(false));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn set_contact_hidden_returns_not_found_for_unknown_contact(+ pool: PgPool,+) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ seed_team(&pool, team_id, "macro|[email protected]").await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo+ .set_contact_hidden(&team_id, &Uuid::now_v7(), true)+ .await;++ assert!(matches!(+ result,+ Err(crate::domain::model::CrmError::ContactNotFoundForTeam)+ ));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn set_contact_hidden_isolates_contacts_across_teams(pool: PgPool) -> anyhow::Result<()> {+ let team_a = Uuid::now_v7();+ let team_b = Uuid::now_v7();+ let owner_a = "macro|[email protected]";+ let owner_b = "macro|[email protected]";+ seed_team(&pool, team_a, owner_a).await?;+ seed_team(&pool, team_b, owner_b).await?;+ let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;+ let link_a = insert_email_link(&pool, owner_a, "[email protected]").await?;+ let contact_a = insert_contact_with_source(&pool, company_a, "[email protected]", link_a).await?;++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ // team_b mutating team_a's contact must fail without touching the row.+ let result = repo.set_contact_hidden(&team_b, &contact_a, true).await;+ assert!(matches!(+ result,+ Err(crate::domain::model::CrmError::ContactNotFoundForTeam)+ ));++ assert_eq!(fetch_contact_hidden(&pool, contact_a).await?, Some(false));+ Ok(())+}diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo/test/set_email_sync.rs b/rust/cloud-storage/crm/src/outbound/companies_repo/test/set_email_sync.rsnew file mode 100644index 0000000000..6ff69a8a57--- /dev/null+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test/set_email_sync.rs@@ -0,0 +1,167 @@+use super::helpers::*;+use crate::domain::companies_repo::*;+use crate::outbound::companies_repo::*;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::PgPool;+use uuid::Uuid;++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn set_email_sync_disable_preserves_contacts_and_sources(pool: PgPool) -> anyhow::Result<()> {+ // Disabling email_sync only affects read-side visibility /+ // permission checks — it must not touch existing contacts.+ // Populate continues to write while sync is off; visibility is+ // controlled by `hidden`. Teams that want to drop contacts should+ // hide the company.+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;+ let alice = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;+ let bob = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ repo.set_email_sync(&team_id, &company_id, false).await?;++ assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));+ // Contacts + sources stay put; their hidden state is untouched.+ assert_eq!(count_contacts(&pool, company_id).await?, 2);+ assert_eq!(count_sources_for_company(&pool, company_id).await?, 2);+ assert_eq!(fetch_contact_hidden(&pool, alice).await?, Some(false));+ assert_eq!(fetch_contact_hidden(&pool, bob).await?, Some(false));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn set_email_sync_enable_preserves_contacts(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ // Start disabled with a lingering contact — re-enabling must NOT touch it.+ let company_id = insert_company(&pool, team_id, false, &["acme.com"]).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;+ insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ repo.set_email_sync(&team_id, &company_id, true).await?;++ assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(true));+ assert_eq!(count_contacts(&pool, company_id).await?, 1);+ assert_eq!(count_sources_for_company(&pool, company_id).await?, 1);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn set_email_sync_returns_not_found_for_unknown_company(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ seed_team(&pool, team_id, "macro|[email protected]").await?;++ let repo = CompaniesRepositoryImpl::new(pool);+ let result = repo.set_email_sync(&team_id, &Uuid::now_v7(), false).await;++ assert!(matches!(+ result,+ Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)+ ));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn set_email_sync_isolates_companies_across_teams(pool: PgPool) -> anyhow::Result<()> {+ let team_a = Uuid::now_v7();+ let team_b = Uuid::now_v7();+ let owner_a = "macro|[email protected]";+ let owner_b = "macro|[email protected]";+ seed_team(&pool, team_a, owner_a).await?;+ seed_team(&pool, team_b, owner_b).await?;+ let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;+ let link_a = insert_email_link(&pool, owner_a, "[email protected]").await?;+ insert_contact_with_source(&pool, company_a, "[email protected]", link_a).await?;++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ // team_b mutating team_a's company must fail without touching the row.+ let result = repo.set_email_sync(&team_b, &company_a, false).await;+ assert!(matches!(+ result,+ Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)+ ));++ assert_eq!(fetch_email_sync(&pool, company_a).await?, Some(true));+ assert_eq!(count_contacts(&pool, company_a).await?, 1);+ assert_eq!(count_sources_for_company(&pool, company_a).await?, 1);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn set_email_sync_disable_handles_multi_domain_company(pool: PgPool) -> anyhow::Result<()> {+ // Multi-domain companies lock each (team, domain) on disable; the+ // flag flips but contacts/sources/domains are preserved.+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ let company_id =+ insert_company(&pool, team_id, true, &["acme.com", "acme.io", "acme.co"]).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;+ insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;+ insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ repo.set_email_sync(&team_id, &company_id, false).await?;++ assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));+ assert_eq!(count_contacts(&pool, company_id).await?, 2);+ assert_eq!(count_sources_for_company(&pool, company_id).await?, 2);+ // Company + its domain rows survive the disable so future populates short-circuit.+ let (domain_count,): (i64,) =+ sqlx::query_as(r#"SELECT COUNT(*) FROM crm_domains WHERE company_id = $1"#)+ .bind(company_id)+ .fetch_one(&pool)+ .await?;+ assert_eq!(domain_count, 3);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn set_email_sync_enable_refuses_hidden_company(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ let company_id = insert_company(&pool, team_id, false, &["acme.com"]).await?;+ sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)+ .bind(company_id)+ .execute(&pool)+ .await?;++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ let result = repo.set_email_sync(&team_id, &company_id, true).await;++ assert!(matches!(+ result,+ Err(crate::domain::model::CrmError::CompanyHidden)+ ));+ // State must be unchanged.+ assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));+ assert_eq!(fetch_company_hidden(&pool, company_id).await?, Some(true));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn set_email_sync_disable_allowed_on_hidden_company(pool: PgPool) -> anyhow::Result<()> {+ // Disabling sync on an already-hidden, already-disabled company is+ // a no-op-shaped call but must not error — the hidden check only+ // fires on the enable path.+ let team_id = Uuid::now_v7();+ seed_team(&pool, team_id, "macro|[email protected]").await?;+ let company_id = insert_company(&pool, team_id, false, &["acme.com"]).await?;+ sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)+ .bind(company_id)+ .execute(&pool)+ .await?;++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ repo.set_email_sync(&team_id, &company_id, false).await?;++ assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));+ assert_eq!(fetch_company_hidden(&pool, company_id).await?, Some(true));+ Ok(())+}diff --git a/rust/cloud-storage/crm/src/outbound/no_op_resolver.rs b/rust/cloud-storage/crm/src/outbound/no_op_resolver.rsindex 33acb706a6..d6e57abd7b 100644--- a/rust/cloud-storage/crm/src/outbound/no_op_resolver.rs+++ b/rust/cloud-storage/crm/src/outbound/no_op_resolver.rs@@ -3,9 +3,9 @@//!//! Used by binaries that need to construct a [`CrmService`] but never//! call [`populate_contact`] — typically HTTP API servers that only-//! read existing CRM rows via [`get_company_by_domain`]. Wiring in a-//! real unfurl-backed resolver in those binaries would force them to-//! carry the reqwest + scraper deps for code paths they never hit.+//! read existing CRM rows. Wiring in a real unfurl-backed resolver in+//! those binaries would force them to carry the reqwest + scraper+//! deps for code paths they never hit.//!//! If a binary using this resolver ever *does* call `populate_contact`,//! the resulting `crm_domain_directory` entries will all have NULL@@ -17,7 +17,6 @@//!//! [`CrmService`]: crate::domain::service::CrmService//! [`populate_contact`]: crate::domain::service::CrmService::populate_contact-//! [`get_company_by_domain`]: crate::domain::service::CrmService::get_company_by_domain//! [`UnfurlCompanyMetadataResolver`]: crate::outbound::unfurl_resolver::UnfurlCompanyMetadataResolveruse crate::domain::{company_metadata_resolver::CompanyMetadataResolver, model::DomainMetadata};diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rsindex ade8d2cc5d..e058670233 100644--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs@@ -291,6 +291,7 @@ use utoipa::OpenApi;crm::inbound::axum_router::set_contact_hidden::handler,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::comments::list_handler,crm::inbound::axum_router::comments::create_handler,crm::inbound::axum_router::comments::edit_handler,@@ -526,6 +527,8 @@ use utoipa::OpenApi;crm::inbound::axum_router::set_company_hidden::SetCompanyHiddenRequest,crm::inbound::axum_router::set_contact_hidden::SetContactHiddenRequest,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::comments::CreateCrmCommentRequest,crm::inbound::axum_router::comments::EditCrmCommentRequest,crm::domain::comment::CrmCommentEntityType,diff --git a/rust/cloud-storage/soup/src/domain/models.rs b/rust/cloud-storage/soup/src/domain/models.rsindex 796ed4ee0c..3469a3bf3d 100644--- a/rust/cloud-storage/soup/src/domain/models.rs+++ b/rust/cloud-storage/soup/src/domain/models.rs@@ -400,13 +400,11 @@ impl SoupRequest<Option<EntityFilterAst>> {SoupQuery::Frecency(_) => return None,};- // No viewed_at signal for crm_company yet — ViewedAt/ViewedUpdated- // fall back to updated_at.let sort = match sort_method {SimpleSortMethod::CreatedAt => CrmCompanyListSort::CreatedAt,- SimpleSortMethod::UpdatedAt- | SimpleSortMethod::ViewedAt- | SimpleSortMethod::ViewedUpdated => CrmCompanyListSort::UpdatedAt,+ SimpleSortMethod::UpdatedAt => CrmCompanyListSort::UpdatedAt,+ SimpleSortMethod::ViewedAt => CrmCompanyListSort::ViewedAt,+ SimpleSortMethod::ViewedUpdated => CrmCompanyListSort::ViewedUpdated,};let mut extract = CrmCompanyFilterExtract::default();@@ -420,6 +418,7 @@ impl SoupRequest<Option<EntityFilterAst>> {Some(GetCrmCompaniesRequest {team_id,+ user_id: self.user.clone(),company_ids: extract.ids,hidden: extract.hidden,sort,@@ -500,6 +499,10 @@ impl SoupRequest<Option<EntityFilterAst>> {pub struct GetCrmCompaniesRequest {/// Team whose CRM companies to list. Derived from the team receipt.pub team_id: Uuid,+ /// Requesting user — used to scope the per-user `UserHistory` join+ /// behind the `Viewed*` sort variants. Always populated; the soup+ /// request always has a user.+ pub user_id: MacroUserIdStr<'static>,/// Filter to specific company ids. Empty = all of the team's/// companies matching `hidden` (subject to the killswitch).pub company_ids: Vec<Uuid>,diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rsindex a84196149b..b3d4a4436e 100644--- a/rust/cloud-storage/soup/src/domain/service.rs+++ b/rust/cloud-storage/soup/src/domain/service.rs@@ -410,6 +410,7 @@ wherelet GetCrmCompaniesRequest {team_id,+ user_id,company_ids,hidden,sort,@@ -419,7 +420,15 @@ whereOk(Either::Right(self.crm_service- .list_companies_for_soup(&team_id, &company_ids, hidden, sort, cursor, limit)+ .list_companies_for_soup(+ &team_id,+ user_id.as_ref(),+ &company_ids,+ hidden,+ sort,+ cursor,+ limit,+ ).await.map_err(|_| SoupErr::CrmErr)?.into_iter()