Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(crm): add email_sync toggle endpoint (#3465)

Evan Hutnikcec284f903ad
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.ts
index cd0de28dbb..85f676d411 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
@@ -575,6 +575,7 @@ export * from './saveDocumentRequestSha';
export * from './saveDocumentResponse';
export * from './saveDocumentResponseData';
export * from './saveDocumentResponseDataPresignedUrl';
+export * from './setEmailSyncRequest';
export * from './setPropertyValue';
export * from './setPropertyValueOneOf';
export * from './setPropertyValueOneOfFive';
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/setEmailSyncRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/setEmailSyncRequest.ts
new file mode 100644
index 0000000000..be1a9a4181
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/setEmailSyncRequest.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Request body for `PUT /crm/companies/{company_id}/email-sync`.
+ */
+export interface SetEmailSyncRequest {
+ /** New value for `crm_companies.email_sync`. Setting to `false`
+permanently deletes the company's CRM contacts and contact sources. */
+ email_sync: boolean;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.ts
index f29ca3ed1f..95e580f837 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -1793,6 +1793,27 @@ export const getChannelParticipantsResponse = zod.array(
getChannelParticipantsResponseItem
);
+/**
+ * @summary Toggle `email_sync` on a CRM company. `false` disables CRM email
+sharing for the company and permanently removes its existing CRM
+contacts and contact sources.
+ */
+export const setEmailSyncParams = zod.object({
+ company_id: zod.uuid().describe('The CRM company to update'),
+});
+
+export const setEmailSyncBody = zod
+ .object({
+ email_sync: zod
+ .boolean()
+ .describe(
+ "New value for `crm_companies.email_sync`. Setting to `false`\npermanently deletes the company's CRM contacts and contact sources."
+ ),
+ })
+ .describe(
+ 'Request body for `PUT \/crm\/companies\/{company_id}\/email-sync`.'
+ );
+
/**
* @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.json
index 29d990707f..986764f72e 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -1753,6 +1753,70 @@
}
}
},
+ "/crm/companies/{company_id}/email-sync": {
+ "put": {
+ "tags": ["crm::inbound::axum_router::set_email_sync"],
+ "summary": "Toggle `email_sync` on a CRM company. `false` disables CRM email\nsharing for the company and permanently removes its existing CRM\ncontacts and contact sources.",
+ "operationId": "set_email_sync",
+ "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/SetEmailSyncRequest"
+ }
+ }
+ },
+ "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"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/documents": {
"get": {
"tags": ["document"],
@@ -11450,6 +11514,17 @@
}
}
},
+ "SetEmailSyncRequest": {
+ "type": "object",
+ "description": "Request body for `PUT /crm/companies/{company_id}/email-sync`.",
+ "required": ["email_sync"],
+ "properties": {
+ "email_sync": {
+ "type": "boolean",
+ "description": "New value for `crm_companies.email_sync`. Setting to `false`\npermanently deletes the company's CRM contacts and contact sources."
+ }
+ }
+ },
"SetPropertyValue": {
"oneOf": [
{
diff --git a/rust/cloud-storage/.sqlx/query-4bc26e583a28d41c4bffc91388a876106b2b6cb446540e36ccb65b6180585840.json b/rust/cloud-storage/.sqlx/query-4bc26e583a28d41c4bffc91388a876106b2b6cb446540e36ccb65b6180585840.json
new file mode 100644
index 0000000000..2c0c60989f
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-4bc26e583a28d41c4bffc91388a876106b2b6cb446540e36ccb65b6180585840.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": "4bc26e583a28d41c4bffc91388a876106b2b6cb446540e36ccb65b6180585840"
+}
diff --git a/rust/cloud-storage/.sqlx/query-56b93f5576bd8863529bec3ee7cb1fd26d228a082f3b68346810321639a3d2ae.json b/rust/cloud-storage/.sqlx/query-56b93f5576bd8863529bec3ee7cb1fd26d228a082f3b68346810321639a3d2ae.json
new file mode 100644
index 0000000000..d65be3c20b
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-56b93f5576bd8863529bec3ee7cb1fd26d228a082f3b68346810321639a3d2ae.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": "56b93f5576bd8863529bec3ee7cb1fd26d228a082f3b68346810321639a3d2ae"
+}
diff --git a/rust/cloud-storage/.sqlx/query-57f0a600c647584f8f9ae3a4200bf0508328d9a492f6f6ba13d4dcc725b201c0.json b/rust/cloud-storage/.sqlx/query-57f0a600c647584f8f9ae3a4200bf0508328d9a492f6f6ba13d4dcc725b201c0.json
new file mode 100644
index 0000000000..e03de11b5b
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-57f0a600c647584f8f9ae3a4200bf0508328d9a492f6f6ba13d4dcc725b201c0.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT LOWER(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": "lower",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "57f0a600c647584f8f9ae3a4200bf0508328d9a492f6f6ba13d4dcc725b201c0"
+}
diff --git a/rust/cloud-storage/.sqlx/query-c08f7032873bddafca439eb4a7dcdeab60aed26e9025fde7ea45b89c4d2cb4ed.json b/rust/cloud-storage/.sqlx/query-c08f7032873bddafca439eb4a7dcdeab60aed26e9025fde7ea45b89c4d2cb4ed.json
new file mode 100644
index 0000000000..351b1b820c
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-c08f7032873bddafca439eb4a7dcdeab60aed26e9025fde7ea45b89c4d2cb4ed.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE crm_companies\n SET email_sync = $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": "c08f7032873bddafca439eb4a7dcdeab60aed26e9025fde7ea45b89c4d2cb4ed"
+}
diff --git a/rust/cloud-storage/.sqlx/query-ea8465e511eb18380f7a05b5c02930a31d7729c0a357e3d3c5044f2906756935.json b/rust/cloud-storage/.sqlx/query-ea8465e511eb18380f7a05b5c02930a31d7729c0a357e3d3c5044f2906756935.json
new file mode 100644
index 0000000000..f7f58d59fa
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-ea8465e511eb18380f7a05b5c02930a31d7729c0a357e3d3c5044f2906756935.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM crm_contacts WHERE company_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "ea8465e511eb18380f7a05b5c02930a31d7729c0a357e3d3c5044f2906756935"
+}
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 19ee32db62..33bc31dfe5 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2639,14 +2639,19 @@ name = "crm"
version = "0.1.0"
dependencies = [
"anyhow",
+ "axum",
"chrono",
+ "entity_access",
"macro_db_migrator",
+ "macro_uuid",
+ "model-error-response",
"serde",
"sqlx",
"thiserror 2.0.17",
"tokio",
"tracing",
"unfurl",
+ "utoipa",
"uuid",
]
diff --git a/rust/cloud-storage/crm/Cargo.toml b/rust/cloud-storage/crm/Cargo.toml
index ea10cc17f9..3ef7bb6d9e 100644
--- a/rust/cloud-storage/crm/Cargo.toml
+++ b/rust/cloud-storage/crm/Cargo.toml
@@ -5,7 +5,17 @@ publish = false
version = "0.1.0"
[features]
-default = ["outbound", "ports"]
+axum = [
+ "dep:axum",
+ "dep:macro_uuid",
+ "dep:model-error-response",
+ "dep:utoipa",
+ "entity_access/axum",
+ "entity_access/inbound",
+ "entity_access/ports",
+]
+default = ["inbound", "outbound", "ports"]
+inbound = ["axum", "ports"]
outbound = ["dep:sqlx", "dep:unfurl", "ports"]
ports = []
@@ -17,6 +27,14 @@ thiserror = { workspace = true }
tracing = { workspace = true }
uuid = { workspace = true }
+entity_access = { path = "../entity_access", default-features = false }
+
+# Axum / inbound dependencies
+axum = { workspace = true, optional = true }
+macro_uuid = { path = "../macro_uuid", optional = true }
+model-error-response = { path = "../model-error-response", optional = true }
+utoipa = { workspace = true, optional = true }
+
# Outbound dependencies
sqlx = { workspace = true, optional = true }
unfurl = { path = "../unfurl", features = ["ports"], optional = true }
diff --git a/rust/cloud-storage/crm/src/domain/companies_repo.rs b/rust/cloud-storage/crm/src/domain/companies_repo.rs
index 73f584d2d2..a510d0e27a 100644
--- a/rust/cloud-storage/crm/src/domain/companies_repo.rs
+++ b/rust/cloud-storage/crm/src/domain/companies_repo.rs
@@ -161,4 +161,15 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
&self,
macro_id: &str,
) -> impl Future<Output = Result<Option<uuid::Uuid>, CrmError>> + Send;
+
+ /// Toggle `crm_companies.email_sync` for `(company_id, team_id)`.
+ /// On disable, the same tx also deletes the company's
+ /// `crm_contacts` and `crm_contact_sources`. Returns
+ /// [`CrmError::CompanyNotFoundForTeam`] on a non-matching pair.
+ fn set_email_sync(
+ &self,
+ team_id: &uuid::Uuid,
+ company_id: &uuid::Uuid,
+ email_sync: 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.rs
index 08264ccb4f..fd5931e4c1 100644
--- a/rust/cloud-storage/crm/src/domain/model.rs
+++ b/rust/cloud-storage/crm/src/domain/model.rs
@@ -63,4 +63,10 @@ pub enum CrmError {
/// Storage layer error
#[error("Storage layer error {0}")]
StorageLayerError(#[from] anyhow::Error),
+ /// Company id is not owned by the requesting team.
+ #[error("crm company not found for team")]
+ CompanyNotFoundForTeam,
+ /// 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.rs
index 0d97eb8060..f4fc690969 100644
--- a/rust/cloud-storage/crm/src/domain/service.rs
+++ b/rust/cloud-storage/crm/src/domain/service.rs
@@ -97,6 +97,17 @@ pub trait CrmService: Clone + Send + Sync + 'static {
&self,
macro_id: &str,
) -> impl Future<Output = Result<Option<uuid::Uuid>, CrmError>> + Send;
+
+ /// Toggle `email_sync` for `(company_id, team_id)`. Disable cascades
+ /// to contacts and contact_sources; see
+ /// [`crate::domain::companies_repo::CompaniesRepository::set_email_sync`].
+ /// Authorization is the caller's responsibility.
+ fn set_email_sync(
+ &self,
+ team_id: &uuid::Uuid,
+ company_id: &uuid::Uuid,
+ email_sync: bool,
+ ) -> impl Future<Output = Result<(), CrmError>> + Send;
}
/// Implementation of [`CrmService`] backed by a [`CompaniesRepository`]
@@ -261,4 +272,16 @@ where
.get_team_id_for_user(macro_id)
.await
}
+
+ #[tracing::instrument(skip(self), err)]
+ async fn set_email_sync(
+ &self,
+ team_id: &uuid::Uuid,
+ company_id: &uuid::Uuid,
+ email_sync: bool,
+ ) -> Result<(), CrmError> {
+ self.companies_repository
+ .set_email_sync(team_id, company_id, email_sync)
+ .await
+ }
}
diff --git a/rust/cloud-storage/crm/src/inbound.rs b/rust/cloud-storage/crm/src/inbound.rs
new file mode 100644
index 0000000000..068e431c1f
--- /dev/null
+++ b/rust/cloud-storage/crm/src/inbound.rs
@@ -0,0 +1,4 @@
+//! Inbound adapters for the CRM domain.
+
+#[cfg(feature = "axum")]
+pub mod axum_router;
diff --git a/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs b/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs
new file mode 100644
index 0000000000..bfb6956808
--- /dev/null
+++ b/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs
@@ -0,0 +1,77 @@
+//! Axum router for CRM endpoints.
+
+/// Toggle the `email_sync` flag on a `crm_companies` row.
+pub mod set_email_sync;
+
+use std::sync::Arc;
+
+use axum::{
+ Json, Router,
+ extract::FromRef,
+ http::StatusCode,
+ response::{IntoResponse, Response},
+ routing::put,
+};
+use entity_access::domain::ports::EntityAccessService;
+use model_error_response::ErrorResponse;
+
+use crate::domain::{model::CrmError, service::CrmService};
+
+/// Router state for the CRM endpoints.
+pub struct CrmRouterState<C, Eas> {
+ /// CRM service.
+ pub service: Arc<C>,
+ /// Entity access service used by the team-scoped extractors.
+ pub entity_access_service: Arc<Eas>,
+}
+
+impl<C, Eas> FromRef<CrmRouterState<C, Eas>> for Arc<Eas> {
+ fn from_ref(state: &CrmRouterState<C, Eas>) -> Self {
+ state.entity_access_service.clone()
+ }
+}
+
+// Manual Clone so C, Eas don't need Clone.
+impl<C, Eas> Clone for CrmRouterState<C, Eas> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ entity_access_service: self.entity_access_service.clone(),
+ }
+ }
+}
+
+/// Build the CRM router with all endpoints.
+pub fn crm_router<C, Eas, S>(state: CrmRouterState<C, Eas>) -> Router<S>
+where
+ C: CrmService,
+ Eas: EntityAccessService,
+ S: Send + Sync + 'static,
+{
+ Router::new()
+ .route(
+ "/companies/{company_id}/email-sync",
+ put(set_email_sync::handler::<C, Eas>),
+ )
+ .with_state(state)
+}
+
+impl IntoResponse for CrmError {
+ fn into_response(self) -> Response {
+ match self {
+ CrmError::CompanyNotFoundForTeam => (
+ StatusCode::NOT_FOUND,
+ Json(ErrorResponse {
+ message: "crm company not found for team".into(),
+ }),
+ ),
+ CrmError::InvalidTeamId | CrmError::StorageLayerError(_) => (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "internal server error".into(),
+ }),
+ ),
+ }
+ .into_response()
+ }
+}
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.rs
new file mode 100644
index 0000000000..080a34492a
--- /dev/null
+++ b/rust/cloud-storage/crm/src/inbound/axum_router/set_email_sync.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 /crm/companies/{company_id}/email-sync`.
+#[derive(Debug, Deserialize, ToSchema)]
+pub struct SetEmailSyncRequest {
+ /// New value for `crm_companies.email_sync`. Setting to `false`
+ /// permanently deletes the company's CRM contacts and contact sources.
+ pub email_sync: bool,
+}
+
+/// Toggle `email_sync` on a CRM company. `false` disables CRM email
+/// sharing for the company and permanently removes its existing CRM
+/// contacts and contact sources.
+#[utoipa::path(
+ put,
+ path = "/crm/companies/{company_id}/email-sync",
+ operation_id = "set_email_sync",
+ params(
+ ("company_id" = Uuid, Path, description = "The CRM company to update"),
+ ),
+ request_body = SetEmailSyncRequest,
+ 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, email_sync = req.email_sync))]
+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<SetEmailSyncRequest>,
+) -> 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_email_sync(&team_id, &company_id, req.email_sync)
+ .await?;
+ Ok(StatusCode::NO_CONTENT)
+}
diff --git a/rust/cloud-storage/crm/src/lib.rs b/rust/cloud-storage/crm/src/lib.rs
index cf6833fa03..15211fb183 100644
--- a/rust/cloud-storage/crm/src/lib.rs
+++ b/rust/cloud-storage/crm/src/lib.rs
@@ -7,11 +7,16 @@
//! # Architecture
//!
//! - **domain**: Contains domain models, ports (traits), and the service implementation
+//! - **inbound**: Contains adapters for incoming requests (Axum handlers)
//! - **outbound**: Contains adapters for external dependencies (PostgreSQL)
/// The domain module contains the domain logic for CRM
pub mod domain;
+/// The inbound module contains the inbound adapters for CRM
+#[cfg(feature = "inbound")]
+pub mod inbound;
+
/// The outbound module contains the outbound adapters for CRM
#[cfg(feature = "outbound")]
pub mod outbound;
diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo.rs b/rust/cloud-storage/crm/src/outbound/companies_repo.rs
index b8b2a4d9c0..b225e41350 100644
--- a/rust/cloud-storage/crm/src/outbound/companies_repo.rs
+++ b/rust/cloud-storage/crm/src/outbound/companies_repo.rs
@@ -1,5 +1,8 @@
//! Implementation of [`CompaniesRepository`] backed by MacroDB.
+#[cfg(test)]
+mod test;
+
use crate::domain::{
companies_repo::CompaniesRepository,
model::{CrmCompany, CrmDomain, CrmError, DomainMetadata},
@@ -534,6 +537,101 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
Ok(())
}
+ #[tracing::instrument(skip(self), err)]
+ async fn set_email_sync(
+ &self,
+ team_id: &uuid::Uuid,
+ company_id: &uuid::Uuid,
+ email_sync: bool,
+ ) -> Result<(), CrmError> {
+ let mut tx = self
+ .pool
+ .begin()
+ .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!(
+ 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()))?;
+ }
+ }
+
+ // Scoping UPDATE on both id AND team_id rejects cross-team callers as NotFound.
+ let updated = sqlx::query_scalar!(
+ r#"
+ UPDATE crm_companies
+ SET email_sync = $3
+ WHERE id = $1 AND team_id = $2
+ RETURNING id
+ "#,
+ company_id,
+ team_id,
+ email_sync,
+ )
+ .fetch_optional(&mut *tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ if updated.is_none() {
+ return Err(CrmError::CompanyNotFoundForTeam);
+ }
+
+ if !email_sync {
+ 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()))?;
+ }
+
+ tx.commit()
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ 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.rs
index 615ffdbb62..c7612c57b4 100644
--- a/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs
+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs
@@ -49,17 +49,81 @@ async fn insert_company(
.await?;
for domain in domains {
- sqlx::query(
- r#"INSERT INTO crm_domains (company_id, team_id, domain) VALUES ($1, $2, $3)"#,
- )
+ 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) VALUES ($1, $2, $3)"#)
+ .bind(contact_id)
.bind(company_id)
- .bind(team_id)
- .bind(*domain)
+ .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)
+}
- Ok(company_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))
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
@@ -147,3 +211,112 @@ async fn returns_company_when_email_sync_is_false(pool: PgPool) -> anyhow::Resul
assert!(!company.email_sync);
Ok(())
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn set_email_sync_disable_clears_contacts_and_sources(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?;
+
+ assert_eq!(count_contacts(&pool, company_id).await?, 2);
+ assert_eq!(count_sources_for_company(&pool, company_id).await?, 2);
+
+ 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?, 0);
+ assert_eq!(count_sources_for_company(&pool, company_id).await?, 0);
+ 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<()> {
+ 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?, 0);
+ assert_eq!(count_sources_for_company(&pool, company_id).await?, 0);
+ // 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(())
+}
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rs
index 9fbc02c406..d4a225be26 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -72,16 +72,23 @@ pub struct InternalFlag {
pub internal: bool,
}
+/// CRM service for DSS — no-op resolver since DSS doesn't populate.
+pub(crate) type DssCrmService = crm::domain::service::CrmServiceImpl<
+ crm::outbound::companies_repo::CompaniesRepositoryImpl,
+ crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,
+>;
+
type DssEmailService = EmailServiceImpl<
EmailPgRepo,
FrecencyQueryServiceImpl<FrecencyPgStorage>,
email::domain::ports::NoOpEnqueuer,
- crm::domain::service::CrmServiceImpl<
- crm::outbound::companies_repo::CompaniesRepositoryImpl,
- crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,
- >,
+ DssCrmService,
>;
+/// CRM router state.
+pub(crate) type DssCrmState =
+ crm::inbound::axum_router::CrmRouterState<DssCrmService, EntityAccessService>;
+
type DssSoupState = SoupRouterState<
SoupImpl<
PgSoupRepo,
@@ -270,6 +277,7 @@ pub(crate) struct ApiContext {
pub call_internal_state: DssCallInternalState,
pub cal_webhook_state: DssCalWebhookState,
pub entity_access_management_service: EntityAccessManagementService,
+ pub crm_state: DssCrmState,
}
env_var! {
diff --git a/rust/cloud-storage/document_storage_service/src/api/mod.rs b/rust/cloud-storage/document_storage_service/src/api/mod.rs
index 988c1fd57a..d96017b680 100644
--- a/rust/cloud-storage/document_storage_service/src/api/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/mod.rs
@@ -215,6 +215,10 @@ fn api_router(state: ApiContext) -> Router {
"/call",
call::inbound::axum_router::call_router(state.call_state.clone()),
)
+ .nest(
+ "/crm",
+ crm::inbound::axum_router::crm_router(state.crm_state.clone()),
+ )
.layer(
ServiceBuilder::new()
.layer(axum::middleware::from_fn(
diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
index 353ba5c7a1..c8106ed4a2 100644
--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
@@ -251,7 +251,10 @@ use utoipa::OpenApi;
github::inbound::github_sync_router::install_sync_handler,
// /internal/sync_service
- sync_service_hex::inbound::axum_router::bulk_wakeup_handler
+ sync_service_hex::inbound::axum_router::bulk_wakeup_handler,
+
+ // /crm
+ crm::inbound::axum_router::set_email_sync::handler,
),
components(
schemas(
@@ -433,6 +436,9 @@ use utoipa::OpenApi;
// Sync service
sync_service_hex::domain::models::BulkWakeupRequest,
sync_service_hex::domain::models::BulkWakeupResponse,
+
+ // CRM
+ crm::inbound::axum_router::set_email_sync::SetEmailSyncRequest,
),
),
tags(
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index 08921ea63e..d4cf314b08 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -593,6 +593,10 @@ async fn main() -> anyhow::Result<()> {
call_internal_state,
cal_webhook_state,
entity_access_management_service,
+ crm_state: crm::inbound::axum_router::CrmRouterState {
+ service: Arc::new(crm_service),
+ entity_access_service: entity_access_service.clone(),
+ },
};
// Spawn the delete document worker