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): log an info line for each CRM contact teardown (#5297)
Evan Hutnik46eff9d96b57
diff --git a/crates/crm/src/domain/companies_repo.rs b/crates/crm/src/domain/companies_repo.rsindex 74b749db16..0edc6b358a 100644--- a/crates/crm/src/domain/companies_repo.rs+++ b/crates/crm/src/domain/companies_repo.rs@@ -5,7 +5,7 @@ use crate::domain::comment::{};use crate::domain::model::{CrmCompanyForSoup, CrmCompanyWithContacts, CrmContact, CrmError, CrmScopePrecheck,- CrmTeamSettings, CrmTeamSettingsPatch, DomainMetadata,+ CrmTeamSettings, CrmTeamSettingsPatch, DepopulateContactOutcome, DomainMetadata,};use chrono::{DateTime, Utc};use serde_json::Value;@@ -278,16 +278,19 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {/// a concurrent in-flight populate for the same `(team_id, domain)`/// can't slip an uncommitted insert past the existence check.///- /// No-op (returns `Ok(())`) when the contact / company / domain is- /// not found for `(team_id, domain, email)`. `domain` and `email` are- /// matched case-insensitively.+ /// No-op when the contact / company / domain is not found for+ /// `(team_id, domain, email)`. `domain` and `email` are matched+ /// case-insensitively.+ ///+ /// Returns which rows the cascade actually deleted, so callers can tell+ /// a real teardown from a no-op — see [`DepopulateContactOutcome`].fn depopulate_contact(&self,team_id: &uuid::Uuid,link_id: &uuid::Uuid,domain: &str,email: &str,- ) -> impl Future<Output = Result<(), CrmError>> + Send;+ ) -> impl Future<Output = Result<DepopulateContactOutcome, CrmError>> + Send;/// Bulk counterpart to [`depopulate_contact`]: removes everything/// the link contributed to a single team's CRM rows. In onediff --git a/crates/crm/src/domain/model.rs b/crates/crm/src/domain/model.rsindex a5f3199215..8f7bb2bc93 100644--- a/crates/crm/src/domain/model.rs+++ b/crates/crm/src/domain/model.rs@@ -191,6 +191,30 @@ pub struct CrmContact {pub updated_at: DateTime<Utc>,}+/// What a depopulate teardown actually removed. Every field is `false` on+/// the no-op paths (unknown contact, malformed email), so+/// [`Self::removed_anything`] distinguishes a real teardown from a call+/// that found nothing to do — the cleanup job logs on that basis.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub struct DepopulateContactOutcome {+ /// The `crm_contact_sources` row for this `(contact, link)` was deleted.+ pub source_deleted: bool,+ /// The `crm_contacts` row was deleted: no sibling source rows remained+ /// and the contact was not `manually_created`.+ pub contact_deleted: bool,+ /// The `crm_companies` row was deleted (cascading to `crm_domains`): no+ /// sibling contacts remained and the company was neither killswitched+ /// (`email_sync = false`) nor `manually_created`.+ pub company_deleted: bool,+}++impl DepopulateContactOutcome {+ /// Whether the teardown deleted any row at all.+ pub fn removed_anything(&self) -> bool {+ self.source_deleted || self.contact_deleted || self.company_deleted+ }+}+/// Result of [`crate::domain::companies_repo::CompaniesRepository::crm_scope_precheck`].////// Carries the per-input authorization status the caller (`EmailService`)diff --git a/crates/crm/src/domain/service.rs b/crates/crm/src/domain/service.rsindex 8eb18d218d..26a0852523 100644--- a/crates/crm/src/domain/service.rs+++ b/crates/crm/src/domain/service.rs@@ -11,7 +11,7 @@ use crate::domain::{generic_email_domains::is_generic_email_domain,model::{CrmCompanyForSoup, CrmCompanyWithContacts, CrmContact, CrmError, CrmScopePrecheck,- CrmTeamSettings, CrmTeamSettingsPatch,+ CrmTeamSettings, CrmTeamSettingsPatch, DepopulateContactOutcome,},};use chrono::{DateTime, Utc};@@ -103,12 +103,15 @@ pub trait CrmService: Clone + Send + Sync + 'static {/// it through the retry path. The caller is expected to gate this/// call on a prior check that the link has no other sent messages to/// `email`.+ ///+ /// Returns which rows the cascade actually deleted; a malformed email+ /// yields the default (nothing removed).fn depopulate_contact(&self,team_id: &uuid::Uuid,link_id: &uuid::Uuid,email: &str,- ) -> impl Future<Output = Result<(), CrmError>> + Send;+ ) -> impl Future<Output = Result<DepopulateContactOutcome, CrmError>> + Send;/// Bulk teardown for one user's email link within one team: drops/// the team's `crm_contact_sources` rows owned by `link_id`, then@@ -620,21 +623,21 @@ whereteam_id: &uuid::Uuid,link_id: &uuid::Uuid,email: &str,- ) -> Result<(), CrmError> {+ ) -> Result<DepopulateContactOutcome, CrmError> {let email = email.trim();let Some((local_part, domain)) = email.split_once('@') else {tracing::debug!(email,"depopulate_contact: skipping malformed email (no '@')");- return Ok(());+ return Ok(DepopulateContactOutcome::default());};if local_part.is_empty() || domain.is_empty() || domain.contains('@') {tracing::debug!(email,"depopulate_contact: skipping malformed email (empty part or multiple '@')");- return Ok(());+ return Ok(DepopulateContactOutcome::default());}self.companies_repository.depopulate_contact(team_id, link_id, domain, email)@@ -1050,7 +1053,7 @@ impl CrmService for NoOpCrmService {_team_id: &uuid::Uuid,_link_id: &uuid::Uuid,_email: &str,- ) -> Result<(), CrmError> {+ ) -> Result<DepopulateContactOutcome, CrmError> {unimplemented!("NoOpCrmService.depopulate_contact")}diff --git a/crates/crm/src/domain/service/test.rs b/crates/crm/src/domain/service/test.rsindex dd849f0133..2f8aea8350 100644--- a/crates/crm/src/domain/service/test.rs+++ b/crates/crm/src/domain/service/test.rs@@ -74,7 +74,7 @@ impl CompaniesRepository for StubRepo {_link_id: &uuid::Uuid,_domain: &str,_email: &str,- ) -> Result<(), CrmError> {+ ) -> Result<DepopulateContactOutcome, CrmError> {unimplemented!()}diff --git a/crates/crm/src/inbound/axum_extractors/test.rs b/crates/crm/src/inbound/axum_extractors/test.rsindex b3d6386121..6332ab8c71 100644--- a/crates/crm/src/inbound/axum_extractors/test.rs+++ b/crates/crm/src/inbound/axum_extractors/test.rs@@ -40,6 +40,7 @@ use crate::{companies_repo::{CrmCompanyListSort, CrmCompanySoupCursor},model::{CrmCompanyForSoup, CrmCompanyWithContacts, CrmContact, CrmError, CrmScopePrecheck,+ DepopulateContactOutcome,},service::CrmService,},@@ -278,7 +279,7 @@ impl CrmService for FakeCrmService {_team_id: &Uuid,_link_id: &Uuid,_email: &str,- ) -> Result<(), CrmError> {+ ) -> Result<DepopulateContactOutcome, CrmError> {panic!("unexpected depopulate_contact call")}diff --git a/crates/crm/src/outbound/companies_repo.rs b/crates/crm/src/outbound/companies_repo.rsindex a584151534..df33febde9 100644--- a/crates/crm/src/outbound/companies_repo.rs+++ b/crates/crm/src/outbound/companies_repo.rs@@ -11,7 +11,7 @@ use crate::domain::{model::{CrmAddressStatus, CrmCompany, CrmCompanyForSoup, CrmCompanyWithContacts, CrmContact,CrmDomain, CrmDomainStatus, CrmError, CrmPermissionRole, CrmScopePrecheck, CrmTeamSettings,- CrmTeamSettingsPatch, DomainMetadata,+ CrmTeamSettingsPatch, DepopulateContactOutcome, DomainMetadata,},};use chrono::{DateTime, Utc};@@ -623,9 +623,10 @@ impl CompaniesRepository for CompaniesRepositoryImpl {link_id: &uuid::Uuid,domain: &str,email: &str,- ) -> Result<(), CrmError> {+ ) -> Result<DepopulateContactOutcome, CrmError> {let normalized_domain = domain.to_ascii_lowercase();let normalized_email = email.to_ascii_lowercase();+ let mut outcome = DepopulateContactOutcome::default();let mut tx = self.pool@@ -671,11 +672,11 @@ impl CompaniesRepository for CompaniesRepositoryImpl {tx.commit().await.map_err(|e| CrmError::StorageLayerError(e.into()))?;- return Ok(());+ return Ok(outcome);};// 1. Drop the per-link source row.- sqlx::query!(+ let source_result = sqlx::query!(r#"DELETE FROM crm_contact_sourcesWHERE contact_id = $1 AND link_id = $2@@ -686,6 +687,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {.execute(&mut *tx).await.map_err(|e| CrmError::StorageLayerError(e.into()))?;+ outcome.source_deleted = source_result.rows_affected() > 0;// 2. Manually created contacts are user data, not derived —// never torn down (they have no sources by construction, so@@ -694,7 +696,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {tx.commit().await.map_err(|e| CrmError::StorageLayerError(e.into()))?;- return Ok(());+ return Ok(outcome);}// Otherwise keep the contact iff any other link in the team@@ -715,13 +717,15 @@ impl CompaniesRepository for CompaniesRepositoryImpl {tx.commit().await.map_err(|e| CrmError::StorageLayerError(e.into()))?;- return Ok(());+ return Ok(outcome);}- sqlx::query!(r#"DELETE FROM crm_contacts WHERE id = $1"#, row.contact_id,)- .execute(&mut *tx)- .await- .map_err(|e| CrmError::StorageLayerError(e.into()))?;+ let contact_result =+ sqlx::query!(r#"DELETE FROM crm_contacts WHERE id = $1"#, row.contact_id,)+ .execute(&mut *tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;+ outcome.contact_deleted = contact_result.rows_affected() > 0;// 3. Keep killswitched companies — dropping would erase the// opt-out and a future populate would recreate as enabled.@@ -731,7 +735,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {tx.commit().await.map_err(|e| CrmError::StorageLayerError(e.into()))?;- return Ok(());+ return Ok(outcome);}let other_contacts = sqlx::query_scalar!(@@ -750,20 +754,22 @@ impl CompaniesRepository for CompaniesRepositoryImpl {tx.commit().await.map_err(|e| CrmError::StorageLayerError(e.into()))?;- return Ok(());+ return Ok(outcome);}// crm_domains cascades via FK.- sqlx::query!(r#"DELETE FROM crm_companies WHERE id = $1"#, row.company_id,)- .execute(&mut *tx)- .await- .map_err(|e| CrmError::StorageLayerError(e.into()))?;+ let company_result =+ sqlx::query!(r#"DELETE FROM crm_companies WHERE id = $1"#, row.company_id,)+ .execute(&mut *tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;+ outcome.company_deleted = company_result.rows_affected() > 0;tx.commit().await.map_err(|e| CrmError::StorageLayerError(e.into()))?;- Ok(())+ Ok(outcome)}#[tracing::instrument(skip(self), err)]diff --git a/crates/crm/src/outbound/companies_repo/test/create_contact.rs b/crates/crm/src/outbound/companies_repo/test/create_contact.rsindex 7ed1830c98..55bd9c0834 100644--- a/crates/crm/src/outbound/companies_repo/test/create_contact.rs+++ b/crates/crm/src/outbound/companies_repo/test/create_contact.rs@@ -267,8 +267,13 @@ async fn populate_merges_into_manual_contact(pool: PgPool) -> anyhow::Result<()>// The populate attached a source row; tearing that link down again// must keep the manual contact (manually_created shields it from// the no-sources orphan cleanup).- repo.depopulate_contact(&team_id, &link_id, "acme.com", "[email protected]")+ let outcome = repo+ .depopulate_contact(&team_id, &link_id, "acme.com", "[email protected]").await?;+ // Only the source row goes; the manual contact and its company stay.+ assert!(outcome.source_deleted);+ assert!(!outcome.contact_deleted);+ assert!(!outcome.company_deleted);assert_eq!(count_contacts(&pool, company_id).await?, 1);assert_eq!(count_sources_for_company(&pool, company_id).await?, 0);Ok(())diff --git a/services/email_service/src/pubsub/backfill/depopulate_crm_contact.rs b/services/email_service/src/pubsub/backfill/depopulate_crm_contact.rsindex e6abf9e147..a872d0fe13 100644--- a/services/email_service/src/pubsub/backfill/depopulate_crm_contact.rs+++ b/services/email_service/src/pubsub/backfill/depopulate_crm_contact.rs@@ -71,7 +71,8 @@ pub async fn depopulate_crm_contact(return Ok(());}- ctx.crm_service+ let outcome = ctx+ .crm_service.depopulate_contact(&team_id, &link.id, &p.contact_email).await.map_err(|e| {@@ -81,5 +82,15 @@ pub async fn depopulate_crm_contact(})})?;+ if outcome.removed_anything() {+ tracing::info!(+ team_id = %team_id,+ source_deleted = outcome.source_deleted,+ contact_deleted = outcome.contact_deleted,+ company_deleted = outcome.company_deleted,+ "Depopulated CRM contact"+ );+ }+Ok(())}diff --git a/services/email_service/src/pubsub/crm_cleanup/process_candidate.rs b/services/email_service/src/pubsub/crm_cleanup/process_candidate.rsindex e57067c329..682ca8ab5e 100644--- a/services/email_service/src/pubsub/crm_cleanup/process_candidate.rs+++ b/services/email_service/src/pubsub/crm_cleanup/process_candidate.rs@@ -85,7 +85,8 @@ pub async fn process_candidate(return Ok(());}- ctx.crm_service+ let outcome = ctx+ .crm_service.depopulate_contact(&team_id, &link.id, contact_email).await.map_err(|e| {@@ -95,5 +96,19 @@ pub async fn process_candidate(})})?;+ // The only record of work actually done: every other branch here is a+ // skip, so without this a run's real teardown count is unobservable.+ if outcome.removed_anything() {+ tracing::info!(+ team_id = %team_id,+ source_deleted = outcome.source_deleted,+ contact_deleted = outcome.contact_deleted,+ company_deleted = outcome.company_deleted,+ "Depopulated CRM contact"+ );+ } else {+ tracing::debug!("Nothing to tear down for contact; skipping depopulation");+ }+Ok(())}