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.

22.6 KB
Raw Blame
//! Integration tests for property definition operations on PropertiesPgRepo.

use super::properties_pg_repo::PropertiesPgRepo;
use super::property_definition_queries;
use crate::domain::model::PropertyDefinitionOwner;
use crate::domain::ports::PropertiesRepo;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use macro_user_id::user_id::MacroUserIdStr;
use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};
use models_properties::{DataType, EntityType};
use sqlx::{Pool, Postgres};
use uuid::Uuid;

fn user_1() -> MacroUserIdStr<'static> {
    MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()
}

fn user_2() -> MacroUserIdStr<'static> {
    MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()
}

fn user_3() -> MacroUserIdStr<'static> {
    MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()
}

fn team_1() -> Uuid {
    "0e000000-0000-0000-0000-000000000001".parse().unwrap()
}

fn team_2() -> Uuid {
    "0e000000-0000-0000-0000-000000000002".parse().unwrap()
}

fn new_option(display_order: i32, value: PropertyOptionValue) -> PropertyOption {
    PropertyOption {
        id: Uuid::nil(),
        property_definition_id: Uuid::nil(),
        display_order,
        value,
        color: None,
        created_at: chrono::Utc::now(),
        updated_at: chrono::Utc::now(),
    }
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../../fixtures", scripts("properties"))
)]
async fn option_batches_filter_requested_ids_and_caller_visibility(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = PropertiesPgRepo::new(pool);
    let priority = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
    let personal = Uuid::parse_str("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")?;
    let empty = Uuid::parse_str("88888888-8888-8888-8888-888888888888")?;
    let foreign = Uuid::parse_str("dddddddd-dddd-dddd-dddd-dddddddddddd")?;
    let system = repo.list_property_definitions(None, None, true).await?[0].id;
    let missing = Uuid::new_v4();
    let ids = [priority, personal, empty, foreign, system, missing];

    let options = repo
        .get_visible_property_options_batch(&ids, &user_1(), Some(team_1()))
        .await?;
    assert_eq!(options.len(), 4);
    assert_eq!(options[&personal].len(), 2);
    assert!(options[&empty].is_empty());
    assert!(options.contains_key(&system));
    assert!(!options.contains_key(&foreign));
    assert!(!options.contains_key(&missing));
    assert_eq!(
        options[&priority]
            .iter()
            .map(|option| option.display_order)
            .collect::<Vec<_>>(),
        vec![0, 1, 2, 3]
    );
    assert_eq!(
        options[&priority][0].value,
        PropertyOptionValue::String("Low".into())
    );

    let outsider_options = repo
        .get_visible_property_options_batch(&ids, &user_2(), None)
        .await?;
    assert_eq!(outsider_options.len(), 1);
    assert!(outsider_options.contains_key(&system));
    assert!(
        repo.get_visible_property_options_batch(&[], &user_1(), Some(team_1()))
            .await?
            .is_empty()
    );
    Ok(())
}

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

    let properties = repo
        .list_property_definitions(Some(team_1()), None, false)
        .await?;

    assert_eq!(properties.len(), 10); // Team 1 has 10 properties

    // Verify they are sorted by display name (case-insensitive alphabetical)
    assert_eq!(properties[0].display_name, "Test Assigned To");
    assert_eq!(properties[1].display_name, "Test Budget");
    assert_eq!(properties[2].display_name, "Test Completed");
    assert_eq!(properties[3].display_name, "Test Department");
    assert_eq!(properties[4].display_name, "Test Description");
    assert_eq!(properties[5].display_name, "Test Due Date");
    assert_eq!(properties[6].display_name, "Test Priority");
    assert_eq!(properties[7].display_name, "Test Relevant Documents");
    assert_eq!(properties[8].display_name, "Test Score");
    assert_eq!(properties[9].display_name, "Test Website");

    Ok(())
}

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

    let properties = repo
        .list_property_definitions(None, Some(&user_1()), false)
        .await?;

    assert_eq!(properties.len(), 2); // User1 has 2 properties
    assert_eq!(properties[0].display_name, "Test Notes");
    assert_eq!(properties[1].display_name, "Test Personal Priority");

    Ok(())
}

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

    let team_property_id = "11111111-1111-1111-1111-111111111111"
        .parse::<Uuid>()
        .unwrap();

    // The team owner can access the team property.
    let property = repo
        .get_property_definition_with_owner(team_property_id, &user_1(), Some(team_1()))
        .await?;
    assert!(property.is_some());

    // A different member of the same team can also access it.
    let property = repo
        .get_property_definition_with_owner(team_property_id, &user_3(), Some(team_1()))
        .await?;
    assert!(property.is_some());

    // A user on a different team cannot access it.
    let property = repo
        .get_property_definition_with_owner(team_property_id, &user_2(), Some(team_2()))
        .await?;
    assert!(property.is_none());

    // A user with no team cannot access it.
    let property = repo
        .get_property_definition_with_owner(team_property_id, &user_2(), None)
        .await?;
    assert!(property.is_none());

    // The owning user can access their own user property.
    let user_property_id = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
        .parse::<Uuid>()
        .unwrap();
    let property = repo
        .get_property_definition_with_owner(user_property_id, &user_1(), Some(team_1()))
        .await?;
    assert!(property.is_some());

    // A different user cannot access someone else's user property.
    let property = repo
        .get_property_definition_with_owner(user_property_id, &user_3(), Some(team_1()))
        .await?;
    assert!(property.is_none());

    Ok(())
}

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

    let properties = repo
        .list_property_definitions_with_options(Some(team_1()), None, false)
        .await?;

    assert_eq!(properties.len(), 10);

    // Priority property should have 4 options, properly ordered.
    let priority_prop = properties
        .iter()
        .find(|p| p.definition.display_name == "Test Priority")
        .unwrap();

    assert_eq!(priority_prop.property_options.len(), 4);
    assert_eq!(priority_prop.property_options[0].display_order, 0);
    assert_eq!(
        priority_prop.property_options[0].value,
        PropertyOptionValue::String("Low".to_string())
    );

    // Non-select properties should have no options.
    let completed_prop = properties
        .iter()
        .find(|p| p.definition.display_name == "Test Completed")
        .unwrap();
    assert_eq!(completed_prop.definition.data_type, DataType::Boolean);
    assert_eq!(completed_prop.property_options.len(), 0);

    // Number select options.
    let score_prop = properties
        .iter()
        .find(|p| p.definition.display_name == "Test Score")
        .unwrap();
    assert_eq!(score_prop.property_options.len(), 5);
    assert_eq!(score_prop.definition.data_type, DataType::SelectNumber);
    assert_eq!(
        score_prop.property_options[0].value,
        PropertyOptionValue::Number(4.0)
    );

    // Multi-select string options.
    let dept_prop = properties
        .iter()
        .find(|p| p.definition.display_name == "Test Department")
        .unwrap();
    assert!(dept_prop.definition.is_multi_select);
    assert_eq!(dept_prop.definition.data_type, DataType::SelectString);
    assert_eq!(dept_prop.property_options.len(), 3);
    assert_eq!(
        dept_prop.property_options[0].value,
        PropertyOptionValue::String("Engineering".to_string())
    );
    assert_eq!(
        dept_prop.property_options[1].value,
        PropertyOptionValue::String("Human Resources".to_string())
    );
    assert_eq!(
        dept_prop.property_options[2].value,
        PropertyOptionValue::String("Marketing".to_string())
    );

    Ok(())
}

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

    let property = repo
        .create_property_definition(
            PropertyDefinitionOwner::Team(team_1()),
            "New Test Property",
            DataType::String,
            false,
            None,
            Vec::new(),
        )
        .await?;

    assert_eq!(property.display_name, "New Test Property");
    assert_eq!(property.data_type, DataType::String);
    assert!(!property.is_multi_select);
    assert!(property.specific_entity_type.is_none());

    Ok(())
}

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

    let property = repo
        .create_property_definition(
            PropertyDefinitionOwner::User(&user_1()),
            "My User Property",
            DataType::Number,
            false,
            None,
            Vec::new(),
        )
        .await?;

    assert_eq!(property.display_name, "My User Property");
    assert_eq!(property.data_type, DataType::Number);

    Ok(())
}

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

    // "Test Priority" already exists for team 1 in the fixture.
    let result = repo
        .create_property_definition(
            PropertyDefinitionOwner::Team(team_1()),
            "Test Priority",
            DataType::String,
            false,
            None,
            Vec::new(),
        )
        .await;

    assert!(result.is_err());

    Ok(())
}

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

    let options = vec![
        new_option(0, PropertyOptionValue::String("Alpha".to_string())),
        new_option(1, PropertyOptionValue::String("Beta".to_string())),
    ];

    let property = repo
        .create_property_definition(
            PropertyDefinitionOwner::Team(team_1()),
            "Select With Options",
            DataType::SelectString,
            false,
            None,
            options,
        )
        .await?;

    let option_count: i64 = sqlx::query_scalar!(
        r#"SELECT COUNT(*) as "count!" FROM property_options WHERE property_definition_id = $1"#,
        property.id
    )
    .fetch_one(&pool)
    .await?;
    assert_eq!(option_count, 2);

    Ok(())
}

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

    let property = repo
        .create_property_definition(
            PropertyDefinitionOwner::Team(team_1()),
            "Document Only Property",
            DataType::String,
            false,
            Some(EntityType::Document),
            Vec::new(),
        )
        .await?;

    assert_eq!(property.specific_entity_type, Some(EntityType::Document));

    Ok(())
}

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

    let property_id = "11111111-1111-1111-1111-111111111111"
        .parse::<Uuid>()
        .unwrap();

    // Verify it exists
    assert!(repo.get_property_definition(property_id).await?.is_some());

    // Delete it
    repo.delete_property_definition(property_id).await?;

    // Verify it's gone
    assert!(repo.get_property_definition(property_id).await?.is_none());

    Ok(())
}

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

    let property_id = "11111111-1111-1111-1111-111111111111"
        .parse::<Uuid>()
        .unwrap();

    // Verify options and entity properties exist for this definition.
    let options_before: i64 = sqlx::query_scalar!(
        r#"SELECT COUNT(*) as "count!" FROM property_options WHERE property_definition_id = $1"#,
        property_id
    )
    .fetch_one(&pool)
    .await?;
    assert!(options_before > 0);

    let entity_props_before: i64 = sqlx::query_scalar!(
        r#"SELECT COUNT(*) as "count!" FROM entity_properties WHERE property_definition_id = $1"#,
        property_id
    )
    .fetch_one(&pool)
    .await?;
    assert!(entity_props_before > 0);

    repo.delete_property_definition(property_id).await?;

    // Verify options and entity properties are also deleted (cascade).
    let options_after: i64 = sqlx::query_scalar!(
        r#"SELECT COUNT(*) as "count!" FROM property_options WHERE property_definition_id = $1"#,
        property_id
    )
    .fetch_one(&pool)
    .await?;
    assert_eq!(options_after, 0);

    let entity_props_after: i64 = sqlx::query_scalar!(
        r#"SELECT COUNT(*) as "count!" FROM entity_properties WHERE property_definition_id = $1"#,
        property_id
    )
    .fetch_one(&pool)
    .await?;
    assert_eq!(entity_props_after, 0);

    Ok(())
}

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

    let property_id = "00000000-0000-0000-0000-000000000000"
        .parse::<Uuid>()
        .unwrap();

    // Deleting non-existent property should succeed (no error)
    repo.delete_property_definition(property_id).await?;

    Ok(())
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../../fixtures", scripts("properties", "tags"))
)]
async fn get_caller_tag_definitions_with_options(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let user1_tags: Uuid = "aa111111-1111-1111-1111-111111111111".parse()?;
    let team1_tags: Uuid = "aa222222-2222-2222-2222-222222222222".parse()?;
    let user2_tags: Uuid = "aa333333-3333-3333-3333-333333333333".parse()?;

    // user1 gets their personal set (first) and their team's set, with
    // options, never another user's personal set.
    let sets = property_definition_queries::get_caller_tag_definitions_with_options(
        &pool,
        "macro|[email protected]",
    )
    .await?;
    assert_eq!(sets.len(), 2);
    assert_eq!(sets[0].definition.id, user1_tags);
    assert_eq!(sets[0].property_options.len(), 2);
    assert_eq!(
        sets[0].property_options[0].value,
        PropertyOptionValue::String("bug-report".to_string())
    );
    assert_eq!(
        sets[0].property_options[0].color,
        Some("#ff0000".to_string())
    );
    assert_eq!(sets[1].definition.id, team1_tags);
    assert_eq!(sets[1].property_options.len(), 1);

    // A teammate without a personal set only gets the team set.
    let sets = property_definition_queries::get_caller_tag_definitions_with_options(
        &pool,
        "macro|[email protected]",
    )
    .await?;
    assert_eq!(sets.len(), 1);
    assert_eq!(sets[0].definition.id, team1_tags);

    // user2 only gets their own personal set (Team 2 has no tag set).
    let sets = property_definition_queries::get_caller_tag_definitions_with_options(
        &pool,
        "macro|[email protected]",
    )
    .await?;
    assert_eq!(sets.len(), 1);
    assert_eq!(sets[0].definition.id, user2_tags);

    Ok(())
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../../fixtures", scripts("properties"))
)]
async fn create_database_property_definition_preserves_type_and_isolates_ownership(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let database_id = macro_uuid::generate_uuid_v7();
    sqlx::query!("INSERT INTO databases (id) VALUES ($1)", database_id)
        .execute(&pool)
        .await?;
    let repo = PropertiesPgRepo::new(pool);
    for (data_type, specific_entity_type) in [
        (DataType::String, None),
        (DataType::Number, None),
        (DataType::Entity, Some(EntityType::User)),
    ] {
        // Database definitions may reuse a label across different table placements.
        let definition = repo
            .create_database_property_definition(
                database_id,
                "Status",
                data_type,
                false,
                specific_entity_type,
            )
            .await?;
        assert_eq!(definition.owner.database_id(), Some(database_id));
        assert_eq!(definition.id.get_version_num(), 7);
        assert_eq!(definition.display_name, "Status");
        assert_eq!(definition.data_type, data_type);
        assert_eq!(definition.specific_entity_type, specific_entity_type);
        assert!(!definition.is_multi_select);
        assert!(!definition.is_system);
        assert!(!definition.is_metadata);
        assert!(repo.get_property_definition(definition.id).await?.is_none());
        assert!(repo.get_property_options(definition.id).await?.is_empty());
    }
    let shared = repo
        .list_property_definitions(None, Some(&user_1()), false)
        .await?;
    assert_eq!(shared.len(), 2);
    Ok(())
}

#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn create_database_property_definition_rejects_missing_database(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = PropertiesPgRepo::new(pool);
    let result = repo
        .create_database_property_definition(
            macro_uuid::generate_uuid_v7(),
            "Missing database",
            DataType::String,
            false,
            None,
        )
        .await;
    assert!(result.is_err());
    Ok(())
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../../fixtures", scripts("properties"))
)]
async fn a_database_binds_system_own_team_and_its_own_definitions_only(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let database_id = Uuid::now_v7();
    let other_database_id = Uuid::now_v7();
    for id in [database_id, other_database_id] {
        sqlx::query!("INSERT INTO databases (id) VALUES ($1)", id,)
            .execute(&pool)
            .await?;
    }
    let repo = PropertiesPgRepo::new(pool);
    let own_column = repo
        .create_database_property_definition(database_id, "Seat", DataType::String, false, None)
        .await?;
    let other_column = repo
        .create_database_property_definition(
            other_database_id,
            "Seat",
            DataType::String,
            false,
            None,
        )
        .await?;
    let system = repo.list_property_definitions(None, None, true).await?[0].id;
    let team_priority = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
    let personal = Uuid::parse_str("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")?;
    let other_team = Uuid::parse_str("dddddddd-dddd-dddd-dddd-dddddddddddd")?;

    let bindable = |id: Uuid| {
        let repo = repo.clone();
        async move {
            repo.get_bindable_property_definition(id, "macro|[email protected]", database_id)
                .await
                .map(|definition| definition.map(|definition| definition.id))
        }
    };
    assert_eq!(bindable(system).await?, Some(system));
    assert_eq!(bindable(team_priority).await?, Some(team_priority));
    assert_eq!(bindable(personal).await?, Some(personal));
    assert_eq!(bindable(own_column.id).await?, Some(own_column.id));
    assert_eq!(bindable(other_team).await?, None);
    assert_eq!(bindable(other_column.id).await?, None);
    assert_eq!(bindable(Uuid::new_v4()).await?, None);
    Ok(())
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../../fixtures", scripts("properties"))
)]
async fn definitions_by_id_include_database_owned_ones_with_their_options(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let database_id = Uuid::now_v7();
    sqlx::query!("INSERT INTO databases (id) VALUES ($1)", database_id,)
        .execute(&pool)
        .await?;
    let repo = PropertiesPgRepo::new(pool);
    let column = repo
        .create_database_property_definition(
            database_id,
            "RSVP",
            DataType::SelectString,
            false,
            None,
        )
        .await?;
    repo.create_property_option(
        column.id,
        0,
        PropertyOptionValue::String("Going".into()),
        None,
    )
    .await?;
    let team_priority = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
    let missing = Uuid::new_v4();

    let mut definitions = repo
        .get_property_definitions_with_options(&[column.id, team_priority, missing])
        .await?;
    definitions.sort_by_key(|definition| definition.definition.display_name.clone());

    assert_eq!(definitions.len(), 2);
    assert_eq!(definitions[0].definition.id, column.id);
    assert_eq!(definitions[0].definition.display_name, "RSVP");
    assert_eq!(
        definitions[0]
            .property_options
            .iter()
            .map(|option| option.value.clone())
            .collect::<Vec<_>>(),
        vec![PropertyOptionValue::String("Going".into())]
    );
    assert_eq!(definitions[1].definition.id, team_priority);
    assert_eq!(definitions[1].property_options.len(), 4);
    assert!(
        repo.get_property_definitions_with_options(&[])
            .await?
            .is_empty()
    );
    Ok(())
}