Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(team): add CRM enable/disable endpoint with team-level killswitch (#3486)
Evan Hutnik1cf5cd6ef499
diff --git a/js/app/packages/service-clients/service-auth/generated/client.ts b/js/app/packages/service-clients/service-auth/generated/client.tsindex ab6c1873f7..799f1e7868 100644--- a/js/app/packages/service-clients/service-auth/generated/client.ts+++ b/js/app/packages/service-clients/service-auth/generated/client.ts@@ -33,6 +33,8 @@ import type {PasswordlessRequest,PasswordRequest,PatchSubscriptionTierRequest,+ PatchTeamCrmSettingsRequest,+ PatchTeamCrmSettingsResponse,PatchTeamRequest,PatchUserGroupRequest,PatchUserOnboardingRequest,@@ -2011,6 +2013,90 @@ export const patchTeam = async (} as patchTeamResponse;};+/**+ * @summary Enables or disables CRM for the team. On enable, kicks off a+best-effort backfill that enqueues a `PopulateCrmForUser` message+per team member (no-op if CRM is already enabled). On disable,+flips the flag and purges the team's CRM data (cascading through+`crm_companies` → `crm_domains` / `crm_contacts` /+`crm_contact_sources`). Requires the caller to be an Admin or+Owner of the team.+ */+export type patchTeamCrmSettingsResponse200 = {+ data: PatchTeamCrmSettingsResponse;+ status: 200;+};++export type patchTeamCrmSettingsResponse400 = {+ data: ErrorResponse;+ status: 400;+};++export type patchTeamCrmSettingsResponse401 = {+ data: ErrorResponse;+ status: 401;+};++export type patchTeamCrmSettingsResponse403 = {+ data: ErrorResponse;+ status: 403;+};++export type patchTeamCrmSettingsResponse404 = {+ data: ErrorResponse;+ status: 404;+};++export type patchTeamCrmSettingsResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type patchTeamCrmSettingsResponseSuccess =+ patchTeamCrmSettingsResponse200 & {+ headers: Headers;+ };+export type patchTeamCrmSettingsResponseError = (+ | patchTeamCrmSettingsResponse400+ | patchTeamCrmSettingsResponse401+ | patchTeamCrmSettingsResponse403+ | patchTeamCrmSettingsResponse404+ | patchTeamCrmSettingsResponse500+) & {+ headers: Headers;+};++export type patchTeamCrmSettingsResponse =+ | patchTeamCrmSettingsResponseSuccess+ | patchTeamCrmSettingsResponseError;++export const getPatchTeamCrmSettingsUrl = () => {+ return `/team/crm`;+};++export const patchTeamCrmSettings = async (+ patchTeamCrmSettingsRequest: PatchTeamCrmSettingsRequest,+ options?: RequestInit+): Promise<patchTeamCrmSettingsResponse> => {+ const res = await fetch(getPatchTeamCrmSettingsUrl(), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchTeamCrmSettingsRequest),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: patchTeamCrmSettingsResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as patchTeamCrmSettingsResponse;+};+/*** @summary Invites a user to a team.*/diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts b/js/app/packages/service-clients/service-auth/generated/schemas/index.tsindex ec5cac7b20..e8dd88e67e 100644--- a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-auth/generated/schemas/index.ts@@ -45,6 +45,8 @@ export * from './passwordlessRequest';export * from './passwordlessRequestReferralCode';export * from './passwordRequest';export * from './patchSubscriptionTierRequest';+export * from './patchTeamCrmSettingsRequest';+export * from './patchTeamCrmSettingsResponse';export * from './patchTeamRequest';export * from './patchTeamRequestName';export * from './patchTeamRequestSlug';diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamCrmSettingsRequest.ts b/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamCrmSettingsRequest.tsnew file mode 100644index 0000000000..78873c869e--- /dev/null+++ b/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamCrmSettingsRequest.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Request body for `PATCH /team/crm`.+ */+export interface PatchTeamCrmSettingsRequest {+ /** The desired CRM state for the team. */+ enabled: boolean;+}diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamCrmSettingsResponse.ts b/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamCrmSettingsResponse.tsnew file mode 100644index 0000000000..8da04103b3--- /dev/null+++ b/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamCrmSettingsResponse.ts@@ -0,0 +1,32 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Response for `PATCH /team/crm`. Reports both the resulting state+and whether this call changed it; for the enable-flip case it also+reports the backfill fan-out tallies.+ */+export interface PatchTeamCrmSettingsResponse {+ /**+ * Number of members for whom a `PopulateCrmForUser` message was+enqueued. Non-zero only on a disabled → enabled transition;+per-user enqueue failures are logged and swallowed.+ * @minimum 0+ */+ backfill_enqueued: number;+ /**+ * Number of members whose enqueue failed (and was swallowed).+Non-zero only on a disabled → enabled transition.+ * @minimum 0+ */+ backfill_failed: number;+ /** True if this call flipped the value (false → true or true →+false). False if the team was already at the requested state. */+ changed: boolean;+ /** The resulting `crm_enabled` value after the call. */+ enabled: boolean;+}diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.jsonindex 1deda772d0..130b57c7c3 100644--- a/js/app/packages/service-clients/service-auth/openapi.json+++ b/js/app/packages/service-clients/service-auth/openapi.json@@ -1673,6 +1673,85 @@}}},+ "/team/crm": {+ "patch": {+ "tags": ["teams::inbound::axum_router::patch_team_crm_settings"],+ "summary": "Enables or disables CRM for the team. On enable, kicks off a\nbest-effort backfill that enqueues a `PopulateCrmForUser` message\nper team member (no-op if CRM is already enabled). On disable,\nflips the flag and purges the team's CRM data (cascading through\n`crm_companies` → `crm_domains` / `crm_contacts` /\n`crm_contact_sources`). Requires the caller to be an Admin or\nOwner of the team.",+ "operationId": "patch_team_crm_settings",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PatchTeamCrmSettingsRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PatchTeamCrmSettingsResponse"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/team/invite": {"post": {"tags": ["teams::inbound::axum_router::invite_to_team"],@@ -3570,6 +3649,47 @@}}},+ "PatchTeamCrmSettingsRequest": {+ "type": "object",+ "description": "Request body for `PATCH /team/crm`.",+ "required": ["enabled"],+ "properties": {+ "enabled": {+ "type": "boolean",+ "description": "The desired CRM state for the team."+ }+ }+ },+ "PatchTeamCrmSettingsResponse": {+ "type": "object",+ "description": "Response for `PATCH /team/crm`. Reports both the resulting state\nand whether this call changed it; for the enable-flip case it also\nreports the backfill fan-out tallies.",+ "required": [+ "enabled",+ "changed",+ "backfill_enqueued",+ "backfill_failed"+ ],+ "properties": {+ "backfill_enqueued": {+ "type": "integer",+ "description": "Number of members for whom a `PopulateCrmForUser` message was\nenqueued. Non-zero only on a disabled → enabled transition;\nper-user enqueue failures are logged and swallowed.",+ "minimum": 0+ },+ "backfill_failed": {+ "type": "integer",+ "description": "Number of members whose enqueue failed (and was swallowed).\nNon-zero only on a disabled → enabled transition.",+ "minimum": 0+ },+ "changed": {+ "type": "boolean",+ "description": "True if this call flipped the value (false → true or true →\nfalse). False if the team was already at the requested state."+ },+ "enabled": {+ "type": "boolean",+ "description": "The resulting `crm_enabled` value after the call."+ }+ }+ },"PatchTeamRequest": {"type": "object","description": "Request to update a team",diff --git a/rust/cloud-storage/.sqlx/query-17eb78883f203e76c823566fa1127a752597dae52b891be1e12526b02fdb2e6c.json b/rust/cloud-storage/.sqlx/query-17eb78883f203e76c823566fa1127a752597dae52b891be1e12526b02fdb2e6c.jsonnew file mode 100644index 0000000000..5e44ab1491--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-17eb78883f203e76c823566fa1127a752597dae52b891be1e12526b02fdb2e6c.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM crm_companies WHERE team_id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "17eb78883f203e76c823566fa1127a752597dae52b891be1e12526b02fdb2e6c"+}diff --git a/rust/cloud-storage/.sqlx/query-5fe0b9eb83e39b8cb89be6aab89099b157418c1e52132b6940fee9bc8c2da4e2.json b/rust/cloud-storage/.sqlx/query-5fe0b9eb83e39b8cb89be6aab89099b157418c1e52132b6940fee9bc8c2da4e2.jsonnew file mode 100644index 0000000000..38f31f37b5--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-5fe0b9eb83e39b8cb89be6aab89099b157418c1e52132b6940fee9bc8c2da4e2.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH prev AS (\n SELECT crm_enabled FROM team_crm_settings WHERE team_id = $1\n ),\n upsert AS (\n INSERT INTO team_crm_settings (team_id, crm_enabled)\n VALUES ($1, TRUE)\n ON CONFLICT (team_id) DO UPDATE\n SET crm_enabled = TRUE,\n updated_at = now()\n RETURNING crm_enabled\n )\n SELECT COALESCE((SELECT crm_enabled FROM prev), FALSE) AS \"prev_enabled!\"\n FROM upsert\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "prev_enabled!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "5fe0b9eb83e39b8cb89be6aab89099b157418c1e52132b6940fee9bc8c2da4e2"+}diff --git a/rust/cloud-storage/.sqlx/query-a547a92f2099dbeb0b1fb2fc9dba7bf0f464619f047b5d967914f7b476722db5.json b/rust/cloud-storage/.sqlx/query-a547a92f2099dbeb0b1fb2fc9dba7bf0f464619f047b5d967914f7b476722db5.jsonnew file mode 100644index 0000000000..5f7d4a2c37--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-a547a92f2099dbeb0b1fb2fc9dba7bf0f464619f047b5d967914f7b476722db5.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO team_crm_settings (team_id, crm_enabled)\n VALUES ($1, FALSE)\n ON CONFLICT (team_id) DO UPDATE\n SET crm_enabled = FALSE,\n updated_at = now()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "a547a92f2099dbeb0b1fb2fc9dba7bf0f464619f047b5d967914f7b476722db5"+}diff --git a/rust/cloud-storage/.sqlx/query-c1ccd5b7d22222b5112aa06f6cb9d19523156de3b771696a069389e5a38cd51d.json b/rust/cloud-storage/.sqlx/query-c1ccd5b7d22222b5112aa06f6cb9d19523156de3b771696a069389e5a38cd51d.jsonnew file mode 100644index 0000000000..738f61d570--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-c1ccd5b7d22222b5112aa06f6cb9d19523156de3b771696a069389e5a38cd51d.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO team_crm_settings (team_id)\n VALUES ($1)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "c1ccd5b7d22222b5112aa06f6cb9d19523156de3b771696a069389e5a38cd51d"+}diff --git a/rust/cloud-storage/.sqlx/query-cc9cd9c1d19f49627d619e8111ccf71139a34878ece29560f7a1c48a73c974d8.json b/rust/cloud-storage/.sqlx/query-cc9cd9c1d19f49627d619e8111ccf71139a34878ece29560f7a1c48a73c974d8.jsonnew file mode 100644index 0000000000..6134ab08e0--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-cc9cd9c1d19f49627d619e8111ccf71139a34878ece29560f7a1c48a73c974d8.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT COALESCE(\n (SELECT crm_enabled FROM team_crm_settings WHERE team_id = $1),\n FALSE\n ) AS \"crm_enabled!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "crm_enabled!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "cc9cd9c1d19f49627d619e8111ccf71139a34878ece29560f7a1c48a73c974d8"+}diff --git a/rust/cloud-storage/.sqlx/query-d357cee4f06a87dd2d7fe9d64a0fd2c9e95591835b82393ecb2492f8966883bb.json b/rust/cloud-storage/.sqlx/query-d357cee4f06a87dd2d7fe9d64a0fd2c9e95591835b82393ecb2492f8966883bb.jsonnew file mode 100644index 0000000000..81fffbddc8--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-d357cee4f06a87dd2d7fe9d64a0fd2c9e95591835b82393ecb2492f8966883bb.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT crm_enabled FROM team_crm_settings WHERE team_id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "crm_enabled",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "d357cee4f06a87dd2d7fe9d64a0fd2c9e95591835b82393ecb2492f8966883bb"+}diff --git a/rust/cloud-storage/.sqlx/query-e951a324bc8638caa7d3d8b3793b5dbe6ce6bfec8f307f22aa7b2bab42a5a13a.json b/rust/cloud-storage/.sqlx/query-e951a324bc8638caa7d3d8b3793b5dbe6ce6bfec8f307f22aa7b2bab42a5a13a.jsonnew file mode 100644index 0000000000..b95788812b--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-e951a324bc8638caa7d3d8b3793b5dbe6ce6bfec8f307f22aa7b2bab42a5a13a.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH upsert AS (\n INSERT INTO team_crm_settings (team_id, crm_enabled)\n VALUES ($1, TRUE)\n ON CONFLICT (team_id) DO UPDATE\n SET crm_enabled = EXCLUDED.crm_enabled,\n updated_at = now()\n WHERE team_crm_settings.crm_enabled IS DISTINCT FROM EXCLUDED.crm_enabled\n RETURNING 1\n )\n SELECT EXISTS (SELECT 1 FROM upsert) AS \"changed!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "changed!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "e951a324bc8638caa7d3d8b3793b5dbe6ce6bfec8f307f22aa7b2bab42a5a13a"+}diff --git a/rust/cloud-storage/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rsindex 38a028834f..f7b4e74524 100644--- a/rust/cloud-storage/authentication_service/src/api/context.rs+++ b/rust/cloud-storage/authentication_service/src/api/context.rs@@ -40,6 +40,7 @@ pub(crate) type TeamsServiceType = teams::domain::team_service::TeamServiceImpl<UserRolesAndPermissionsServiceImpl<MacroDB, MacroDB>,NotificationIngressType,teams::outbound::crm_enqueuer::SqsCrmEnqueuer,+ teams::outbound::team_crm_settings_repo::TeamCrmSettingsRepositoryImpl,>;type RateLimiter = RateLimitServiceImpl<RedisRateLimitAdapter<redis::Client>>;diff --git a/rust/cloud-storage/authentication_service/src/api/swagger.rs b/rust/cloud-storage/authentication_service/src/api/swagger.rsindex e9e9ea1400..55c8343dd2 100644--- a/rust/cloud-storage/authentication_service/src/api/swagger.rs+++ b/rust/cloud-storage/authentication_service/src/api/swagger.rs@@ -1,7 +1,7 @@use model::authentication::login::request::{AppleLoginRequest, PasswordRequest};use teams::domain::model::{- PatchTeamRequest, PatchTeamUserRole, Team, TeamInviteDetails, TeamMember, TeamPlan, TeamRole,- TeamWithMembers,+ PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamRequest, PatchTeamUserRole,+ Team, TeamInviteDetails, TeamMember, TeamPlan, TeamRole, TeamWithMembers,};use teams::inbound::axum_router::get_team_invites::TeamInvitesResponse as TeamTeamInvitesResponse;use teams::inbound::axum_router::get_user_invites::TeamInvitesResponse as UserTeamInvitesResponse;@@ -124,6 +124,7 @@ use model::user::{teams::inbound::axum_router::invite_to_team::handler::<crate::api::context::TeamsServiceType>,teams::inbound::axum_router::get_team_invites::handler::<crate::api::context::TeamsServiceType>,teams::inbound::axum_router::patch_team::handler::<crate::api::context::TeamsServiceType>,+ teams::inbound::axum_router::patch_team_crm_settings::handler::<crate::api::context::TeamsServiceType>,teams::inbound::axum_router::reject_invitation::handler::<crate::api::context::TeamsServiceType>,teams::inbound::axum_router::get_user_invites::handler::<crate::api::context::TeamsServiceType>,teams::inbound::axum_router::get_user_teams::handler::<crate::api::context::TeamsServiceType>,@@ -196,6 +197,8 @@ use model::user::{InviteToTeamRequest,PatchTeamRequest,PatchTeamUserRole,+ PatchTeamCrmSettingsRequest,+ PatchTeamCrmSettingsResponse,TeamTeamInvitesResponse,UserTeamInvitesResponse,diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rsindex fed2c79987..66d51a1f11 100644--- a/rust/cloud-storage/authentication_service/src/main.rs+++ b/rust/cloud-storage/authentication_service/src/main.rs@@ -244,6 +244,8 @@ async fn main() -> anyhow::Result<()> {let customer_repo_impl =CustomerRepositoryImpl::new(stripe_client.clone(), config.stripe_price_id.clone());let team_channels_repo_impl = TeamChannelsRepositoryImpl::new(db.clone());+ let team_crm_settings_repo_impl =+ teams::outbound::team_crm_settings_repo::TeamCrmSettingsRepositoryImpl::new(db.clone());let notification_ingress_service = Arc::new(notification_ingress_service);@@ -256,6 +258,7 @@ async fn main() -> anyhow::Result<()> {user_roles_and_permissions_service.clone(),notification_ingress_service.clone(),crm_enqueuer,+ team_crm_settings_repo_impl,);let github_link_service_impl = GithubLinkServiceImpl::new(diff --git a/rust/cloud-storage/crm/src/domain/companies_repo.rs b/rust/cloud-storage/crm/src/domain/companies_repo.rsindex 3b5f6fbd27..12f76cf71b 100644--- a/rust/cloud-storage/crm/src/domain/companies_repo.rs+++ b/rust/cloud-storage/crm/src/domain/companies_repo.rs@@ -20,10 +20,18 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {/// Performs the company/domain/contact/contact_source upserts in a single/// transaction:///+ /// 0. Read `team_crm_settings.crm_enabled` for `team_id`. If missing+ /// or `false`, the team has CRM turned off team-wide: no rows+ /// are written and the method returns `Ok(())` so the caller+ /// can ack the job. The read happens inside this tx (after the+ /// advisory lock) so a concurrent `PATCH /team/crm`+ /// disable — which flips the flag and purges `crm_companies` in+ /// one tx — can't race past us and leave an orphan row./// 1. Look up the company for `(team_id, domain)`./// - If a row exists with `email_sync = false` the team has opted- /// this domain out (the killswitch): no rows are written and the- /// method returns `Ok(())` so the caller can ack the job.+ /// 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./// - Otherwise a new `crm_companies` row and a matching/// `crm_domains` row are inserted. The company name itselfdiff --git a/rust/cloud-storage/crm/src/domain/service.rs b/rust/cloud-storage/crm/src/domain/service.rsindex 3e9c831a3e..b87ceaf83e 100644--- a/rust/cloud-storage/crm/src/domain/service.rs+++ b/rust/cloud-storage/crm/src/domain/service.rs@@ -22,9 +22,10 @@ pub trait CrmService: Clone + Send + Sync + 'static {/// Idempotently records that `email` was seen from the mailbox/// identified by `link_id`, for the team `team_id`. Upserts/// `crm_companies` (+ `crm_domains`), `crm_contacts`, and- /// `crm_contact_sources` in a single transaction. If the team has- /// opted the contact's domain out (`crm_companies.email_sync = false`)- /// the call is a no-op.+ /// `crm_contact_sources` in a single transaction. The call is a+ /// no-op when either killswitch is engaged: the team-level+ /// `team_crm_settings.crm_enabled = false`, or the per-domain+ /// `crm_companies.email_sync = false` for the contact's domain.////// `name` is the display name observed for `email` on this user's/// link — typically `email_contacts.name`, which the caller looks updiff --git a/rust/cloud-storage/crm/src/outbound/companies_repo.rs b/rust/cloud-storage/crm/src/outbound/companies_repo.rsindex 0227ac7bc5..fd4af6d1e7 100644--- a/rust/cloud-storage/crm/src/outbound/companies_repo.rs+++ b/rust/cloud-storage/crm/src/outbound/companies_repo.rs@@ -187,9 +187,36 @@ impl CompaniesRepository for CompaniesRepositoryImpl {.await.map_err(|e| CrmError::StorageLayerError(e.into()))?;- // Look up the company for this (team, domain). The 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.+ // 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.+ let team_crm_enabled = sqlx::query_scalar!(+ r#"+ SELECT COALESCE(+ (SELECT crm_enabled FROM team_crm_settings WHERE team_id = $1),+ FALSE+ ) AS "crm_enabled!"+ "#,+ team_id,+ )+ .fetch_one(&mut *tx)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ if !team_crm_enabled {+ tx.commit()+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;+ 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.let existing = sqlx::query!(r#"SELECT c.id, c.email_syncdiff --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.rsindex b8ff9fa18b..c5e8623ea0 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@@ -9,9 +9,11 @@ use models_email::email::service::pubsub::{DetailedError, FailureReason, Process/// 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. A killswitch row-/// (`crm_companies.email_sync = false` for the contact's domain) is also a-/// no-op — see [`crm::domain::companies_repo::CompaniesRepository::populate_contact`].+/// `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`].////// Company metadata (name, description, icon) is resolved and cached/// inside `crm_service.populate_contact` via thediff --git a/rust/cloud-storage/macro_db_client/migrations/20260522130000_team_crm_settings.down.sql b/rust/cloud-storage/macro_db_client/migrations/20260522130000_team_crm_settings.down.sqlnew file mode 100644index 0000000000..deb530fa7a--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260522130000_team_crm_settings.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS team_crm_settings;diff --git a/rust/cloud-storage/macro_db_client/migrations/20260522130000_team_crm_settings.up.sql b/rust/cloud-storage/macro_db_client/migrations/20260522130000_team_crm_settings.up.sqlnew file mode 100644index 0000000000..895b9e2161--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260522130000_team_crm_settings.up.sql@@ -0,0 +1,7 @@+CREATE TABLE IF NOT EXISTS team_crm_settings+(+ team_id UUID PRIMARY KEY NOT NULL REFERENCES team (id) ON DELETE CASCADE,+ crm_enabled BOOLEAN NOT NULL DEFAULT FALSE,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);diff --git a/rust/cloud-storage/teams/src/domain.rs b/rust/cloud-storage/teams/src/domain.rsindex 8cea096395..d53574023b 100644--- a/rust/cloud-storage/teams/src/domain.rs+++ b/rust/cloud-storage/teams/src/domain.rs@@ -1,5 +1,6 @@pub mod crm_enqueuer;pub mod customer_repo;pub mod model;+pub mod team_crm_settings_repo;pub mod team_repo;pub mod team_service;diff --git a/rust/cloud-storage/teams/src/domain/model.rs b/rust/cloud-storage/teams/src/domain/model.rsindex e1670f54ad..eae37bea9d 100644--- a/rust/cloud-storage/teams/src/domain/model.rs+++ b/rust/cloud-storage/teams/src/domain/model.rs@@ -121,6 +121,34 @@ pub struct TeamMembers {pub invited: Vec<TeamInviteDetails>,}+/// Request body for `PATCH /team/crm`.+#[derive(Debug, Clone, serde::Deserialize)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+pub struct PatchTeamCrmSettingsRequest {+ /// The desired CRM state for the team.+ pub enabled: bool,+}++/// Response for `PATCH /team/crm`. Reports both the resulting state+/// and whether this call changed it; for the enable-flip case it also+/// reports the backfill fan-out tallies.+#[derive(Debug, Clone, serde::Serialize)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+pub struct PatchTeamCrmSettingsResponse {+ /// The resulting `crm_enabled` value after the call.+ pub enabled: bool,+ /// True if this call flipped the value (false → true or true →+ /// false). False if the team was already at the requested state.+ pub changed: bool,+ /// Number of members for whom a `PopulateCrmForUser` message was+ /// enqueued. Non-zero only on a disabled → enabled transition;+ /// per-user enqueue failures are logged and swallowed.+ pub backfill_enqueued: usize,+ /// Number of members whose enqueue failed (and was swallowed).+ /// Non-zero only on a disabled → enabled transition.+ pub backfill_failed: usize,+}+/// Detailed information about a team invite#[derive(Debug, Clone, serde::Serialize)]#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]diff --git a/rust/cloud-storage/teams/src/domain/team_crm_settings_repo.rs b/rust/cloud-storage/teams/src/domain/team_crm_settings_repo.rsnew file mode 100644index 0000000000..1b73ec21df--- /dev/null+++ b/rust/cloud-storage/teams/src/domain/team_crm_settings_repo.rs@@ -0,0 +1,59 @@+//! Outbound port for the `team_crm_settings` table and the bulk+//! teardown of a team's CRM data.+//!+//! CRM data (`crm_companies` and the cascading `crm_domains` /+//! `crm_contacts` / `crm_contact_sources` rows) is owned by macrodb,+//! same as `team_crm_settings`. We expose both behind a single port so+//! the disable flow can flip the flag and drop the data atomically in+//! one transaction.++use crate::domain::model::TeamError;++/// Repository for team-level CRM enable/disable state.+pub trait TeamCrmSettingsRepository: Clone + Send + Sync + 'static {+ /// Returns the current `crm_enabled` state for the team, or `false`+ /// if no row exists yet (the default).+ fn get_crm_enabled(+ &self,+ team_id: &uuid::Uuid,+ ) -> impl Future<Output = Result<bool, TeamError>> + Send;++ /// Upserts `crm_enabled = true` for the team. Returns `true` if+ /// this call flipped the value (previously absent or `false`), or+ /// `false` if it was already `true` (in which case the caller+ /// should skip the backfill fan-out).+ fn enable_crm(+ &self,+ team_id: &uuid::Uuid,+ ) -> impl Future<Output = Result<bool, TeamError>> + Send;++ /// Atomically upserts `crm_enabled = false` for the team and+ /// deletes every `crm_companies` row owned by the team. The FK+ /// cascade from `crm_companies` clears `crm_domains`,+ /// `crm_contacts`, and `crm_contact_sources`. Idempotent — safe to+ /// call when already disabled (the DELETE just affects zero rows).+ fn disable_crm_and_purge_data(+ &self,+ team_id: &uuid::Uuid,+ ) -> impl Future<Output = Result<(), TeamError>> + Send;+}++/// No-op repository for tests/callers that don't exercise CRM+/// settings. Reports CRM as disabled and treats every mutation as a+/// success without recording state.+#[derive(Clone, Debug, Default)]+pub struct NoOpTeamCrmSettingsRepository;++impl TeamCrmSettingsRepository for NoOpTeamCrmSettingsRepository {+ async fn get_crm_enabled(&self, _team_id: &uuid::Uuid) -> Result<bool, TeamError> {+ Ok(false)+ }++ async fn enable_crm(&self, _team_id: &uuid::Uuid) -> Result<bool, TeamError> {+ Ok(true)+ }++ async fn disable_crm_and_purge_data(&self, _team_id: &uuid::Uuid) -> Result<(), TeamError> {+ Ok(())+ }+}diff --git a/rust/cloud-storage/teams/src/domain/team_repo.rs b/rust/cloud-storage/teams/src/domain/team_repo.rsindex e92efef31e..54e73fd9db 100644--- a/rust/cloud-storage/teams/src/domain/team_repo.rs+++ b/rust/cloud-storage/teams/src/domain/team_repo.rs@@ -9,7 +9,7 @@ use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStruse crate::domain::model::{AcceptedTeamInvite, CreateTeamError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError,- PatchTeamRequest, RemoveTeamInviteError, RemoveUserFromTeamError,+ PatchTeamCrmSettingsResponse, PatchTeamRequest, RemoveTeamInviteError, RemoveUserFromTeamError,RestorePermissionsForTeamMembersError, RevokePermissionsForTeamMembersError, Team, TeamError,TeamInvite, TeamInviteDetails, TeamMember, TeamMembers, TeamPlan, TeamRole, TeamWithMembers,};@@ -315,7 +315,7 @@ pub trait TeamService: Clone + Send + Sync + 'static {/// Restores permissions for all team members./// This is used when a team subscription becomes active again.- /// NOTE: this is not exposed via axum and is meant for internal usage within stripe webhook only.+ /// NOTE: this is not exposed via axum and is meant for internal usage within stripe webhook only.fn restore_permissions_for_team_members(&self,team_id: &uuid::Uuid,@@ -359,4 +359,16 @@ pub trait TeamService: Clone + Send + Sync + 'static {) -> impl Future<Output = Result<HashSet<roles_and_permissions::domain::model::PermissionId>, TeamError>,> + Send;++ /// Enables or disables CRM for a team. On a `false → true`+ /// transition, fans out a `PopulateCrmForUser` enqueue per current+ /// team member (best-effort, log-and-swallow). On any disable call,+ /// flips the flag and purges the team's `crm_companies` rows in a+ /// single transaction — the FK cascade clears the rest of the CRM+ /// tables. Idempotent in both directions.+ fn set_team_crm_enabled(+ &self,+ entity_access_receipt: EntityAccessReceipt<AdminTeamRole>,+ enabled: bool,+ ) -> impl Future<Output = Result<PatchTeamCrmSettingsResponse, TeamError>> + Send;}diff --git a/rust/cloud-storage/teams/src/domain/team_service.rs b/rust/cloud-storage/teams/src/domain/team_service.rsindex fa017bcd4a..76e2fcaeb6 100644--- a/rust/cloud-storage/teams/src/domain/team_service.rs+++ b/rust/cloud-storage/teams/src/domain/team_service.rs@@ -26,17 +26,18 @@ use crate::domain::{customer_repo::CustomerRepository,model::{CreateTeamError, CustomerError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError,- PatchTeamRequest, RemoveTeamInviteError, RemoveUserFromTeamError,- RestorePermissionsForTeamMembersError, RevokePermissionsForTeamMembersError, Team,- TeamError, TeamInvite, TeamInviteDetails, TeamMember, TeamMembers, TeamRole,- TeamWithMembers,+ PatchTeamCrmSettingsResponse, PatchTeamRequest, RemoveTeamInviteError,+ RemoveUserFromTeamError, RestorePermissionsForTeamMembersError,+ RevokePermissionsForTeamMembersError, Team, TeamError, TeamInvite, TeamInviteDetails,+ TeamMember, TeamMembers, TeamRole, TeamWithMembers,},+ team_crm_settings_repo::TeamCrmSettingsRepository,team_repo::{TeamChannelsRepository, TeamMembersService, TeamRepository, TeamService},};/// Implementation of the TeamService using a TeamRepository#[derive(Debug)]-pub struct TeamServiceImpl<TR, CR, TCR, URPS, NI, CE>+pub struct TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS>whereTR: TeamRepository,CR: CustomerRepository,@@ -44,6 +45,7 @@ whereURPS: UserRolesAndPermissionsService,NI: NotificationIngress,CE: CrmEnqueuer,+ TCRMS: TeamCrmSettingsRepository,{/// The underlying team repositoryteam_repository: TR,@@ -59,9 +61,12 @@ where/// fired from `create_team` / `join_team` / `remove_user_from_team`./// See [`CrmEnqueuer`].crm_enqueuer: CE,+ /// Repository for the `team_crm_settings` row and the bulk CRM+ /// teardown invoked from `set_team_crm_enabled`.+ team_crm_settings_repository: TCRMS,}-impl<TR, CR, TCR, URPS, NI, CE> Clone for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE>+impl<TR, CR, TCR, URPS, NI, CE, TCRMS> Clone for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS>whereTR: TeamRepository,CR: CustomerRepository,@@ -69,6 +74,7 @@ whereURPS: UserRolesAndPermissionsService,NI: NotificationIngress,CE: CrmEnqueuer,+ TCRMS: TeamCrmSettingsRepository,{fn clone(&self) -> Self {Self {@@ -78,11 +84,12 @@ whereuser_roles_and_permissions_service: self.user_roles_and_permissions_service.clone(),notification_ingress: self.notification_ingress.clone(),crm_enqueuer: self.crm_enqueuer.clone(),+ team_crm_settings_repository: self.team_crm_settings_repository.clone(),}}}-impl<TR, CR, TCR, URPS, NI, CE> TeamServiceImpl<TR, CR, TCR, URPS, NI, CE>+impl<TR, CR, TCR, URPS, NI, CE, TCRMS> TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS>whereTR: TeamRepository,CR: CustomerRepository,@@ -90,6 +97,7 @@ whereURPS: UserRolesAndPermissionsService,NI: NotificationIngress,CE: CrmEnqueuer,+ TCRMS: TeamCrmSettingsRepository,{/// Creates a new TeamServicepub fn new(@@ -99,6 +107,7 @@ whereuser_roles_and_permissions_service: URPS,notification_ingress: Arc<NI>,crm_enqueuer: CE,+ team_crm_settings_repository: TCRMS,) -> Self {Self {team_repository,@@ -107,11 +116,12 @@ whereuser_roles_and_permissions_service,notification_ingress,crm_enqueuer,+ team_crm_settings_repository,}}}-impl<TR, CR, TCR, URPS, NI, CE> TeamServiceImpl<TR, CR, TCR, URPS, NI, CE>+impl<TR, CR, TCR, URPS, NI, CE, TCRMS> TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS>whereTR: TeamRepository,CR: CustomerRepository,@@ -119,6 +129,7 @@ whereURPS: UserRolesAndPermissionsService,NI: NotificationIngress,CE: CrmEnqueuer,+ TCRMS: TeamCrmSettingsRepository,{/// Gets the teams subscription id/// If the team doesn't have a subscription yet, it will convert the owners personal subscription into a team subscription@@ -231,7 +242,8 @@ impl GetTeamSubscriptionError {}}-impl<TR, CR, TCR, URPS, NI, CE> TeamMembersService for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE>+impl<TR, CR, TCR, URPS, NI, CE, TCRMS> TeamMembersService+ for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS>whereTR: TeamRepository,CR: CustomerRepository,@@ -239,6 +251,7 @@ whereURPS: UserRolesAndPermissionsService,NI: NotificationIngress,CE: CrmEnqueuer,+ TCRMS: TeamCrmSettingsRepository,{#[tracing::instrument(skip(self), err)]async fn list_team_members(@@ -255,7 +268,8 @@ where}}-impl<TR, CR, TCR, URPS, NI, CE> TeamService for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE>+impl<TR, CR, TCR, URPS, NI, CE, TCRMS> TeamService+ for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS>whereTR: TeamRepository,CR: CustomerRepository,@@ -263,6 +277,7 @@ whereURPS: UserRolesAndPermissionsService,NI: NotificationIngress,CE: CrmEnqueuer,+ TCRMS: TeamCrmSettingsRepository,{#[tracing::instrument(skip(self), err)]async fn create_team(@@ -270,27 +285,12 @@ whereuser_id: &MacroUserIdStr<'_>,team_name: &str,) -> Result<Team, CreateTeamError> {- let team = self.team_repository.create_team(user_id, team_name).await?;-- // Best-effort: ask the email service to seed CRM tables from this- // user's historical sent mail. Log and swallow failures — the team- // is already committed and the email-service consumer is idempotent,- // so a missed enqueue can be retried (or covered by per-message CRM- // fan-out) without leaving the system in an inconsistent state.- if let Err(e) = self- .crm_enqueuer- .enqueue_populate_crm_for_user(user_id)- .await- {- tracing::error!(- error = ?e,- team_id = %team.id,- macro_id = %user_id,- "Failed to enqueue PopulateCrmForUser after create_team; CRM tables will not be seeded from sent-mail history (per-message fan-out will still cover future sends)"- );- }-- Ok(team)+ // New teams start with `team_crm_settings.crm_enabled = false`+ // (seeded by `team_repository.create_team`), so there's nothing+ // for the email-backfill fan-out to populate yet. The fan-out+ // happens later, on the disabled → enabled transition in+ // `set_team_crm_enabled`.+ self.team_repository.create_team(user_id, team_name).await}#[tracing::instrument(skip(self), err)]@@ -873,4 +873,82 @@ where.await.map_err(|e| TeamError::StorageLayerError(e.into()))}++ #[tracing::instrument(skip(self), err)]+ async fn set_team_crm_enabled(+ &self,+ entity_access_receipt: EntityAccessReceipt<AdminTeamRole>,+ enabled: bool,+ ) -> Result<PatchTeamCrmSettingsResponse, TeamError> {+ let team_id =+ macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();++ if enabled {+ // Fetch the members *before* flipping the flag so a member-list+ // failure leaves the flag untouched — a retry will then re-run+ // the full backfill instead of hitting the early-return below.+ let members = self.team_repository.get_team_members(&team_id).await?;++ let changed = self+ .team_crm_settings_repository+ .enable_crm(&team_id)+ .await?;++ if !changed {+ return Ok(PatchTeamCrmSettingsResponse {+ enabled: true,+ changed: false,+ backfill_enqueued: 0,+ backfill_failed: 0,+ });+ }++ let mut enqueued = 0usize;+ let mut failed = 0usize;++ for member in members {+ match self+ .crm_enqueuer+ .enqueue_populate_crm_for_user(&member.user_id)+ .await+ {+ Ok(()) => enqueued += 1,+ Err(e) => {+ failed += 1;+ tracing::error!(+ error = ?e,+ team_id = %team_id,+ macro_id = %member.user_id,+ "Failed to enqueue PopulateCrmForUser during team CRM enable"+ );+ }+ }+ }++ Ok(PatchTeamCrmSettingsResponse {+ enabled: true,+ changed: true,+ backfill_enqueued: enqueued,+ backfill_failed: failed,+ })+ } else {+ let was_enabled = self+ .team_crm_settings_repository+ .get_crm_enabled(&team_id)+ .await?;++ // Run the disable+purge unconditionally so a stale row left+ // over from a prior failed disable still gets cleaned up.+ self.team_crm_settings_repository+ .disable_crm_and_purge_data(&team_id)+ .await?;++ Ok(PatchTeamCrmSettingsResponse {+ enabled: false,+ changed: was_enabled,+ backfill_enqueued: 0,+ backfill_failed: 0,+ })+ }+ }}diff --git a/rust/cloud-storage/teams/src/domain/team_service/test.rs b/rust/cloud-storage/teams/src/domain/team_service/test.rsindex 7295a9690c..06713a3240 100644--- a/rust/cloud-storage/teams/src/domain/team_service/test.rs+++ b/rust/cloud-storage/teams/src/domain/team_service/test.rs@@ -20,7 +20,9 @@ use roles_and_permissions::domain::{port::UserRolesAndPermissionsService,};-use crate::domain::crm_enqueuer::NoOpCrmEnqueuer;+use crate::domain::{+ crm_enqueuer::NoOpCrmEnqueuer, team_crm_settings_repo::NoOpTeamCrmSettingsRepository,+};fn test_team_receipt<T: RequiredPermission>(team_id: uuid::Uuid,@@ -706,6 +708,7 @@ fn build_service(MockUserRolesAndPermissionsService::default(),notification_ingress.clone(),NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,);(service, notification_ingress)}@@ -865,6 +868,7 @@ fn build_service_with_team(MockUserRolesAndPermissionsService::default(),notification_ingress,NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,);(service, role_calls, name_calls)}@@ -1064,6 +1068,7 @@ async fn test_join_team_increments_customer_seat_count() {roles_service,Arc::new(MockNotificationIngress::new(HashSet::new())),NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,);service.join_team(&invite_id, &user_id).await.unwrap();@@ -1112,6 +1117,7 @@ async fn test_join_team_rolls_back_accept_when_customer_increment_fails() {roles_service,Arc::new(MockNotificationIngress::new(HashSet::new())),NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,);let err = service.join_team(&invite_id, &user_id).await.err().unwrap();@@ -1162,6 +1168,7 @@ async fn test_remove_user_from_team_decrements_customer_seat_count() {roles_service,Arc::new(MockNotificationIngress::new(HashSet::new())),NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,);service@@ -1220,6 +1227,7 @@ async fn test_remove_user_from_team_rolls_back_remove_when_customer_decrement_faroles_service,Arc::new(MockNotificationIngress::new(HashSet::new())),NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,);let err = service@@ -1275,6 +1283,7 @@ async fn test_join_team_rolls_back_customer_roles_and_accept_when_channel_add_faroles_service,Arc::new(MockNotificationIngress::new(HashSet::new())),NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,);let err = service.join_team(&invite_id, &user_id).await.err().unwrap();@@ -1330,6 +1339,7 @@ async fn test_remove_user_from_team_rolls_back_customer_and_remove_when_channel_roles_service,Arc::new(MockNotificationIngress::new(HashSet::new())),NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,);let err = servicediff --git a/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs b/rust/cloud-storage/teams/src/inbound/axum_router/mod.rsindex c623c6b685..f04224447f 100644--- a/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs+++ b/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs@@ -20,6 +20,8 @@ pub mod invite_to_team;pub mod join_team;/// Update a team.pub mod patch_team;+/// Enable / disable CRM for a team.+pub mod patch_team_crm_settings;/// Reject a team invitation.pub mod reject_invitation;/// Remove a user from a team.@@ -87,6 +89,7 @@ where.route("/", get(get_team::handler::<T, Eas>)).route("/", patch(patch_team::handler::<T, Eas>)).route("/", delete(delete_team::handler::<T, Eas>))+ .route("/crm", patch(patch_team_crm_settings::handler::<T, Eas>)).route("/invites", get(get_team_invites::handler::<T, Eas>)).route("/invite", post(invite_to_team::handler::<T, Eas>)).route(diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/patch_team_crm_settings.rs b/rust/cloud-storage/teams/src/inbound/axum_router/patch_team_crm_settings.rsnew file mode 100644index 0000000000..dec5405d3a--- /dev/null+++ b/rust/cloud-storage/teams/src/inbound/axum_router/patch_team_crm_settings.rs@@ -0,0 +1,47 @@+use axum::{Json, extract::State};+use entity_access::{+ domain::{models::AdminTeamRole, ports::EntityAccessService},+ inbound::axum_extractors::MacroUserTeamExtractor,+};+use model_error_response::ErrorResponse;++use crate::domain::{+ model::{PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, TeamError},+ team_repo::TeamService,+};++use super::TeamRouterState;++/// Enables or disables CRM for the team. On enable, kicks off a+/// best-effort backfill that enqueues a `PopulateCrmForUser` message+/// per team member (no-op if CRM is already enabled). On disable,+/// flips the flag and purges the team's CRM data (cascading through+/// `crm_companies` → `crm_domains` / `crm_contacts` /+/// `crm_contact_sources`). Requires the caller to be an Admin or+/// Owner of the team.+#[utoipa::path(+ patch,+ path = "/team/crm",+ operation_id = "patch_team_crm_settings",+ request_body = PatchTeamCrmSettingsRequest,+ responses(+ (status = 200, body = PatchTeamCrmSettingsResponse),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 403, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ ),+)]+#[tracing::instrument(skip_all, err)]+pub async fn handler<T: TeamService, Eas: EntityAccessService>(+ access: MacroUserTeamExtractor<AdminTeamRole, Eas>,+ State(state): State<TeamRouterState<T, Eas>>,+ Json(req): Json<PatchTeamCrmSettingsRequest>,+) -> Result<Json<PatchTeamCrmSettingsResponse>, TeamError> {+ let response = state+ .service+ .set_team_crm_enabled(access.entity_access_receipt, req.enabled)+ .await?;+ Ok(Json(response))+}diff --git a/rust/cloud-storage/teams/src/outbound.rs b/rust/cloud-storage/teams/src/outbound.rsindex 5a7f07bd86..42006c938d 100644--- a/rust/cloud-storage/teams/src/outbound.rs+++ b/rust/cloud-storage/teams/src/outbound.rs@@ -1,4 +1,5 @@pub mod crm_enqueuer;pub mod customer_repo;pub mod team_channels_repo;+pub mod team_crm_settings_repo;pub mod team_repo;diff --git a/rust/cloud-storage/teams/src/outbound/team_crm_settings_repo.rs b/rust/cloud-storage/teams/src/outbound/team_crm_settings_repo.rsnew file mode 100644index 0000000000..0e84cb7b74--- /dev/null+++ b/rust/cloud-storage/teams/src/outbound/team_crm_settings_repo.rs@@ -0,0 +1,93 @@+//! MacroDB-backed adapter for+//! [`crate::domain::team_crm_settings_repo::TeamCrmSettingsRepository`].+//!+//! Owns the `team_crm_settings` row for each team and the bulk+//! teardown of `crm_companies` (with FK cascade) when CRM is disabled.++use crate::domain::{model::TeamError, team_crm_settings_repo::TeamCrmSettingsRepository};+use sqlx::PgPool;++/// Macrodb-backed [`TeamCrmSettingsRepository`].+#[derive(Clone, Debug)]+pub struct TeamCrmSettingsRepositoryImpl {+ pool: PgPool,+}++impl TeamCrmSettingsRepositoryImpl {+ /// Creates a new repository wrapping the given macrodb pool.+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }+}++impl TeamCrmSettingsRepository for TeamCrmSettingsRepositoryImpl {+ #[tracing::instrument(skip(self), err)]+ async fn get_crm_enabled(&self, team_id: &uuid::Uuid) -> Result<bool, TeamError> {+ let enabled = sqlx::query_scalar!(+ r#"SELECT crm_enabled FROM team_crm_settings WHERE team_id = $1"#,+ team_id,+ )+ .fetch_optional(&self.pool)+ .await?;++ Ok(enabled.unwrap_or(false))+ }++ #[tracing::instrument(skip(self), err)]+ async fn enable_crm(&self, team_id: &uuid::Uuid) -> Result<bool, TeamError> {+ // Upsert with a `DO UPDATE WHERE … IS DISTINCT FROM …` clause so+ // only one caller actually flips false → true. ON CONFLICT+ // serializes concurrent INSERTs on the same `team_id` via the PK+ // row lock; whichever transaction wins the lock first runs its+ // UPDATE (matched by the WHERE), later callers see the row+ // already at TRUE and the UPDATE is skipped. The CTE returns a+ // row only when an INSERT or matched-UPDATE happened, so+ // `EXISTS(...)` is true iff this call caused the state change.+ let changed = sqlx::query_scalar!(+ r#"+ WITH upsert AS (+ INSERT INTO team_crm_settings (team_id, crm_enabled)+ VALUES ($1, TRUE)+ ON CONFLICT (team_id) DO UPDATE+ SET crm_enabled = EXCLUDED.crm_enabled,+ updated_at = now()+ WHERE team_crm_settings.crm_enabled IS DISTINCT FROM EXCLUDED.crm_enabled+ RETURNING 1+ )+ SELECT EXISTS (SELECT 1 FROM upsert) AS "changed!"+ "#,+ team_id,+ )+ .fetch_one(&self.pool)+ .await?;++ Ok(changed)+ }++ #[tracing::instrument(skip(self), err)]+ async fn disable_crm_and_purge_data(&self, team_id: &uuid::Uuid) -> Result<(), TeamError> {+ let mut tx = self.pool.begin().await?;++ sqlx::query!(+ r#"+ INSERT INTO team_crm_settings (team_id, crm_enabled)+ VALUES ($1, FALSE)+ ON CONFLICT (team_id) DO UPDATE+ SET crm_enabled = FALSE,+ updated_at = now()+ "#,+ team_id,+ )+ .execute(&mut *tx)+ .await?;++ // FK cascade clears crm_domains / crm_contacts /+ // crm_contact_sources owned by these companies.+ sqlx::query!(r#"DELETE FROM crm_companies WHERE team_id = $1"#, team_id,)+ .execute(&mut *tx)+ .await?;++ tx.commit().await?;+ Ok(())+ }+}diff --git a/rust/cloud-storage/teams/src/outbound/team_repo.rs b/rust/cloud-storage/teams/src/outbound/team_repo.rsindex a2f2826530..df461e2096 100644--- a/rust/cloud-storage/teams/src/outbound/team_repo.rs+++ b/rust/cloud-storage/teams/src/outbound/team_repo.rs@@ -174,6 +174,20 @@ impl TeamRepositoryImpl {.execute(&mut *transaction).await?;+ // Seed the team's CRM settings row. `crm_enabled` defaults to+ // FALSE — toggled on later via `PATCH /team/crm`. Created in+ // the same tx as the team itself so the row always exists for+ // any team that exists.+ sqlx::query!(+ r#"+ INSERT INTO team_crm_settings (team_id)+ VALUES ($1)+ "#,+ &team.id,+ )+ .execute(&mut *transaction)+ .await?;+transaction.commit().await?;Ok(team)