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.

37.9 KB
Raw Blame
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use macro_user_id::cowlike::CowLike;
use macro_uuid::Uuid;
use model_entity::EntityType;
use model_owner::{Owner, OwnerType};
use models_permissions::share_permission::access_level::AccessLevel;
use models_permissions::share_permission::channel_share_permission::{
    UpdateChannelSharePermission, UpdateOperation,
};
use sqlx::Row as _;
use sqlx::types::chrono::{DateTime, Utc};
use sqlx::{Pool, Postgres, Transaction};

use super::*;

const ROOT_PROJECT_ID: Uuid = Uuid::from_u128(0x11111111_1111_1111_1111_111111111111);
const CHILD_PROJECT_ID: Uuid = Uuid::from_u128(0x22222222_2222_2222_2222_222222222222);
const EMPTY_PROJECT_ID: Uuid = Uuid::from_u128(0x33333333_3333_3333_3333_333333333333);
const DOC_ROOT_ID: Uuid = Uuid::from_u128(0x44444444_4444_4444_4444_444444444444);
const DOC_CHILD_ID: Uuid = Uuid::from_u128(0x55555555_5555_5555_5555_555555555555);
const CHAT_CHILD_ID: Uuid = Uuid::from_u128(0x66666666_6666_6666_6666_666666666666);
const CHAT_ROOT_ID: Uuid = Uuid::from_u128(0x77777777_7777_7777_7777_777777777777);

#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn bulk_user_upsert_raises_viewers_and_adds_strangers_but_leaves_the_owner(
    pool: Pool<Postgres>,
) {
    let session_id = Uuid::from_u128(0x77777777_7777_7777_7777_777777777779);
    let owner = MacroUserIdStr::try_from_email("[email protected]").unwrap();
    let viewer = MacroUserIdStr::try_from_email("[email protected]").unwrap();
    let stranger = MacroUserIdStr::try_from_email("[email protected]").unwrap();
    let mut tx = pool.begin().await.unwrap();
    for (user, level) in [(&owner, AccessLevel::Owner), (&viewer, AccessLevel::View)] {
        insert_entity_access_for_test(
            &mut tx,
            &session_id,
            EntityType::AgentSession,
            user.as_ref(),
            EntityAccessSourceType::User,
            level,
            None,
        )
        .await;
    }
    tx.commit().await.unwrap();

    upsert_user_entity_access_bulk(
        &pool,
        &[owner.clone(), viewer.clone(), stranger.clone()],
        &session_id,
        EntityType::AgentSession,
        AccessLevel::Edit,
    )
    .await
    .unwrap();

    let rows = fetch_entity_access_rows(&pool, &session_id, EntityType::AgentSession).await;
    let level_of = |user: &MacroUserIdStr<'_>| {
        rows.iter()
            .find(|row| row.source_id == user.as_ref())
            .map(|row| row.access_level)
            .expect("a row for every user")
    };
    assert_eq!(level_of(&owner), AccessLevel::Owner);
    assert_eq!(level_of(&viewer), AccessLevel::Edit);
    assert_eq!(level_of(&stranger), AccessLevel::Edit);
}

#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn session_channel_edit_grant_is_idempotent_and_removable(pool: Pool<Postgres>) {
    let session_id = Uuid::from_u128(0x77777777_7777_7777_7777_777777777778);
    for _ in 0..2 {
        let mut tx = pool.begin().await.unwrap();
        update_entity_access_channel_share_permissions(
            &mut tx,
            &session_id,
            EntityType::AgentSession,
            &[UpdateChannelSharePermission {
                operation: UpdateOperation::Add,
                channel_id: "session-channel".to_owned(),
                access_level: Some(AccessLevel::Edit),
            }],
        )
        .await
        .unwrap();
        tx.commit().await.unwrap();
    }
    let rows = fetch_channel_rows(&pool, "session-channel").await;
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0].entity_type, "agent_session");
    assert_eq!(rows[0].access_level, AccessLevel::Edit);
    assert!(rows[0].granted_from_project_id.is_none());
    let mut tx = pool.begin().await.unwrap();
    update_entity_access_channel_share_permissions(
        &mut tx,
        &session_id,
        EntityType::AgentSession,
        &[UpdateChannelSharePermission {
            operation: UpdateOperation::Remove,
            channel_id: "session-channel".to_owned(),
            access_level: None,
        }],
    )
    .await
    .unwrap();
    tx.commit().await.unwrap();
    assert!(
        fetch_channel_rows(&pool, "session-channel")
            .await
            .is_empty()
    );
}

#[derive(Debug)]
struct Row {
    entity_id: Uuid,
    entity_type: String,
    source_id: String,
    access_level: AccessLevel,
    granted_from_project_id: Option<String>,
}

async fn fetch_channel_rows(pool: &Pool<Postgres>, channel_id: &str) -> Vec<Row> {
    // Runtime query (not the compile-time macro) so this test file does not
    // require a `.sqlx` cache entry to build.
    sqlx::query(
        r#"
        SELECT
            entity_id,
            entity_type,
            source_id,
            access_level,
            granted_from_project_id
        FROM entity_access
        WHERE source_id = $1 AND source_type = 'channel'
        ORDER BY entity_type, entity_id, granted_from_project_id NULLS FIRST
        "#,
    )
    .bind(channel_id)
    .map(|r: sqlx::postgres::PgRow| Row {
        entity_id: r.get("entity_id"),
        entity_type: r.get("entity_type"),
        source_id: r.get("source_id"),
        access_level: r.get("access_level"),
        granted_from_project_id: r.get("granted_from_project_id"),
    })
    .fetch_all(pool)
    .await
    .unwrap()
}

#[derive(Debug)]
struct EntityAccessRow {
    source_id: String,
    source_type: String,
    access_level: AccessLevel,
    granted_from_project_id: Option<String>,
    created_at: DateTime<Utc>,
    updated_at: DateTime<Utc>,
}

async fn insert_entity_access_for_test(
    transaction: &mut Transaction<'_, Postgres>,
    entity_id: &Uuid,
    entity_type: EntityType,
    source_id: &str,
    source_type: EntityAccessSourceType,
    access_level: AccessLevel,
    granted_from_project_id: Option<&str>,
) {
    // Runtime query (not the compile-time macro) so this test helper does not
    // require a `.sqlx` cache entry to build.
    sqlx::query(
        r#"
        INSERT INTO entity_access (
            entity_id,
            entity_type,
            source_id,
            source_type,
            access_level,
            granted_from_project_id
        )
        VALUES ($1, $2, $3, $4, $5, $6)
        "#,
    )
    .bind(entity_id)
    .bind(entity_type.as_ref())
    .bind(source_id)
    .bind(source_type)
    .bind(access_level)
    .bind(granted_from_project_id)
    .execute(transaction.as_mut())
    .await
    .unwrap();
}

async fn fetch_entity_access_rows(
    pool: &Pool<Postgres>,
    entity_id: &Uuid,
    entity_type: EntityType,
) -> Vec<EntityAccessRow> {
    // Runtime query (not the compile-time macro) so this test helper does not
    // require a `.sqlx` cache entry to build.
    sqlx::query(
        r#"
        SELECT
            source_id,
            source_type::text AS source_type,
            access_level,
            granted_from_project_id,
            created_at,
            updated_at
        FROM entity_access
        WHERE entity_id = $1 AND entity_type = $2
        ORDER BY source_type, source_id, granted_from_project_id NULLS FIRST
        "#,
    )
    .bind(entity_id)
    .bind(entity_type.as_ref())
    .map(|r: sqlx::postgres::PgRow| EntityAccessRow {
        source_id: r.get("source_id"),
        source_type: r.get("source_type"),
        access_level: r.get("access_level"),
        granted_from_project_id: r.get("granted_from_project_id"),
        created_at: r.get("created_at"),
        updated_at: r.get("updated_at"),
    })
    .fetch_all(pool)
    .await
    .unwrap()
}

fn grants(rows: &[EntityAccessRow]) -> Vec<(&str, &str, AccessLevel, Option<&str>)> {
    rows.iter()
        .map(|row| {
            (
                row.source_type.as_str(),
                row.source_id.as_str(),
                row.access_level,
                row.granted_from_project_id.as_deref(),
            )
        })
        .collect()
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../fixtures", scripts("upsert_test_data"))
)]
async fn upsert_single_channel_to_chat(pool: Pool<Postgres>) {
    let mut tx = pool.begin().await.unwrap();

    let perms = vec![UpdateChannelSharePermission {
        operation: UpdateOperation::Add,
        channel_id: "channel-1".to_string(),
        access_level: Some(AccessLevel::Edit),
    }];

    update_entity_access_channel_share_permissions(
        &mut tx,
        &CHAT_ROOT_ID,
        EntityType::Chat,
        &perms,
    )
    .await
    .unwrap();
    tx.commit().await.unwrap();

    let rows = fetch_channel_rows(&pool, "channel-1").await;
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0].entity_id, CHAT_ROOT_ID);
    assert_eq!(rows[0].entity_type, "chat");
    assert_eq!(rows[0].source_id, "channel-1");
    assert_eq!(rows[0].access_level, AccessLevel::Edit);
    assert!(rows[0].granted_from_project_id.is_none());
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../fixtures", scripts("upsert_test_data"))
)]
async fn upsert_multiple_channels_to_document(pool: Pool<Postgres>) {
    let mut tx = pool.begin().await.unwrap();

    let perms = vec![
        UpdateChannelSharePermission {
            operation: UpdateOperation::Add,
            channel_id: "channel-a".to_string(),
            access_level: Some(AccessLevel::View),
        },
        UpdateChannelSharePermission {
            operation: UpdateOperation::Add,
            channel_id: "channel-b".to_string(),
            access_level: Some(AccessLevel::Comment),
        },
        UpdateChannelSharePermission {
            operation: UpdateOperation::Add,
            channel_id: "channel-c".to_string(),
            access_level: None, // defaults to View
        },
    ];

    update_entity_access_channel_share_permissions(
        &mut tx,
        &DOC_ROOT_ID,
        EntityType::Document,
        &perms,
    )
    .await
    .unwrap();
    tx.commit().await.unwrap();

    let mut all_rows = Vec::new();
    for ch in ["channel-a", "channel-b", "channel-c"] {
        all_rows.extend(fetch_channel_rows(&pool, ch).await);
    }

    assert_eq!(all_rows.len(), 3);
    let by_ch: std::collections::HashMap<_, _> =
        all_rows.iter().map(|r| (r.source_id.as_str(), r)).collect();

    assert_eq!(by_ch["channel-a"].access_level, AccessLevel::View);
    assert_eq!(by_ch["channel-b"].access_level, AccessLevel::Comment);
    assert_eq!(by_ch["channel-c"].access_level, AccessLevel::View);
    assert!(
        all_rows
            .iter()
            .all(|r| r.entity_id == DOC_ROOT_ID && r.entity_type == "document")
    );
    assert!(all_rows.iter().all(|r| r.granted_from_project_id.is_none()));
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../fixtures", scripts("upsert_test_data"))
)]
async fn upsert_to_project_inserts_direct_grant_and_inherited_rows(pool: Pool<Postgres>) {
    let mut tx = pool.begin().await.unwrap();

    let perms = vec![UpdateChannelSharePermission {
        operation: UpdateOperation::Add,
        channel_id: "channel-1".to_string(),
        access_level: Some(AccessLevel::Comment),
    }];

    update_entity_access_channel_share_permissions(
        &mut tx,
        &ROOT_PROJECT_ID,
        EntityType::Project,
        &perms,
    )
    .await
    .unwrap();
    tx.commit().await.unwrap();

    let rows = fetch_channel_rows(&pool, "channel-1").await;
    // root project (direct), child project (inherited), doc-root (inherited),
    // doc-child (inherited), chat-child (inherited), chat-root (inherited) = 6
    assert_eq!(rows.len(), 6);

    // All rows are for channel-1 with Comment access.
    assert!(rows.iter().all(|r| r.access_level == AccessLevel::Comment));

    // The project itself: direct grant (NULL granted_from)
    let project_row = rows
        .iter()
        .find(|r| r.entity_id == ROOT_PROJECT_ID && r.entity_type == "project")
        .unwrap();
    assert!(project_row.granted_from_project_id.is_none());

    // Every other row: inherited from ROOT_PROJECT_ID
    let inherited: Vec<_> = rows
        .iter()
        .filter(|r| !(r.entity_id == ROOT_PROJECT_ID && r.entity_type == "project"))
        .collect();
    assert_eq!(inherited.len(), 5);
    let root_str = ROOT_PROJECT_ID.to_string();
    assert!(
        inherited
            .iter()
            .all(|r| r.granted_from_project_id.as_deref() == Some(root_str.as_str()))
    );

    // Spot-check each expected nested entity is present.
    assert!(
        inherited
            .iter()
            .any(|r| r.entity_id == CHILD_PROJECT_ID && r.entity_type == "project")
    );
    assert!(
        inherited
            .iter()
            .any(|r| r.entity_id == DOC_ROOT_ID && r.entity_type == "document")
    );
    assert!(
        inherited
            .iter()
            .any(|r| r.entity_id == DOC_CHILD_ID && r.entity_type == "document")
    );
    assert!(
        inherited
            .iter()
            .any(|r| r.entity_id == CHAT_CHILD_ID && r.entity_type == "chat")
    );
    assert!(
        inherited
            .iter()
            .any(|r| r.entity_id == CHAT_ROOT_ID && r.entity_type == "chat")
    );
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../fixtures", scripts("upsert_test_data"))
)]
async fn replace_updates_access_level_on_existing_row(pool: Pool<Postgres>) {
    // First: insert a row with View
    let mut tx = pool.begin().await.unwrap();
    let perms = vec![UpdateChannelSharePermission {
        operation: UpdateOperation::Add,
        channel_id: "channel-1".to_string(),
        access_level: Some(AccessLevel::View),
    }];
    update_entity_access_channel_share_permissions(
        &mut tx,
        &DOC_ROOT_ID,
        EntityType::Document,
        &perms,
    )
    .await
    .unwrap();
    tx.commit().await.unwrap();

    let initial = fetch_channel_rows(&pool, "channel-1").await;
    assert_eq!(initial.len(), 1);
    assert_eq!(initial[0].access_level, AccessLevel::View);

    // Second: replace with Edit
    let mut tx = pool.begin().await.unwrap();
    let perms = vec![UpdateChannelSharePermission {
        operation: UpdateOperation::Replace,
        channel_id: "channel-1".to_string(),
        access_level: Some(AccessLevel::Edit),
    }];
    update_entity_access_channel_share_permissions(
        &mut tx,
        &DOC_ROOT_ID,
        EntityType::Document,
        &perms,
    )
    .await
    .unwrap();
    tx.commit().await.unwrap();

    let after = fetch_channel_rows(&pool, "channel-1").await;
    // Still exactly one row — the existing row was updated, not duplicated.
    assert_eq!(after.len(), 1);
    assert_eq!(after[0].entity_id, DOC_ROOT_ID);
    assert_eq!(after[0].access_level, AccessLevel::Edit);
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../fixtures", scripts("upsert_test_data"))
)]
async fn remove_then_upsert_in_same_call_yields_upserted_state(pool: Pool<Postgres>) {
    // Pre-populate: View access on chat-root for channel-1
    let mut tx = pool.begin().await.unwrap();
    update_entity_access_channel_share_permissions(
        &mut tx,
        &CHAT_ROOT_ID,
        EntityType::Chat,
        &[UpdateChannelSharePermission {
            operation: UpdateOperation::Add,
            channel_id: "channel-1".to_string(),
            access_level: Some(AccessLevel::View),
        }],
    )
    .await
    .unwrap();
    tx.commit().await.unwrap();

    // Now: remove + upsert the same channel in a single call. Final state
    // should be the upsert (Edit), since remove runs first, then upsert.
    let mut tx = pool.begin().await.unwrap();
    let perms = vec![
        UpdateChannelSharePermission {
            operation: UpdateOperation::Remove,
            channel_id: "channel-1".to_string(),
            access_level: None,
        },
        UpdateChannelSharePermission {
            operation: UpdateOperation::Add,
            channel_id: "channel-1".to_string(),
            access_level: Some(AccessLevel::Edit),
        },
    ];
    update_entity_access_channel_share_permissions(
        &mut tx,
        &CHAT_ROOT_ID,
        EntityType::Chat,
        &perms,
    )
    .await
    .unwrap();
    tx.commit().await.unwrap();

    let rows = fetch_channel_rows(&pool, "channel-1").await;
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0].entity_id, CHAT_ROOT_ID);
    assert_eq!(rows[0].access_level, AccessLevel::Edit);
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../fixtures", scripts("upsert_test_data"))
)]
async fn upsert_to_project_with_no_children_inserts_only_project_row(pool: Pool<Postgres>) {
    let mut tx = pool.begin().await.unwrap();

    let perms = vec![UpdateChannelSharePermission {
        operation: UpdateOperation::Add,
        channel_id: "channel-1".to_string(),
        access_level: Some(AccessLevel::View),
    }];

    update_entity_access_channel_share_permissions(
        &mut tx,
        &EMPTY_PROJECT_ID,
        EntityType::Project,
        &perms,
    )
    .await
    .unwrap();
    tx.commit().await.unwrap();

    let rows = fetch_channel_rows(&pool, "channel-1").await;
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0].entity_id, EMPTY_PROJECT_ID);
    assert_eq!(rows[0].entity_type, "project");
    assert!(rows[0].granted_from_project_id.is_none());
    assert_eq!(rows[0].access_level, AccessLevel::View);
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../fixtures", scripts("upsert_test_data"))
)]
async fn remove_non_owner_user_entity_access_removes_direct_non_owner_users(pool: Pool<Postgres>) {
    let owner_id = "macro|[email protected]";
    let mut tx = pool.begin().await.unwrap();

    insert_entity_access_for_test(
        &mut tx,
        &DOC_ROOT_ID,
        EntityType::Document,
        owner_id,
        EntityAccessSourceType::User,
        AccessLevel::Owner,
        None,
    )
    .await;
    insert_entity_access_for_test(
        &mut tx,
        &DOC_ROOT_ID,
        EntityType::Document,
        "macro|[email protected]",
        EntityAccessSourceType::User,
        AccessLevel::View,
        None,
    )
    .await;
    insert_entity_access_for_test(
        &mut tx,
        &DOC_ROOT_ID,
        EntityType::Document,
        "macro|[email protected]",
        EntityAccessSourceType::User,
        AccessLevel::Edit,
        None,
    )
    .await;

    remove_non_owner_user_entity_access(&mut tx, &DOC_ROOT_ID, EntityType::Document, owner_id)
        .await
        .unwrap();
    tx.commit().await.unwrap();

    let rows = fetch_entity_access_rows(&pool, &DOC_ROOT_ID, EntityType::Document).await;
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0].source_type, "user");
    assert_eq!(rows[0].source_id, owner_id);
    assert_eq!(rows[0].access_level, AccessLevel::Owner);
    assert!(rows[0].granted_from_project_id.is_none());
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../fixtures", scripts("upsert_test_data"))
)]
async fn remove_non_owner_user_entity_access_preserves_non_user_inherited_and_other_entities(
    pool: Pool<Postgres>,
) {
    let owner_id = "macro|[email protected]";
    let shared_user_id = "macro|[email protected]";
    let root_project_id = ROOT_PROJECT_ID.to_string();
    let mut tx = pool.begin().await.unwrap();

    insert_entity_access_for_test(
        &mut tx,
        &DOC_ROOT_ID,
        EntityType::Document,
        owner_id,
        EntityAccessSourceType::User,
        AccessLevel::Owner,
        None,
    )
    .await;
    insert_entity_access_for_test(
        &mut tx,
        &DOC_ROOT_ID,
        EntityType::Document,
        shared_user_id,
        EntityAccessSourceType::User,
        AccessLevel::View,
        None,
    )
    .await;
    insert_entity_access_for_test(
        &mut tx,
        &DOC_ROOT_ID,
        EntityType::Document,
        shared_user_id,
        EntityAccessSourceType::User,
        AccessLevel::View,
        Some(root_project_id.as_str()),
    )
    .await;
    insert_entity_access_for_test(
        &mut tx,
        &DOC_ROOT_ID,
        EntityType::Document,
        "team-1",
        EntityAccessSourceType::Team,
        AccessLevel::Edit,
        None,
    )
    .await;
    insert_entity_access_for_test(
        &mut tx,
        &DOC_ROOT_ID,
        EntityType::Document,
        "channel-1",
        EntityAccessSourceType::Channel,
        AccessLevel::Comment,
        None,
    )
    .await;
    insert_entity_access_for_test(
        &mut tx,
        &DOC_CHILD_ID,
        EntityType::Document,
        "macro|[email protected]",
        EntityAccessSourceType::User,
        AccessLevel::View,
        None,
    )
    .await;
    insert_entity_access_for_test(
        &mut tx,
        &DOC_ROOT_ID,
        EntityType::Chat,
        "macro|[email protected]",
        EntityAccessSourceType::User,
        AccessLevel::View,
        None,
    )
    .await;

    remove_non_owner_user_entity_access(&mut tx, &DOC_ROOT_ID, EntityType::Document, owner_id)
        .await
        .unwrap();
    tx.commit().await.unwrap();

    let target_rows = fetch_entity_access_rows(&pool, &DOC_ROOT_ID, EntityType::Document).await;
    assert_eq!(target_rows.len(), 4);
    assert!(target_rows.iter().any(|r| {
        r.source_type == "user"
            && r.source_id == owner_id
            && r.access_level == AccessLevel::Owner
            && r.granted_from_project_id.is_none()
    }));
    assert!(target_rows.iter().any(|r| {
        r.source_type == "user"
            && r.source_id == shared_user_id
            && r.access_level == AccessLevel::View
            && r.granted_from_project_id.as_deref() == Some(root_project_id.as_str())
    }));
    assert!(target_rows.iter().any(|r| {
        r.source_type == "team"
            && r.source_id == "team-1"
            && r.access_level == AccessLevel::Edit
            && r.granted_from_project_id.is_none()
    }));
    assert!(target_rows.iter().any(|r| {
        r.source_type == "channel"
            && r.source_id == "channel-1"
            && r.access_level == AccessLevel::Comment
            && r.granted_from_project_id.is_none()
    }));
    assert!(!target_rows.iter().any(|r| {
        r.source_type == "user"
            && r.source_id == shared_user_id
            && r.granted_from_project_id.is_none()
    }));

    let other_entity_rows =
        fetch_entity_access_rows(&pool, &DOC_CHILD_ID, EntityType::Document).await;
    assert_eq!(other_entity_rows.len(), 1);
    assert_eq!(other_entity_rows[0].source_type, "user");
    assert_eq!(
        other_entity_rows[0].source_id,
        "macro|[email protected]"
    );
    assert_eq!(other_entity_rows[0].access_level, AccessLevel::View);
    assert!(other_entity_rows[0].granted_from_project_id.is_none());

    let other_type_rows = fetch_entity_access_rows(&pool, &DOC_ROOT_ID, EntityType::Chat).await;
    assert_eq!(other_type_rows.len(), 1);
    assert_eq!(other_type_rows[0].source_type, "user");
    assert_eq!(other_type_rows[0].source_id, "macro|[email protected]");
    assert_eq!(other_type_rows[0].access_level, AccessLevel::View);
    assert!(other_type_rows[0].granted_from_project_id.is_none());
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../fixtures", scripts("upsert_test_data"))
)]
async fn delete_user_entity_access_rows_removes_targeted_direct_grants_only(pool: Pool<Postgres>) {
    let initiative_id = Uuid::from_u128(0x0b01);
    let other_initiative_id = Uuid::from_u128(0x0b02);
    let root_project_id = ROOT_PROJECT_ID.to_string();
    let owner = MacroUserIdStr::try_from_email("[email protected]").unwrap();
    let alice = MacroUserIdStr::try_from_email("[email protected]").unwrap();
    let bob = MacroUserIdStr::try_from_email("[email protected]").unwrap();
    let carol = MacroUserIdStr::try_from_email("[email protected]").unwrap();

    let mut tx = pool.begin().await.unwrap();
    for (user, access_level, granted_from_project_id) in [
        (&owner, AccessLevel::Owner, None),
        (&alice, AccessLevel::Edit, None),
        (&bob, AccessLevel::View, None),
        (&bob, AccessLevel::Edit, Some(root_project_id.as_str())),
        (&carol, AccessLevel::View, None),
    ] {
        insert_entity_access_for_test(
            &mut tx,
            &initiative_id,
            EntityType::Initiative,
            user.as_ref(),
            EntityAccessSourceType::User,
            access_level,
            granted_from_project_id,
        )
        .await;
    }
    insert_entity_access_for_test(
        &mut tx,
        &initiative_id,
        EntityType::Initiative,
        BOT_PRINCIPAL,
        EntityAccessSourceType::Bot,
        AccessLevel::Edit,
        None,
    )
    .await;
    for (source_id, source_type, access_level) in [
        ("team-1", EntityAccessSourceType::Team, AccessLevel::Edit),
        (
            "channel-1",
            EntityAccessSourceType::Channel,
            AccessLevel::Comment,
        ),
    ] {
        insert_entity_access_for_test(
            &mut tx,
            &initiative_id,
            EntityType::Initiative,
            source_id,
            source_type,
            access_level,
            None,
        )
        .await;
    }
    insert_entity_access_for_test(
        &mut tx,
        &other_initiative_id,
        EntityType::Initiative,
        alice.as_ref(),
        EntityAccessSourceType::User,
        AccessLevel::Edit,
        None,
    )
    .await;
    insert_entity_access_for_test(
        &mut tx,
        &initiative_id,
        EntityType::Document,
        alice.as_ref(),
        EntityAccessSourceType::User,
        AccessLevel::Edit,
        None,
    )
    .await;

    delete_user_entity_access_rows(
        &mut tx,
        &initiative_id,
        EntityType::Initiative,
        &[owner.clone(), alice.clone(), bob.clone()],
    )
    .await
    .unwrap();
    tx.commit().await.unwrap();

    let rows = fetch_entity_access_rows(&pool, &initiative_id, EntityType::Initiative).await;
    assert_eq!(
        grants(&rows),
        vec![
            ("bot", BOT_PRINCIPAL, AccessLevel::Edit, None),
            ("channel", "channel-1", AccessLevel::Comment, None),
            ("team", "team-1", AccessLevel::Edit, None),
            (
                "user",
                "macro|[email protected]",
                AccessLevel::Edit,
                Some(root_project_id.as_str()),
            ),
            ("user", "macro|[email protected]", AccessLevel::View, None),
            ("user", "macro|[email protected]", AccessLevel::Owner, None),
        ]
    );

    let other_entity_rows =
        fetch_entity_access_rows(&pool, &other_initiative_id, EntityType::Initiative).await;
    assert_eq!(
        grants(&other_entity_rows),
        vec![("user", "macro|[email protected]", AccessLevel::Edit, None)]
    );

    let other_type_rows =
        fetch_entity_access_rows(&pool, &initiative_id, EntityType::Document).await;
    assert_eq!(
        grants(&other_type_rows),
        vec![("user", "macro|[email protected]", AccessLevel::Edit, None)]
    );
}

#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn delete_user_entity_access_rows_without_user_ids_keeps_every_row(pool: Pool<Postgres>) {
    let initiative_id = Uuid::from_u128(0x0b03);
    let owner = MacroUserIdStr::try_from_email("[email protected]").unwrap();
    let alice = MacroUserIdStr::try_from_email("[email protected]").unwrap();

    let mut tx = pool.begin().await.unwrap();
    for (user, access_level) in [(&owner, AccessLevel::Owner), (&alice, AccessLevel::Edit)] {
        insert_entity_access_for_test(
            &mut tx,
            &initiative_id,
            EntityType::Initiative,
            user.as_ref(),
            EntityAccessSourceType::User,
            access_level,
            None,
        )
        .await;
    }

    delete_user_entity_access_rows(&mut tx, &initiative_id, EntityType::Initiative, &[])
        .await
        .unwrap();
    tx.commit().await.unwrap();

    let rows = fetch_entity_access_rows(&pool, &initiative_id, EntityType::Initiative).await;
    assert_eq!(
        grants(&rows),
        vec![
            ("user", "macro|[email protected]", AccessLevel::Edit, None),
            ("user", "macro|[email protected]", AccessLevel::Owner, None),
        ]
    );
}

#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn delete_user_entity_access_rows_keeps_team_and_channel_grants_that_share_a_targeted_user_id(
    pool: Pool<Postgres>,
) {
    let initiative_id = Uuid::from_u128(0x0b04);
    let alice = MacroUserIdStr::try_from_email("[email protected]").unwrap();

    let mut tx = pool.begin().await.unwrap();
    for (source_type, access_level) in [
        (EntityAccessSourceType::User, AccessLevel::Edit),
        (EntityAccessSourceType::Team, AccessLevel::Edit),
        (EntityAccessSourceType::Channel, AccessLevel::Comment),
    ] {
        insert_entity_access_for_test(
            &mut tx,
            &initiative_id,
            EntityType::Initiative,
            alice.as_ref(),
            source_type,
            access_level,
            None,
        )
        .await;
    }

    delete_user_entity_access_rows(
        &mut tx,
        &initiative_id,
        EntityType::Initiative,
        &[alice.clone()],
    )
    .await
    .unwrap();
    tx.commit().await.unwrap();

    let rows = fetch_entity_access_rows(&pool, &initiative_id, EntityType::Initiative).await;
    assert_eq!(
        grants(&rows),
        vec![
            ("channel", alice.as_ref(), AccessLevel::Comment, None),
            ("team", alice.as_ref(), AccessLevel::Edit, None),
        ]
    );
}

const OWNER_TEAM_ID: Uuid = Uuid::from_u128(0x0000000a_0000_0000_0000_00000000000a);
const BOT_PRINCIPAL: &str = "bot|0000000b-0000-0000-0000-00000000000b";

fn user_owner() -> Owner {
    Owner::User(MacroUserIdStr::try_from_email("[email protected]").unwrap())
}

async fn grant_owner_committed(pool: &Pool<Postgres>, entity_id: &Uuid, owner: &Owner) {
    let mut tx = pool.begin().await.unwrap();
    upsert_owner_grant(&mut tx, entity_id, EntityType::Document, owner)
        .await
        .unwrap();
    tx.commit().await.unwrap();
}

#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn owner_grant_twice_is_a_no_op(pool: Pool<Postgres>) {
    let entity_id = Uuid::from_u128(0x0a01);
    grant_owner_committed(&pool, &entity_id, &user_owner()).await;
    grant_owner_committed(&pool, &entity_id, &user_owner()).await;

    let rows = fetch_entity_access_rows(&pool, &entity_id, EntityType::Document).await;
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0].access_level, AccessLevel::Owner);
    assert!(rows[0].granted_from_project_id.is_none());
    assert_eq!(rows[0].updated_at, rows[0].created_at);
}

#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn owner_grant_raises_direct_edit_to_owner_and_leaves_other_principals(pool: Pool<Postgres>) {
    let entity_id = Uuid::from_u128(0x0a02);
    let owner = user_owner();
    let mut tx = pool.begin().await.unwrap();
    insert_entity_access_for_test(
        &mut tx,
        &entity_id,
        EntityType::Document,
        &owner.principal_id(),
        EntityAccessSourceType::User,
        AccessLevel::Edit,
        None,
    )
    .await;
    insert_entity_access_for_test(
        &mut tx,
        &entity_id,
        EntityType::Document,
        "macro|[email protected]",
        EntityAccessSourceType::User,
        AccessLevel::View,
        None,
    )
    .await;
    tx.commit().await.unwrap();

    let before = fetch_entity_access_rows(&pool, &entity_id, EntityType::Document).await;
    let before_owner = before
        .iter()
        .find(|row| row.source_id == owner.principal_id())
        .unwrap();
    let before_updated_at = before_owner.updated_at;

    grant_owner_committed(&pool, &entity_id, &owner).await;

    let rows = fetch_entity_access_rows(&pool, &entity_id, EntityType::Document).await;
    assert_eq!(rows.len(), 2, "updated in place, not duplicated");
    let owner_row = rows
        .iter()
        .find(|row| row.source_id == owner.principal_id())
        .unwrap();
    assert_eq!(owner_row.access_level, AccessLevel::Owner);
    assert!(owner_row.granted_from_project_id.is_none());
    assert!(owner_row.updated_at > before_updated_at);
    let viewer_row = rows
        .iter()
        .find(|row| row.source_id == "macro|[email protected]")
        .unwrap();
    assert_eq!(viewer_row.access_level, AccessLevel::View);
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../fixtures", scripts("upsert_test_data"))
)]
async fn owner_grant_leaves_project_inherited_rows_untouched(pool: Pool<Postgres>) {
    let owner = user_owner();
    let root = ROOT_PROJECT_ID.to_string();
    let mut tx = pool.begin().await.unwrap();
    insert_entity_access_for_test(
        &mut tx,
        &DOC_ROOT_ID,
        EntityType::Document,
        &owner.principal_id(),
        EntityAccessSourceType::User,
        AccessLevel::Edit,
        Some(&root),
    )
    .await;
    tx.commit().await.unwrap();

    grant_owner_committed(&pool, &DOC_ROOT_ID, &owner).await;
    grant_owner_committed(&pool, &DOC_ROOT_ID, &owner).await;

    let rows = fetch_entity_access_rows(&pool, &DOC_ROOT_ID, EntityType::Document).await;
    assert_eq!(rows.len(), 2, "inherited row and direct row coexist");
    let inherited = rows
        .iter()
        .find(|row| row.granted_from_project_id.is_some())
        .unwrap();
    assert_eq!(
        inherited.granted_from_project_id.as_deref(),
        Some(root.as_str())
    );
    assert_eq!(inherited.access_level, AccessLevel::Edit);
    assert_eq!(inherited.updated_at, inherited.created_at);
    let direct = rows
        .iter()
        .find(|row| row.granted_from_project_id.is_none())
        .unwrap();
    assert_eq!(direct.access_level, AccessLevel::Owner);
}

#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn owner_grant_maps_user_bot_and_team_to_their_access_source(pool: Pool<Postgres>) {
    let cases = [
        (user_owner(), "user", "macro|[email protected]".to_owned()),
        (
            Owner::parse(OwnerType::Bot, BOT_PRINCIPAL).unwrap(),
            "bot",
            BOT_PRINCIPAL.to_owned(),
        ),
        (
            Owner::Team(OWNER_TEAM_ID),
            "team",
            OWNER_TEAM_ID.to_string(),
        ),
    ];
    for (i, (owner, expected_source_type, expected_source_id)) in cases.into_iter().enumerate() {
        let entity_id = Uuid::from_u128(0x0a10 + i as u128);
        grant_owner_committed(&pool, &entity_id, &owner).await;

        let rows = fetch_entity_access_rows(&pool, &entity_id, EntityType::Document).await;
        assert_eq!(rows.len(), 1, "{owner:?}");
        assert_eq!(rows[0].source_type, expected_source_type, "{owner:?}");
        assert_eq!(rows[0].source_id, expected_source_id, "{owner:?}");
        assert_eq!(rows[0].access_level, AccessLevel::Owner);
        assert!(rows[0].granted_from_project_id.is_none());
    }
}

#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn ensuring_comment_access_upgrades_view_and_preserves_stronger_grants(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let entity = Uuid::now_v7();
    sqlx::query!(
        "INSERT INTO \"SharePermission\" (id) VALUES ($1)",
        entity.to_string()
    )
    .execute(&pool)
    .await?;
    sqlx::query!("INSERT INTO calls (id, room_name, created_by, share_permission_id) VALUES ($1, 'test-room', 'macro|[email protected]', $2)", entity, entity.to_string()).execute(&pool).await?;
    for (email, existing) in [
        ("[email protected]", Some(AccessLevel::Owner)),
        ("[email protected]", Some(AccessLevel::Edit)),
        ("[email protected]", Some(AccessLevel::View)),
        ("[email protected]", Some(AccessLevel::Comment)),
        ("[email protected]", None),
    ] {
        let user = MacroUserIdStr::try_from_email(email)?;
        if let Some(level) = existing {
            let mut tx = pool.begin().await?;
            insert_entity_access_row(
                &mut tx,
                &entity,
                EntityType::Call,
                user.as_ref(),
                EntityAccessSourceType::User,
                level,
            )
            .await?;
            tx.commit().await?;
        }
        sqlx::query!(
            "INSERT INTO call_participants (call_id, user_id) VALUES ($1, $2)",
            entity,
            user.as_ref()
        )
        .execute(&pool)
        .await?;
        for _ in 0..2 {
            ensure_call_participant_comment_access(&pool, &entity, user.clone()).await?;
        }
        let level = sqlx::query_scalar!(
            r#"SELECT access_level AS "access_level!: AccessLevel" FROM entity_access WHERE entity_id = $1 AND entity_type = 'call' AND source_id = $2 AND source_type = 'user' AND granted_from_project_id IS NULL"#,
            entity, user.as_ref(),
        ).fetch_one(&pool).await?;
        assert_eq!(
            level,
            match existing {
                Some(AccessLevel::Owner) => AccessLevel::Owner,
                Some(AccessLevel::Edit) => AccessLevel::Edit,
                _ => AccessLevel::Comment,
            }
        );
    }
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../call/fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn participant_grants_reject_channel_calls_nonparticipants_and_departed_users(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let call_id = Uuid::from_u128(0x00000000_0000_0000_0000_0000000ca110);
    let participant = MacroUserIdStr::try_from_email("[email protected]")?;
    ensure_call_participant_comment_access(&pool, &call_id, participant.copied()).await?;
    assert!(
        !fetch_entity_access_rows(&pool, &call_id, EntityType::Call)
            .await
            .iter()
            .any(|row| row.source_id == participant.as_ref())
    );

    sqlx::query!("UPDATE calls SET channel_id = NULL WHERE id = $1", call_id)
        .execute(&pool)
        .await?;
    let stranger = MacroUserIdStr::try_from_email("[email protected]")?;
    ensure_call_participant_comment_access(&pool, &call_id, stranger.copied()).await?;
    sqlx::query!(
        "UPDATE call_participants SET left_at = now() WHERE call_id = $1 AND user_id = $2",
        call_id,
        participant.as_ref()
    )
    .execute(&pool)
    .await?;
    ensure_call_participant_comment_access(&pool, &call_id, participant.copied()).await?;
    let rows = fetch_entity_access_rows(&pool, &call_id, EntityType::Call).await;
    assert!(
        !rows
            .iter()
            .any(|row| row.source_id == participant.as_ref() || row.source_id == stranger.as_ref())
    );
    Ok(())
}