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.

15.6 KB
Raw Blame
#![deny(missing_docs)]
//! Domain models for invitation email notifications.
//!
//! Contains the [`InviteToMacro`] referral notification, the [`InviteToTeamMetadata`] team
//! invitation notification and its [`InviteePlan`], the [`ChannelInviteMetadata`] channel
//! invitation, the [`ColleagueJoinedMacro`] colleague join email, and the [`ReferralCode`]
//! newtype.

#[cfg(test)]
mod test;

mod call_invite;
pub use call_invite::CallInvite;

mod colleague_joined;
pub use colleague_joined::ColleagueJoinedMacro;

use askama::Template;
use macro_env::Environment;
use macro_user_id::cowlike::CowLike;
use macro_user_id::email::EmailStr;
use macro_user_id::email::ReadEmailParts;
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::Entity;
use notification::domain::models::{
    NotifCollapseKey, Notification, NotificationExtEmail, NotificationExtIos, NotificationTitle,
    RateLimitConfig, RateLimitKey,
    apple::{APNSPushNotification, AlertDictionary, Aps, PushNotificationData},
    queue_message::EmailContent,
};
use serde::{Deserialize, Serialize};
use std::time::Duration;
use url::Url;
use utoipa::ToSchema;
use uuid::Uuid;

const DISPLAY_NAME_MAX_CHARS: usize = 64;

/// Puts an untrusted display name on one line and caps it. Returns `None` when nothing
/// printable is left.
fn single_line_name(raw: Option<&str>) -> Option<String> {
    let words: Vec<&str> = raw?
        .split(|c: char| c.is_whitespace() || c.is_control())
        .filter(|word| !word.is_empty())
        .collect();
    let capped: String = words
        .join(" ")
        .chars()
        .take(DISPLAY_NAME_MAX_CHARS)
        .collect();
    let name = capped.trim_end();
    (!name.is_empty()).then(|| name.to_owned())
}

/// Wrapper for the referral code to make it type safe
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ReferralCode(pub String);

/// The metadata for a referral-to-macro notification.
#[derive(Debug, Serialize, Deserialize, Clone, Template)]
#[template(path = "invite.html")]
pub struct InviteToMacro {
    /// The recipient email.
    pub recipient_email: EmailStr<'static>,
    /// The referral code which is templated into the email to track the sender
    /// and reward them.
    pub referral_code: ReferralCode,
    /// The sender's profile picture URL, if available.
    pub sender_profile_picture_url: Option<Url>,
    /// The sender's display name, if they have set one.
    pub sender_name: Option<String>,
    /// The sender's email address.
    #[serde(default)]
    pub sender_email: Option<String>,
}

impl InviteToMacro {
    fn referral_url(&self) -> Url {
        let env = Environment::new_or_prod();
        get_url(env, &self.referral_code)
    }
}

impl Notification for InviteToMacro {
    const TYPE_NAME: &'static str = "invite_to_macro";
}

const MINUTES_PER_WEEK: u64 = 60 * 24 * 7;

fn frontend_host(env: Environment) -> Url {
    let host = match env {
        Environment::Production => "https://macro.com".to_string(),
        Environment::Develop => "https://dev.macro.com".to_string(),
        Environment::Local => {
            #[expect(clippy::disallowed_methods, reason = "Only used when running locally")]
            let port = std::env::var("FRONTEND_PORT").unwrap_or_else(|_| "3000".to_string());
            format!("http://localhost:{port}")
        }
    };

    Url::parse(&host).expect("all the inputs are static, valid values")
}

fn signup_url(env: Environment) -> Url {
    let mut url = frontend_host(env);
    url.set_path("/app/signup");
    url
}

fn get_url(env: Environment, code: &ReferralCode) -> Url {
    let mut url = signup_url(env);
    url.query_pairs_mut()
        .clear()
        .append_pair("referral_code", &code.0)
        .finish();
    url
}

impl NotificationExtEmail for InviteToMacro {
    fn format_email(&self) -> EmailContent {
        let sender = self
            .sender_name
            .as_deref()
            .or(self.sender_email.as_deref())
            .unwrap_or("A Macro user");
        EmailContent::new(
            format!("{} has invited you to join Macro", sender),
            self.render()
                .expect("InviteToMacro template render failed in format_email"),
        )
    }

    fn rate_limit_config() -> RateLimitConfig {
        // 1 invite email per user per week
        RateLimitConfig {
            max_count: 1,
            window: Duration::from_mins(MINUTES_PER_WEEK),
        }
    }

    fn rate_limit_key(&self) -> RateLimitKey {
        RateLimitKey::builder(&Self::TYPE_NAME)
            .append(&self.recipient_email.0.as_ref())
            .finish()
    }
}

/// Metadata for when a user is invited to a channel.
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema, Template)]
#[serde(rename_all = "camelCase")]
#[template(path = "invite_to_channel.html")]
pub struct ChannelInviteMetadata {
    /// The user who sent the invitation
    #[serde(alias = "invited_by")]
    #[schema(value_type = String)]
    pub invited_by: MacroUserIdStr<'static>,
    /// The name of the channel
    #[serde(default)]
    #[serde(alias = "channel_name")]
    pub channel_name: String,
    /// Whether this is a direct message rather than a channel invitation.
    /// Older notification payloads retain channel-invitation wording.
    #[serde(default)]
    pub is_direct_message: bool,
    /// Stable DM message identity used while building the email delivery key.
    /// The serialized email bundle carries the key; notification metadata does not.
    #[serde(skip)]
    pub message_id: Option<Uuid>,
    /// Destination used while building a separate email retry key per recipient.
    #[serde(skip)]
    pub email_recipient: Option<MacroUserIdStr<'static>>,
    /// Message content to show in the invite email, when the invite was triggered by a message.
    #[serde(default)]
    pub message_content: Option<String>,
    /// The sender's profile picture URL, if available.
    #[serde(default)]
    pub sender_profile_picture_url: Option<String>,
}

impl ChannelInviteMetadata {
    fn signup_url(&self) -> Url {
        signup_url(Environment::new_or_prod())
    }

    fn sender_display(&self) -> &str {
        self.invited_by.email_str()
    }
}

impl Notification for ChannelInviteMetadata {
    const TYPE_NAME: &'static str = "channel_invite";
}

impl NotificationTitle for ChannelInviteMetadata {
    fn format_title(
        &self,
        _sender_id: Option<MacroUserIdStr<'_>>,
    ) -> Result<String, rootcause::Report> {
        let email = self.invited_by.email_part();
        let sender = email.email_str();
        if self.is_direct_message {
            Ok(format!("{sender} sent you a message"))
        } else {
            Ok(format!(
                "{sender} invited you to join #{}",
                self.channel_name
            ))
        }
    }

    fn format_body(
        &self,
        _sender_id: Option<MacroUserIdStr<'_>>,
    ) -> Result<String, rootcause::Report> {
        Ok("Open macro to continue".to_string())
    }
}

impl NotificationExtEmail for ChannelInviteMetadata {
    fn format_email(&self) -> EmailContent {
        let sender = self.sender_display();
        let subject = if self.is_direct_message {
            format!("{sender} sent you a message on Macro")
        } else {
            format!("{sender} has invited you to join #{}", self.channel_name)
        };
        EmailContent::new(
            subject,
            self.render()
                .expect("ChannelInviteMetadata template render failed in format_email"),
        )
    }

    fn rate_limit_config() -> RateLimitConfig {
        RateLimitConfig {
            max_count: 1,
            window: Duration::from_hours(24 * 7),
        }
    }

    fn rate_limit_key(&self) -> RateLimitKey {
        if self.is_direct_message
            && let Some(message_id) = self.message_id
        {
            return RateLimitKey::builder(&Self::TYPE_NAME)
                .append(&message_id)
                .append(&self.email_recipient)
                .finish();
        }
        RateLimitKey::builder(&Self::TYPE_NAME)
            .append(&self.invited_by)
            .append(&self.channel_name)
            .finish()
    }
}

impl NotificationExtIos for ChannelInviteMetadata {
    type NotifData = PushNotificationData;

    fn collapse_key(&self, entity: &Entity<'_>) -> NotifCollapseKey {
        let entity_type: &'static str = entity.entity_type.into();
        NotifCollapseKey::new(entity_type).append(&entity.entity_id)
    }

    fn as_apns<'a>(
        &self,
        sender_id: Option<MacroUserIdStr<'a>>,
        _entity: &Entity<'_>,
        notification_id: Uuid,
    ) -> Option<APNSPushNotification<Self::NotifData>> {
        let title = self
            .format_title(sender_id.as_ref().map(CowLike::copied))
            .ok()?;
        let body = self.format_body(sender_id).ok()?;
        let mutable_content = self.sender_profile_picture_url.as_ref().map(|_| 1);
        Some(APNSPushNotification {
            aps: Aps {
                alert: Some(notification::domain::models::apple::Alert::Dictionary(
                    AlertDictionary {
                        title: Some(title),
                        body: Some(body),
                        ..Default::default()
                    },
                )),
                mutable_content,
                ..Default::default()
            },
            push_notification_data: PushNotificationData {
                notification_id,
                sender_profile_picture_url: self.sender_profile_picture_url.clone(),
                recipient_id: None,
                navigation: None,
            },
        })
    }
}

/// Metadata for when a user is invited to a team.
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema, Template)]
#[serde(rename_all = "camelCase")]
#[template(path = "invite_to_team.html")]
pub struct InviteToTeamMetadata {
    /// The name of the team being invited to
    #[serde(alias = "team_name")]
    pub team_name: String,
    /// The unique identifier of the team
    #[serde(alias = "team_id")]
    pub team_id: Uuid,
    /// The unique identifier of the team invite
    #[serde(alias = "team_invite_id")]
    pub team_invite_id: Uuid,
    /// The user who sent the invitation
    #[serde(alias = "invited_by")]
    #[schema(value_type = String)]
    pub invited_by: MacroUserIdStr<'static>,
    /// Role/permission level in the team
    pub role: Option<String>,

    /// The sender's profile picture URL, if available.
    #[serde(default)]
    #[schema(value_type = Option<String>)]
    pub sender_profile_picture_url: Option<Url>,

    /// What the invitee gets by joining, as the team stood when the invite was sent.
    #[serde(default, alias = "invitee_plan")]
    pub invitee_plan: InviteePlan,

    /// Whether this email reminds the invitee of an invite they have not answered.
    #[serde(default)]
    pub reminder: bool,

    /// Whether the invite creates an agent account.
    #[serde(default)]
    pub is_agent: bool,

    /// The inviter's display name, when they have set one. It is user-provided, so it is shown
    /// on one line, capped, and escaped; the email falls back to the inviter's address.
    #[serde(default, alias = "inviter_name")]
    pub inviter_name: Option<String>,
}

/// What a team invitee gets by joining.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, Default, PartialEq, Eq, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum InviteePlan {
    /// Macro's free plan. Invites sent before the plan was recorded read as
    /// this, which stays true: joining a team never costs the invitee anything.
    #[default]
    Free,
    /// A Pro seat that a paying, trialing, or enterprise team covers.
    Premium,
}

/// Longest team name that still fits on the email's join button.
const MAX_BUTTON_TEAM_NAME_CHARS: usize = 24;

impl InviteToTeamMetadata {
    /// Returns the team invite URL for the current environment.
    pub fn invite_url(&self) -> Url {
        let env = Environment::new_or_prod();

        let mut url = frontend_host(env);
        let invite_id = self.team_invite_id.to_string();
        if self.is_agent {
            url.set_path("/app/signup/agent");
            url.query_pairs_mut().append_pair("team_invite", &invite_id);
        } else {
            url.set_path("/app/team-invite");
            url.query_pairs_mut().append_pair("id", &invite_id);
        }

        url
    }

    fn inviter_email(&self) -> &str {
        self.invited_by.email_str()
    }

    fn inviter_display_name(&self) -> Option<String> {
        single_line_name(self.inviter_name.as_deref())
    }

    /// The inviter's name, or their address when they have not set one.
    fn inviter(&self) -> String {
        self.inviter_display_name()
            .unwrap_or_else(|| self.inviter_email().to_owned())
    }

    /// The plain-text alternative to the HTML body. It mirrors the HTML's copy.
    fn text_body(&self) -> String {
        let inviter = match self.inviter_display_name() {
            Some(name) => format!("{name} ({})", self.inviter_email()),
            None => self.inviter_email().to_owned(),
        };
        let team = &self.team_name;
        let plan = match self.invitee_plan {
            InviteePlan::Premium => format!(
                "Pro is included: {team} covers your seat, so you get every AI model and agent at no cost to you."
            ),
            InviteePlan::Free => format!(
                "Free to join: there's nothing to pay. Accept the invite to start working with {team} in Macro."
            ),
        };
        let url = self.invite_url();

        format!(
            "{inviter} invited you to the {team} team on Macro. Macro brings your documents, \
             tasks, and conversations together in one place.\n\n\
             {plan}\n\n\
             Accept the invite by signing in or signing up with this email address:\n\
             {url}\n\n\
             Not expecting this invite? You can ignore this email.\n"
        )
    }

    /// Names the team on the button unless the name would crowd it.
    fn join_label(&self) -> String {
        if self.team_name.chars().count() <= MAX_BUTTON_TEAM_NAME_CHARS {
            format!("Join {}", self.team_name)
        } else {
            "Join team".to_string()
        }
    }
}

impl Notification for InviteToTeamMetadata {
    const TYPE_NAME: &'static str = "invite_to_team";
}

impl NotificationExtEmail for InviteToTeamMetadata {
    fn format_email(&self) -> EmailContent {
        EmailContent {
            subject: format!(
                "{}{} invited you to join {} on Macro",
                if self.reminder { "Reminder: " } else { "" },
                self.inviter(),
                self.team_name
            ),
            body: self
                .render()
                .expect("InviteToTeamMetadata template render failed in format_email"),
            text: Some(self.text_body()),
            // An address as a display name reads as spoofing to mail filters, so an inviter
            // without a name leaves Macro's own sender name in place.
            from_name: self.inviter_display_name(),
            reply_to: Some(EmailStr(self.invited_by.email_part()).into_owned()),
        }
    }

    fn rate_limit_config() -> RateLimitConfig {
        // Long enough to stop repeat mail to one address, short enough that an
        // inviter can resend when someone says the email never came.
        RateLimitConfig {
            max_count: 1,
            window: Duration::from_hours(1),
        }
    }

    /// One bucket per invite (one invite per recipient per team), so inviting
    /// several teammates at once emails each of them. Resends reuse the invite.
    fn rate_limit_key(&self) -> RateLimitKey {
        RateLimitKey::builder(&Self::TYPE_NAME)
            .append(&self.team_id)
            .append(&self.team_invite_id)
            .finish()
    }
}