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): track updated_at on crm_companies and crm_contacts (#3520)

Evan Hutnik4d365539d03b
diff --git a/rust/cloud-storage/.sqlx/query-050da6296d73cdc66ea8dbffcb10267162c71897f66fc9de39ef28c23ab6f918.json b/rust/cloud-storage/.sqlx/query-050da6296d73cdc66ea8dbffcb10267162c71897f66fc9de39ef28c23ab6f918.json
new file mode 100644
index 0000000000..cefe3a50d0
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-050da6296d73cdc66ea8dbffcb10267162c71897f66fc9de39ef28c23ab6f918.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE crm_companies SET updated_at = now() WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "050da6296d73cdc66ea8dbffcb10267162c71897f66fc9de39ef28c23ab6f918"
+}
diff --git a/rust/cloud-storage/.sqlx/query-98bb8b9d6b4503d0999adb71e7199b1722bd75592887848fa07373e79af717dd.json b/rust/cloud-storage/.sqlx/query-3f084390f0f997762642796059a56b37dc19270a95b8e12e9e86d53824562037.json
similarity index 64%
rename from rust/cloud-storage/.sqlx/query-98bb8b9d6b4503d0999adb71e7199b1722bd75592887848fa07373e79af717dd.json
rename to rust/cloud-storage/.sqlx/query-3f084390f0f997762642796059a56b37dc19270a95b8e12e9e86d53824562037.json
index f0c73d8e9e..bb4b2dee3f 100644
--- a/rust/cloud-storage/.sqlx/query-98bb8b9d6b4503d0999adb71e7199b1722bd75592887848fa07373e79af717dd.json
+++ b/rust/cloud-storage/.sqlx/query-3f084390f0f997762642796059a56b37dc19270a95b8e12e9e86d53824562037.json
@@ -1,6 +1,6 @@
{
"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 ",
+ "query": "\n SELECT c.id, c.team_id, c.email_sync, c.hidden, c.created_at, c.updated_at\n FROM crm_companies c\n JOIN crm_domains d ON d.company_id = c.id\n WHERE c.team_id = $1\n AND LOWER(d.domain) = $2\n LIMIT 1\n ",
"describe": {
"columns": [
{
@@ -27,6 +27,11 @@
"ordinal": 4,
"name": "created_at",
"type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
}
],
"parameters": {
@@ -40,8 +45,9 @@
false,
false,
false,
+ false,
false
]
},
- "hash": "98bb8b9d6b4503d0999adb71e7199b1722bd75592887848fa07373e79af717dd"
+ "hash": "3f084390f0f997762642796059a56b37dc19270a95b8e12e9e86d53824562037"
}
diff --git a/rust/cloud-storage/.sqlx/query-6c77980a2f5bad42f7b99481c3cbaeabb6e10d11cd1f2926d3c27cb62a8025c5.json b/rust/cloud-storage/.sqlx/query-e4aca09a26dc2a0796695eee062ba4e66a1d6861c962f05d77c206bbce252f6a.json
similarity index 70%
rename from rust/cloud-storage/.sqlx/query-6c77980a2f5bad42f7b99481c3cbaeabb6e10d11cd1f2926d3c27cb62a8025c5.json
rename to rust/cloud-storage/.sqlx/query-e4aca09a26dc2a0796695eee062ba4e66a1d6861c962f05d77c206bbce252f6a.json
index cc6f8a9dc3..be388437f9 100644
--- a/rust/cloud-storage/.sqlx/query-6c77980a2f5bad42f7b99481c3cbaeabb6e10d11cd1f2926d3c27cb62a8025c5.json
+++ b/rust/cloud-storage/.sqlx/query-e4aca09a26dc2a0796695eee062ba4e66a1d6861c962f05d77c206bbce252f6a.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO crm_contacts (company_id, email, name)\n VALUES ($1, $2, $3)\n ON CONFLICT (company_id, email) DO UPDATE\n SET name = COALESCE(crm_contacts.name, EXCLUDED.name)\n RETURNING id\n ",
+ "query": "\n INSERT INTO crm_contacts (company_id, email, name)\n VALUES ($1, $2, $3)\n ON CONFLICT (company_id, email) DO UPDATE\n SET name = COALESCE(crm_contacts.name, EXCLUDED.name),\n updated_at = now()\n RETURNING id\n ",
"describe": {
"columns": [
{
@@ -20,5 +20,5 @@
false
]
},
- "hash": "6c77980a2f5bad42f7b99481c3cbaeabb6e10d11cd1f2926d3c27cb62a8025c5"
+ "hash": "e4aca09a26dc2a0796695eee062ba4e66a1d6861c962f05d77c206bbce252f6a"
}
diff --git a/rust/cloud-storage/crm/src/domain/companies_repo.rs b/rust/cloud-storage/crm/src/domain/companies_repo.rs
index 68ebfeb3f2..d2f4696055 100644
--- a/rust/cloud-storage/crm/src/domain/companies_repo.rs
+++ b/rust/cloud-storage/crm/src/domain/companies_repo.rs
@@ -32,16 +32,16 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
/// this domain out (the per-domain killswitch): no rows are
/// written and the method returns `Ok(())` so the caller can
/// ack the job.
- /// - If a row exists with `email_sync = true` it is reused.
+ /// - If a row exists with `email_sync = true` it is reused and its
+ /// `updated_at` is refreshed.
/// - Otherwise a new `crm_companies` row and a matching
/// `crm_domains` row are inserted. The company name itself
/// lives in `crm_domain_directory` keyed by `domain`, not on
/// `crm_companies` — see [`lookup_domain_metadata`] /
/// [`upsert_domain_metadata`].
- /// 2. Upsert `crm_contacts (company_id, email, name)` with
- /// `ON CONFLICT DO UPDATE SET name = COALESCE(crm_contacts.name, EXCLUDED.name)`
- /// so the first non-NULL name wins and later populates can't
- /// overwrite it.
+ /// 2. Upsert `crm_contacts (company_id, email, name)`, refreshing
+ /// `updated_at` on existing contacts while preserving the first
+ /// non-NULL name with `name = COALESCE(crm_contacts.name, EXCLUDED.name)`.
/// 3. Upsert `crm_contact_sources (contact_id, link_id)` with
/// `ON CONFLICT DO NOTHING`.
///
diff --git a/rust/cloud-storage/crm/src/domain/model.rs b/rust/cloud-storage/crm/src/domain/model.rs
index 4ae6f16419..c846e6ab7c 100644
--- a/rust/cloud-storage/crm/src/domain/model.rs
+++ b/rust/cloud-storage/crm/src/domain/model.rs
@@ -24,6 +24,8 @@ pub struct CrmCompany {
pub hidden: bool,
/// When the company was created
pub created_at: DateTime<Utc>,
+ /// When the company was last updated
+ pub updated_at: DateTime<Utc>,
/// All domains associated with this company
pub domains: Vec<CrmDomain>,
}
diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo.rs b/rust/cloud-storage/crm/src/outbound/companies_repo.rs
index 2ab7eb8513..edeb0a7e4f 100644
--- a/rust/cloud-storage/crm/src/outbound/companies_repo.rs
+++ b/rust/cloud-storage/crm/src/outbound/companies_repo.rs
@@ -106,7 +106,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
let company = sqlx::query!(
r#"
- SELECT c.id, c.team_id, c.email_sync, c.hidden, c.created_at
+ SELECT c.id, c.team_id, c.email_sync, c.hidden, c.created_at, c.updated_at
FROM crm_companies c
JOIN crm_domains d ON d.company_id = c.id
WHERE c.team_id = $1
@@ -151,6 +151,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
email_sync: company.email_sync,
hidden: company.hidden,
created_at: company.created_at,
+ updated_at: company.updated_at,
domains,
}))
}
@@ -245,7 +246,17 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
return Ok(());
}
- Some(row) => row.id,
+ Some(row) => {
+ sqlx::query!(
+ r#"UPDATE crm_companies SET updated_at = now() WHERE id = $1"#,
+ row.id,
+ )
+ .execute(&mut *tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ row.id
+ }
None => {
let new_company = sqlx::query!(
r#"
@@ -298,6 +309,14 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
+ sqlx::query!(
+ r#"UPDATE crm_companies SET updated_at = now() WHERE id = $1"#,
+ existing_company_id,
+ )
+ .execute(&mut *tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
sqlx::query!(r#"DELETE FROM crm_companies WHERE id = $1"#, new_company.id,)
.execute(&mut *tx)
.await
@@ -315,15 +334,16 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
// populate). On conflict, COALESCE preserves the existing
// crm_contacts.name when it's non-NULL, so the first non-empty
// name wins and a subsequent populate from a different team
- // member can't overwrite it. If the existing name is NULL
- // (previous populate ran before email_contacts had a name), the
- // conflict path still gets a chance to fill it.
+ // member can't overwrite it. The conflict path still performs
+ // an UPDATE for existing contacts so `updated_at` reflects the
+ // latest populate even when the stored name is unchanged.
let contact_id = sqlx::query_scalar!(
r#"
INSERT INTO crm_contacts (company_id, email, name)
VALUES ($1, $2, $3)
ON CONFLICT (company_id, email) DO UPDATE
- SET name = COALESCE(crm_contacts.name, EXCLUDED.name)
+ SET name = COALESCE(crm_contacts.name, EXCLUDED.name),
+ updated_at = now()
RETURNING id
"#,
company_id,
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 85a2721cc6..76119197c3 100644
--- a/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs
+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs
@@ -144,6 +144,30 @@ async fn fetch_contact_hidden(pool: &PgPool, contact_id: Uuid) -> sqlx::Result<O
Ok(row.map(|(h,)| h))
}
+async fn fetch_company_updated_at(
+ pool: &PgPool,
+ company_id: Uuid,
+) -> sqlx::Result<Option<chrono::DateTime<chrono::Utc>>> {
+ let row: Option<(chrono::DateTime<chrono::Utc>,)> =
+ sqlx::query_as(r#"SELECT updated_at FROM crm_companies WHERE id = $1"#)
+ .bind(company_id)
+ .fetch_optional(pool)
+ .await?;
+ Ok(row.map(|(updated_at,)| updated_at))
+}
+
+async fn fetch_contact_updated_at(
+ pool: &PgPool,
+ contact_id: Uuid,
+) -> sqlx::Result<Option<chrono::DateTime<chrono::Utc>>> {
+ let row: Option<(chrono::DateTime<chrono::Utc>,)> =
+ sqlx::query_as(r#"SELECT updated_at FROM crm_contacts WHERE id = $1"#)
+ .bind(contact_id)
+ .fetch_optional(pool)
+ .await?;
+ Ok(row.map(|(updated_at,)| updated_at))
+}
+
#[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();
@@ -651,6 +675,84 @@ async fn service_populate_contact_same_domain_check_is_case_insensitive(
Ok(())
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn service_populate_contact_refreshes_existing_company_and_contact_updated_at(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner_id = "macro|[email protected]";
+ seed_team(&pool, team_id, owner_id).await?;
+ enable_crm_for_team(&pool, team_id).await?;
+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;
+
+ let old_updated_at: chrono::DateTime<chrono::Utc> =
+ sqlx::query_scalar(r#"SELECT now() - INTERVAL '1 hour'"#)
+ .fetch_one(&pool)
+ .await?;
+
+ let company_id = Uuid::now_v7();
+ sqlx::query(
+ r#"INSERT INTO crm_companies (id, team_id, email_sync, updated_at)
+ VALUES ($1, $2, TRUE, $3)"#,
+ )
+ .bind(company_id)
+ .bind(team_id)
+ .bind(old_updated_at)
+ .execute(&pool)
+ .await?;
+
+ sqlx::query(r#"INSERT INTO crm_domains (company_id, team_id, domain) VALUES ($1, $2, $3)"#)
+ .bind(company_id)
+ .bind(team_id)
+ .bind("acme.com")
+ .execute(&pool)
+ .await?;
+
+ let contact_id = Uuid::now_v7();
+ sqlx::query(
+ r#"INSERT INTO crm_contacts (id, company_id, email, updated_at)
+ VALUES ($1, $2, $3, $4)"#,
+ )
+ .bind(contact_id)
+ .bind(company_id)
+ .bind(old_updated_at)
+ .execute(&pool)
+ .await?;
+
+ sqlx::query(r#"INSERT INTO crm_contact_sources (contact_id, link_id) VALUES ($1, $2)"#)
+ .bind(contact_id)
+ .bind(link_id)
+ .execute(&pool)
+ .await?;
+
+ let service = CrmServiceImpl::new(
+ CompaniesRepositoryImpl::new(pool.clone()),
+ NoOpCompanyMetadataResolver,
+ );
+
+ service
+ .populate_contact(
+ &team_id,
+ &link_id,
+ Some("Alice"),
+ )
+ .await?;
+
+ let company_updated_at = fetch_company_updated_at(&pool, company_id)
+ .await?
+ .expect("company should still exist");
+ let contact_updated_at = fetch_contact_updated_at(&pool, contact_id)
+ .await?
+ .expect("contact should still exist");
+
+ assert!(company_updated_at > old_updated_at);
+ assert!(contact_updated_at > old_updated_at);
+ Ok(())
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn service_populate_contact_writes_when_domain_differs(pool: PgPool) -> anyhow::Result<()> {
let team_id = Uuid::now_v7();
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260525152844_crm_updated_at.down.sql b/rust/cloud-storage/macro_db_client/migrations/20260525152844_crm_updated_at.down.sql
new file mode 100644
index 0000000000..acb02e9a66
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260525152844_crm_updated_at.down.sql
@@ -0,0 +1,10 @@
+DROP TRIGGER IF EXISTS crm_contacts_set_updated_at ON crm_contacts;
+DROP TRIGGER IF EXISTS crm_companies_set_updated_at ON crm_companies;
+
+DROP FUNCTION IF EXISTS set_crm_updated_at();
+
+ALTER TABLE crm_contacts
+ DROP COLUMN IF EXISTS updated_at;
+
+ALTER TABLE crm_companies
+ DROP COLUMN IF EXISTS updated_at;
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260525152844_crm_updated_at.up.sql b/rust/cloud-storage/macro_db_client/migrations/20260525152844_crm_updated_at.up.sql
new file mode 100644
index 0000000000..e68f6015b9
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260525152844_crm_updated_at.up.sql
@@ -0,0 +1,25 @@
+ALTER TABLE crm_companies
+ ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
+
+ALTER TABLE crm_contacts
+ ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
+
+CREATE OR REPLACE FUNCTION set_crm_updated_at()
+RETURNS TRIGGER AS $$
+BEGIN
+ NEW.updated_at = now();
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+
+DROP TRIGGER IF EXISTS crm_companies_set_updated_at ON crm_companies;
+CREATE TRIGGER crm_companies_set_updated_at
+ BEFORE UPDATE ON crm_companies
+ FOR EACH ROW
+ EXECUTE FUNCTION set_crm_updated_at();
+
+DROP TRIGGER IF EXISTS crm_contacts_set_updated_at ON crm_contacts;
+CREATE TRIGGER crm_contacts_set_updated_at
+ BEFORE UPDATE ON crm_contacts
+ FOR EACH ROW
+ EXECUTE FUNCTION set_crm_updated_at();