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.

11.2 KB
Raw Blame
//! GetCompany tool for reading a single CRM company's details.

use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use ai_toolset::{ToolAnnotated, ToolAnnotations};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use entity_access::domain::{
    models::{
        Entity, EntityAccessReceipt, EntityPermission, EntityType, TeamRole, ViewAccessLevel,
    },
    ports::EntityAccessService,
};
use models_properties::DataType;
use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;
use models_properties::service::property_option::PropertyOptionValue;
use properties::PropertiesService;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::domain::{
    model::{CrmContact, CrmError},
    service::CrmService,
};

use super::{
    CrmToolContext, ToolCompanyStage, company_view_receipt, crm_error, extract_company_crm_props,
    load_stage_option_catalog,
};

/// A contact belonging to the company.
#[derive(Debug, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct CompanyContactItem {
    /// The CRM contact id.
    pub id: Uuid,
    /// The contact's email address, if it has one.
    pub email: Option<String>,
    /// The contact's display name, when known.
    pub name: Option<String>,
    /// Most recent known interaction with this contact.
    pub last_interaction: DateTime<Utc>,
}

impl From<CrmContact> for CompanyContactItem {
    fn from(contact: CrmContact) -> Self {
        Self {
            id: contact.id,
            email: contact.email,
            name: contact.name,
            last_interaction: contact.last_interaction,
        }
    }
}

/// An option available on a select-type company property.
#[derive(Debug, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct CompanyPropertyOption {
    /// The option id to use when setting select values via SetEntityProperty.
    pub id: Uuid,
    /// The option's display value.
    pub display_value: String,
}

/// A property attached to the company (builtin or custom).
#[derive(Debug, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct CompanyPropertyItem {
    /// The property definition id. Use with SetEntityProperty (entity_type=company).
    pub property_definition_id: Uuid,
    /// Human-readable property name.
    pub display_name: String,
    /// The data type (boolean, date, number, string, select_string, select_number, tag, entity, link).
    pub data_type: String,
    /// Whether the property supports multiple values.
    pub is_multi_select: bool,
    /// Whether this is a system-defined property.
    pub is_system: bool,
    /// The current value, if set.
    pub current_value: Option<serde_json::Value>,
    /// Available options for select-type properties.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub options: Vec<CompanyPropertyOption>,
}

/// Response from the [`GetCompany`] tool.
#[derive(Debug, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct GetCompanyResponse {
    /// The CRM company id.
    pub id: Uuid,
    /// Company display name, when resolved.
    pub name: Option<String>,
    /// Short company description, when resolved.
    pub description: Option<String>,
    /// The company's email domains, primary domain first.
    pub domains: Vec<String>,
    /// Whether the company is hidden from the team's CRM listings.
    pub hidden: bool,
    /// Whether team-wide email sharing is enabled for this company.
    pub email_sync: bool,
    /// Earliest known email interaction with this company.
    pub first_interaction: DateTime<Utc>,
    /// Most recent known email interaction with this company.
    pub last_interaction: DateTime<Utc>,
    /// The company's own Stage property, if set; separate from any
    /// pipeline entry's stage.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stage: Option<ToolCompanyStage>,
    /// Macro user id of the company's owner, if set.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub owner_user_id: Option<String>,
    /// The company's revenue (dollars), if set.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub revenue: Option<f64>,
    /// Contacts attached to this company.
    pub contacts: Vec<CompanyContactItem>,
    /// All properties attached to this company (builtin Stage / Owner /
    /// Revenue plus custom ones), with current values and select options.
    pub properties: Vec<CompanyPropertyItem>,
    /// Human-readable summary.
    pub summary: String,
}

/// Fetch one CRM company by id.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[schemars(
    title = "GetCompany",
    description = "Fetch one of the team's CRM companies by id, with its domains, contacts, its own Stage / Owner / Revenue properties (not a pipeline deal's), and all attached property values (including custom properties and the valid stage options). Use ListCompanies to find company ids. To change one of the company's own properties (its Stage, Owner, Revenue or a custom property) call SetEntityProperty with entity_type=company, the company id, and a property_definition_id / option id from this response. Deals in a pipeline have their own stage and fields: find them with FindPipelineEntries (recordIds = this company's id) and change them with UpdatePipelineEntries."
)]
pub struct GetCompany {
    /// The CRM company id to fetch.
    #[schemars(description = "The CRM company id (UUID), e.g. from ListCompanies.")]
    pub company_id: Uuid,
}

impl ToolAnnotated for GetCompany {
    const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Read company");
}

#[async_trait]
impl<CSvc, ESvc, PSvc> AsyncTool<CrmToolContext<CSvc, ESvc, PSvc>> for GetCompany
where
    CSvc: CrmService,
    ESvc: EntityAccessService,
    PSvc: PropertiesService,
{
    type Output = GetCompanyResponse;

    #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, company_id=%self.company_id), err)]
    async fn call(
        &self,
        service_context: ServiceContext<CrmToolContext<CSvc, ESvc, PSvc>>,
        request_context: RequestContext,
    ) -> ToolResult<Self::Output> {
        tracing::info!(params=?self, "Get CRM company");

        let company_id = self.company_id.to_string();

        let (receipt, team_id) = company_view_receipt(
            &*service_context.entity_access_service,
            &request_context,
            self.company_id,
        )
        .await?;

        let record = service_context
            .service
            .get_company_for_team(&receipt)
            .await
            .map_err(crm_error)?
            .ok_or_else(|| crm_error(CrmError::CompanyNotFoundForTeam))?;

        // Asserted rather than minted: view access to this company was just
        // verified by `company_view_receipt`.
        let properties_access =
            EntityAccessReceipt::<ViewAccessLevel>::dangerously_assert_authenticated_user(
                request_context.user_id.clone(),
                &company_id,
                EntityType::CrmCompany,
            );
        let properties = service_context
            .properties
            .get_entity_properties_with_definitions(&properties_access)
            .await
            .map_err(|e| ToolCallError {
                description: "failed to load company properties".to_string(),
                internal_error: e.into(),
            })?;

        // `company_view_receipt` resolved `team_id` from the
        // ownership row that granted access, so the caller's membership of
        // that team is proven; Member is the floor every member satisfies.
        let team_receipt = EntityAccessReceipt::try_new_authenticated_user(
            request_context.user_id.clone(),
            Entity {
                entity_id: team_id.to_string(),
                entity_type: EntityType::Team,
            },
            EntityPermission::TeamRole {
                role: TeamRole::Member,
            },
        )
        .map_err(|e| ToolCallError {
            description: "failed to verify access to the CRM company".to_string(),
            internal_error: e.into(),
        })?;
        let stage_catalog =
            load_stage_option_catalog(&*service_context.properties, &team_receipt).await?;
        let crm_props = extract_company_crm_props(&properties, &stage_catalog);

        let name = record.name.clone();
        let summary = format!(
            "CRM company {}{} with {} contact{}, {} propert{}.",
            name.as_deref().unwrap_or("(unnamed)"),
            crm_props
                .stage
                .as_ref()
                .map(|s| format!(" in stage {}", s.label))
                .unwrap_or_default(),
            record.contacts.len(),
            if record.contacts.len() == 1 { "" } else { "s" },
            properties.len(),
            if properties.len() == 1 { "y" } else { "ies" },
        );

        Ok(GetCompanyResponse {
            id: record.company.id,
            name,
            description: record.description,
            domains: record
                .company
                .domains
                .iter()
                .map(|d| d.domain.clone())
                .collect(),
            hidden: record.company.hidden,
            email_sync: record.company.email_sync,
            // The repo fills `company.created_at` / `updated_at` from
            // `crm_companies.first_interaction` / `last_interaction`, so
            // these really are the interaction endpoints, not
            // row-lifecycle timestamps.
            first_interaction: record.company.created_at,
            last_interaction: record.company.updated_at,
            stage: crm_props.stage,
            owner_user_id: crm_props.owner_user_id,
            revenue: crm_props.revenue,
            contacts: record.contacts.into_iter().map(Into::into).collect(),
            properties: properties.into_iter().map(to_property_item).collect(),
            summary,
        })
    }
}

fn to_property_item(prop: EntityPropertyWithDefinition) -> CompanyPropertyItem {
    let data_type = match prop.definition.data_type {
        DataType::Boolean => "boolean",
        DataType::Date => "date",
        DataType::DateRange => "date_range",
        DataType::Number => "number",
        DataType::String => "string",
        DataType::SelectNumber => "select_number",
        DataType::SelectString => "select_string",
        DataType::Tag => "tag",
        DataType::Entity => "entity",
        DataType::Link => "link",
    }
    .to_string();

    let current_value = prop
        .value
        .as_ref()
        .map(|v| serde_json::to_value(v).unwrap_or(serde_json::Value::Null));

    let options = prop
        .options
        .unwrap_or_default()
        .into_iter()
        .map(|option| CompanyPropertyOption {
            id: option.id,
            display_value: match option.value {
                PropertyOptionValue::String(s) => s,
                PropertyOptionValue::Number(n) => n.to_string(),
            },
        })
        .collect();

    CompanyPropertyItem {
        property_definition_id: prop.property.property_definition_id,
        display_name: prop.definition.display_name,
        data_type,
        is_multi_select: prop.definition.is_multi_select,
        is_system: prop.definition.is_system,
        current_value,
        options,
    }
}