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 first_interaction/last_interaction + is_sent populate gate (#3548)

Evan Hutnik892c851c70ce
diff --git a/rust/cloud-storage/.sqlx/query-036fca567f0d90c18fe528869a2e734700b1978cdf1a62bcefcb3a9bad3b6eb5.json b/rust/cloud-storage/.sqlx/query-036fca567f0d90c18fe528869a2e734700b1978cdf1a62bcefcb3a9bad3b6eb5.json
new file mode 100644
index 0000000000..c3bae2d564
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-036fca567f0d90c18fe528869a2e734700b1978cdf1a62bcefcb3a9bad3b6eb5.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE crm_companies\n SET updated_at = now(),\n first_interaction = CASE\n WHEN $4 THEN LEAST(first_interaction, $2)\n ELSE first_interaction\n END,\n last_interaction = GREATEST(last_interaction, $3)\n WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz",
+ "Timestamptz",
+ "Bool"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "036fca567f0d90c18fe528869a2e734700b1978cdf1a62bcefcb3a9bad3b6eb5"
+}
diff --git a/rust/cloud-storage/.sqlx/query-050da6296d73cdc66ea8dbffcb10267162c71897f66fc9de39ef28c23ab6f918.json b/rust/cloud-storage/.sqlx/query-050da6296d73cdc66ea8dbffcb10267162c71897f66fc9de39ef28c23ab6f918.json
deleted file mode 100644
index cefe3a50d0..0000000000
--- a/rust/cloud-storage/.sqlx/query-050da6296d73cdc66ea8dbffcb10267162c71897f66fc9de39ef28c23ab6f918.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "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-2194bac364c297d48f6b8a5b196418b06f71f933fc2a9ecb5d04beb2c07fd35b.json b/rust/cloud-storage/.sqlx/query-2194bac364c297d48f6b8a5b196418b06f71f933fc2a9ecb5d04beb2c07fd35b.json
new file mode 100644
index 0000000000..d12d20bcdf
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-2194bac364c297d48f6b8a5b196418b06f71f933fc2a9ecb5d04beb2c07fd35b.json
@@ -0,0 +1,27 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO crm_contacts (company_id, email, name, first_interaction, last_interaction)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (company_id, email) DO UPDATE\n SET name = COALESCE(crm_contacts.name, EXCLUDED.name),\n updated_at = now(),\n first_interaction = CASE\n WHEN $6 THEN LEAST(crm_contacts.first_interaction, EXCLUDED.first_interaction)\n ELSE crm_contacts.first_interaction\n END,\n last_interaction = GREATEST(crm_contacts.last_interaction, EXCLUDED.last_interaction)\n RETURNING id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Timestamptz",
+ "Timestamptz",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "2194bac364c297d48f6b8a5b196418b06f71f933fc2a9ecb5d04beb2c07fd35b"
+}
diff --git a/rust/cloud-storage/.sqlx/query-4c9cd8085118a9ee2076c12a09f4e41c9e9d93550acd5c691de63e313a5c9b54.json b/rust/cloud-storage/.sqlx/query-4c9cd8085118a9ee2076c12a09f4e41c9e9d93550acd5c691de63e313a5c9b54.json
new file mode 100644
index 0000000000..3b9dad77be
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-4c9cd8085118a9ee2076c12a09f4e41c9e9d93550acd5c691de63e313a5c9b54.json
@@ -0,0 +1,40 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n LOWER(c.email_address) AS \"email!\",\n c.name AS \"name\",\n MIN(m.internal_date_ts) AS \"first_at!\",\n MAX(m.internal_date_ts) AS \"last_at!\"\n FROM email_messages m\n JOIN email_message_recipients r ON r.message_id = m.id\n JOIN email_contacts c ON c.id = r.contact_id\n WHERE m.link_id = $1\n AND m.is_sent = true\n AND m.internal_date_ts IS NOT NULL\n GROUP BY LOWER(c.email_address), c.name\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "email!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "name",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 2,
+ "name": "first_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 3,
+ "name": "last_at!",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null,
+ true,
+ null,
+ null
+ ]
+ },
+ "hash": "4c9cd8085118a9ee2076c12a09f4e41c9e9d93550acd5c691de63e313a5c9b54"
+}
diff --git a/rust/cloud-storage/.sqlx/query-61d663d08e05ea919df584b273c67e2d99c3981222a87e823892706e4b9354ac.json b/rust/cloud-storage/.sqlx/query-61d663d08e05ea919df584b273c67e2d99c3981222a87e823892706e4b9354ac.json
new file mode 100644
index 0000000000..a25b42db28
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-61d663d08e05ea919df584b273c67e2d99c3981222a87e823892706e4b9354ac.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE crm_companies\n SET updated_at = now(),\n first_interaction = CASE\n WHEN $4 THEN LEAST(first_interaction, $2)\n ELSE first_interaction\n END,\n last_interaction = GREATEST(last_interaction, $3)\n WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz",
+ "Timestamptz",
+ "Bool"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "61d663d08e05ea919df584b273c67e2d99c3981222a87e823892706e4b9354ac"
+}
diff --git a/rust/cloud-storage/.sqlx/query-7fb579182c5ebbf4516b104b3f4b5956f4d84fb449358a83393d0491d712f44f.json b/rust/cloud-storage/.sqlx/query-7fb579182c5ebbf4516b104b3f4b5956f4d84fb449358a83393d0491d712f44f.json
new file mode 100644
index 0000000000..9c89dd91e5
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-7fb579182c5ebbf4516b104b3f4b5956f4d84fb449358a83393d0491d712f44f.json
@@ -0,0 +1,40 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n LOWER(c.email_address) AS \"email!\",\n c.name AS \"name\",\n MIN(m.internal_date_ts) AS \"first_at!\",\n MAX(m.internal_date_ts) AS \"last_at!\"\n FROM email_messages m\n JOIN email_contacts c ON c.id = m.from_contact_id\n WHERE m.link_id = $1\n AND m.is_sent = false\n AND m.from_contact_id IS NOT NULL\n AND m.internal_date_ts IS NOT NULL\n GROUP BY LOWER(c.email_address), c.name\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "email!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "name",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 2,
+ "name": "first_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 3,
+ "name": "last_at!",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null,
+ true,
+ null,
+ null
+ ]
+ },
+ "hash": "7fb579182c5ebbf4516b104b3f4b5956f4d84fb449358a83393d0491d712f44f"
+}
diff --git a/rust/cloud-storage/.sqlx/query-1b10aa25f5e73a6f33bb2e4cc000644ee2329d7917c9d6692e52b803eaad1e81.json b/rust/cloud-storage/.sqlx/query-896b6aa18d1cbdf28df4b24758813d0327649d0b807a60928142de0d6a2ce5e8.json
similarity index 59%
rename from rust/cloud-storage/.sqlx/query-1b10aa25f5e73a6f33bb2e4cc000644ee2329d7917c9d6692e52b803eaad1e81.json
rename to rust/cloud-storage/.sqlx/query-896b6aa18d1cbdf28df4b24758813d0327649d0b807a60928142de0d6a2ce5e8.json
index 6e368ae2f5..2e3dd4d309 100644
--- a/rust/cloud-storage/.sqlx/query-1b10aa25f5e73a6f33bb2e4cc000644ee2329d7917c9d6692e52b803eaad1e81.json
+++ b/rust/cloud-storage/.sqlx/query-896b6aa18d1cbdf28df4b24758813d0327649d0b807a60928142de0d6a2ce5e8.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT EXISTS (\n SELECT 1\n FROM email_messages m\n JOIN email_message_recipients r ON r.message_id = m.id\n JOIN email_contacts c ON c.id = r.contact_id\n WHERE m.link_id = $1\n AND m.is_sent = true\n AND LOWER(c.email_address) = $2\n LIMIT 1\n ) AS \"exists!\"\n ",
+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM email_messages m\n JOIN email_message_recipients r ON r.message_id = m.id\n JOIN email_contacts c ON c.id = r.contact_id\n WHERE m.link_id = $1\n AND m.is_sent = true\n AND LOWER(c.email_address) = $2\n UNION ALL\n SELECT 1\n FROM email_messages m\n JOIN email_contacts c ON c.id = m.from_contact_id\n WHERE m.link_id = $1\n AND m.is_sent = false\n AND LOWER(c.email_address) = $2\n LIMIT 1\n ) AS \"exists!\"\n ",
"describe": {
"columns": [
{
@@ -19,5 +19,5 @@
null
]
},
- "hash": "1b10aa25f5e73a6f33bb2e4cc000644ee2329d7917c9d6692e52b803eaad1e81"
+ "hash": "896b6aa18d1cbdf28df4b24758813d0327649d0b807a60928142de0d6a2ce5e8"
}
diff --git a/rust/cloud-storage/.sqlx/query-5a21a770cc376a29715d9becc8a69193889b701c49f3bbef18e69f340b041eba.json b/rust/cloud-storage/.sqlx/query-a10bb7f95f88136b0bdf505b0338c8a87045ca5aa3d85cefbba8111c65892870.json
similarity index 52%
rename from rust/cloud-storage/.sqlx/query-5a21a770cc376a29715d9becc8a69193889b701c49f3bbef18e69f340b041eba.json
rename to rust/cloud-storage/.sqlx/query-a10bb7f95f88136b0bdf505b0338c8a87045ca5aa3d85cefbba8111c65892870.json
index 827fdca86e..49be80e7ce 100644
--- a/rust/cloud-storage/.sqlx/query-5a21a770cc376a29715d9becc8a69193889b701c49f3bbef18e69f340b041eba.json
+++ b/rust/cloud-storage/.sqlx/query-a10bb7f95f88136b0bdf505b0338c8a87045ca5aa3d85cefbba8111c65892870.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO crm_companies (team_id)\n VALUES ($1)\n RETURNING id\n ",
+ "query": "\n INSERT INTO crm_companies (team_id, first_interaction, last_interaction)\n VALUES ($1, $2, $3)\n RETURNING id\n ",
"describe": {
"columns": [
{
@@ -11,12 +11,14 @@
],
"parameters": {
"Left": [
- "Uuid"
+ "Uuid",
+ "Timestamptz",
+ "Timestamptz"
]
},
"nullable": [
false
]
},
- "hash": "5a21a770cc376a29715d9becc8a69193889b701c49f3bbef18e69f340b041eba"
+ "hash": "a10bb7f95f88136b0bdf505b0338c8a87045ca5aa3d85cefbba8111c65892870"
}
diff --git a/rust/cloud-storage/.sqlx/query-b9bacf772f93b494f7664caa2f90aa0a816f897a0f4f9bdcc2bbeded8e4409cd.json b/rust/cloud-storage/.sqlx/query-b9bacf772f93b494f7664caa2f90aa0a816f897a0f4f9bdcc2bbeded8e4409cd.json
deleted file mode 100644
index f9d7b175f2..0000000000
--- a/rust/cloud-storage/.sqlx/query-b9bacf772f93b494f7664caa2f90aa0a816f897a0f4f9bdcc2bbeded8e4409cd.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT DISTINCT\n LOWER(c.email_address) AS \"email!\",\n c.name AS \"name\"\n FROM email_messages m\n JOIN email_message_recipients r ON r.message_id = m.id\n JOIN email_contacts c ON c.id = r.contact_id\n WHERE m.link_id = $1\n AND m.is_sent = true\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "email!",
- "type_info": "Text"
- },
- {
- "ordinal": 1,
- "name": "name",
- "type_info": "Varchar"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- null,
- true
- ]
- },
- "hash": "b9bacf772f93b494f7664caa2f90aa0a816f897a0f4f9bdcc2bbeded8e4409cd"
-}
diff --git a/rust/cloud-storage/.sqlx/query-e4aca09a26dc2a0796695eee062ba4e66a1d6861c962f05d77c206bbce252f6a.json b/rust/cloud-storage/.sqlx/query-e4aca09a26dc2a0796695eee062ba4e66a1d6861c962f05d77c206bbce252f6a.json
deleted file mode 100644
index be388437f9..0000000000
--- a/rust/cloud-storage/.sqlx/query-e4aca09a26dc2a0796695eee062ba4e66a1d6861c962f05d77c206bbce252f6a.json
+++ /dev/null
@@ -1,24 +0,0 @@
-{
- "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 updated_at = now()\n RETURNING id\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "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 d2f4696055..0bf25ee30b 100644
--- a/rust/cloud-storage/crm/src/domain/companies_repo.rs
+++ b/rust/cloud-storage/crm/src/domain/companies_repo.rs
@@ -1,6 +1,7 @@
//! Port for persistence operations on CRM companies.
use crate::domain::model::{CrmCompany, CrmError, CrmScopePrecheck, DomainMetadata};
+use chrono::{DateTime, Utc};
/// The CompaniesRepository defines persistence operations for CRM
/// companies and their associated domains.
@@ -50,12 +51,44 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
/// this user's link (sourced from `email_contacts.name` by the
/// caller); pass `None` when no display name is available.
///
+ /// `first_at` / `last_at` are the contact's known interaction
+ /// range. Per-message callers set both to the message's
+ /// `internal_date_ts`; the historical seed pre-aggregates MIN/MAX
+ /// across the contact's messages. Written to `first_interaction` /
+ /// `last_interaction` (not `created_at` / `updated_at`, which keep
+ /// their row-lifecycle semantics — DEFAULT `now()` on INSERT and
+ /// the `set_crm_updated_at` trigger on UPDATE).
+ ///
+ /// `is_sent` flags whether the populating message was sent by the
+ /// user. Insert semantics:
+ ///
+ /// - **`is_sent=true`**: full populate. INSERT a new
+ /// `crm_companies` row when none exists; on existing, refresh
+ /// `first_interaction = LEAST(stored, $first_at)` and
+ /// `last_interaction = GREATEST(stored, $last_at)`. Upsert
+ /// `crm_contacts` with the same merge. Upsert
+ /// `crm_contact_sources`.
+ /// - **`is_sent=false`**: no-op when no `crm_companies` row exists
+ /// for `(team, domain)`. When one exists, refresh only the
+ /// company's `last_interaction = GREATEST(stored, $last_at)`
+ /// (do NOT touch `first_interaction`). Upsert `crm_contacts` —
+ /// new contacts INSERT with both endpoints; existing contacts
+ /// get `last_interaction = GREATEST(...)` only. Upsert
+ /// `crm_contact_sources`.
+ ///
+ /// The `email_sync=false` per-domain killswitch short-circuits in
+ /// both directions. Source rows track all interactions (sent or
+ /// received), not just sent — see also
+ /// [`CompaniesRepository::depopulate_contact`].
+ ///
/// The caller is expected to have ensured a `crm_domain_directory`
/// entry exists for `domain` (via [`upsert_domain_metadata`]) before
- /// invoking — this method writes no metadata of its own.
+ /// invoking when `is_sent=true` — this method writes no metadata of
+ /// its own. `is_sent=false` doesn't need it.
///
/// [`lookup_domain_metadata`]: CompaniesRepository::lookup_domain_metadata
/// [`upsert_domain_metadata`]: CompaniesRepository::upsert_domain_metadata
+ #[allow(clippy::too_many_arguments)]
fn populate_contact(
&self,
team_id: &uuid::Uuid,
@@ -63,6 +96,9 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
domain: &str,
email: &str,
name: Option<&str>,
+ first_at: DateTime<Utc>,
+ last_at: DateTime<Utc>,
+ is_sent: bool,
) -> impl Future<Output = Result<(), CrmError>> + Send;
/// Read the cached [`DomainMetadata`] for `domain` from
diff --git a/rust/cloud-storage/crm/src/domain/service.rs b/rust/cloud-storage/crm/src/domain/service.rs
index 0b34e7cdae..4cab422c85 100644
--- a/rust/cloud-storage/crm/src/domain/service.rs
+++ b/rust/cloud-storage/crm/src/domain/service.rs
@@ -6,6 +6,7 @@ use crate::domain::{
generic_email_domains::is_generic_email_domain,
model::{CrmCompany, CrmError, CrmScopePrecheck},
};
+use chrono::{DateTime, Utc};
/// The CrmService exposes operations over CRM records (companies, their
/// domains and contacts).
@@ -46,6 +47,29 @@ pub trait CrmService: Clone + Send + Sync + 'static {
/// failure — that's the negative cache). The directory write is its
/// own transaction so the populate tx never holds locks across an
/// HTTP fetch.
+ ///
+ /// `first_at` / `last_at` are the contact's known activity range
+ /// for this populate. Per-message paths pass the message's
+ /// `internal_date_ts` as both (single message = single endpoint).
+ /// The historical seed (`populate_crm_for_user`) pre-aggregates
+ /// MIN/MAX over the contact's matching messages and passes the
+ /// real range, so a single populate per contact stamps the CRM
+ /// rows with the full span. Callers without a real timestamp pass
+ /// `Utc::now()`. `created_at` / `updated_at` keep their
+ /// row-lifecycle semantics (DEFAULT `now()` /
+ /// `set_crm_updated_at` trigger).
+ ///
+ /// `is_sent` flags whether the populating message was sent by the
+ /// user. The write matrix:
+ ///
+ /// | `is_sent` | No `crm_companies` row | Existing `crm_companies` row (`email_sync=true`) |
+ /// |---|---|---|
+ /// | `true` | INSERT company + contact + source; `first_interaction = $first_at`, `last_interaction = $last_at`. | UPDATE company `first=LEAST(stored, $first_at), last=GREATEST(stored, $last_at)` + upsert contact (same merge) + upsert source. |
+ /// | `false` | **No-op** — no domain-metadata resolve, no inserts. | UPDATE company `last=GREATEST(stored, $last_at)` only (do NOT touch `first_interaction`) + upsert contact (INSERT sets both endpoints; ON CONFLICT bumps `last` only) + upsert source. |
+ ///
+ /// The `email_sync=false` per-domain killswitch short-circuits in
+ /// both directions.
+ #[allow(clippy::too_many_arguments)]
fn populate_contact(
&self,
team_id: &uuid::Uuid,
@@ -53,6 +77,9 @@ pub trait CrmService: Clone + Send + Sync + 'static {
user_email: &str,
email: &str,
name: Option<&str>,
+ first_at: DateTime<Utc>,
+ last_at: DateTime<Utc>,
+ is_sent: bool,
) -> impl Future<Output = Result<(), CrmError>> + Send;
/// Reverses [`populate_contact`] for one `(link_id, email)`. Drops the
@@ -211,6 +238,7 @@ where
}
#[tracing::instrument(skip(self), err)]
+ #[allow(clippy::too_many_arguments)]
async fn populate_contact(
&self,
team_id: &uuid::Uuid,
@@ -218,6 +246,9 @@ where
user_email: &str,
email: &str,
name: Option<&str>,
+ first_at: DateTime<Utc>,
+ last_at: DateTime<Utc>,
+ is_sent: bool,
) -> Result<(), CrmError> {
let email = email.trim();
let Some((local_part, domain)) = email.split_once('@') else {
@@ -272,11 +303,19 @@ where
// its own transaction, idempotent under concurrent populates
// for the same domain (first-write-wins via the unique index
// on `LOWER(domain)`).
- if self
- .companies_repository
- .lookup_domain_metadata(domain)
- .await?
- .is_none()
+ //
+ // Skip the resolve when `is_sent=false`: a received-direction
+ // populate never inserts a new `crm_companies` row, so we don't
+ // need to seed metadata. If the domain is already tracked the
+ // directory entry was written when its first sent message
+ // populated; if it isn't tracked, this call will no-op in the
+ // repo anyway.
+ if is_sent
+ && self
+ .companies_repository
+ .lookup_domain_metadata(domain)
+ .await?
+ .is_none()
{
let metadata = self.metadata_resolver.resolve(domain).await;
self.companies_repository
@@ -285,7 +324,9 @@ where
}
self.companies_repository
- .populate_contact(team_id, link_id, domain, email, name)
+ .populate_contact(
+ team_id, link_id, domain, email, name, first_at, last_at, is_sent,
+ )
.await
}
diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo.rs b/rust/cloud-storage/crm/src/outbound/companies_repo.rs
index edeb0a7e4f..a3f57f7f50 100644
--- a/rust/cloud-storage/crm/src/outbound/companies_repo.rs
+++ b/rust/cloud-storage/crm/src/outbound/companies_repo.rs
@@ -10,6 +10,7 @@ use crate::domain::{
DomainMetadata,
},
};
+use chrono::{DateTime, Utc};
use sqlx::PgPool;
/// PostgreSQL-backed [`CompaniesRepository`].
@@ -26,10 +27,8 @@ impl CompaniesRepositoryImpl {
}
/// 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.
+ /// domain on the company, sorted — same scheme `populate_contact` /
+ /// `depopulate_contact` use, sorted order prevents deadlock.
async fn lock_company_domains(
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
team_id: &uuid::Uuid,
@@ -62,9 +61,7 @@ impl CompaniesRepositoryImpl {
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
+ /// Drop the company's sources then contacts. Caller must hold the
/// per-domain advisory locks (see [`Self::lock_company_domains`]).
async fn delete_company_contacts(
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
@@ -157,6 +154,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
}
#[tracing::instrument(skip(self), err)]
+ #[allow(clippy::too_many_arguments)]
async fn populate_contact(
&self,
team_id: &uuid::Uuid,
@@ -164,6 +162,9 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
domain: &str,
email: &str,
name: Option<&str>,
+ first_at: DateTime<Utc>,
+ last_at: DateTime<Utc>,
+ is_sent: bool,
) -> Result<(), CrmError> {
let normalized_domain = domain.to_ascii_lowercase();
let normalized_email = email.to_ascii_lowercase();
@@ -174,15 +175,9 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
- // Serialize on (team_id, lower(domain)) for the duration of this
- // transaction. Without this lock two concurrent populate_contact
- // calls can both observe "no existing company" and both insert one,
- // leaving the team with duplicate crm_companies rows. The
- // UNIQUE(team_id, LOWER(domain)) on crm_domains catches the race at
- // the second insert, but only after the first transaction has
- // already created an orphan company. The advisory lock prevents
- // that orphan from ever existing. Lock scope is the (team, domain)
- // key only — different teams/different domains run in parallel.
+ // Serialize on (team, lower(domain)): the unique constraint on
+ // crm_domains catches the race only after an orphan crm_companies
+ // row was already inserted by the loser.
sqlx::query!(
r#"SELECT pg_advisory_xact_lock(hashtextextended($1, 0))"#,
format!("{team_id}:{normalized_domain}"),
@@ -191,12 +186,9 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
- // Team-level CRM killswitch. Disable flips
- // `team_crm_settings.crm_enabled` and purges `crm_companies` in
- // the same transaction, so reading the flag here — inside our
- // tx, after the advisory lock — guarantees we see the disable's
- // commit and don't strand an orphan row it already raced past.
- // Missing row = default false = treat as disabled.
+ // Team killswitch. Read inside the tx (after the lock) so a
+ // concurrent disable+purge can't race past us. Missing row =
+ // default false.
let team_crm_enabled = sqlx::query_scalar!(
r#"
SELECT COALESCE(
@@ -217,10 +209,8 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
return Ok(());
}
- // Look up the company for this (team, domain). The per-domain
- // killswitch lives here: a pre-existing row with
- // email_sync=false means the team has opted this domain out and
- // we must not write anything.
+ // Per-domain killswitch: existing row with email_sync=false
+ // means the team has opted this domain out, no-op.
let existing = sqlx::query!(
r#"
SELECT c.id, c.email_sync
@@ -239,17 +229,30 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
let company_id = match existing {
Some(row) if !row.email_sync => {
- // Killswitch: team has opted this domain out. Commit the
- // (empty) transaction and return so the caller acks.
+ // Killswitch: domain opted out, ack and exit.
tx.commit()
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
return Ok(());
}
Some(row) => {
+ // `last_interaction` always bumps via GREATEST.
+ // `first_interaction` only LEAST-merges on is_sent=true:
+ // received-direction populates must not pull the anchor
+ // backwards.
sqlx::query!(
- r#"UPDATE crm_companies SET updated_at = now() WHERE id = $1"#,
+ r#"UPDATE crm_companies
+ SET updated_at = now(),
+ first_interaction = CASE
+ WHEN $4 THEN LEAST(first_interaction, $2)
+ ELSE first_interaction
+ END,
+ last_interaction = GREATEST(last_interaction, $3)
+ WHERE id = $1"#,
row.id,
+ first_at,
+ last_at,
+ is_sent,
)
.execute(&mut *tx)
.await
@@ -257,27 +260,33 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
row.id
}
+ None if !is_sent => {
+ // Received-direction never creates a company row.
+ tx.commit()
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+ return Ok(());
+ }
None => {
+ // Seed interaction columns from the producer's known
+ // range so backfilled mail keeps accurate timestamps.
let new_company = sqlx::query!(
r#"
- INSERT INTO crm_companies (team_id)
- VALUES ($1)
+ INSERT INTO crm_companies (team_id, first_interaction, last_interaction)
+ VALUES ($1, $2, $3)
RETURNING id
"#,
team_id,
+ first_at,
+ last_at,
)
.fetch_one(&mut *tx)
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
- // The advisory lock guarantees no concurrent insert for the
- // same (team_id, lower(domain)). The UNIQUE index on
- // crm_domains backs that promise up — `ON CONFLICT DO
- // NOTHING` is defensive. If it does fire (e.g. an old row
- // predating the advisory lock somehow exists), the
- // crm_companies row we just inserted would be orphaned with
- // no domain pointing at it. Detect via rows_affected, look
- // up the real company id, and delete the orphan.
+ // Defensive ON CONFLICT — the advisory lock should
+ // prevent it, but if it fires we'd orphan the company
+ // we just inserted, so we recover via rows_affected.
let domain_insert = sqlx::query!(
r#"
INSERT INTO crm_domains (company_id, team_id, domain)
@@ -309,9 +318,21 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
+ // is_sent is true here (the !is_sent arm exited);
+ // CASE kept for symmetry with the regular path.
sqlx::query!(
- r#"UPDATE crm_companies SET updated_at = now() WHERE id = $1"#,
+ r#"UPDATE crm_companies
+ SET updated_at = now(),
+ first_interaction = CASE
+ WHEN $4 THEN LEAST(first_interaction, $2)
+ ELSE first_interaction
+ END,
+ last_interaction = GREATEST(last_interaction, $3)
+ WHERE id = $1"#,
existing_company_id,
+ first_at,
+ last_at,
+ is_sent,
)
.execute(&mut *tx)
.await
@@ -329,26 +350,29 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
}
};
- // Upsert the contact. `name` is supplied by the caller (the
- // backfill consumer looks it up in email_contacts before invoking
- // 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. The conflict path still performs
- // an UPDATE for existing contacts so `updated_at` reflects the
- // latest populate even when the stored name is unchanged.
+ // First non-NULL name wins (COALESCE preserves existing).
+ // `last_interaction` always GREATEST; `first_interaction`
+ // LEAST-merges only on is_sent=true (mirrors company rule).
let contact_id = sqlx::query_scalar!(
r#"
- INSERT INTO crm_contacts (company_id, email, name)
- VALUES ($1, $2, $3)
+ INSERT INTO crm_contacts (company_id, email, name, first_interaction, last_interaction)
+ VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (company_id, email) DO UPDATE
SET name = COALESCE(crm_contacts.name, EXCLUDED.name),
- updated_at = now()
+ updated_at = now(),
+ first_interaction = CASE
+ WHEN $6 THEN LEAST(crm_contacts.first_interaction, EXCLUDED.first_interaction)
+ ELSE crm_contacts.first_interaction
+ END,
+ last_interaction = GREATEST(crm_contacts.last_interaction, EXCLUDED.last_interaction)
RETURNING id
"#,
company_id,
normalized_email,
name,
+ first_at,
+ last_at,
+ is_sent,
)
.fetch_one(&mut *tx)
.await
@@ -391,16 +415,8 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
- // Take the lock BEFORE looking at any state. A concurrent
- // populate_contact for the same (team, domain) might have a tx
- // open that has inserted rows but hasn't committed yet — without
- // the lock our SELECT below would miss those rows, return
- // Ok(()) here, and the in-flight populate would then commit and
- // leave the team with CRM data for a since-deleted sent message.
- // Holding the lock for the rest of this tx forces populate to
- // either commit first (we then see + tear down its rows) or
- // wait until we're done (its row will be inserted after, and
- // a future depopulate will catch it).
+ // Lock BEFORE observing state: a concurrent populate could
+ // commit rows for a since-deleted sent message otherwise.
sqlx::query!(
r#"SELECT pg_advisory_xact_lock(hashtextextended($1, 0))"#,
format!("{team_id}:{normalized_domain}"),
@@ -409,9 +425,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
- // Resolve (contact_id, company_id, email_sync) for this
- // (team, domain, email). Returning None here means there is
- // nothing to tear down: commit the empty tx and ack.
+ // None here = nothing to tear down.
let Some(row) = sqlx::query!(
r#"
SELECT
@@ -479,13 +493,8 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
- // 3. Keep the company when other contacts in the team still
- // belong to it, OR when the team has opted the domain out.
- // The killswitch (`email_sync = false`) is stored on
- // crm_companies and is configuration, not derived data;
- // dropping the company would silently erase the opt-out and
- // a future populate would recreate the row with the default
- // `email_sync = true`.
+ // 3. Keep killswitched companies — dropping would erase the
+ // opt-out and a future populate would recreate as enabled.
if !row.email_sync {
tx.commit()
.await
@@ -512,8 +521,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
return Ok(());
}
- // crm_domains FK is ON DELETE CASCADE — deleting the company
- // takes its domain rows with it.
+ // crm_domains cascades via FK.
sqlx::query!(r#"DELETE FROM crm_companies WHERE id = $1"#, row.company_id,)
.execute(&mut *tx)
.await
@@ -573,12 +581,8 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
- // 3. Drop every company in this team that no longer has any
- // contact AND is not killswitched. Companies with
- // `email_sync = false` are preserved so the team's
- // configuration survives teardown — a future populate will
- // re-find the row and short-circuit on the same flag.
- // `crm_domains` falls out via FK cascade.
+ // 3. Drop orphan non-killswitched companies. crm_domains
+ // cascades via FK.
sqlx::query!(
r#"
DELETE FROM crm_companies co
@@ -634,11 +638,8 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
metadata: &DomainMetadata,
) -> Result<(), CrmError> {
let normalized_domain = domain.to_ascii_lowercase();
- // First-write-wins: the unique index is on `LOWER(domain)`, so
- // a concurrent populate of the same domain hits the conflict
- // path and we leave the existing row untouched (treat-as-forever
- // cache). Negative cache entries (all-NULL fields) are inserted
- // verbatim so subsequent populates suppress the resolver call.
+ // First-write-wins. Negative cache entries (all-NULL) are
+ // preserved to suppress future resolver calls.
sqlx::query!(
r#"
INSERT INTO crm_domain_directory (domain, name, description, icon_url)
@@ -671,19 +672,12 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
if !email_sync {
- // 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.
+ // Hold the same per-domain locks populate_contact takes so
+ // an in-flight populate can't slip past our killswitch.
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.
+ // Refuse enable on hidden — populate would recreate under a
+ // hidden company. FOR UPDATE blocks concurrent hide.
let row = sqlx::query!(
r#"
SELECT hidden
@@ -706,7 +700,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
}
}
- // Scoping UPDATE on both id AND team_id rejects cross-team callers as NotFound.
+ // Scoping on (id, team_id) rejects cross-team as NotFound.
let updated = sqlx::query_scalar!(
r#"
UPDATE crm_companies
@@ -751,12 +745,9 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.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.
+ // Hiding implies email_sync=false; flip both atomically.
+ // Domain locks block in-flight populates past their
+ // killswitch check.
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.
@@ -780,9 +771,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
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.
+ // Un-hide leaves email_sync alone; re-enable is separate.
let updated = sqlx::query_scalar!(
r#"
UPDATE crm_companies
@@ -816,8 +805,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
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.
+ // Scope via the contact's company; cross-team = NotFound.
let updated = sqlx::query_scalar!(
r#"
UPDATE crm_contacts ct
@@ -877,9 +865,8 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.map_err(|e| CrmError::StorageLayerError(e.into()))?
.unwrap_or(false);
- // When the team killswitch is off, the email service will reject the
- // request with `CrmDisabledForTeam` before looking at per-input
- // statuses — so skip the probes entirely.
+ // Killswitch off: caller rejects with CrmDisabledForTeam, so
+ // skip the per-input probes.
if !crm_enabled {
return Ok(CrmScopePrecheck {
crm_enabled: false,
@@ -891,9 +878,8 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
let domain_statuses: Vec<CrmDomainStatus> = if domains.is_empty() {
Vec::new()
} else {
- // `WITH ORDINALITY` + `ORDER BY input.ord` guarantees output
- // row order matches the input list — `CrmScopePrecheck.domains`
- // documents that contract.
+ // `WITH ORDINALITY` + `ORDER BY input.ord` preserves the
+ // input order (contract on `CrmScopePrecheck.domains`).
sqlx::query!(
r#"
SELECT
@@ -927,16 +913,12 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
let address_statuses: Vec<CrmAddressStatus> = if addresses.is_empty() {
Vec::new()
} else {
- // Pre-materialize the team's contact rows in a derived table,
- // then hash-join against the input array. Avoids LATERAL's
- // per-outer-row execution. Safe to assume at most one row per
- // (team, email) thanks to crm_contacts_company_id_email_key
- // UNIQUE (company_id, email) plus the populate-path invariant
- // that an email's domain uniquely identifies its company
- // within a team (via crm_domains_team_id_lower_domain_unique).
- // `WITH ORDINALITY` + `ORDER BY input.ord` guarantees output
- // row order matches the input list — `CrmScopePrecheck.addresses`
- // documents that contract.
+ // Hash-join via derived table (avoids LATERAL per-row).
+ // At most one row per (team, email) by virtue of
+ // crm_contacts UNIQUE(company_id, email) +
+ // crm_domains UNIQUE(team_id, lower(domain)).
+ // ORDER BY input.ord preserves input order
+ // (contract on `CrmScopePrecheck.addresses`).
sqlx::query!(
r#"
SELECT
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 76119197c3..2ea133157b 100644
--- a/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs
+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs
@@ -43,12 +43,15 @@ async fn insert_company(
) -> sqlx::Result<Uuid> {
let company_id = Uuid::now_v7();
- sqlx::query(r#"INSERT INTO crm_companies (id, team_id, email_sync) VALUES ($1, $2, $3)"#)
- .bind(company_id)
- .bind(team_id)
- .bind(email_sync)
- .execute(pool)
- .await?;
+ sqlx::query(
+ r#"INSERT INTO crm_companies (id, team_id, email_sync, first_interaction, last_interaction)
+ VALUES ($1, $2, $3, now(), now())"#,
+ )
+ .bind(company_id)
+ .bind(team_id)
+ .bind(email_sync)
+ .execute(pool)
+ .await?;
for domain in domains {
sqlx::query(r#"INSERT INTO crm_domains (company_id, team_id, domain) VALUES ($1, $2, $3)"#)
@@ -84,12 +87,15 @@ async fn insert_contact_with_source(
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(email)
- .execute(pool)
- .await?;
+ sqlx::query(
+ r#"INSERT INTO crm_contacts (id, company_id, email, first_interaction, last_interaction)
+ VALUES ($1, $2, $3, now(), now())"#,
+ )
+ .bind(contact_id)
+ .bind(company_id)
+ .bind(email)
+ .execute(pool)
+ .await?;
sqlx::query(r#"INSERT INTO crm_contact_sources (contact_id, link_id) VALUES ($1, $2)"#)
.bind(contact_id)
.bind(link_id)
@@ -168,6 +174,60 @@ async fn fetch_contact_updated_at(
Ok(row.map(|(updated_at,)| updated_at))
}
+async fn fetch_company_interactions(
+ pool: &PgPool,
+ company_id: Uuid,
+) -> sqlx::Result<Option<(chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>)>> {
+ sqlx::query_as(r#"SELECT first_interaction, last_interaction FROM crm_companies WHERE id = $1"#)
+ .bind(company_id)
+ .fetch_optional(pool)
+ .await
+}
+
+async fn fetch_contact_interactions(
+ pool: &PgPool,
+ contact_id: Uuid,
+) -> sqlx::Result<Option<(chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>)>> {
+ sqlx::query_as(r#"SELECT first_interaction, last_interaction FROM crm_contacts WHERE id = $1"#)
+ .bind(contact_id)
+ .fetch_optional(pool)
+ .await
+}
+
+async fn fetch_company_for_domain(
+ pool: &PgPool,
+ team_id: Uuid,
+ domain: &str,
+) -> sqlx::Result<Option<Uuid>> {
+ let row: Option<(Uuid,)> = sqlx::query_as(
+ r#"SELECT c.id
+ FROM crm_companies c
+ JOIN crm_domains d ON d.company_id = c.id
+ WHERE c.team_id = $1 AND LOWER(d.domain) = LOWER($2)
+ LIMIT 1"#,
+ )
+ .bind(team_id)
+ .bind(domain)
+ .fetch_optional(pool)
+ .await?;
+ Ok(row.map(|(id,)| id))
+}
+
+async fn fetch_contact_id(
+ pool: &PgPool,
+ company_id: Uuid,
+ email: &str,
+) -> sqlx::Result<Option<Uuid>> {
+ let row: Option<(Uuid,)> = sqlx::query_as(
+ r#"SELECT id FROM crm_contacts WHERE company_id = $1 AND LOWER(email) = LOWER($2) LIMIT 1"#,
+ )
+ .bind(company_id)
+ .bind(email)
+ .fetch_optional(pool)
+ .await?;
+ Ok(row.map(|(id,)| id))
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn returns_none_when_no_company_for_domain(pool: PgPool) -> anyhow::Result<()> {
let team_id = Uuid::now_v7();
@@ -632,6 +692,9 @@ async fn service_populate_contact_skips_when_domain_matches_user_domain(
None,
+ chrono::Utc::now(),
+ chrono::Utc::now(),
+ true,
)
.await?;
@@ -665,6 +728,9 @@ async fn service_populate_contact_same_domain_check_is_case_insensitive(
None,
+ chrono::Utc::now(),
+ chrono::Utc::now(),
+ true,
)
.await?;
@@ -692,8 +758,8 @@ async fn service_populate_contact_refreshes_existing_company_and_contact_updated
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)"#,
+ r#"INSERT INTO crm_companies (id, team_id, email_sync, updated_at, first_interaction, last_interaction)
+ VALUES ($1, $2, TRUE, $3, $3, $3)"#,
)
.bind(company_id)
.bind(team_id)
@@ -710,8 +776,8 @@ async fn service_populate_contact_refreshes_existing_company_and_contact_updated
let contact_id = Uuid::now_v7();
sqlx::query(
- r#"INSERT INTO crm_contacts (id, company_id, email, updated_at)
- VALUES ($1, $2, $3, $4)"#,
+ r#"INSERT INTO crm_contacts (id, company_id, email, updated_at, first_interaction, last_interaction)
+ VALUES ($1, $2, $3, $4, $4, $4)"#,
)
.bind(contact_id)
.bind(company_id)
@@ -738,6 +804,9 @@ async fn service_populate_contact_refreshes_existing_company_and_contact_updated
Some("Alice"),
+ chrono::Utc::now(),
+ chrono::Utc::now(),
+ true,
)
.await?;
@@ -767,7 +836,16 @@ async fn service_populate_contact_writes_when_domain_differs(pool: PgPool) -> an
);
service
- .populate_contact(&team_id, &link_id, "[email protected]", "[email protected]", None)
+ .populate_contact(
+ &team_id,
+ &link_id,
+ None,
+ chrono::Utc::now(),
+ chrono::Utc::now(),
+ true,
+ )
.await?;
assert_eq!(
@@ -919,3 +997,553 @@ async fn precheck_address_does_not_leak_other_team_contacts(pool: PgPool) -> any
assert!(!result.addresses[0].exists);
Ok(())
}
+
+/// Received-direction populate for an unknown `(team, domain)` is a
+/// no-op: only sent-direction may create a new `crm_companies` row.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn populate_contact_is_sent_false_skips_when_no_company(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner_id = "macro|[email protected]";
+ seed_team(&pool, team_id, owner_id).await?;
+ enable_crm_for_team(&pool, team_id).await?;
+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;
+
+ let service = CrmServiceImpl::new(
+ CompaniesRepositoryImpl::new(pool.clone()),
+ NoOpCompanyMetadataResolver,
+ );
+
+ let now = chrono::Utc::now();
+ service
+ .populate_contact(
+ &team_id,
+ &link_id,
+ None,
+ now,
+ now,
+ false,
+ )
+ .await?;
+
+ assert_eq!(
+ count_companies_for_domain(&pool, team_id, "acme.com").await?,
+ 0,
+ "received-direction populate must not create a crm_companies row"
+ );
+ Ok(())
+}
+
+/// Brand-new company + contact INSERT writes `first_interaction` and
+/// `last_interaction` directly from the payload's distinct `first_at` /
+/// `last_at` (covers the historical-seed range, e.g. 2020→2024).
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn populate_contact_insert_seeds_first_and_last_from_payload(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner_id = "macro|[email protected]";
+ seed_team(&pool, team_id, owner_id).await?;
+ enable_crm_for_team(&pool, team_id).await?;
+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;
+
+ let first: chrono::DateTime<chrono::Utc> = "2020-01-01T00:00:00Z".parse()?;
+ let last: chrono::DateTime<chrono::Utc> = "2024-06-15T00:00:00Z".parse()?;
+
+ let service = CrmServiceImpl::new(
+ CompaniesRepositoryImpl::new(pool.clone()),
+ NoOpCompanyMetadataResolver,
+ );
+
+ service
+ .populate_contact(
+ &team_id,
+ &link_id,
+ None,
+ first,
+ last,
+ true,
+ )
+ .await?;
+
+ let company_id = fetch_company_for_domain(&pool, team_id, "acme.com")
+ .await?
+ .expect("company should be inserted");
+ let (company_first, company_last) = fetch_company_interactions(&pool, company_id)
+ .await?
+ .expect("company interactions");
+ assert_eq!(company_first, first);
+ assert_eq!(company_last, last);
+
+ let contact_id = fetch_contact_id(&pool, company_id, "[email protected]")
+ .await?
+ .expect("contact should be inserted");
+ let (contact_first, contact_last) = fetch_contact_interactions(&pool, contact_id)
+ .await?
+ .expect("contact interactions");
+ assert_eq!(contact_first, first);
+ assert_eq!(contact_last, last);
+ Ok(())
+}
+
+/// Sent-direction populate against an existing row merges
+/// `first_interaction` via `LEAST` (older message pulls it back) and
+/// `last_interaction` via `GREATEST` (newer message pushes it forward),
+/// on both the company and contact rows.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn populate_contact_is_sent_true_merges_first_least_and_last_greatest(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner_id = "macro|[email protected]";
+ seed_team(&pool, team_id, owner_id).await?;
+ enable_crm_for_team(&pool, team_id).await?;
+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;
+
+ let initial: chrono::DateTime<chrono::Utc> = "2022-06-01T00:00:00Z".parse()?;
+ let older: chrono::DateTime<chrono::Utc> = "2020-01-01T00:00:00Z".parse()?;
+ let newer: chrono::DateTime<chrono::Utc> = "2024-12-31T00:00:00Z".parse()?;
+
+ let service = CrmServiceImpl::new(
+ CompaniesRepositoryImpl::new(pool.clone()),
+ NoOpCompanyMetadataResolver,
+ );
+
+ // First populate establishes the row at `initial`.
+ service
+ .populate_contact(
+ &team_id,
+ &link_id,
+ None,
+ initial,
+ initial,
+ true,
+ )
+ .await?;
+
+ let company_id = fetch_company_for_domain(&pool, team_id, "acme.com")
+ .await?
+ .expect("company");
+ let contact_id = fetch_contact_id(&pool, company_id, "[email protected]")
+ .await?
+ .expect("contact");
+
+ // A backfilled older message should pull first_interaction back via LEAST.
+ service
+ .populate_contact(
+ &team_id,
+ &link_id,
+ None,
+ older,
+ older,
+ true,
+ )
+ .await?;
+
+ let (company_first, company_last) = fetch_company_interactions(&pool, company_id)
+ .await?
+ .expect("interactions");
+ assert_eq!(company_first, older);
+ assert_eq!(company_last, initial);
+ let (contact_first, contact_last) = fetch_contact_interactions(&pool, contact_id)
+ .await?
+ .expect("interactions");
+ assert_eq!(contact_first, older);
+ assert_eq!(contact_last, initial);
+
+ // A newer message should push last_interaction forward via GREATEST,
+ // leaving first_interaction at `older`.
+ service
+ .populate_contact(
+ &team_id,
+ &link_id,
+ None,
+ newer,
+ newer,
+ true,
+ )
+ .await?;
+
+ let (company_first, company_last) = fetch_company_interactions(&pool, company_id)
+ .await?
+ .expect("interactions");
+ assert_eq!(company_first, older);
+ assert_eq!(company_last, newer);
+ Ok(())
+}
+
+/// Received-direction populate against an existing row must not pull
+/// `first_interaction` backwards — even with an older timestamp — but
+/// still GREATEST-merges `last_interaction` when newer. Asserts both
+/// company and contact.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn populate_contact_is_sent_false_leaves_first_interaction_unchanged(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner_id = "macro|[email protected]";
+ seed_team(&pool, team_id, owner_id).await?;
+ enable_crm_for_team(&pool, team_id).await?;
+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;
+
+ let baseline: chrono::DateTime<chrono::Utc> = "2022-06-01T00:00:00Z".parse()?;
+ let older: chrono::DateTime<chrono::Utc> = "2020-01-01T00:00:00Z".parse()?;
+ let newer: chrono::DateTime<chrono::Utc> = "2024-12-31T00:00:00Z".parse()?;
+
+ let service = CrmServiceImpl::new(
+ CompaniesRepositoryImpl::new(pool.clone()),
+ NoOpCompanyMetadataResolver,
+ );
+
+ // Sent populate seeds the row at `baseline`.
+ service
+ .populate_contact(
+ &team_id,
+ &link_id,
+ None,
+ baseline,
+ baseline,
+ true,
+ )
+ .await?;
+
+ let company_id = fetch_company_for_domain(&pool, team_id, "acme.com")
+ .await?
+ .expect("company");
+ let contact_id = fetch_contact_id(&pool, company_id, "[email protected]")
+ .await?
+ .expect("contact");
+
+ // Received populate with an older timestamp must NOT pull
+ // first_interaction backwards on either row.
+ service
+ .populate_contact(
+ &team_id,
+ &link_id,
+ None,
+ older,
+ older,
+ false,
+ )
+ .await?;
+
+ let (company_first, _) = fetch_company_interactions(&pool, company_id)
+ .await?
+ .expect("interactions");
+ assert_eq!(
+ company_first, baseline,
+ "received populate must not pull company first_interaction backwards"
+ );
+ let (contact_first, _) = fetch_contact_interactions(&pool, contact_id)
+ .await?
+ .expect("interactions");
+ assert_eq!(
+ contact_first, baseline,
+ "received populate must not pull contact first_interaction backwards"
+ );
+
+ // Received populate with a newer timestamp still bumps last_interaction.
+ service
+ .populate_contact(
+ &team_id,
+ &link_id,
+ None,
+ newer,
+ newer,
+ false,
+ )
+ .await?;
+
+ let (_, company_last) = fetch_company_interactions(&pool, company_id)
+ .await?
+ .expect("interactions");
+ assert_eq!(company_last, newer);
+ let (_, contact_last) = fetch_contact_interactions(&pool, contact_id)
+ .await?
+ .expect("interactions");
+ assert_eq!(contact_last, newer);
+ Ok(())
+}
+
+/// Received-direction populate at a known company creates a new
+/// `crm_contacts` row (seeded with both timestamps) and a
+/// `crm_contact_sources` row — verifying sources now track
+/// interactions in both directions.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn populate_contact_is_sent_false_inserts_contact_at_existing_company(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner_id = "macro|[email protected]";
+ seed_team(&pool, team_id, owner_id).await?;
+ enable_crm_for_team(&pool, team_id).await?;
+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;
+
+ let baseline: chrono::DateTime<chrono::Utc> = "2022-06-01T00:00:00Z".parse()?;
+ let received_at: chrono::DateTime<chrono::Utc> = "2024-09-15T00:00:00Z".parse()?;
+
+ let service = CrmServiceImpl::new(
+ CompaniesRepositoryImpl::new(pool.clone()),
+ NoOpCompanyMetadataResolver,
+ );
+
+ // Sent populate establishes the company via [email protected].
+ service
+ .populate_contact(
+ &team_id,
+ &link_id,
+ None,
+ baseline,
+ baseline,
+ true,
+ )
+ .await?;
+
+ let company_id = fetch_company_for_domain(&pool, team_id, "acme.com")
+ .await?
+ .expect("company");
+ assert_eq!(count_contacts(&pool, company_id).await?, 1);
+
+ // Received-direction populate for a *new* address at the same
+ // company creates a contact row + source row.
+ service
+ .populate_contact(
+ &team_id,
+ &link_id,
+ Some("Bob"),
+ received_at,
+ received_at,
+ false,
+ )
+ .await?;
+
+ assert_eq!(
+ count_contacts(&pool, company_id).await?,
+ 2,
+ "received-direction populate must insert a contact under the known company"
+ );
+ let bob_id = fetch_contact_id(&pool, company_id, "[email protected]")
+ .await?
+ .expect("bob contact");
+ let (bob_first, bob_last) = fetch_contact_interactions(&pool, bob_id)
+ .await?
+ .expect("bob interactions");
+ assert_eq!(bob_first, received_at);
+ assert_eq!(bob_last, received_at);
+ assert_eq!(
+ count_sources_for_company(&pool, company_id).await?,
+ 2,
+ "received-direction populate must write a crm_contact_sources row"
+ );
+ Ok(())
+}
+
+/// Team-level CRM killswitch (`team_crm_settings.crm_enabled = false`
+/// or missing) short-circuits populate in both directions before any
+/// rows are written.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn populate_contact_team_killswitch_off_noops_both_directions(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner_id = "macro|[email protected]";
+ seed_team(&pool, team_id, owner_id).await?;
+ // Intentionally do NOT enable_crm_for_team — team_crm_settings row is
+ // missing, which is treated as crm_enabled = false.
+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;
+
+ let service = CrmServiceImpl::new(
+ CompaniesRepositoryImpl::new(pool.clone()),
+ NoOpCompanyMetadataResolver,
+ );
+
+ let now = chrono::Utc::now();
+
+ service
+ .populate_contact(
+ &team_id,
+ &link_id,
+ None,
+ now,
+ now,
+ true,
+ )
+ .await?;
+ service
+ .populate_contact(
+ &team_id,
+ &link_id,
+ None,
+ now,
+ now,
+ false,
+ )
+ .await?;
+
+ assert_eq!(
+ count_companies_for_domain(&pool, team_id, "acme.com").await?,
+ 0,
+ "team killswitch must short-circuit both directions"
+ );
+ Ok(())
+}
+
+/// Per-domain killswitch (`crm_companies.email_sync = false`)
+/// short-circuits populate in both directions: interaction columns
+/// stay at the stored baseline and no contact / source rows land.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn populate_contact_per_domain_killswitch_noops_both_directions(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner_id = "macro|[email protected]";
+ seed_team(&pool, team_id, owner_id).await?;
+ enable_crm_for_team(&pool, team_id).await?;
+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;
+
+ // Seed a killswitched company for the domain. Baseline timestamp
+ // is parsed from a string so it has zero sub-microsecond precision
+ // — Postgres `TIMESTAMPTZ` only stores microseconds, and
+ // `chrono::Utc::now()` would carry nanos that get silently
+ // truncated and break the `assert_eq` below.
+ let company_id = insert_company(&pool, team_id, false, &["acme.com"]).await?;
+ let baseline: chrono::DateTime<chrono::Utc> = "2024-01-01T00:00:00Z".parse()?;
+ sqlx::query(
+ r#"UPDATE crm_companies
+ SET first_interaction = $2, last_interaction = $2
+ WHERE id = $1"#,
+ )
+ .bind(company_id)
+ .bind(baseline)
+ .execute(&pool)
+ .await?;
+
+ let service = CrmServiceImpl::new(
+ CompaniesRepositoryImpl::new(pool.clone()),
+ NoOpCompanyMetadataResolver,
+ );
+
+ let later: chrono::DateTime<chrono::Utc> = "2024-01-08T00:00:00Z".parse()?;
+
+ for is_sent in [true, false] {
+ service
+ .populate_contact(
+ &team_id,
+ &link_id,
+ None,
+ later,
+ later,
+ is_sent,
+ )
+ .await?;
+ }
+
+ // Killswitch must keep the company's interaction columns at the
+ // baseline and prevent contact / source inserts.
+ let (first, last) = fetch_company_interactions(&pool, company_id)
+ .await?
+ .expect("company");
+ assert_eq!(first, baseline);
+ assert_eq!(last, baseline);
+ assert_eq!(count_contacts(&pool, company_id).await?, 0);
+ assert_eq!(count_sources_for_company(&pool, company_id).await?, 0);
+ Ok(())
+}
+
+/// Historical-seed-style populate (`first_at != last_at`) against an
+/// already-tracked row expands the stored range outward: `first` pulls
+/// back via LEAST and `last` pushes forward via GREATEST in the same
+/// call.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn populate_contact_seed_style_range_merges_into_existing(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner_id = "macro|[email protected]";
+ seed_team(&pool, team_id, owner_id).await?;
+ enable_crm_for_team(&pool, team_id).await?;
+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;
+
+ let baseline: chrono::DateTime<chrono::Utc> = "2022-06-01T00:00:00Z".parse()?;
+
+ let service = CrmServiceImpl::new(
+ CompaniesRepositoryImpl::new(pool.clone()),
+ NoOpCompanyMetadataResolver,
+ );
+
+ // Establish the rows at `baseline`.
+ service
+ .populate_contact(
+ &team_id,
+ &link_id,
+ None,
+ baseline,
+ baseline,
+ true,
+ )
+ .await?;
+
+ let company_id = fetch_company_for_domain(&pool, team_id, "acme.com")
+ .await?
+ .expect("company");
+ let contact_id = fetch_contact_id(&pool, company_id, "[email protected]")
+ .await?
+ .expect("contact");
+
+ // Historical-seed-style populate: distinct first_at < last_at,
+ // is_sent=true, hitting an already-populated contact. Should pull
+ // first_interaction earlier AND push last_interaction later.
+ let seed_first: chrono::DateTime<chrono::Utc> = "2010-03-15T00:00:00Z".parse()?;
+ let seed_last: chrono::DateTime<chrono::Utc> = "2024-12-31T00:00:00Z".parse()?;
+ service
+ .populate_contact(
+ &team_id,
+ &link_id,
+ None,
+ seed_first,
+ seed_last,
+ true,
+ )
+ .await?;
+
+ let (company_first, company_last) = fetch_company_interactions(&pool, company_id)
+ .await?
+ .expect("interactions");
+ assert_eq!(company_first, seed_first);
+ assert_eq!(company_last, seed_last);
+ let (contact_first, contact_last) = fetch_contact_interactions(&pool, contact_id)
+ .await?
+ .expect("interactions");
+ assert_eq!(contact_first, seed_first);
+ assert_eq!(contact_last, seed_last);
+ Ok(())
+}
diff --git a/rust/cloud-storage/email_db_client/src/contacts/get.rs b/rust/cloud-storage/email_db_client/src/contacts/get.rs
index e0ddaceed4..4aa1e250c3 100644
--- a/rust/cloud-storage/email_db_client/src/contacts/get.rs
+++ b/rust/cloud-storage/email_db_client/src/contacts/get.rs
@@ -12,6 +12,11 @@ use std::collections::{HashMap, HashSet};
pub type ThreadContactsMap = HashMap<Uuid, Vec<(String, Option<String>)>>;
+/// `(email, name, first_at, last_at)` for a contact's known activity
+/// range on a link — what the `populate_crm_for_user` historical seed
+/// hands to `PopulateCrmContact`.
+pub type CrmContactRange = (String, Option<String>, DateTime<Utc>, DateTime<Utc>);
+
/// fetch message sender from db
#[tracing::instrument(skip(pool), err)]
pub async fn get_sender_by_message_id(
@@ -74,49 +79,101 @@ struct RecipientQueryResult {
recipient_type: db::address::EmailRecipientType,
}
-/// Returns the deduped, lowercased set of recipient email addresses that
-/// appear on any sent message (`email_messages.is_sent = true`) on the
-/// given `link_id`. Walks To/Cc/Bcc indiscriminately — the caller is
-/// responsible for any filtering (e.g. dropping the user's own address).
-///
-/// Returns `(lowercased_email, name)` pairs — `email_contacts` is unique
-/// per `(link_id, email_address)`, so each address appears at most once
-/// in the result with the single display name stored on its row. `name`
-/// is `None` when no display name was recorded.
+/// One row per sent-message recipient on `link_id`, with the
+/// `(email, name, first_at, last_at)` shape ready to fan out to
+/// `PopulateCrmContact`. `first_at` / `last_at` are
+/// `MIN(internal_date_ts)` / `MAX(internal_date_ts)` over the contact's
+/// matching messages — so a single populate job per contact carries
+/// the full known activity range. `email` is lowercased; `name` comes
+/// from `email_contacts.name`. Messages with `internal_date_ts IS NULL`
+/// are filtered out so the MIN/MAX is always non-null for emitted rows.
///
-/// Used by the `PopulateCrmForUser` backfill step to enumerate the
-/// contacts a user has previously emailed so they can be seeded into
-/// their team's CRM tables.
+/// Used by the `PopulateCrmForUser` backfill step.
#[tracing::instrument(skip(pool), err)]
pub async fn fetch_sent_message_recipient_contacts_by_link(
pool: &PgPool,
link_id: Uuid,
-) -> anyhow::Result<Vec<(String, Option<String>)>> {
+) -> anyhow::Result<Vec<CrmContactRange>> {
let rows = sqlx::query!(
r#"
- SELECT DISTINCT
- LOWER(c.email_address) AS "email!",
- c.name AS "name"
+ SELECT
+ LOWER(c.email_address) AS "email!",
+ c.name AS "name",
+ MIN(m.internal_date_ts) AS "first_at!",
+ MAX(m.internal_date_ts) AS "last_at!"
FROM email_messages m
JOIN email_message_recipients r ON r.message_id = m.id
JOIN email_contacts c ON c.id = r.contact_id
WHERE m.link_id = $1
AND m.is_sent = true
+ AND m.internal_date_ts IS NOT NULL
+ GROUP BY LOWER(c.email_address), c.name
"#,
link_id,
)
.fetch_all(pool)
.await?;
- Ok(rows.into_iter().map(|r| (r.email, r.name)).collect())
+ Ok(rows
+ .into_iter()
+ .map(|r| (r.email, r.name, r.first_at, r.last_at))
+ .collect())
}
-/// Returns true iff `link_id` still has at least one sent message whose
-/// recipients (to/cc/bcc) include `email`. Used by the depopulate-CRM-
-/// contact backfill step as the pre-check: if any sent message remains,
-/// the CRM source row must stay. `email` is matched case-insensitively.
+/// One row per external sender on received messages on `link_id`,
+/// with the `(email, name, first_at, last_at)` shape — mirror of
+/// [`fetch_sent_message_recipient_contacts_by_link`] for the received
+/// direction. Drafts have `from_contact_id = NULL` so they're filtered
+/// out automatically. `first_at` / `last_at` are MIN/MAX of
+/// `internal_date_ts` over the contact's received messages.
+///
+/// Used by the `PopulateCrmForUser` backfill step to enumerate
+/// external parties the link has received mail from so they can bump
+/// `last_interaction` on already-tracked CRM companies (and create
+/// contacts at those companies). Received-direction populates never
+/// create new `crm_companies` rows — see
+/// [`crm::domain::companies_repo::CompaniesRepository::populate_contact`].
#[tracing::instrument(skip(pool), err)]
-pub async fn link_has_sent_message_to(
+pub async fn fetch_received_sender_contacts_by_link(
+ pool: &PgPool,
+ link_id: Uuid,
+) -> anyhow::Result<Vec<CrmContactRange>> {
+ let rows = sqlx::query!(
+ r#"
+ SELECT
+ LOWER(c.email_address) AS "email!",
+ c.name AS "name",
+ MIN(m.internal_date_ts) AS "first_at!",
+ MAX(m.internal_date_ts) AS "last_at!"
+ FROM email_messages m
+ JOIN email_contacts c ON c.id = m.from_contact_id
+ WHERE m.link_id = $1
+ AND m.is_sent = false
+ AND m.from_contact_id IS NOT NULL
+ AND m.internal_date_ts IS NOT NULL
+ GROUP BY LOWER(c.email_address), c.name
+ "#,
+ link_id,
+ )
+ .fetch_all(pool)
+ .await?;
+
+ Ok(rows
+ .into_iter()
+ .map(|r| (r.email, r.name, r.first_at, r.last_at))
+ .collect())
+}
+
+/// Returns true iff `link_id` still has at least one message that
+/// touches `email` in either direction: a sent message whose
+/// recipients (to/cc/bcc) include `email`, **or** a received message
+/// whose `from_contact_id` matches `email`. Used by the
+/// depopulate-CRM-contact backfill step as the pre-check — sources
+/// now track interactions in both directions, so the source row must
+/// stay until both directions are gone. `email` is matched
+/// case-insensitively.
+#[tracing::instrument(skip(pool), err)]
+pub async fn link_has_any_message_with(
pool: &PgPool,
link_id: Uuid,
email: &str,
@@ -132,6 +189,13 @@ pub async fn link_has_sent_message_to(
WHERE m.link_id = $1
AND m.is_sent = true
AND LOWER(c.email_address) = $2
+ UNION ALL
+ SELECT 1
+ FROM email_messages m
+ JOIN email_contacts c ON c.id = m.from_contact_id
+ WHERE m.link_id = $1
+ AND m.is_sent = false
+ AND LOWER(c.email_address) = $2
LIMIT 1
) AS "exists!"
"#,
diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rs
index 72e1e60d9c..c40cb8f27a 100644
--- a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rs
@@ -2,7 +2,8 @@ use crate::convert::map_message_resource_to_service;
use crate::pubsub::backfill::increment_counters;
use crate::pubsub::context::PubSubContext;
use crate::pubsub::util::{
- CheckGmailRateLimitArgs, check_gmail_rate_limit, enqueue_populate_crm_contacts,
+ CheckGmailRateLimitArgs, CrmContactRecipient, check_gmail_rate_limit,
+ enqueue_populate_crm_contacts,
};
use crate::util::process_pre_insert::process_message_pre_insert;
use anyhow::Context;
@@ -81,22 +82,50 @@ pub async fn backfill_message(
})
})?;
- // For messages sent BY the user, fan out a PopulateCrmContact job per
- // recipient so the CRM tables learn about the contacts the team has been
- // emailing. ON CONFLICT DO NOTHING on the consumer side keeps duplicate
+ // Fan out a PopulateCrmContact job per address involved in the
+ // message — every non-draft message contributes, in both
+ // directions. Sent: enumerate to/cc/bcc (recipients the team
+ // emailed). Received: enumerate `from` (external sender). The
+ // consumer branches on `is_sent` to decide whether a new
+ // `crm_companies` row may be inserted — received-direction
+ // populates only ever touch already-tracked companies.
+ //
+ // Drafts are skipped: their from = the user, their to/cc/bcc may
+ // not be finalized, and they don't represent real correspondence.
+ //
+ // ON CONFLICT DO NOTHING on the consumer side keeps duplicate
// enqueues (e.g. retried backfill_message attempts) harmless. The
// display name from the gmail header is threaded through so the
// consumer doesn't have to re-query email_contacts.
- if message.is_sent {
+ // `internal_date_ts` is passed as `message_at`; `contact_id` is
+ // `None` here because we already carry `message_at` and the
+ // contact row may not exist yet at producer time.
+ if !message.is_draft {
let self_email = link.email_address.0.as_ref().to_ascii_lowercase();
- let recipients: Vec<(String, Option<String>)> = message
- .to
- .iter()
- .chain(&message.cc)
- .chain(&message.bcc)
- .map(|c| (c.email.clone(), c.name.clone()))
- .collect();
- enqueue_populate_crm_contacts(ctx, link.id, &self_email, recipients).await?;
+ // Single message → single timestamp covers both endpoints. The
+ // consumer's stored-value merge converges as more messages come
+ // in. `Utc::now()` fallback when Gmail returned no
+ // internal_date_ts.
+ let at = message.internal_date_ts.unwrap_or_else(chrono::Utc::now);
+ let recipients: Vec<CrmContactRecipient> = if message.is_sent {
+ message
+ .to
+ .iter()
+ .chain(&message.cc)
+ .chain(&message.bcc)
+ .map(|c| (c.email.clone(), c.name.clone(), at, at))
+ .collect()
+ } else {
+ message
+ .from
+ .iter()
+ .map(|c| (c.email.clone(), c.name.clone(), at, at))
+ .collect()
+ };
+ if !recipients.is_empty() {
+ enqueue_populate_crm_contacts(ctx, link.id, &self_email, recipients, message.is_sent)
+ .await?;
+ }
}
// Handle all success-related operations
diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/depopulate_crm_contact.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/depopulate_crm_contact.rs
index e3aeaa6477..e6abf9e147 100644
--- a/rust/cloud-storage/email_service/src/pubsub/backfill/depopulate_crm_contact.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/depopulate_crm_contact.rs
@@ -15,10 +15,13 @@ use models_email::email::service::pubsub::{DetailedError, FailureReason, Process
/// [`crm::domain::companies_repo::CompaniesRepository::depopulate_contact`].
///
/// Pre-check: before invoking the CRM cascade we verify via
-/// [`email_db_client::contacts::get::link_has_sent_message_to`] that this
-/// link no longer has any sent message to `contact_email`. If a sibling
-/// sent message still exists, we ack the job without touching CRM —
-/// duplicate enqueues from retries or out-of-order processing land here.
+/// [`email_db_client::contacts::get::link_has_any_message_with`] that
+/// this link no longer has any message (sent or received) involving
+/// `contact_email`. Sources track interactions in both directions, so
+/// the row must stay until both directions are gone. If a sibling
+/// message still exists in either direction, we ack the job without
+/// touching CRM — duplicate enqueues from retries or out-of-order
+/// processing land here.
///
/// The check runs outside the CRM crate's advisory lock, so a brand-new
/// sent message landing in the microseconds between the check and the
@@ -48,7 +51,7 @@ pub async fn depopulate_crm_contact(
return Ok(());
};
- let still_has_sent = email_db_client::contacts::get::link_has_sent_message_to(
+ let still_has_any = email_db_client::contacts::get::link_has_any_message_with(
&ctx.db,
link.id,
&p.contact_email,
@@ -57,12 +60,14 @@ pub async fn depopulate_crm_contact(
.map_err(|e| {
ProcessingError::Retryable(DetailedError {
reason: FailureReason::DatabaseQueryFailed,
- source: e.context("Failed to check remaining sent messages for contact"),
+ source: e.context("Failed to check remaining messages with contact"),
})
})?;
- if still_has_sent {
- tracing::debug!("Link still has other sent messages to contact; skipping depopulation");
+ if still_has_any {
+ tracing::debug!(
+ "Link still has other messages with contact (sent or received); skipping depopulation"
+ );
return Ok(());
}
diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/populate_crm_contact.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/populate_crm_contact.rs
index a312194c27..29a2c3c3e6 100644
--- a/rust/cloud-storage/email_service/src/pubsub/backfill/populate_crm_contact.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/populate_crm_contact.rs
@@ -4,21 +4,23 @@ use models_email::email::service::backfill::PopulateCrmContactPayload;
use models_email::email::service::link;
use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};
-/// Idempotently records a contact the user has emailed into the CRM tables.
+/// Records a CRM interaction for one `(link, contact_email)` —
+/// possibly inserting new `crm_companies` / `crm_contacts` /
+/// `crm_contact_sources` rows.
///
-/// Fanned out one-per-recipient from `backfill_message` when the message was
-/// sent by the user. Resolves the user's team (no-op if the user has no
-/// team), then upserts `crm_companies`/`crm_domains`/`crm_contacts`/
-/// `crm_contact_sources` atomically. The call is a no-op when either
-/// killswitch is engaged: the team-level `team_crm_settings.crm_enabled
-/// = false` (toggled via `PATCH /team/crm`), or the per-domain
-/// `crm_companies.email_sync = false` for the contact's domain. See
-/// [`crm::domain::companies_repo::CompaniesRepository::populate_contact`].
+/// Fanned out one-per-address from `backfill_message`, `upsert_message`,
+/// and `populate_crm_for_user`. Every non-draft message contributes:
+/// sent-direction populates fan out per to/cc/bcc recipient and may
+/// insert new company rows; received-direction populates fan out for
+/// the sender and only touch already-tracked companies. The consumer
+/// resolves the team for the link (no-op if no team), then delegates
+/// to [`crm::domain::service::CrmService::populate_contact`] which
+/// applies the full insert / update matrix.
///
-/// Company metadata (name, description, icon) is resolved and cached
-/// inside `crm_service.populate_contact` via the
-/// `crm_domain_directory` lookup → resolver → upsert path, so the
-/// consumer here doesn't need to know how that's done.
+/// `first_at` / `last_at` come from the producer pre-computed. Per-
+/// message paths set both to the message's `internal_date_ts` (with
+/// `Utc::now()` fallback at the producer when Gmail returned none).
+/// The historical seed aggregates MIN/MAX per contact in SQL.
#[tracing::instrument(skip(ctx), err, fields(contact_email = %p.contact_email, link_id = %link.id))]
pub async fn populate_crm_contact(
ctx: &PubSubContext,
@@ -50,6 +52,9 @@ pub async fn populate_crm_contact(
link.email_address.0.as_ref(),
&p.contact_email,
p.contact_name.as_deref(),
+ p.first_at,
+ p.last_at,
+ p.is_sent,
)
.await
.map_err(|e| {
diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/populate_crm_for_user.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/populate_crm_for_user.rs
index 80fbd5041e..9d7a1686dc 100644
--- a/rust/cloud-storage/email_service/src/pubsub/backfill/populate_crm_for_user.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/populate_crm_for_user.rs
@@ -53,22 +53,39 @@ pub async fn populate_crm_for_user(
let self_email = link.email_address.0.as_ref().to_ascii_lowercase();
- // Pull every distinct recipient (email + display name) from sent
- // messages on this link. Mirrors what backfill_message would have
- // produced if the per-message fan-out had been running when these
- // messages were first backfilled — including the name from
- // email_contacts so the consumer can set crm_contacts.name without
- // its own round-trip.
- let recipients = email_db_client::contacts::get::fetch_sent_message_recipient_contacts_by_link(
- &ctx.db, link.id,
- )
- .await
- .map_err(|e| {
- ProcessingError::Retryable(DetailedError {
- reason: FailureReason::DatabaseQueryFailed,
- source: e.context("Failed to fetch sent-message recipients"),
- })
- })?;
+ // The by_link queries aggregate MIN/MAX of `internal_date_ts` per
+ // contact, so each fan-out job carries the contact's full known
+ // activity range. The consumer stamps `first_interaction` /
+ // `last_interaction` directly from those endpoints.
+ //
+ // Two fan-outs: sent recipients (`is_sent=true`, may create new
+ // `crm_companies` rows), then received senders (`is_sent=false`,
+ // only updates already-tracked rows). Sent first so received-pass
+ // contacts at brand-new companies can also land. Both passes are
+ // idempotent.
+ let sent_recipients =
+ email_db_client::contacts::get::fetch_sent_message_recipient_contacts_by_link(
+ &ctx.db, link.id,
+ )
+ .await
+ .map_err(|e| {
+ ProcessingError::Retryable(DetailedError {
+ reason: FailureReason::DatabaseQueryFailed,
+ source: e.context("Failed to fetch sent-message recipients"),
+ })
+ })?;
+
+ enqueue_populate_crm_contacts(ctx, link.id, &self_email, sent_recipients, true).await?;
+
+ let received_senders =
+ email_db_client::contacts::get::fetch_received_sender_contacts_by_link(&ctx.db, link.id)
+ .await
+ .map_err(|e| {
+ ProcessingError::Retryable(DetailedError {
+ reason: FailureReason::DatabaseQueryFailed,
+ source: e.context("Failed to fetch received-message senders"),
+ })
+ })?;
- enqueue_populate_crm_contacts(ctx, link.id, &self_email, recipients).await
+ enqueue_populate_crm_contacts(ctx, link.id, &self_email, received_senders, false).await
}
diff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/delete_message.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/delete_message.rs
index f35c0f865b..eb462d8b58 100644
--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/delete_message.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/delete_message.rs
@@ -37,12 +37,14 @@ pub async fn delete_message(
}
};
- // For sent messages, snapshot the recipients before deletion so we can
- // tear down the CRM source rows we created in `populate_crm_contact` /
- // `upsert_message`. Received messages don't contribute to CRM, so the
- // snapshot is skipped for them. Generic addresses are dropped here for
- // parity with the producer side.
- let recipient_emails: Vec<String> = if message.is_sent {
+ // Snapshot the addresses that may have contributed CRM source rows
+ // for this message so we can tear them down. Both directions can
+ // create sources (per the populate path): sent messages →
+ // to/cc/bcc recipients, received messages → from (sender). Drafts
+ // never reach CRM populate, so they don't need depopulate either.
+ let crm_emails: Vec<String> = if message.is_draft {
+ Vec::new()
+ } else if message.is_sent {
let recipients =
email_db_client::contacts::get::fetch_db_recipients(&ctx.db, message.db_id)
.await
@@ -61,7 +63,18 @@ pub async fn delete_message(
.filter_map(|(contact, _)| contact.email_address)
.collect()
} else {
- Vec::new()
+ // Received: the sender is the external party that may have a
+ // CRM source row tied to this link.
+ let sender =
+ email_db_client::contacts::get::get_sender_by_message_id(&ctx.db, message.db_id)
+ .await
+ .map_err(|e| {
+ ProcessingError::Retryable(DetailedError {
+ reason: FailureReason::DatabaseQueryFailed,
+ source: e.context("Failed to fetch sender for deleted message".to_string()),
+ })
+ })?;
+ sender.into_iter().filter_map(|c| c.email_address).collect()
};
// Enqueue CRM teardown BEFORE the delete commits, so a transient
@@ -69,12 +82,12 @@ pub async fn delete_message(
// message row is already gone (SQS retry would then short-circuit
// at the `None` arm above and never re-enqueue). If enqueue
// succeeds but the delete below fails, the depopulate consumer's
- // `link_has_sent_message_to` pre-check sees the message still in
+ // `link_has_any_message_with` pre-check sees the message still in
// place and acks without touching CRM — so the ordering is safe in
// both directions.
- if !recipient_emails.is_empty() {
+ if !crm_emails.is_empty() {
let self_email = link.email_address.0.as_ref().to_ascii_lowercase();
- enqueue_depopulate_crm_contacts(ctx, link.id, &self_email, recipient_emails).await?;
+ enqueue_depopulate_crm_contacts(ctx, link.id, &self_email, crm_emails).await?;
}
let mut tx = ctx.db.begin().await.map_err(|e| {
diff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs
index 16902fd91b..b79af3d983 100644
--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs
@@ -4,7 +4,7 @@ use crate::pubsub::inbox_sync::operations::shared::notify_search;
use crate::pubsub::inbox_sync::process;
use crate::pubsub::inbox_sync::process::check_gmail_rate_limit_inbox_sync;
use crate::pubsub::util::cg_refresh_email;
-use crate::pubsub::util::enqueue_populate_crm_contacts;
+use crate::pubsub::util::{CrmContactRecipient, enqueue_populate_crm_contacts};
use crate::util::process_pre_insert::{process_message_pre_insert, process_threads_pre_insert};
use crate::util::upload_attachment::{UploadAttachmentContext, upload_attachment};
use contacts::domain::ports::ContactsIngress;
@@ -107,24 +107,35 @@ pub async fn upsert_message(
.filter(|e| !email_utils::is_generic_email(e))
.collect::<Vec<_>>();
- // Snapshot `(email, name)` pairs for the CRM populate fan-out below.
- // We capture it here (before `message` is moved into
- // `process_and_insert_message`) so the consumer can write
+ // Snapshot `(email, name, first_at, last_at)` tuples for the CRM
+ // populate fan-out below. Captured here (before `message` is moved
+ // into `process_and_insert_message`) so the consumer can write
// `crm_contacts.name` without a separate email_contacts lookup.
- // No producer-side filtering — the crm crate is the single source
- // of truth for "what belongs in the CRM" (generic-provider domains,
- // killswitched companies, etc.) and applying the same rules here
- // would just drift over time.
- let crm_recipients: Vec<(String, Option<String>)> = if is_sent {
+ //
+ // Single message → single timestamp covers both endpoints; the
+ // consumer merges with the stored range over time. Sent: enumerate
+ // to/cc/bcc. Received: enumerate `from`. Drafts are skipped — they
+ // don't represent real correspondence. No producer-side filtering
+ // of addresses — the crm crate is the single source of truth.
+ let is_draft = message.is_draft;
+ // `Utc::now()` fallback when Gmail returned no internal_date_ts.
+ let at = message.internal_date_ts.unwrap_or_else(chrono::Utc::now);
+ let crm_recipients: Vec<CrmContactRecipient> = if is_draft {
+ Vec::new()
+ } else if is_sent {
message
.to
.iter()
.chain(&message.cc)
.chain(&message.bcc)
- .map(|c| (c.email.clone(), c.name.clone()))
+ .map(|c| (c.email.clone(), c.name.clone(), at, at))
.collect()
} else {
- Vec::new()
+ message
+ .from
+ .iter()
+ .map(|c| (c.email.clone(), c.name.clone(), at, at))
+ .collect()
};
// determine if message's thread already exists in the database
@@ -216,13 +227,13 @@ pub async fn upsert_message(
)
.await?;
- // For messages sent BY the user, fan out a PopulateCrmContact job per
- // recipient so the CRM tables learn about the contacts the team has
- // been emailing. Mirrors the backfill path in backfill_message.rs;
- // `crm_recipients` was snapshotted above before `message` was moved.
- if is_sent {
+ // Fan out a PopulateCrmContact job per address. Mirrors
+ // `backfill_message.rs`: sent → to/cc/bcc, received → from,
+ // drafts → skipped. The consumer branches on `is_sent` for the
+ // company-insert gate.
+ if !crm_recipients.is_empty() {
let self_email = link.email_address.0.as_ref().to_ascii_lowercase();
- enqueue_populate_crm_contacts(ctx, link.id, &self_email, crm_recipients).await?;
+ enqueue_populate_crm_contacts(ctx, link.id, &self_email, crm_recipients, is_sent).await?;
}
notify_search(ctx, link, message_db_id, is_spam_or_trash).await?;
diff --git a/rust/cloud-storage/email_service/src/pubsub/util.rs b/rust/cloud-storage/email_service/src/pubsub/util.rs
index 19113403d7..b503fe5579 100644
--- a/rust/cloud-storage/email_service/src/pubsub/util.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/util.rs
@@ -1,6 +1,7 @@
use crate::pubsub::context::PubSubContext;
use crate::util::redis::RedisClient;
use crate::util::redis::rate_limit::RateLimitArgs;
+use chrono::{DateTime, Utc};
use connection_gateway_client::client::ConnectionGatewayClient;
/// shared utils across different pubsub workers
use models_email::email::service::backfill::{
@@ -12,6 +13,12 @@ use models_email::gmail::operations::GmailApiOperation;
use std::collections::HashSet;
use uuid::Uuid;
+/// One recipient tuple `(email, name, first_at, last_at)` fed into
+/// [`enqueue_populate_crm_contacts`]. Per-message paths use the same
+/// timestamp for both endpoints; the historical seed passes the
+/// contact's pre-aggregated MIN/MAX.
+pub type CrmContactRecipient = (String, Option<String>, DateTime<Utc>, DateTime<Utc>);
+
/// Arguments for checking Gmail API rate limits
pub struct CheckGmailRateLimitArgs<'a> {
pub redis_client: &'a RedisClient,
@@ -130,23 +137,33 @@ fn normalized_non_self_contact_emails(
/// Producer-side fan-out helper: normalizes and enqueues one
/// `PopulateCrmContact` message per distinct, non-self contact.
///
-/// Takes `(email, name)` pairs so the consumer can write
-/// `crm_contacts.name` without a follow-up round-trip to `email_contacts`.
-/// `name` comes from the gmail message's recipient header on the
-/// per-message paths (`backfill_message`, `upsert_message`) and from
-/// `email_contacts.name` on the historical path (`populate_crm_for_user`).
+/// Takes `(email, name, first_at, last_at)` tuples. `name` comes from
+/// the gmail message's recipient header on per-message paths and from
+/// `email_contacts.name` on the historical path. `first_at` /
+/// `last_at` carry the contact's known activity range — per-message
+/// paths set both to `message.internal_date_ts`; the historical seed
+/// sets them to MIN/MAX from its aggregating SQL.
+///
+/// `is_sent` flags whether the populating message was sent by the user
+/// (true) or received (false). One fan-out batch is one direction;
+/// callers that need to enqueue both (the historical seed) call this
+/// helper twice. The consumer uses the flag to gate company INSERTs
+/// and `first_interaction` LEAST-merging (received-direction never
+/// creates a new `crm_companies` row and never moves
+/// `first_interaction` backwards).
///
/// Email validation rules and dedup match
/// [`normalized_non_self_contact_emails`]; dedup is by email only, so the
-/// first name seen for a given address in this batch wins.
+/// first name / timestamps seen for a given address in this batch win.
pub async fn enqueue_populate_crm_contacts(
ctx: &PubSubContext,
link_id: Uuid,
self_email: &str,
- contacts: impl IntoIterator<Item = (String, Option<String>)>,
+ contacts: impl IntoIterator<Item = CrmContactRecipient>,
+ is_sent: bool,
) -> Result<(), ProcessingError> {
let mut seen: HashSet<String> = HashSet::new();
- for (raw_email, contact_name) in contacts {
+ for (raw_email, contact_name, first_at, last_at) in contacts {
let contact_email = raw_email.trim().to_ascii_lowercase();
let Some((local, domain)) = contact_email.split_once('@') else {
continue;
@@ -164,6 +181,9 @@ pub async fn enqueue_populate_crm_contacts(
payload: PopulateCrmContactPayload {
contact_email,
contact_name,
+ first_at,
+ last_at,
+ is_sent,
},
}),
};
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260526175147_crm_interaction_timestamps.down.sql b/rust/cloud-storage/macro_db_client/migrations/20260526175147_crm_interaction_timestamps.down.sql
new file mode 100644
index 0000000000..ab5f871a4b
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260526175147_crm_interaction_timestamps.down.sql
@@ -0,0 +1,11 @@
+ALTER TABLE crm_contacts
+ DROP COLUMN IF EXISTS last_interaction;
+
+ALTER TABLE crm_contacts
+ DROP COLUMN IF EXISTS first_interaction;
+
+ALTER TABLE crm_companies
+ DROP COLUMN IF EXISTS last_interaction;
+
+ALTER TABLE crm_companies
+ DROP COLUMN IF EXISTS first_interaction;
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260526175147_crm_interaction_timestamps.up.sql b/rust/cloud-storage/macro_db_client/migrations/20260526175147_crm_interaction_timestamps.up.sql
new file mode 100644
index 0000000000..e2a97c0a85
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260526175147_crm_interaction_timestamps.up.sql
@@ -0,0 +1,43 @@
+ALTER TABLE crm_companies
+ ADD COLUMN IF NOT EXISTS first_interaction TIMESTAMPTZ;
+
+ALTER TABLE crm_companies
+ ADD COLUMN IF NOT EXISTS last_interaction TIMESTAMPTZ;
+
+ALTER TABLE crm_contacts
+ ADD COLUMN IF NOT EXISTS first_interaction TIMESTAMPTZ;
+
+ALTER TABLE crm_contacts
+ ADD COLUMN IF NOT EXISTS last_interaction TIMESTAMPTZ;
+
+-- Backfill existing rows from `created_at` — the row's first-write
+-- time is the best timestamp we have without an expensive aggregation
+-- against email_messages. Future populates will LEAST/GREATEST-merge
+-- the real message_at values in.
+UPDATE crm_companies
+ SET first_interaction = created_at
+ WHERE first_interaction IS NULL;
+
+UPDATE crm_companies
+ SET last_interaction = created_at
+ WHERE last_interaction IS NULL;
+
+UPDATE crm_contacts
+ SET first_interaction = created_at
+ WHERE first_interaction IS NULL;
+
+UPDATE crm_contacts
+ SET last_interaction = created_at
+ WHERE last_interaction IS NULL;
+
+ALTER TABLE crm_companies
+ ALTER COLUMN first_interaction SET NOT NULL;
+
+ALTER TABLE crm_companies
+ ALTER COLUMN last_interaction SET NOT NULL;
+
+ALTER TABLE crm_contacts
+ ALTER COLUMN first_interaction SET NOT NULL;
+
+ALTER TABLE crm_contacts
+ ALTER COLUMN last_interaction SET NOT NULL;
diff --git a/rust/cloud-storage/models_email/src/email/service/backfill.rs b/rust/cloud-storage/models_email/src/email/service/backfill.rs
index 491e33c0bb..d88a9a5ee9 100644
--- a/rust/cloud-storage/models_email/src/email/service/backfill.rs
+++ b/rust/cloud-storage/models_email/src/email/service/backfill.rs
@@ -280,6 +280,34 @@ pub struct PopulateCrmContactPayload {
/// no display name was associated with the address.
#[serde(default)]
pub contact_name: Option<String>,
+ /// Earliest interaction timestamp the producer knows about for this
+ /// contact. Per-message paths set this to `message.internal_date_ts`
+ /// (or `Utc::now()` when the message has none). The historical seed
+ /// (`populate_crm_for_user`) sets it to MIN(internal_date_ts)
+ /// across the contact's matching messages. Written to
+ /// `first_interaction` on INSERT and LEAST-merged into the stored
+ /// value on UPDATE (only when `is_sent=true` — received-direction
+ /// populates don't pull the anchor backwards).
+ pub first_at: DateTime<Utc>,
+ /// Latest interaction timestamp the producer knows about for this
+ /// contact. Per-message paths set this to `message.internal_date_ts`
+ /// (or `Utc::now()` when the message has none). The historical seed
+ /// sets it to MAX(internal_date_ts) across the contact's matching
+ /// messages. Written to `last_interaction` on INSERT and
+ /// GREATEST-merged into the stored value on UPDATE regardless of
+ /// direction.
+ pub last_at: DateTime<Utc>,
+ /// `true` when the populating message was sent BY the user; `false`
+ /// when it was received. Controls the consumer's insert semantics:
+ /// `true` may INSERT a new `crm_companies` row for an unknown
+ /// domain; `false` no-ops when the company isn't already tracked
+ /// (received-direction populates only update existing rows). When
+ /// the company IS tracked, both directions insert-or-update the
+ /// `crm_contacts` row and add a `crm_contact_sources` row. See
+ /// [`crm::domain::service::CrmService::populate_contact`] for the
+ /// full matrix.
+ #[serde(default)]
+ pub is_sent: bool,
}
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]