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.

13.4 KB
Raw Blame
use super::*;
use crate::domain::{models::EmailBackfillStatus, ports::EmailUserRepo};

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../../../../fixtures", scripts("email_message"))
)]
async fn test_link_by_fusionauth_and_macro_id_found(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = EmailPgRepo::new(pool);

    let macro_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
    let link = repo
        .link_by_fusionauth_and_macro_id("fa-user-1", macro_id, UserProvider::Gmail)
        .await?;

    assert!(link.is_some(), "Link should exist");
    let link = link.unwrap();
    assert_eq!(
        link.id,
        Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?
    );
    assert_eq!(link.fusionauth_user_id, "fa-user-1");
    assert_eq!(link.provider, UserProvider::Gmail);
    assert!(link.is_sync_active);

    Ok(())
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../../../../fixtures", scripts("email_message"))
)]
async fn test_link_by_fusionauth_and_macro_id_wrong_fusionauth(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = EmailPgRepo::new(pool);

    let macro_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
    let link = repo
        .link_by_fusionauth_and_macro_id("nonexistent-fa-user", macro_id, UserProvider::Gmail)
        .await?;

    assert!(
        link.is_none(),
        "Wrong fusionauth_user_id should return None"
    );

    Ok(())
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../../../../fixtures", scripts("email_message"))
)]
async fn test_link_by_fusionauth_and_macro_id_wrong_macro_id(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = EmailPgRepo::new(pool);

    let macro_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
    let link = repo
        .link_by_fusionauth_and_macro_id("fa-user-1", macro_id, UserProvider::Gmail)
        .await?;

    assert!(link.is_none(), "Wrong macro_id should return None");

    Ok(())
}

#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_inboxes_for_macro_id_includes_own_and_delegated(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    // macro_user_links FK-references "User" (which FK-references macro_user), so
    // the delegating and delegated accounts must exist as real users.
    sqlx::query(
        r#"
        INSERT INTO "macro_user" (id, username, email, stripe_customer_id) VALUES
            ('c1000000-0000-0000-0000-000000000001', 'alice', '[email protected]', 'stripe_alice'),
            ('c2000000-0000-0000-0000-000000000002', 'shared', '[email protected]', 'stripe_shared')
        "#,
    )
    .execute(&pool)
    .await?;

    sqlx::query(
        r#"
        INSERT INTO "User" (id, email, name, macro_user_id) VALUES
            ('macro|[email protected]', '[email protected]', 'Alice', 'c1000000-0000-0000-0000-000000000001'),
            ('macro|[email protected]', '[email protected]', 'Shared Inbox', 'c2000000-0000-0000-0000-000000000002')
        "#,
    )
    .execute(&pool)
    .await?;

    sqlx::query(
        r#"
        INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at) VALUES
            ('a1000000-0000-0000-0000-000000000001'::uuid, 'macro|[email protected]', 'fa-alice', '[email protected]', 'GMAIL', true, NOW() - INTERVAL '2 hours', NOW()),
            ('a2000000-0000-0000-0000-000000000002'::uuid, 'macro|[email protected]', 'fa-alice', '[email protected]', 'GMAIL', true, NOW() - INTERVAL '1 hour', NOW()),
            ('5e000000-0000-0000-0000-000000000003'::uuid, 'macro|[email protected]', 'fa-shared', '[email protected]', 'GMAIL', true, NOW(), NOW()),
            ('5f000000-0000-0000-0000-000000000005'::uuid, 'macro|[email protected]', 'fa-shared', '[email protected]', 'GMAIL', true, NOW(), NOW()),
            ('b0000000-0000-0000-0000-000000000004'::uuid, 'macro|[email protected]', 'fa-bob', '[email protected]', 'GMAIL', true, NOW(), NOW())
        "#,
    )
    .execute(&pool)
    .await?;

    // alice is the primary; only shared@'s first inbox is delegated to her.
    // bob is unrelated.
    sqlx::query(
        r#"
        INSERT INTO macro_user_links (primary_macro_id, child_macro_id, link_id) VALUES
            ('macro|[email protected]', 'macro|[email protected]', '5e000000-0000-0000-0000-000000000003'::uuid)
        "#,
    )
    .execute(&pool)
    .await?;

    let repo = EmailPgRepo::new(pool);
    let macro_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
    let links = repo.inboxes_for_macro_id(macro_id.clone()).await?;

    let emails: std::collections::HashSet<&str> =
        links.iter().map(|l| l.email_address.0.as_ref()).collect();

    assert_eq!(
        links.len(),
        3,
        "alice's two own inboxes plus the one delegated inbox"
    );
    assert!(emails.contains("[email protected]"));
    assert!(emails.contains("[email protected]"));
    assert!(
        emails.contains("[email protected]"),
        "delegated inbox must be included"
    );
    assert!(
        !emails.contains("[email protected]"),
        "child's inbox outside the link-scoped grant must be excluded"
    );
    assert!(
        !emails.contains("[email protected]"),
        "unrelated inbox must be excluded"
    );

    let detailed_emails = repo
        .user_inbox_details(macro_id)
        .await?
        .into_iter()
        .map(|inbox| inbox.email_address.0.as_ref().to_owned())
        .collect::<std::collections::HashSet<_>>();
    assert_eq!(
        detailed_emails,
        emails.into_iter().map(str::to_owned).collect(),
        "enriched inbox details must preserve owned and delegated scoping"
    );

    Ok(())
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../../../../fixtures", scripts("email_message"))
)]
async fn user_inbox_details_maps_enriched_owned_inbox(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
    sqlx::query!(
        r#"
        UPDATE email_links
        SET needs_reauth = TRUE
        WHERE id = $1
        "#,
        link_id
    )
    .execute(&pool)
    .await?;
    sqlx::query!(
        r#"
        INSERT INTO email_settings (link_id, signature_on_replies_forwards, signature)
        VALUES ($1, TRUE, '<p>Regards</p>')
        "#,
        link_id
    )
    .execute(&pool)
    .await?;
    sqlx::query!(
        r#"
        INSERT INTO email_backfill_jobs (id, link_id, fusionauth_user_id, status)
        VALUES ($1, $2, 'fa-user-1', 'InProgress')
        "#,
        Uuid::from_u128(901),
        link_id
    )
    .execute(&pool)
    .await?;
    sqlx::query!(
        r#"
        INSERT INTO email_contacts (id, link_id, email_address, sfs_photo_url)
        VALUES ($1, $2, '[email protected]', 'https://example.com/inbox.png')
        "#,
        Uuid::from_u128(902),
        link_id
    )
    .execute(&pool)
    .await?;

    let details = EmailPgRepo::new(pool)
        .user_inbox_details(MacroUserIdStr::parse_from_str("macro|[email protected]")?)
        .await?;

    assert_eq!(details.len(), 1);
    let inbox = &details[0];
    assert_eq!(inbox.id, link_id);
    assert_eq!(inbox.email_address.0.as_ref(), "[email protected]");
    assert_eq!(inbox.provider, UserProvider::Gmail);
    assert!(inbox.is_sync_active);
    assert!(inbox.needs_reauth);
    assert!(inbox.is_primary);
    assert_eq!(
        inbox.latest_backfill_status,
        Some(EmailBackfillStatus::InProgress)
    );
    assert!(inbox.settings.signature_on_replies_forwards);
    assert_eq!(inbox.settings.signature.as_deref(), Some("<p>Regards</p>"));
    assert_eq!(
        inbox.photo_url.as_deref(),
        Some("https://example.com/inbox.png")
    );
    assert!(inbox.needs_calendar_permission);
    assert!(!inbox.calendar_disabled);
    assert!(!inbox.has_calendar_data);
    Ok(())
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../../../../fixtures", scripts("email_message"))
)]
async fn user_inbox_details_reports_the_calendar_grant(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
    let scopes = calendar_events::domain::models::GOOGLE_CALENDAR_SCOPES.map(str::to_owned);
    sqlx::query!(
        r#"
        INSERT INTO email_link_google_scopes (link_id, granted_scopes, calendar_disabled_at)
        VALUES ($1, $2, now())
        "#,
        link_id,
        &scopes,
    )
    .execute(&pool)
    .await?;

    let details = EmailPgRepo::new(pool)
        .user_inbox_details(MacroUserIdStr::parse_from_str("macro|[email protected]")?)
        .await?;

    let inbox = &details[0];
    assert!(!inbox.needs_calendar_permission);
    assert!(inbox.calendar_disabled);
    assert!(!inbox.has_calendar_data);
    Ok(())
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../../../../fixtures", scripts("email_message"))
)]
async fn test_link_by_fusionauth_email_provider_found(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = EmailPgRepo::new(pool);

    let link = repo
        .link_by_fusionauth_email_provider("fa-user-1", "[email protected]", UserProvider::Gmail)
        .await?;

    assert!(link.is_some(), "Link should exist for the fixture row");
    let link = link.unwrap();
    assert_eq!(link.fusionauth_user_id, "fa-user-1");
    assert_eq!(link.email_address.0.as_ref(), "[email protected]");
    assert_eq!(link.provider, UserProvider::Gmail);

    Ok(())
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../../../../fixtures", scripts("email_message"))
)]
async fn test_link_by_fusionauth_email_provider_wrong_email(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = EmailPgRepo::new(pool);

    let link = repo
        .link_by_fusionauth_email_provider("fa-user-1", "[email protected]", UserProvider::Gmail)
        .await?;

    assert!(link.is_none(), "Wrong email should return None");

    Ok(())
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../../../../fixtures", scripts("email_message"))
)]
async fn test_link_by_fusionauth_email_provider_wrong_fusionauth(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = EmailPgRepo::new(pool);

    let link = repo
        .link_by_fusionauth_email_provider(
            "nonexistent-fa-user",
            "[email protected]",
            UserProvider::Gmail,
        )
        .await?;

    assert!(
        link.is_none(),
        "Wrong fusionauth_user_id should return None"
    );

    Ok(())
}

#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_owned_link_for_thread_resolves_own_and_delegated(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    // macro_user_links FK-references "User" (which FK-references macro_user).
    sqlx::query(
        r#"
        INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES
            ('d1000000-0000-0000-0000-000000000001'::uuid, 'child', '[email protected]', 'stripe_child'),
            ('d2000000-0000-0000-0000-000000000002'::uuid, 'primary', '[email protected]', 'stripe_primary'),
            ('d3000000-0000-0000-0000-000000000003'::uuid, 'stranger', '[email protected]', 'stripe_stranger')
        "#,
    )
    .execute(&pool)
    .await?;

    sqlx::query(
        r#"
        INSERT INTO "User" (id, email, macro_user_id) VALUES
            ('macro|[email protected]', '[email protected]', 'd1000000-0000-0000-0000-000000000001'::uuid),
            ('macro|[email protected]', '[email protected]', 'd2000000-0000-0000-0000-000000000002'::uuid),
            ('macro|[email protected]', '[email protected]', 'd3000000-0000-0000-0000-000000000003'::uuid)
        "#,
    )
    .execute(&pool)
    .await?;

    sqlx::query(
        r#"
        INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at) VALUES
            ('c0000000-0000-0000-0000-000000000001'::uuid, 'macro|[email protected]', 'fa-child', '[email protected]', 'GMAIL', true, NOW(), NOW())
        "#,
    )
    .execute(&pool)
    .await?;

    sqlx::query(
        r#"INSERT INTO email_threads (id, link_id)
           VALUES ('c0000000-0000-0000-0000-0000000000ff'::uuid, 'c0000000-0000-0000-0000-000000000001'::uuid)"#,
    )
    .execute(&pool)
    .await?;

    sqlx::query(
        r#"INSERT INTO macro_user_links (primary_macro_id, child_macro_id, link_id)
           VALUES ('macro|[email protected]', 'macro|[email protected]', 'c0000000-0000-0000-0000-000000000001'::uuid)"#,
    )
    .execute(&pool)
    .await?;

    let repo = EmailPgRepo::new(pool);
    let thread_id = Uuid::parse_str("c0000000-0000-0000-0000-0000000000ff")?;
    let link_id = Uuid::parse_str("c0000000-0000-0000-0000-000000000001")?;

    // delegate resolves the shared inbox
    let delegated = repo
        .owned_link_for_thread(
            thread_id,
            MacroUserIdStr::parse_from_str("macro|[email protected]")?,
        )
        .await?;
    assert_eq!(delegated.map(|l| l.id), Some(link_id));

    // owner resolves their own inbox
    let owned = repo
        .owned_link_for_thread(
            thread_id,
            MacroUserIdStr::parse_from_str("macro|[email protected]")?,
        )
        .await?;
    assert_eq!(owned.map(|l| l.id), Some(link_id));

    // an unrelated but real user resolves nothing
    let none = repo
        .owned_link_for_thread(
            thread_id,
            MacroUserIdStr::parse_from_str("macro|[email protected]")?,
        )
        .await?;
    assert!(none.is_none());

    Ok(())
}