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.

33.4 KB
Raw Blame
//! Port for persistence operations on CRM companies.

use crate::domain::model::{
    CrmBlockedDomain, CrmCompanyForSoup, CrmCompanyWithContacts, CrmContact, CrmError,
    CrmScopePrecheck, CrmTeamSettings, CrmTeamSettingsPatch, DepopulateContactOutcome,
    DomainMetadata,
};
use chrono::{DateTime, Utc};

/// Sort order for [`CompaniesRepository::list_companies_for_soup`]. All
/// variants tiebreak on `id DESC` for deterministic pagination. The two
/// `Viewed*` variants require a `user_id` (the `UserHistory` join is
/// per-user); rows the user has never opened sort to NULL (`ViewedAt`
/// drops them to the bottom; `ViewedUpdated` falls back to
/// `last_interaction`).
#[derive(Debug, Clone, Copy)]
pub enum CrmCompanyListSort {
    /// Sort by `crm_companies.last_interaction` DESC.
    UpdatedAt,
    /// Sort by `crm_companies.first_interaction` DESC.
    CreatedAt,
    /// Sort by the user's `UserHistory."updatedAt"` DESC (when this user
    /// last opened the company). Unviewed rows sort to NULL (bottom).
    ViewedAt,
    /// Sort by `COALESCE(UserHistory."updatedAt", last_interaction)` DESC
    /// — recently viewed bubble up, with a graceful fallback to
    /// activity recency for unviewed rows.
    ViewedUpdated,
}

/// Keyset cursor for [`CompaniesRepository::list_companies_for_soup`].
/// Carries the sort timestamp + id of the previous soup page's last row
/// so the next page seeks strictly past it. `None` = first page.
#[derive(Debug, Clone, Copy)]
pub struct CrmCompanySoupCursor {
    /// Sort timestamp of the previous page's last row, expressed in the
    /// sort method's units: `first_interaction` for `CreatedAt`,
    /// `last_interaction` for `UpdatedAt`, `UserHistory."updatedAt"` for
    /// `ViewedAt`, and `COALESCE(uh."updatedAt", last_interaction)` for
    /// `ViewedUpdated`.
    pub last_sort_ts: DateTime<Utc>,
    /// Id of the previous page's last row; tiebreaks equal timestamps.
    pub last_id: uuid::Uuid,
}

/// The CompaniesRepository defines persistence operations for CRM
/// companies and their associated domains.
pub trait CompaniesRepository: Clone + Send + Sync + 'static {
    /// List authorized contacts across enabled teams. Apply visibility and
    /// predicates before choosing one record per lowercased full email (latest
    /// interaction, then highest ID). Deduplicate before seeking/limiting. An
    /// ID-only filter is exact hydration and retains each requested record.
    fn list_contacts_for_soup(
        &self,
        scope: super::contact_listing::CrmContactListScope<'_>,
        viewer_id: &str,
        query: &super::contact_listing::CrmContactListQuery,
    ) -> impl Future<Output = Result<Vec<super::contact_listing::CrmContactForSoup>, CrmError>> + Send;

    /// Resolve `record` to the records its associated items match, under the
    /// same visibility as the scope's contact listings: CRM-enabled teams
    /// only, and hidden companies and contacts are visible only to the owning
    /// team's admins and owners. `None` when the record is not visible.
    fn resolve_association(
        &self,
        scope: super::contact_listing::CrmContactListScope<'_>,
        record: super::association::CrmAssociation,
    ) -> impl Future<Output = Result<Option<super::association::CrmRecordAssociation>, CrmError>> + Send;

    /// Resolve the complete activity scope with no contact email deduplication.
    /// Membership and CRM settings gate rows; hidden records never participate.
    fn resolve_activity(
        &self,
        scope: super::contact_listing::CrmContactListScope<'_>,
    ) -> impl Future<Output = Result<super::association::CrmRecordAssociation, CrmError>> + Send;

    /// Idempotently records that `email` (which lives on `domain`) was seen
    /// from the mailbox identified by `link_id`, for the team `team_id`.
    /// 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 it is reused and its `updated_at` is
    ///      refreshed. Populate runs regardless of the company's
    ///      `email_sync` — that flag is purely a visibility/permission
    ///      gate consumed at read time (soup, email permissions). The
    ///      decoupling means re-enabling sync exposes the full history
    ///      with no backfill, because the writes never stopped.
    ///    - Otherwise a new `crm_companies` row and a matching
    ///      `crm_domains` row are inserted. The company name itself
    ///      lives in `crm_domain_directory` keyed by `domain`, not on
    ///      `crm_companies` — see [`lookup_domain_metadata`] /
    ///      [`upsert_domain_metadata`].
    /// 2. Upsert `crm_contacts (company_id, email, name)`, refreshing
    ///    `updated_at` on existing contacts while preserving the first
    ///    non-NULL name with `name = COALESCE(crm_contacts.name, EXCLUDED.name)`.
    /// 3. Upsert `crm_contact_sources (contact_id, link_id)` with
    ///    `ON CONFLICT DO NOTHING`.
    ///
    /// `domain` and `email` are both normalized to lowercase before storage
    /// and comparison. `name` is the display name observed for `email` on
    /// 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`.
    /// - **Blocked domain**: no-op when the domain is on the team's
    ///   blocklist ([`CompaniesRepository::block_domain`]).
    /// - **`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`.
    ///
    /// 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 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,
        link_id: &uuid::Uuid,
        domain: &str,
        email: &str,
        name: Option<&str>,
        first_at: DateTime<Utc>,
        last_at: DateTime<Utc>,
        is_sent: bool,
    ) -> impl Future<Output = Result<(), CrmError>> + Send;

    /// Files a personal-provider address (gmail.com etc.) as a contact
    /// without a company, the counterpart of [`populate_contact`] for
    /// domains no company may own. In one transaction, under the same
    /// per-`(team, lower(domain))` advisory lock:
    ///
    /// 1. No-ops when the team's CRM is off, the team keeps personal
    ///    emails out (`exclude_personal_emails`, the default), or the
    ///    domain is on the team's blocklist.
    /// 2. `is_sent = true` upserts the company-less contact for
    ///    `(team, lower(email))`, merging interactions like
    ///    [`populate_contact`]; `is_sent = false` only refreshes an
    ///    existing one (received mail never creates a contact).
    /// 3. Records the `crm_contact_sources` row for `link_id`.
    ///
    /// [`populate_contact`]: CompaniesRepository::populate_contact
    #[expect(
        clippy::too_many_arguments,
        reason = "mirrors populate_contact's inputs"
    )]
    fn populate_unfiled_contact(
        &self,
        team_id: &uuid::Uuid,
        link_id: &uuid::Uuid,
        domain: &str,
        email: &str,
        name: Option<&str>,
        first_at: DateTime<Utc>,
        last_at: DateTime<Utc>,
        is_sent: bool,
    ) -> impl Future<Output = Result<(), CrmError>> + Send;

    /// Manually creates a contact for `team_id` without a company, with
    /// a display `name` and an optional `email` (any domain). Returns
    /// [`CrmError::CrmDisabledForTeam`] when the team's CRM is off and
    /// [`CrmError::ContactAlreadyExistsForCompany`] when the team
    /// already has a company-less contact for the email. The row is
    /// `manually_created`, so link teardown never deletes it.
    fn create_contact_for_team(
        &self,
        team_id: &uuid::Uuid,
        email: Option<&str>,
        name: &str,
        now: DateTime<Utc>,
    ) -> impl Future<Output = Result<CrmContact, CrmError>> + Send;

    /// The domains `team_id` keeps out of email sync, alphabetically.
    fn list_blocked_domains(
        &self,
        team_id: &uuid::Uuid,
    ) -> impl Future<Output = Result<Vec<CrmBlockedDomain>, CrmError>> + Send;

    /// Adds `domain` (lowercase) to `team_id`'s blocklist and hides what
    /// the CRM already holds for it: the company owning the domain with
    /// its contacts, and company-less contacts at the domain.
    /// Idempotent.
    fn block_domain(
        &self,
        team_id: &uuid::Uuid,
        domain: &str,
    ) -> impl Future<Output = Result<(), CrmError>> + Send;

    /// Removes `domain` (lowercase) from `team_id`'s blocklist and
    /// un-hides what [`CompaniesRepository::block_domain`] hid.
    /// Idempotent.
    fn unblock_domain(
        &self,
        team_id: &uuid::Uuid,
        domain: &str,
    ) -> impl Future<Output = Result<(), CrmError>> + Send;

    /// Creates a team-owned company by name, optionally with a domain.
    /// Enforces the CRM killswitch, serializes domain creation with populate,
    /// and returns [`CrmError::CompanyAlreadyExistsForTeam`] for a domain
    /// already tracked by the team. Without a domain, creates no directory or
    /// domain rows. Names need not be unique. The caller validates inputs and
    /// ensures directory metadata for any supplied domain.
    ///
    /// Stores the team's name override and manual-creation marker, seeding
    /// interaction timestamps from `now`, then hydrates through
    /// [`Self::get_company_for_team`].
    fn create_company_for_team(
        &self,
        team_id: &uuid::Uuid,
        domain: Option<&str>,
        name: &str,
        now: DateTime<Utc>,
    ) -> impl Future<Output = Result<CrmCompanyWithContacts, CrmError>> + Send;

    /// Manually creates a contact under `company_id` (scoped to
    /// `team_id`) with a display `name` and an optional `email`. In a single
    /// transaction:
    ///
    /// 1. Reads the team killswitch; returns
    ///    [`CrmError::CrmDisabledForTeam`] when off.
    /// 2. Locks the company row (`FOR UPDATE`, serializing with the
    ///    hide/un-hide contact cascade) and scopes it to `team_id`.
    ///    Missing, cross-team, or — for `include_hidden = false`
    ///    (member) callers — hidden companies return
    ///    [`CrmError::CompanyNotFoundForTeam`].
    /// 3. Inserts the `crm_contacts` row, inheriting the company's
    ///    current `hidden` (an admin adding a contact to a hidden
    ///    company gets a hidden contact, matching populate's
    ///    inheritance). Returns
    ///    [`CrmError::ContactAlreadyExistsForCompany`] when the company
    ///    already has a contact for the email.
    ///
    /// `email` is normalized to lowercase before storage. Both
    /// interaction endpoints seed from `now`; later populates for the
    /// same `(company, email)` merge real timestamps via LEAST/GREATEST
    /// and keep the manual `name` (first non-NULL name wins).
    ///
    /// The row is stamped `manually_created = TRUE` so the depopulate
    /// orphan cleanup ([`depopulate_contact`] /
    /// [`depopulate_link_in_team`]) never deletes it — manual contacts
    /// have no `crm_contact_sources` rows and would otherwise be
    /// indistinguishable from derived-data orphans.
    ///
    /// [`depopulate_contact`]: CompaniesRepository::depopulate_contact
    /// [`depopulate_link_in_team`]: CompaniesRepository::depopulate_link_in_team
    fn create_contact_for_company(
        &self,
        team_id: &uuid::Uuid,
        company_id: &uuid::Uuid,
        email: Option<&str>,
        name: &str,
        now: DateTime<Utc>,
        include_hidden: bool,
    ) -> impl Future<Output = Result<CrmContact, CrmError>> + Send;

    /// Read the cached [`DomainMetadata`] for `domain` from
    /// `crm_domain_directory`, if any. `domain` is matched
    /// case-insensitively. Returns `Ok(None)` when no row exists for
    /// the domain — the caller is expected to resolve via
    /// [`crate::domain::company_metadata_resolver::CompanyMetadataResolver`]
    /// and then [`upsert_domain_metadata`] (or, when the resolver is
    /// unavailable, [`insert_pending_domain`]) before retrying.
    ///
    /// `Some(DomainMetadata { name: None, ... })` is distinct from
    /// `None`: the domain already has an entry, either resolved to
    /// nothing useful (the negative cache) or still pending for the
    /// enrichment worker. Either way callers don't resolve it inline.
    ///
    /// [`upsert_domain_metadata`]: CompaniesRepository::upsert_domain_metadata
    /// [`insert_pending_domain`]: CompaniesRepository::insert_pending_domain
    fn lookup_domain_metadata(
        &self,
        domain: &str,
    ) -> impl Future<Output = Result<Option<DomainMetadata>, CrmError>> + Send;

    /// Store resolved `metadata` for `domain` in `crm_domain_directory`
    /// and stamp it resolved. The directory is a global cache: a
    /// resolved row (whether populated or all-NULL) is first-write-wins
    /// and preserved as-is; a pending row is filled in. `domain` is
    /// lower-cased before storage.
    ///
    /// Idempotent under concurrent calls — racing producers can both
    /// resolve the same domain and both call this method; the second
    /// is a no-op.
    fn upsert_domain_metadata(
        &self,
        domain: &str,
        metadata: &DomainMetadata,
    ) -> impl Future<Output = Result<(), CrmError>> + Send;

    /// Insert a pending `crm_domain_directory` row for `domain` (no
    /// metadata, not resolved) unless the domain already has a row.
    /// Read paths treat it like a negative-cache row; the enrichment
    /// worker claims it through [`claim_pending_domains`].
    ///
    /// [`claim_pending_domains`]: CompaniesRepository::claim_pending_domains
    fn insert_pending_domain(
        &self,
        domain: &str,
    ) -> impl Future<Output = Result<(), CrmError>> + Send;

    /// Claim up to `limit` pending `crm_domain_directory` rows whose
    /// domain some team still tracks, with fewer than `max_attempts`
    /// enrichment attempts and no attempt since `attempted_before`.
    /// Claiming counts an attempt and stamps it now, so concurrent
    /// workers skip the claimed rows until `attempted_before` passes
    /// them. Returns the claimed domains.
    fn claim_pending_domains(
        &self,
        limit: i64,
        max_attempts: i16,
        attempted_before: DateTime<Utc>,
    ) -> impl Future<Output = Result<Vec<String>, CrmError>> + Send;

    /// Reverses [`populate_contact`] for one `(link_id, email)`: drops the
    /// matching `crm_contact_sources` row, then `crm_contacts` if no other
    /// source rows remain for that contact, then `crm_companies` (cascading
    /// to `crm_domains`) if no other contact rows remain for that company
    /// **and** the company has `email_sync = true`. Companies with
    /// `email_sync = false` are kept because that flag is an explicit
    /// team-side opt-out (the team turned off email sharing for this
    /// company) — preserving the row makes the choice survive a link
    /// teardown so a future populate doesn't re-discover the company
    /// in a "default sync = true" state.
    ///
    /// Source and contact rows are derived data and are always cleaned
    /// up regardless of the company's `email_sync` — except rows with
    /// `manually_created = TRUE` (user-created via
    /// [`create_contact_for_company`] / [`create_company_for_team`]),
    /// which are never deleted by this teardown.
    ///
    /// [`create_contact_for_company`]: CompaniesRepository::create_contact_for_company
    /// [`create_company_for_team`]: CompaniesRepository::create_company_for_team
    ///
    /// The whole cascade runs in a single transaction that begins by
    /// acquiring the same advisory lock [`populate_contact`] takes (key
    /// `"{team_id}:{lower(domain)}"`) **before** observing any state, so
    /// a concurrent in-flight populate for the same `(team_id, domain)`
    /// can't slip an uncommitted insert past the existence check.
    ///
    /// No-op when the contact / company / domain is not found for
    /// `(team_id, domain, email)`. `domain` and `email` are matched
    /// case-insensitively.
    ///
    /// Returns which rows the cascade actually deleted, so callers can tell
    /// a real teardown from a no-op — see [`DepopulateContactOutcome`].
    fn depopulate_contact(
        &self,
        team_id: &uuid::Uuid,
        link_id: &uuid::Uuid,
        domain: &str,
        email: &str,
    ) -> impl Future<Output = Result<DepopulateContactOutcome, CrmError>> + Send;

    /// Whether [`depopulate_contact`] would find a contact to act on for
    /// `(team_id, domain, email)`: the same lookup, under the same advisory
    /// lock, with nothing deleted. `false` means `depopulate_contact` is a
    /// no-op for every link in the team.
    fn has_depopulate_target(
        &self,
        team_id: &uuid::Uuid,
        domain: &str,
        email: &str,
    ) -> impl Future<Output = Result<bool, CrmError>> + Send;

    /// Filters `(link_id, email)` pairs down to those that currently have a
    /// `crm_contact_sources` row — i.e. the pairs where this link actually
    /// contributed something [`depopulate_contact`] would tear down.
    ///
    /// Exists so the nightly cleanup job can drop never-tracked contacts
    /// before fanning out a message per candidate: the candidate table is fed
    /// by every message deletion, but CRM only tracks a small subset of
    /// correspondents, so most candidates have nothing to remove.
    ///
    /// `email` is matched case-insensitively against `crm_contacts.email`.
    /// Returns the surviving pairs with their emails lowercased; input order
    /// is not preserved and unmatched pairs are simply absent.
    fn link_contact_pairs_with_sources(
        &self,
        pairs: &[(uuid::Uuid, String)],
    ) -> impl Future<Output = Result<Vec<(uuid::Uuid, String)>, CrmError>> + Send;

    /// Bulk counterpart to [`depopulate_contact`]: removes everything
    /// the link contributed to a single team's CRM rows. In one
    /// transaction:
    ///   1. Delete every `crm_contact_sources` row whose `link_id`
    ///      matches AND whose contact lives under `team_id`.
    ///   2. Delete every `crm_contacts` row in `team_id` that has no
    ///      remaining `crm_contact_sources` (orphaned by step 1 or by
    ///      any earlier cleanup race).
    ///   3. Delete every `crm_companies` row in `team_id` that has no
    ///      remaining `crm_contacts` AND `email_sync = true`. Companies
    ///      with `email_sync = false` are preserved so the team's
    ///      explicit "off" choice survives the link teardown.
    ///      `crm_domains` falls out via FK cascade.
    ///
    /// Scoping every query to `team_id` keeps the blast radius bounded
    /// — sources the link contributed to a *different* team (from a
    /// prior membership) are untouched — and lets the orphan cleanup
    /// run as a single SQL pass per layer instead of snapshotting
    /// candidate ids into memory first.
    ///
    /// Does NOT take per-`(team, domain)` advisory locks. A link can
    /// span many domains within a team, and a concurrent populate on
    /// the same team won't see the user as a member once the team
    /// membership change has propagated, so the race window is benign.
    ///
    /// Used by the `DepopulateCrmForUser` backfill step (fired when a
    /// user is removed from a team).
    fn depopulate_link_in_team(
        &self,
        team_id: &uuid::Uuid,
        link_id: &uuid::Uuid,
    ) -> impl Future<Output = Result<(), CrmError>> + Send;

    /// Returns the team id that `macro_id` belongs to. When the user is on
    /// multiple teams the highest-privileged role wins (Postgres orders the
    /// `team_role` enum as `member < admin < owner`), matching the
    /// behavior of `entity_access::ports::get_user_team`. Returns
    /// `Ok(None)` when the user has no team membership.
    fn get_team_id_for_user(
        &self,
        macro_id: &str,
    ) -> impl Future<Output = Result<Option<uuid::Uuid>, CrmError>> + Send;

    /// Toggle `crm_companies.email_sync` for `(company_id, team_id)`.
    /// The flag is purely a **visibility/permission gate** consumed at
    /// read time — soup queries and email-permission checks require
    /// `email_sync = true` before exposing emails team-wide. Populate
    /// runs regardless, so toggling this flag never destroys data and
    /// re-enabling never requires a backfill. Returns
    /// [`CrmError::CompanyNotFoundForTeam`] on a non-matching pair.
    /// Refuses to set `email_sync = true` when the company has
    /// `hidden = true` (returns [`CrmError::CompanyHidden`]) — keeps
    /// the "hide = full opt-out" UX (un-hide first if you really want
    /// sync back on).
    fn set_email_sync(
        &self,
        team_id: &uuid::Uuid,
        company_id: &uuid::Uuid,
        email_sync: bool,
    ) -> impl Future<Output = Result<(), CrmError>> + Send;

    /// Toggle `crm_companies.hidden` for `(company_id, team_id)`. The
    /// company's contacts cascade with the flag — hide soft-hides every
    /// `crm_contacts` row (`hidden = TRUE`) and un-hide restores them
    /// (`hidden = FALSE`). Contact data and `crm_contact_sources` are
    /// preserved across the cycle, so un-hide is a true reverse of
    /// hide. The cascade overwrites individual contact-hide state set
    /// via [`set_contact_hidden`]; un-hide blanket-resets contacts to
    /// visible regardless of how each one got hidden.
    ///
    /// Hide additionally forces `email_sync = false` — purely a
    /// product/UX coupling that says "hide = full opt-out, including
    /// team email sharing". Populate doesn't read `email_sync`, so the
    /// flip has no write-side effect by itself; the contact-cascade
    /// is what stops a hidden company from accumulating visible
    /// contacts. Un-hide leaves `email_sync` alone — re-enable
    /// explicitly via [`set_email_sync`].
    ///
    /// Both branches hold the same per-`(team, domain)` advisory locks
    /// [`populate_contact`] takes so a populate-vs-hide race can't
    /// observe a stale `hidden` value mid-cascade — without the lock,
    /// a populate could read `hidden = false` then write a visible
    /// contact under a company that's about to commit `hidden = true`.
    ///
    /// Returns [`CrmError::CompanyNotFoundForTeam`] on a non-matching
    /// pair.
    ///
    /// [`set_email_sync`]: CompaniesRepository::set_email_sync
    /// [`set_contact_hidden`]: CompaniesRepository::set_contact_hidden
    fn set_company_hidden(
        &self,
        team_id: &uuid::Uuid,
        company_id: &uuid::Uuid,
        hidden: bool,
    ) -> impl Future<Output = Result<(), CrmError>> + Send;

    /// Set the team-scoped display-name override
    /// (`crm_companies.custom_name`) for `(company_id, team_id)`. Read
    /// paths COALESCE the override over the global
    /// `crm_domain_directory` name, so the new name takes effect on
    /// every listing/search immediately; the directory itself is never
    /// touched (it is global across teams). `include_hidden` mirrors
    /// the other write paths: `false` (member) callers can't reach
    /// hidden companies. Returns
    /// [`CrmError::CompanyNotFoundForTeam`] when the company doesn't
    /// exist, belongs to another team, or is hidden from the caller.
    fn set_company_custom_name(
        &self,
        team_id: &uuid::Uuid,
        company_id: &uuid::Uuid,
        name: &str,
        include_hidden: bool,
    ) -> impl Future<Output = Result<(), CrmError>> + Send;

    /// Toggle `crm_contacts.hidden` for `contact_id`, scoped to
    /// `team_id` via the contact's company. Returns
    /// [`CrmError::ContactNotFoundForTeam`] when the contact does not
    /// exist or belongs to another team.
    fn set_contact_hidden(
        &self,
        team_id: &uuid::Uuid,
        contact_id: &uuid::Uuid,
        hidden: bool,
    ) -> impl Future<Output = Result<(), CrmError>> + Send;

    /// Set `crm_contacts.name` for `contact_id`, scoped to `team_id`
    /// via the contact's company. Unlike company names there is no
    /// global directory involved — `name` is already a team-scoped
    /// column — so this is a plain overwrite. `include_hidden` mirrors
    /// the read paths ([`get_contact_for_team`]): `false` (member)
    /// callers can't reach a hidden contact or a contact under a
    /// hidden company. Returns [`CrmError::ContactNotFoundForTeam`]
    /// when the contact doesn't exist, belongs to another team, or is
    /// hidden from the caller.
    ///
    /// [`get_contact_for_team`]: CompaniesRepository::get_contact_for_team
    fn set_contact_name(
        &self,
        team_id: &uuid::Uuid,
        contact_id: &uuid::Uuid,
        name: &str,
        include_hidden: bool,
    ) -> impl Future<Output = Result<(), CrmError>> + Send;

    /// Batched authorization probe for a CRM-scoped email query. Returns
    /// per-input status the email service maps into typed `EmailErr`
    /// variants (`CrmDomainNotFound`, `CrmDomainNotPermitted`,
    /// `CrmAddressNotFound`, `CrmAddressNotPermitted`,
    /// `CrmDisabledForTeam`).
    ///
    /// `domains` and `addresses` are expected to be lowercased by the
    /// caller. Either may be empty; both may be non-empty but the
    /// service-layer caller enforces mutual exclusivity.
    ///
    /// Read-only and not transactional — the dynamic query that follows
    /// re-checks the team-level killswitch via JOIN to close the race.
    fn crm_scope_precheck(
        &self,
        team_id: &uuid::Uuid,
        domains: &[String],
        addresses: &[String],
    ) -> impl Future<Output = Result<CrmScopePrecheck, CrmError>> + Send;

    /// Lists a team's CRM companies for the soup feed, hydrated with
    /// domains and primary-domain directory metadata. Honors the
    /// team-level killswitch (missing or `crm_enabled = false` →
    /// empty). `hidden = None` or `Some(false)` returns visible
    /// companies; `Some(true)` returns hidden companies — the caller
    /// is responsible for enforcing admin/owner role before reaching
    /// this method (soup's axum router does this). Empty `company_ids`
    /// = all rows matching the `hidden` filter; non-empty = whitelist.
    /// `cursor` seeks strictly past the previous soup page's last row
    /// (`None` = first page). All sort orders tiebreak on `id DESC`.
    ///
    /// `user_id` scopes the per-user `UserHistory` join used by the
    /// `Viewed*` sort variants. Pass the requesting user's id verbatim
    /// (as stored in `team_user.user_id` / `UserHistory."userId"`);
    /// internal callers without a user can pass an empty string —
    /// `Viewed*` sorts then collapse to NULL (no viewed-at signal).
    #[allow(clippy::too_many_arguments)]
    fn list_companies_for_soup(
        &self,
        team_id: &uuid::Uuid,
        user_id: &str,
        company_ids: &[uuid::Uuid],
        hidden: Option<bool>,
        sort: CrmCompanyListSort,
        cursor: Option<CrmCompanySoupCursor>,
        limit: i64,
    ) -> impl Future<Output = Result<Vec<CrmCompanyForSoup>, CrmError>> + Send;

    /// Lists the contacts of `company_id`, scoped to `team_id` via the
    /// contact's company. Returns
    /// [`CrmError::CompanyNotFoundForTeam`] when the company doesn't
    /// exist, isn't owned by the team, or — for non-admin viewers
    /// (`include_hidden = false`) — is hidden. With `include_hidden =
    /// false` hidden contacts are filtered out and hidden parent
    /// companies 404; with `include_hidden = true` (admin/owner) every
    /// owned contact is returned and hidden parent companies are
    /// reachable. Ordered alphabetically (case-insensitive) by display
    /// name, falling back to email when the contact has no name; ties
    /// break on `id DESC`.
    fn list_contacts_for_company(
        &self,
        team_id: &uuid::Uuid,
        company_id: &uuid::Uuid,
        include_hidden: bool,
    ) -> impl Future<Output = Result<Vec<CrmContact>, CrmError>> + Send;

    /// Fetches a single CRM contact by id, scoped to `team_id` via the
    /// contact's company. Returns `Ok(None)` when the contact doesn't
    /// exist, belongs to a different team, or — for non-admin viewers
    /// (`include_hidden = false`) — the contact or its parent company
    /// is hidden. With `include_hidden = true` (admin/owner) every
    /// owned contact is reachable. The handler converts `None` into a
    /// 404 [`CrmError::ContactNotFoundForTeam`].
    fn get_contact_for_team(
        &self,
        team_id: &uuid::Uuid,
        contact_id: &uuid::Uuid,
        include_hidden: bool,
    ) -> impl Future<Output = Result<Option<CrmContact>, CrmError>> + Send;

    /// Searches the team's contacts whose email or name contains `query`
    /// (case-insensitive), most recently interacted first, at most `limit`
    /// rows. An empty query lists the most recent contacts. Hidden contacts
    /// and contacts under hidden companies are excluded unless
    /// `include_hidden` (admin/owner).
    fn search_contacts_for_team(
        &self,
        team_id: &uuid::Uuid,
        query: &str,
        limit: i64,
        include_hidden: bool,
    ) -> impl Future<Output = Result<Vec<CrmContact>, CrmError>> + Send;

    /// Fetches a single CRM contact by email, scoped to `team_id` via the
    /// contact's company. Email matching is case-insensitive. Returns
    /// `Ok(None)` when the contact doesn't exist, belongs to a different
    /// team, or — for non-admin viewers (`include_hidden = false`) — the
    /// contact or its parent company is hidden. With `include_hidden = true`
    /// (admin/owner), every owned contact is reachable.
    /// Returns [`CrmError::InvalidRequest`] if multiple visible contacts match;
    /// callers must select an explicit contact ID rather than guess a company.
    fn get_contact_by_email_for_team(
        &self,
        team_id: &uuid::Uuid,
        email: &str,
        include_hidden: bool,
    ) -> impl Future<Output = Result<Option<CrmContact>, CrmError>> + Send;

    /// Fetches a single CRM company by id, scoped to `team_id`,
    /// hydrated with all domains (ordered by `created_at ASC` —
    /// primary first), the primary domain's `crm_domain_directory`
    /// display metadata (name + description), and the company's full
    /// contact list (subject to `include_hidden`). Returns `Ok(None)`
    /// when the company doesn't exist, belongs to a different team,
    /// or — for non-admin viewers (`include_hidden = false`) — the
    /// company is hidden. With `include_hidden = true` (admin/owner)
    /// every owned company is reachable. The handler converts `None`
    /// into a 404 [`CrmError::CompanyNotFoundForTeam`].
    fn get_company_for_team(
        &self,
        team_id: &uuid::Uuid,
        company_id: &uuid::Uuid,
        include_hidden: bool,
    ) -> impl Future<Output = Result<Option<CrmCompanyWithContacts>, CrmError>> + Send;

    /// Read the team's CRM configuration from `team_crm_settings`.
    /// A missing row yields [`CrmTeamSettings::default`].
    fn get_team_settings(
        &self,
        team_id: &uuid::Uuid,
    ) -> impl Future<Output = Result<CrmTeamSettings, CrmError>> + Send;

    /// Field-wise partial upsert of the team's CRM configuration.
    /// Unprovided fields keep their current values (or column defaults
    /// on insert); `team_views` is replaced whole. Never touches
    /// `crm_enabled`. Returns the resulting row.
    fn update_team_settings(
        &self,
        team_id: &uuid::Uuid,
        patch: &CrmTeamSettingsPatch,
    ) -> impl Future<Output = Result<CrmTeamSettings, CrmError>> + Send;
}