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): hide companies and contacts (#3474)
Evan Hutnik0c03425d4a5d
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 2b3250782f..6a53d33351 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@@ -585,6 +585,8 @@ export * from './saveDocumentRequestSha';export * from './saveDocumentResponse';export * from './saveDocumentResponseData';export * from './saveDocumentResponseDataPresignedUrl';+export * from './setCompanyHiddenRequest';+export * from './setContactHiddenRequest';export * from './setEmailSyncRequest';export * from './setPropertyValue';export * from './setPropertyValueOneOf';diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/setCompanyHiddenRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/setCompanyHiddenRequest.tsnew file mode 100644index 0000000000..8f20918b02--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/setCompanyHiddenRequest.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Request body for `PUT /companies/{company_id}/hidden`.+ */+export interface SetCompanyHiddenRequest {+ /** New value for `crm_companies.hidden`. Setting to `true` hides+the company from CRM listings AND disables `email_sync` (which+permanently deletes the company's contacts and contact sources).+Setting to `false` un-hides the company; `email_sync` is left+untouched and the team must re-enable it explicitly. */+ hidden: boolean;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/setContactHiddenRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/setContactHiddenRequest.tsnew file mode 100644index 0000000000..92729cf10f--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/setContactHiddenRequest.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Request body for `PUT /contacts/{contact_id}/hidden`.+ */+export interface SetContactHiddenRequest {+ /** New value for `crm_contacts.hidden`. `true` hides the contact+from CRM listings for the team; `false` un-hides it. Display-only+— does not affect populate/depopulate. */+ hidden: boolean;+}diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex e37d5f8db5..3e64b910cc 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -1814,6 +1814,42 @@ export const setEmailSyncBody = zod'Request body for `PUT \/crm\/companies\/{company_id}\/email-sync`.');+/**+ * @summary Toggle `hidden` on a CRM company. Hiding also disables `email_sync`+and cascades to clearing the company's contacts and contact sources.+ */+export const setCompanyHiddenParams = zod.object({+ company_id: zod.uuid().describe('The CRM company to update'),+});++export const setCompanyHiddenBody = zod+ .object({+ hidden: zod+ .boolean()+ .describe(+ "New value for `crm_companies.hidden`. Setting to `true` hides\nthe company from CRM listings AND disables `email_sync` (which\npermanently deletes the company's contacts and contact sources).\nSetting to `false` un-hides the company; `email_sync` is left\nuntouched and the team must re-enable it explicitly."+ ),+ })+ .describe('Request body for `PUT \/companies\/{company_id}\/hidden`.');++/**+ * @summary Toggle `hidden` on a CRM contact. Hiding is a display-only opt-out+scoped to the team that owns the contact's company.+ */+export const setContactHiddenParams = zod.object({+ contact_id: zod.uuid().describe('The CRM contact to update'),+});++export const setContactHiddenBody = zod+ .object({+ hidden: zod+ .boolean()+ .describe(+ 'New value for `crm_contacts.hidden`. `true` hides the contact\nfrom CRM listings for the team; `false` un-hides it. Display-only\n— does not affect populate\/depopulate.'+ ),+ })+ .describe('Request body for `PUT \/contacts\/{contact_id}\/hidden`.');+/*** @summary Gets the users documents to populate their recent document list*/diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 276b847705..335870352e 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -1780,6 +1780,144 @@},"required": true},+ "responses": {+ "204": {+ "description": ""+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "409": {+ "description": "Company is hidden; un-hide before enabling email sync",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/crm/companies/{company_id}/hidden": {+ "put": {+ "tags": ["crm::inbound::axum_router::set_company_hidden"],+ "summary": "Toggle `hidden` on a CRM company. Hiding also disables `email_sync`\nand cascades to clearing the company's contacts and contact sources.",+ "operationId": "set_company_hidden",+ "parameters": [+ {+ "name": "company_id",+ "in": "path",+ "description": "The CRM company to update",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SetCompanyHiddenRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "204": {+ "description": ""+ },+ "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/contacts/{contact_id}/hidden": {+ "put": {+ "tags": ["crm::inbound::axum_router::set_contact_hidden"],+ "summary": "Toggle `hidden` on a CRM contact. Hiding is a display-only opt-out\nscoped to the team that owns the contact's company.",+ "operationId": "set_contact_hidden",+ "parameters": [+ {+ "name": "contact_id",+ "in": "path",+ "description": "The CRM contact to update",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SetContactHiddenRequest"+ }+ }+ },+ "required": true+ },"responses": {"204": {"description": ""@@ -11564,6 +11702,28 @@}}},+ "SetCompanyHiddenRequest": {+ "type": "object",+ "description": "Request body for `PUT /companies/{company_id}/hidden`.",+ "required": ["hidden"],+ "properties": {+ "hidden": {+ "type": "boolean",+ "description": "New value for `crm_companies.hidden`. Setting to `true` hides\nthe company from CRM listings AND disables `email_sync` (which\npermanently deletes the company's contacts and contact sources).\nSetting to `false` un-hides the company; `email_sync` is left\nuntouched and the team must re-enable it explicitly."+ }+ }+ },+ "SetContactHiddenRequest": {+ "type": "object",+ "description": "Request body for `PUT /contacts/{contact_id}/hidden`.",+ "required": ["hidden"],+ "properties": {+ "hidden": {+ "type": "boolean",+ "description": "New value for `crm_contacts.hidden`. `true` hides the contact\nfrom CRM listings for the team; `false` un-hides it. Display-only\n— does not affect populate/depopulate."+ }+ }+ },"SetEmailSyncRequest": {"type": "object","description": "Request body for `PUT /crm/companies/{company_id}/email-sync`.",diff --git a/rust/cloud-storage/.sqlx/query-1e615fa31568d6c34562bfcddcb0bf15bc140116859a9af9e09dc1374f79629c.json b/rust/cloud-storage/.sqlx/query-1e615fa31568d6c34562bfcddcb0bf15bc140116859a9af9e09dc1374f79629c.jsonnew file mode 100644index 0000000000..43eff5a888--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-1e615fa31568d6c34562bfcddcb0bf15bc140116859a9af9e09dc1374f79629c.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM crm_contact_sources\n WHERE contact_id IN (\n SELECT id FROM crm_contacts WHERE company_id = $1\n )\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "1e615fa31568d6c34562bfcddcb0bf15bc140116859a9af9e09dc1374f79629c"+}diff --git a/rust/cloud-storage/.sqlx/query-45e8619173ce143a2908e7874cac1d14a38ad27be4af19f4558d1439e5e1108b.json b/rust/cloud-storage/.sqlx/query-45e8619173ce143a2908e7874cac1d14a38ad27be4af19f4558d1439e5e1108b.jsonnew file mode 100644index 0000000000..8cd4920d2d--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-45e8619173ce143a2908e7874cac1d14a38ad27be4af19f4558d1439e5e1108b.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE crm_companies\n SET hidden = FALSE\n WHERE id = $1 AND team_id = $2\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "45e8619173ce143a2908e7874cac1d14a38ad27be4af19f4558d1439e5e1108b"+}diff --git a/rust/cloud-storage/.sqlx/query-625647495ec63c951181a5aad2e295875f274892253d2cd1ae925e6898a70466.json b/rust/cloud-storage/.sqlx/query-625647495ec63c951181a5aad2e295875f274892253d2cd1ae925e6898a70466.jsonnew file mode 100644index 0000000000..48b4157687--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-625647495ec63c951181a5aad2e295875f274892253d2cd1ae925e6898a70466.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT hidden\n FROM crm_companies\n WHERE id = $1 AND team_id = $2\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "hidden",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "625647495ec63c951181a5aad2e295875f274892253d2cd1ae925e6898a70466"+}diff --git a/rust/cloud-storage/.sqlx/query-668d2494990d4f281575d7261bec1f4ad8cd78266d7f725b6035bb95b9ad567e.json b/rust/cloud-storage/.sqlx/query-668d2494990d4f281575d7261bec1f4ad8cd78266d7f725b6035bb95b9ad567e.jsonnew file mode 100644index 0000000000..85ceafa3e5--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-668d2494990d4f281575d7261bec1f4ad8cd78266d7f725b6035bb95b9ad567e.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE crm_companies\n SET hidden = $3\n WHERE id = $1 AND team_id = $2\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Bool"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "668d2494990d4f281575d7261bec1f4ad8cd78266d7f725b6035bb95b9ad567e"+}diff --git a/rust/cloud-storage/.sqlx/query-79bc5e3d91f3713ddb29cf42590eca0703771ea550311dfe651cc4cc063d34db.json b/rust/cloud-storage/.sqlx/query-79bc5e3d91f3713ddb29cf42590eca0703771ea550311dfe651cc4cc063d34db.jsonnew file mode 100644index 0000000000..fdeb62938d--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-79bc5e3d91f3713ddb29cf42590eca0703771ea550311dfe651cc4cc063d34db.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT LOWER(domain) AS \"domain!\"\n FROM crm_domains\n WHERE company_id = $1 AND team_id = $2\n ORDER BY LOWER(domain) ASC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "domain!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "79bc5e3d91f3713ddb29cf42590eca0703771ea550311dfe651cc4cc063d34db"+}diff --git a/rust/cloud-storage/.sqlx/query-9728f991ee1e5bff78e52700ce2c4d2d8e8113701d39452faa3147bb18974926.json b/rust/cloud-storage/.sqlx/query-9728f991ee1e5bff78e52700ce2c4d2d8e8113701d39452faa3147bb18974926.jsonnew file mode 100644index 0000000000..efdf6f8f33--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-9728f991ee1e5bff78e52700ce2c4d2d8e8113701d39452faa3147bb18974926.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE crm_contacts ct\n SET hidden = $3\n FROM crm_companies co\n WHERE ct.id = $1\n AND ct.company_id = co.id\n AND co.team_id = $2\n RETURNING ct.id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Bool"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "9728f991ee1e5bff78e52700ce2c4d2d8e8113701d39452faa3147bb18974926"+}diff --git a/rust/cloud-storage/.sqlx/query-98bb8b9d6b4503d0999adb71e7199b1722bd75592887848fa07373e79af717dd.json b/rust/cloud-storage/.sqlx/query-98bb8b9d6b4503d0999adb71e7199b1722bd75592887848fa07373e79af717dd.jsonnew file mode 100644index 0000000000..f0c73d8e9e--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-98bb8b9d6b4503d0999adb71e7199b1722bd75592887848fa07373e79af717dd.json@@ -0,0 +1,47 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT c.id, c.team_id, c.email_sync, c.hidden, c.created_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"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "98bb8b9d6b4503d0999adb71e7199b1722bd75592887848fa07373e79af717dd"+}diff --git a/rust/cloud-storage/.sqlx/query-a6b5613f666d5c6d73c4f8a817e02554c21e5b44768f5761c1d19d019f7208c4.json b/rust/cloud-storage/.sqlx/query-a6b5613f666d5c6d73c4f8a817e02554c21e5b44768f5761c1d19d019f7208c4.jsonnew file mode 100644index 0000000000..18efa7779e--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-a6b5613f666d5c6d73c4f8a817e02554c21e5b44768f5761c1d19d019f7208c4.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE crm_companies\n SET hidden = TRUE, email_sync = FALSE\n WHERE id = $1 AND team_id = $2\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "a6b5613f666d5c6d73c4f8a817e02554c21e5b44768f5761c1d19d019f7208c4"+}diff --git a/rust/cloud-storage/.sqlx/query-e57d0a84a9cb67f987d4a53bfb123136039849d1c3c5ff81463691e0ae271f74.json b/rust/cloud-storage/.sqlx/query-e57d0a84a9cb67f987d4a53bfb123136039849d1c3c5ff81463691e0ae271f74.jsonnew file mode 100644index 0000000000..1f42113c88--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-e57d0a84a9cb67f987d4a53bfb123136039849d1c3c5ff81463691e0ae271f74.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT hidden\n FROM crm_companies\n WHERE id = $1 AND team_id = $2\n FOR UPDATE\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "hidden",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "e57d0a84a9cb67f987d4a53bfb123136039849d1c3c5ff81463691e0ae271f74"+}diff --git a/rust/cloud-storage/crm/src/domain/companies_repo.rs b/rust/cloud-storage/crm/src/domain/companies_repo.rsindex a510d0e27a..3b5f6fbd27 100644--- a/rust/cloud-storage/crm/src/domain/companies_repo.rs+++ b/rust/cloud-storage/crm/src/domain/companies_repo.rs@@ -166,10 +166,42 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {/// On disable, the same tx also deletes the company's/// `crm_contacts` and `crm_contact_sources`. Returns/// [`CrmError::CompanyNotFoundForTeam`] on a non-matching pair.+ /// Refuses to set `email_sync = true` when the company has+ /// `hidden = true` (returns [`CrmError::CompanyHidden`]) — a hidden+ /// company would otherwise have populate re-create contacts under+ /// it. Un-hide first if you really want sync back on.fn set_email_sync(&self,team_id: &uuid::Uuid,company_id: &uuid::Uuid,email_sync: bool,) -> impl Future<Output = Result<(), CrmError>> + Send;++ /// Toggle `crm_companies.hidden` for `(company_id, team_id)`. When+ /// `hidden = true` this also sets `email_sync = false` and tears+ /// down the company's `crm_contacts` and `crm_contact_sources` in+ /// the **same transaction**, holding the same per-`(team, domain)`+ /// advisory locks [`set_email_sync`] takes. Un-hide (`hidden =+ /// false`) only flips the flag; `email_sync` is left as-is.+ /// Returns [`CrmError::CompanyNotFoundForTeam`] on a non-matching+ /// pair.+ ///+ /// [`set_email_sync`]: CompaniesRepository::set_email_sync+ fn set_company_hidden(+ &self,+ team_id: &uuid::Uuid,+ company_id: &uuid::Uuid,+ hidden: bool,+ ) -> impl Future<Output = Result<(), CrmError>> + Send;++ /// Toggle `crm_contacts.hidden` for `contact_id`, scoped to+ /// `team_id` via the contact's company. Returns+ /// [`CrmError::ContactNotFoundForTeam`] when the contact does not+ /// exist or belongs to another team.+ fn set_contact_hidden(+ &self,+ team_id: &uuid::Uuid,+ contact_id: &uuid::Uuid,+ hidden: bool,+ ) -> impl Future<Output = Result<(), CrmError>> + Send;}diff --git a/rust/cloud-storage/crm/src/domain/model.rs b/rust/cloud-storage/crm/src/domain/model.rsindex fd5931e4c1..d235a8e2df 100644--- a/rust/cloud-storage/crm/src/domain/model.rs+++ b/rust/cloud-storage/crm/src/domain/model.rs@@ -17,6 +17,11 @@ pub struct CrmCompany {pub team_id: uuid::Uuid,/// Whether email sync is enabled for this companypub email_sync: bool,+ /// Whether the company is hidden from CRM listings for the owning+ /// team. Display-only opt-out; setting it to `true` also forces+ /// `email_sync = false` (see+ /// [`crate::domain::service::CrmService::set_company_hidden`]).+ pub hidden: bool,/// When the company was createdpub created_at: DateTime<Utc>,/// All domains associated with this company@@ -66,6 +71,14 @@ pub enum CrmError {/// Company id is not owned by the requesting team.#[error("crm company not found for team")]CompanyNotFoundForTeam,+ /// Contact id is not owned by the requesting team.+ #[error("crm contact not found for team")]+ ContactNotFoundForTeam,+ /// Tried to mutate a CRM company in a way that contradicts its+ /// `hidden = true` state — currently raised when attempting to+ /// re-enable `email_sync` on a hidden company.+ #[error("crm company is hidden")]+ CompanyHidden,/// Entity access receipt did not contain a valid team UUID.#[error("invalid team id in entity access receipt")]InvalidTeamId,diff --git a/rust/cloud-storage/crm/src/domain/service.rs b/rust/cloud-storage/crm/src/domain/service.rsindex f4fc690969..3e9c831a3e 100644--- a/rust/cloud-storage/crm/src/domain/service.rs+++ b/rust/cloud-storage/crm/src/domain/service.rs@@ -108,6 +108,31 @@ pub trait CrmService: Clone + Send + Sync + 'static {company_id: &uuid::Uuid,email_sync: bool,) -> impl Future<Output = Result<(), CrmError>> + Send;++ /// Toggle the `hidden` flag on a CRM company for `(company_id,+ /// team_id)`. Hiding (`true`) also forces `email_sync = false` and+ /// tears down contacts/sources atomically; see+ /// [`crate::domain::companies_repo::CompaniesRepository::set_company_hidden`].+ /// Un-hiding (`false`) leaves `email_sync` as-is — the team must+ /// re-enable sync explicitly. Authorization is the caller's+ /// responsibility.+ fn set_company_hidden(+ &self,+ team_id: &uuid::Uuid,+ company_id: &uuid::Uuid,+ hidden: bool,+ ) -> impl Future<Output = Result<(), CrmError>> + Send;++ /// Toggle the `hidden` flag on a CRM contact, scoped to `team_id`+ /// via the contact's company. Hiding is a display-only opt-out and+ /// does not affect populate/depopulate. Authorization is the+ /// caller's responsibility.+ fn set_contact_hidden(+ &self,+ team_id: &uuid::Uuid,+ contact_id: &uuid::Uuid,+ hidden: bool,+ ) -> impl Future<Output = Result<(), CrmError>> + Send;}/// Implementation of [`CrmService`] backed by a [`CompaniesRepository`]@@ -284,4 +309,28 @@ where.set_email_sync(team_id, company_id, email_sync).await}++ #[tracing::instrument(skip(self), err)]+ async fn set_company_hidden(+ &self,+ team_id: &uuid::Uuid,+ company_id: &uuid::Uuid,+ hidden: bool,+ ) -> Result<(), CrmError> {+ self.companies_repository+ .set_company_hidden(team_id, company_id, hidden)+ .await+ }++ #[tracing::instrument(skip(self), err)]+ async fn set_contact_hidden(+ &self,+ team_id: &uuid::Uuid,+ contact_id: &uuid::Uuid,+ hidden: bool,+ ) -> Result<(), CrmError> {+ self.companies_repository+ .set_contact_hidden(team_id, contact_id, hidden)+ .await+ }}diff --git a/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs b/rust/cloud-storage/crm/src/inbound/axum_router/mod.rsindex bfb6956808..49919a7d1d 100644--- a/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs+++ b/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs@@ -3,6 +3,12 @@/// Toggle the `email_sync` flag on a `crm_companies` row.pub mod set_email_sync;+/// Toggle the `hidden` flag on a `crm_companies` row.+pub mod set_company_hidden;++/// Toggle the `hidden` flag on a `crm_contacts` row.+pub mod set_contact_hidden;+use std::sync::Arc;use axum::{@@ -53,6 +59,14 @@ where"/companies/{company_id}/email-sync",put(set_email_sync::handler::<C, Eas>),)+ .route(+ "/companies/{company_id}/hidden",+ put(set_company_hidden::handler::<C, Eas>),+ )+ .route(+ "/contacts/{contact_id}/hidden",+ put(set_contact_hidden::handler::<C, Eas>),+ ).with_state(state)}@@ -65,6 +79,18 @@ impl IntoResponse for CrmError {message: "crm company not found for team".into(),}),),+ CrmError::ContactNotFoundForTeam => (+ StatusCode::NOT_FOUND,+ Json(ErrorResponse {+ message: "crm contact not found for team".into(),+ }),+ ),+ CrmError::CompanyHidden => (+ StatusCode::CONFLICT,+ Json(ErrorResponse {+ message: "crm company is hidden; un-hide before enabling email sync".into(),+ }),+ ),CrmError::InvalidTeamId | CrmError::StorageLayerError(_) => (StatusCode::INTERNAL_SERVER_ERROR,Json(ErrorResponse {diff --git a/rust/cloud-storage/crm/src/inbound/axum_router/set_company_hidden.rs b/rust/cloud-storage/crm/src/inbound/axum_router/set_company_hidden.rsnew file mode 100644index 0000000000..33e6a84292--- /dev/null+++ b/rust/cloud-storage/crm/src/inbound/axum_router/set_company_hidden.rs@@ -0,0 +1,62 @@+use axum::{+ Json,+ extract::{Path, State},+ http::StatusCode,+};+use entity_access::{+ domain::{models::AdminTeamRole, ports::EntityAccessService},+ inbound::axum_extractors::MacroUserTeamExtractor,+};+use model_error_response::ErrorResponse;+use serde::Deserialize;+use utoipa::ToSchema;+use uuid::Uuid;++use crate::domain::{model::CrmError, service::CrmService};++use super::CrmRouterState;++/// Request body for `PUT /companies/{company_id}/hidden`.+#[derive(Debug, Deserialize, ToSchema)]+pub struct SetCompanyHiddenRequest {+ /// New value for `crm_companies.hidden`. Setting to `true` hides+ /// the company from CRM listings AND disables `email_sync` (which+ /// permanently deletes the company's contacts and contact sources).+ /// Setting to `false` un-hides the company; `email_sync` is left+ /// untouched and the team must re-enable it explicitly.+ pub hidden: bool,+}++/// Toggle `hidden` on a CRM company. Hiding also disables `email_sync`+/// and cascades to clearing the company's contacts and contact sources.+#[utoipa::path(+ put,+ path = "/crm/companies/{company_id}/hidden",+ operation_id = "set_company_hidden",+ params(+ ("company_id" = Uuid, Path, description = "The CRM company to update"),+ ),+ request_body = SetCompanyHiddenRequest,+ responses(+ (status = 204),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ ),+)]+#[tracing::instrument(skip_all, err, fields(company_id = %company_id, hidden = req.hidden))]+pub async fn handler<C: CrmService, Eas: EntityAccessService>(+ access: MacroUserTeamExtractor<AdminTeamRole, Eas>,+ State(state): State<CrmRouterState<C, Eas>>,+ Path(company_id): Path<Uuid>,+ Json(req): Json<SetCompanyHiddenRequest>,+) -> Result<StatusCode, CrmError> {+ let team_id = macro_uuid::string_to_uuid(&access.entity_access_receipt.entity().entity_id)+ .map_err(|_| CrmError::InvalidTeamId)?;++ state+ .service+ .set_company_hidden(&team_id, &company_id, req.hidden)+ .await?;+ Ok(StatusCode::NO_CONTENT)+}diff --git a/rust/cloud-storage/crm/src/inbound/axum_router/set_contact_hidden.rs b/rust/cloud-storage/crm/src/inbound/axum_router/set_contact_hidden.rsnew file mode 100644index 0000000000..8f10ff7cf1--- /dev/null+++ b/rust/cloud-storage/crm/src/inbound/axum_router/set_contact_hidden.rs@@ -0,0 +1,60 @@+use axum::{+ Json,+ extract::{Path, State},+ http::StatusCode,+};+use entity_access::{+ domain::{models::AdminTeamRole, ports::EntityAccessService},+ inbound::axum_extractors::MacroUserTeamExtractor,+};+use model_error_response::ErrorResponse;+use serde::Deserialize;+use utoipa::ToSchema;+use uuid::Uuid;++use crate::domain::{model::CrmError, service::CrmService};++use super::CrmRouterState;++/// Request body for `PUT /contacts/{contact_id}/hidden`.+#[derive(Debug, Deserialize, ToSchema)]+pub struct SetContactHiddenRequest {+ /// New value for `crm_contacts.hidden`. `true` hides the contact+ /// from CRM listings for the team; `false` un-hides it. Display-only+ /// — does not affect populate/depopulate.+ pub hidden: bool,+}++/// Toggle `hidden` on a CRM contact. Hiding is a display-only opt-out+/// scoped to the team that owns the contact's company.+#[utoipa::path(+ put,+ path = "/crm/contacts/{contact_id}/hidden",+ operation_id = "set_contact_hidden",+ params(+ ("contact_id" = Uuid, Path, description = "The CRM contact to update"),+ ),+ request_body = SetContactHiddenRequest,+ responses(+ (status = 204),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ ),+)]+#[tracing::instrument(skip_all, err, fields(contact_id = %contact_id, hidden = req.hidden))]+pub async fn handler<C: CrmService, Eas: EntityAccessService>(+ access: MacroUserTeamExtractor<AdminTeamRole, Eas>,+ State(state): State<CrmRouterState<C, Eas>>,+ Path(contact_id): Path<Uuid>,+ Json(req): Json<SetContactHiddenRequest>,+) -> Result<StatusCode, CrmError> {+ let team_id = macro_uuid::string_to_uuid(&access.entity_access_receipt.entity().entity_id)+ .map_err(|_| CrmError::InvalidTeamId)?;++ state+ .service+ .set_contact_hidden(&team_id, &contact_id, req.hidden)+ .await?;+ Ok(StatusCode::NO_CONTENT)+}diff --git a/rust/cloud-storage/crm/src/inbound/axum_router/set_email_sync.rs b/rust/cloud-storage/crm/src/inbound/axum_router/set_email_sync.rsindex 080a34492a..b770ed3a72 100644--- a/rust/cloud-storage/crm/src/inbound/axum_router/set_email_sync.rs+++ b/rust/cloud-storage/crm/src/inbound/axum_router/set_email_sync.rs@@ -39,6 +39,7 @@ pub struct SetEmailSyncRequest {(status = 204),(status = 401, body = ErrorResponse),(status = 404, body = ErrorResponse),+ (status = 409, body = ErrorResponse, description = "Company is hidden; un-hide before enabling email sync"),(status = 500, body = ErrorResponse),),)]diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo.rs b/rust/cloud-storage/crm/src/outbound/companies_repo.rsindex b225e41350..0227ac7bc5 100644--- a/rust/cloud-storage/crm/src/outbound/companies_repo.rs+++ b/rust/cloud-storage/crm/src/outbound/companies_repo.rs@@ -21,6 +21,75 @@ impl CompaniesRepositoryImpl {pub fn new(pool: PgPool) -> Self {Self { pool }}++ /// Take per-`(team_id, lower(domain))` advisory locks for every+ /// domain attached to the company, in sorted order. This is the+ /// same lock scheme `populate_contact` and `depopulate_contact`+ /// hold, so any caller mutating company-scoped sync state should+ /// take these locks before observing contacts/sources.+ async fn lock_company_domains(+ tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,+ team_id: &uuid::Uuid,+ company_id: &uuid::Uuid,+ ) -> Result<(), CrmError> {+ let domains = sqlx::query_scalar!(+ r#"+ SELECT LOWER(domain) AS "domain!"+ FROM crm_domains+ WHERE company_id = $1 AND team_id = $2+ ORDER BY LOWER(domain) ASC+ "#,+ company_id,+ team_id,+ )+ .fetch_all(&mut **tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ for domain in domains {+ sqlx::query!(+ r#"SELECT pg_advisory_xact_lock(hashtextextended($1, 0))"#,+ format!("{team_id}:{domain}"),+ )+ .execute(&mut **tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;+ }++ Ok(())+ }++ /// Delete every `crm_contact_sources` row pointing at a contact in+ /// `company_id`, then every `crm_contacts` row for the company.+ /// Caller is expected to be inside a tx that already holds the+ /// per-domain advisory locks (see [`Self::lock_company_domains`]).+ async fn delete_company_contacts(+ tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,+ company_id: &uuid::Uuid,+ ) -> Result<(), CrmError> {+ sqlx::query!(+ r#"+ DELETE FROM crm_contact_sources+ WHERE contact_id IN (+ SELECT id FROM crm_contacts WHERE company_id = $1+ )+ "#,+ company_id,+ )+ .execute(&mut **tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ sqlx::query!(+ r#"DELETE FROM crm_contacts WHERE company_id = $1"#,+ company_id,+ )+ .execute(&mut **tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ Ok(())+ }}impl CompaniesRepository for CompaniesRepositoryImpl {@@ -34,7 +103,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {let company = sqlx::query!(r#"- SELECT c.id, c.team_id, c.email_sync, c.created_at+ SELECT c.id, c.team_id, c.email_sync, c.hidden, c.created_atFROM crm_companies cJOIN crm_domains d ON d.company_id = c.idWHERE c.team_id = $1@@ -77,6 +146,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {id: company.id,team_id: company.team_id,email_sync: company.email_sync,+ hidden: company.hidden,created_at: company.created_at,domains,}))@@ -550,35 +620,39 @@ impl CompaniesRepository for CompaniesRepositoryImpl {.await.map_err(|e| CrmError::StorageLayerError(e.into()))?;- // Disable path takes the same per-(team, domain) advisory locks- // populate_contact uses. Without this, a populate that already- // passed its killswitch check could insert a contact into a- // company we're about to disable. Sorted lookup gives a- // deterministic lock order — populates only hold one domain lock- // at a time, so deadlock isn't possible.if !email_sync {- let domains = sqlx::query_scalar!(+ // Disable path holds the same per-(team, domain) advisory+ // locks populate_contact uses, so a populate already past+ // its killswitch check can't slip a contact in after we+ // observe state. Populates only hold one domain lock at a+ // time, so deadlock isn't possible.+ Self::lock_company_domains(&mut tx, team_id, company_id).await?;+ } else {+ // Enabling on a hidden company would let populate re-create+ // contacts under a row the team has explicitly hidden, so+ // refuse. Lock the row FOR UPDATE so a concurrent hide can't+ // commit between this check and the email_sync UPDATE below.+ // Domain locks aren't needed because we don't mutate+ // contacts on the enable path.+ let row = sqlx::query!(r#"- SELECT LOWER(domain) AS "domain!"- FROM crm_domains- WHERE company_id = $1 AND team_id = $2- ORDER BY LOWER(domain) ASC+ SELECT hidden+ FROM crm_companies+ WHERE id = $1 AND team_id = $2+ FOR UPDATE"#,company_id,team_id,)- .fetch_all(&mut *tx)+ .fetch_optional(&mut *tx).await.map_err(|e| CrmError::StorageLayerError(e.into()))?;- for domain in domains {- sqlx::query!(- r#"SELECT pg_advisory_xact_lock(hashtextextended($1, 0))"#,- format!("{team_id}:{domain}"),- )- .execute(&mut *tx)- .await- .map_err(|e| CrmError::StorageLayerError(e.into()))?;+ let Some(row) = row else {+ return Err(CrmError::CompanyNotFoundForTeam);+ };+ if row.hidden {+ return Err(CrmError::CompanyHidden);}}@@ -603,26 +677,79 @@ impl CompaniesRepository for CompaniesRepositoryImpl {}if !email_sync {- sqlx::query!(+ Self::delete_company_contacts(&mut tx, company_id).await?;+ }++ tx.commit()+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ Ok(())+ }++ #[tracing::instrument(skip(self), err)]+ async fn set_company_hidden(+ &self,+ team_id: &uuid::Uuid,+ company_id: &uuid::Uuid,+ hidden: bool,+ ) -> Result<(), CrmError> {+ let mut tx = self+ .pool+ .begin()+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ if hidden {+ // Hiding implies opting out of email sync — flip both flags+ // and tear down contacts/sources in one transaction so a+ // partial failure can't leave the company visible with its+ // contacts gone. Take the per-(team, domain) advisory locks+ // first so a concurrent populate past its killswitch check+ // can't slip a contact in after we observe state.+ Self::lock_company_domains(&mut tx, team_id, company_id).await?;++ // Scoping UPDATE on both id AND team_id rejects cross-team callers as NotFound.+ let updated = sqlx::query_scalar!(r#"- DELETE FROM crm_contact_sources- WHERE contact_id IN (- SELECT id FROM crm_contacts WHERE company_id = $1- )+ UPDATE crm_companies+ SET hidden = TRUE, email_sync = FALSE+ WHERE id = $1 AND team_id = $2+ RETURNING id"#,company_id,+ team_id,)- .execute(&mut *tx)+ .fetch_optional(&mut *tx).await.map_err(|e| CrmError::StorageLayerError(e.into()))?;- sqlx::query!(- r#"DELETE FROM crm_contacts WHERE company_id = $1"#,+ if updated.is_none() {+ return Err(CrmError::CompanyNotFoundForTeam);+ }++ Self::delete_company_contacts(&mut tx, company_id).await?;+ } else {+ // Un-hide only flips the flag — email_sync stays whatever+ // the team last set it to. Re-enabling sync is an explicit+ // separate action.+ let updated = sqlx::query_scalar!(+ r#"+ UPDATE crm_companies+ SET hidden = FALSE+ WHERE id = $1 AND team_id = $2+ RETURNING id+ "#,company_id,+ team_id,)- .execute(&mut *tx)+ .fetch_optional(&mut *tx).await.map_err(|e| CrmError::StorageLayerError(e.into()))?;++ if updated.is_none() {+ return Err(CrmError::CompanyNotFoundForTeam);+ }}tx.commit()@@ -632,6 +759,40 @@ impl CompaniesRepository for CompaniesRepositoryImpl {Ok(())}+ #[tracing::instrument(skip(self), err)]+ async fn set_contact_hidden(+ &self,+ team_id: &uuid::Uuid,+ contact_id: &uuid::Uuid,+ hidden: bool,+ ) -> Result<(), CrmError> {+ // Scope to team via the contact's company. A contact owned by a+ // different team's company won't match and we return NotFound.+ let updated = sqlx::query_scalar!(+ r#"+ UPDATE crm_contacts ct+ SET hidden = $3+ FROM crm_companies co+ WHERE ct.id = $1+ AND ct.company_id = co.id+ AND co.team_id = $2+ RETURNING ct.id+ "#,+ contact_id,+ team_id,+ hidden,+ )+ .fetch_optional(&self.pool)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ if updated.is_none() {+ return Err(CrmError::ContactNotFoundForTeam);+ }++ Ok(())+ }+#[tracing::instrument(skip(self), err)]async fn get_team_id_for_user(&self, macro_id: &str) -> Result<Option<uuid::Uuid>, CrmError> {sqlx::query_scalar!(diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs b/rust/cloud-storage/crm/src/outbound/companies_repo/test.rsindex c7612c57b4..41a4f3ebc3 100644--- a/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs@@ -1,4 +1,6 @@use super::*;+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;@@ -126,6 +128,22 @@ async fn fetch_email_sync(pool: &PgPool, company_id: Uuid) -> sqlx::Result<OptioOk(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))+}+#[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();@@ -320,3 +338,222 @@ async fn set_email_sync_disable_handles_multi_domain_company(pool: PgPool) -> anassert_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_also_disables_email_sync(+ 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?;+ 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));+ assert_eq!(count_contacts(&pool, company_id).await?, 0);+ assert_eq!(count_sources_for_company(&pool, company_id).await?, 0);+ 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(())+}diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rsindex c8106ed4a2..4020e44b4c 100644--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs@@ -255,6 +255,8 @@ use utoipa::OpenApi;// /crmcrm::inbound::axum_router::set_email_sync::handler,+ crm::inbound::axum_router::set_company_hidden::handler,+ crm::inbound::axum_router::set_contact_hidden::handler,),components(schemas(@@ -439,6 +441,8 @@ use utoipa::OpenApi;// CRMcrm::inbound::axum_router::set_email_sync::SetEmailSyncRequest,+ crm::inbound::axum_router::set_company_hidden::SetCompanyHiddenRequest,+ crm::inbound::axum_router::set_contact_hidden::SetContactHiddenRequest,),),tags(diff --git a/rust/cloud-storage/macro_db_client/migrations/20260521203029_crm_hidden.down.sql b/rust/cloud-storage/macro_db_client/migrations/20260521203029_crm_hidden.down.sqlnew file mode 100644index 0000000000..117776e97e--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260521203029_crm_hidden.down.sql@@ -0,0 +1,8 @@+DROP INDEX IF EXISTS crm_contacts_visible_company_id_idx;+DROP INDEX IF EXISTS crm_companies_visible_team_id_idx;++ALTER TABLE crm_contacts+ DROP COLUMN IF EXISTS hidden;++ALTER TABLE crm_companies+ DROP COLUMN IF EXISTS hidden;diff --git a/rust/cloud-storage/macro_db_client/migrations/20260521203029_crm_hidden.up.sql b/rust/cloud-storage/macro_db_client/migrations/20260521203029_crm_hidden.up.sqlnew file mode 100644index 0000000000..a7c979e920--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260521203029_crm_hidden.up.sql@@ -0,0 +1,13 @@+ALTER TABLE crm_companies+ ADD COLUMN IF NOT EXISTS hidden BOOLEAN NOT NULL DEFAULT FALSE;++ALTER TABLE crm_contacts+ ADD COLUMN IF NOT EXISTS hidden BOOLEAN NOT NULL DEFAULT FALSE;++CREATE INDEX IF NOT EXISTS crm_companies_visible_team_id_idx+ ON crm_companies (team_id)+ WHERE hidden = FALSE;++CREATE INDEX IF NOT EXISTS crm_contacts_visible_company_id_idx+ ON crm_contacts (company_id)+ WHERE hidden = FALSE;