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.

19.0 KB
Raw Blame
//! Tests for system properties PostgreSQL repository.

use models_properties::EntityType;

use super::*;
use crate::domain::model::{PropertyRow, SystemPropertyKey};
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use sqlx::{Pool, Postgres};

#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn initiative_initialization_preserves_values_and_folder_namespace(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    use crate::domain::service::{SystemPropertiesService, SystemPropertiesServiceImpl};
    let repo = PgSystemPropertiesRepository::new(pool.clone());
    let service = SystemPropertiesServiceImpl::new(repo.clone());
    let entity_id = "initiative-initialization";
    // An identical legacy folder id is a separate property owner.
    repo.bulk_upsert_properties(vec![PropertyRow::entity_reference(
        entity_id,
        EntityType::Project,
        SystemPropertyKey::ASSIGNEES_UUID,
        EntityType::User,
        vec!["macro|[email protected]".into()],
        None,
    )])
    .await?;
    service
        .attach_initiative_properties(vec![entity_id.into()])
        .await?;
    repo.bulk_upsert_properties(vec![PropertyRow::entity_reference(
        entity_id,
        EntityType::Initiative,
        SystemPropertyKey::ASSIGNEES_UUID,
        EntityType::User,
        vec!["macro|[email protected]".into()],
        None,
    )])
    .await?;
    service
        .attach_initiative_properties(vec![entity_id.into()])
        .await?;

    let rows = sqlx::query!(
        r#"
        SELECT entity_type AS "entity_type: EntityType", property_definition_id, values
        FROM entity_properties
        WHERE entity_id = $1
        "#,
        entity_id,
    )
    .fetch_all(&pool)
    .await?;
    assert_eq!(rows.len(), 5);
    let initiatives: Vec<_> = rows
        .iter()
        .filter(|row| row.entity_type == EntityType::Initiative)
        .collect();
    assert_eq!(initiatives.len(), 4);
    for row in initiatives {
        if row.property_definition_id == SystemPropertyKey::ASSIGNEES_UUID {
            assert_eq!(
                row.values.as_ref().unwrap()["value"][0]["entity_id"],
                "macro|[email protected]"
            );
        } else {
            assert!(row.values.as_ref().unwrap().is_null());
        }
    }
    let folder = rows
        .iter()
        .find(|row| row.entity_type == EntityType::Project)
        .unwrap();
    assert_eq!(
        folder.values.as_ref().unwrap()["value"][0]["entity_id"],
        "macro|[email protected]"
    );
    Ok(())
}

/// Helper to count task properties
async fn count_task_properties(pool: &Pool<Postgres>, entity_id: &str) -> i64 {
    sqlx::query_scalar::<_, i64>(
        "SELECT COUNT(*) FROM entity_properties WHERE entity_id = $1 AND entity_type = 'TASK'",
    )
    .bind(entity_id)
    .fetch_one(pool)
    .await
    .unwrap()
}

/// Helper to get task property values
async fn get_task_property_values(
    pool: &Pool<Postgres>,
    entity_id: &str,
) -> Vec<(Uuid, Option<serde_json::Value>)> {
    sqlx::query_as::<_, (Uuid, Option<serde_json::Value>)>(
        "SELECT property_definition_id, values FROM entity_properties WHERE entity_id = $1 AND entity_type = 'TASK' ORDER BY property_definition_id",
    )
    .bind(entity_id)
    .fetch_all(pool)
    .await
    .unwrap()
}

// ============================================================================
// bulk_upsert_properties tests
// ============================================================================

#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_bulk_upsert_properties_insert(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = PgSystemPropertiesRepository::new(pool.clone());

    let entity_id = "test-task-insert";
    let rows = vec![
        PropertyRow::null_value(
            entity_id,
            EntityType::Task,
            SystemPropertyKey::Status.uuid(),
        ),
        PropertyRow::null_value(
            entity_id,
            EntityType::Task,
            SystemPropertyKey::Priority.uuid(),
        ),
    ];

    repo.bulk_upsert_properties(rows).await?;

    let count = count_task_properties(&pool, entity_id).await;
    assert_eq!(count, 2, "Should have inserted 2 properties");

    Ok(())
}

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

    let entity_id = "source-task-with-props";
    let custom_notes_id: Uuid = "cccccccc-cccc-cccc-cccc-cccccccccc01".parse().unwrap();

    // Update Custom Notes (STRING type) - already has "This is a custom note" from fixture
    let rows = vec![PropertyRow::string_value(
        entity_id,
        EntityType::Task,
        custom_notes_id,
        "Updated note",
    )];

    repo.bulk_upsert_properties(rows).await?;

    let properties = get_task_property_values(&pool, entity_id).await;
    let notes_prop = properties.iter().find(|(id, _)| *id == custom_notes_id);

    assert_eq!(
        notes_prop.unwrap().1.as_ref().unwrap(),
        &serde_json::json!({"type": "String", "value": "Updated note"}),
        "Custom Notes should be updated"
    );

    Ok(())
}

#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_bulk_upsert_properties_empty(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = PgSystemPropertiesRepository::new(pool.clone());

    // Empty input should succeed without error
    repo.bulk_upsert_properties(vec![]).await?;

    Ok(())
}

#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_bulk_upsert_properties_multiple_entities(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = PgSystemPropertiesRepository::new(pool.clone());

    let rows = vec![
        PropertyRow::null_value("task-a", EntityType::Task, SystemPropertyKey::Status.uuid()),
        PropertyRow::null_value(
            "task-a",
            EntityType::Task,
            SystemPropertyKey::Priority.uuid(),
        ),
        PropertyRow::null_value("task-b", EntityType::Task, SystemPropertyKey::Status.uuid()),
        PropertyRow::null_value("task-c", EntityType::Task, SystemPropertyKey::Status.uuid()),
    ];

    repo.bulk_upsert_properties(rows).await?;

    assert_eq!(count_task_properties(&pool, "task-a").await, 2);
    assert_eq!(count_task_properties(&pool, "task-b").await, 1);
    assert_eq!(count_task_properties(&pool, "task-c").await, 1);

    Ok(())
}

#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_bulk_insert_properties_if_absent_keeps_first_write(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = PgSystemPropertiesRepository::new(pool.clone());
    let entity_id = "email-doc-first-write";
    let subject_id = SystemPropertyKey::Subject.uuid();

    repo.bulk_insert_properties_if_absent(vec![PropertyRow::string_value(
        entity_id,
        EntityType::Document,
        subject_id,
        "original subject",
    )])
    .await?;
    repo.bulk_insert_properties_if_absent(vec![PropertyRow::string_value(
        entity_id,
        EntityType::Document,
        subject_id,
        "forwarded subject",
    )])
    .await?;

    let stored = sqlx::query_scalar!(
        r#"
        SELECT values
        FROM entity_properties
        WHERE entity_id = $1 AND property_definition_id = $2
        "#,
        entity_id,
        subject_id,
    )
    .fetch_one(&pool)
    .await?;

    assert_eq!(
        stored.unwrap(),
        serde_json::json!({"type": "String", "value": "original subject"})
    );

    Ok(())
}

// ============================================================================
// copy_task_properties tests
// ============================================================================

#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_copy_task_properties_empty_source(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = PgSystemPropertiesRepository::new(pool.clone());

    let from_task_id = "source-task-123";
    let to_task_id = "dest-task-456";

    // Copy from empty source - should still create system properties with null values
    repo.copy_task_properties(from_task_id, to_task_id).await?;

    // Should have 10 system properties with null values
    let count = count_task_properties(&pool, to_task_id).await;
    assert_eq!(count, 10, "Should have 10 system task properties");

    // All values should be null
    let properties = get_task_property_values(&pool, to_task_id).await;
    for (_, value) in &properties {
        assert!(value.is_none(), "All properties should be null");
    }

    Ok(())
}

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

    let from_task_id = "source-task-with-props";
    let to_task_id = "dest-task-new";

    // Copy properties (source has 2 system + 2 custom properties from fixture)
    repo.copy_task_properties(from_task_id, to_task_id).await?;

    // Destination should have 12 properties:
    // - 4 copied (Status, Priority, Custom Notes, Custom Tags)
    // - 8 null system properties backfilled
    let count = count_task_properties(&pool, to_task_id).await;
    assert_eq!(
        count, 12,
        "Should have 12 properties (4 copied + 8 backfilled)"
    );

    // Check that status was copied with correct SelectOption value
    let properties = get_task_property_values(&pool, to_task_id).await;

    let status_prop = properties
        .iter()
        .find(|(id, _)| *id == SystemPropertyKey::Status.uuid());
    assert!(status_prop.is_some(), "Status property should exist");
    assert_eq!(
        status_prop.unwrap().1.as_ref().unwrap(),
        &serde_json::json!({"type": "SelectOption", "value": ["00000001-0000-0000-0002-000000000002"]}), // In Progress
        "Status value should be copied"
    );

    let priority_prop = properties
        .iter()
        .find(|(id, _)| *id == SystemPropertyKey::Priority.uuid());
    assert!(priority_prop.is_some(), "Priority property should exist");
    assert_eq!(
        priority_prop.unwrap().1.as_ref().unwrap(),
        &serde_json::json!({"type": "SelectOption", "value": ["00000001-0000-0000-0003-000000000003"]}), // High
        "Priority value should be copied"
    );

    Ok(())
}

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

    let from_task_id = "source-task-with-props";
    let to_task_id = "dest-task-custom";

    // Custom property IDs from fixture
    let custom_notes_id: Uuid = "cccccccc-cccc-cccc-cccc-cccccccccc01".parse().unwrap();
    let custom_tags_id: Uuid = "cccccccc-cccc-cccc-cccc-cccccccccc02".parse().unwrap();

    repo.copy_task_properties(from_task_id, to_task_id).await?;

    let properties = get_task_property_values(&pool, to_task_id).await;

    // Check Custom Notes was copied
    let notes_prop = properties.iter().find(|(id, _)| *id == custom_notes_id);
    assert!(
        notes_prop.is_some(),
        "Custom Notes property should be copied"
    );
    assert_eq!(
        notes_prop.unwrap().1.as_ref().unwrap(),
        &serde_json::json!({"type": "String", "value": "This is a custom note"}),
        "Custom Notes value should be copied"
    );

    // Check Custom Tags was copied
    let tags_prop = properties.iter().find(|(id, _)| *id == custom_tags_id);
    assert!(tags_prop.is_some(), "Custom Tags property should be copied");
    assert_eq!(
        tags_prop.unwrap().1.as_ref().unwrap(),
        &serde_json::json!({"type": "SelectOption", "value": ["00000000-0000-0000-0000-000000000101"]}), // urgent
        "Custom Tags value should be copied"
    );

    Ok(())
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "../../../fixtures", scripts("system_properties"))
)]
async fn test_copy_task_properties_does_not_join_the_project(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = PgSystemPropertiesRepository::new(pool.clone());
    let from_task_id = "source-task-with-props";
    let to_task_id = "dest-task-project";
    sqlx::query!(
        r#"
        INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)
        VALUES (gen_random_uuid(), $1, 'TASK', $2, $3)
        "#,
        from_task_id,
        SystemPropertyKey::PROJECT_UUID,
        serde_json::json!({
            "type": "EntityReference",
            "value": [{"entity_id": "00000000-0000-0000-0000-0000000000aa", "entity_type": "INITIATIVE"}]
        }),
    )
    .execute(&pool)
    .await?;

    repo.copy_task_properties(from_task_id, to_task_id).await?;

    let properties = get_task_property_values(&pool, to_task_id).await;
    assert!(!properties.is_empty(), "other properties are copied");
    assert!(
        properties
            .iter()
            .all(|(id, _)| *id != SystemPropertyKey::PROJECT_UUID),
        "the copy must not join the source's project"
    );
    Ok(())
}

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

    let from_task_id = "source-task-overwrite"; // Status = Completed
    let to_task_id = "dest-task-existing"; // Status = Not Started

    // Copy should overwrite destination value
    repo.copy_task_properties(from_task_id, to_task_id).await?;

    let properties = get_task_property_values(&pool, to_task_id).await;
    let status_prop = properties
        .iter()
        .find(|(id, _)| *id == SystemPropertyKey::Status.uuid());

    assert_eq!(
        status_prop.unwrap().1.as_ref().unwrap(),
        &serde_json::json!({"type": "SelectOption", "value": ["00000001-0000-0000-0002-000000000004"]}), // Completed (from source)
        "Destination value should be overwritten with source value"
    );

    Ok(())
}

#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_copy_task_properties_idempotent(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = PgSystemPropertiesRepository::new(pool.clone());

    let from_task_id = "source-task-idempotent";
    let to_task_id = "dest-task-idempotent";

    // Copy twice
    repo.copy_task_properties(from_task_id, to_task_id).await?;
    repo.copy_task_properties(from_task_id, to_task_id).await?;

    // Should still have exactly 10 properties
    let count = count_task_properties(&pool, to_task_id).await;
    assert_eq!(
        count, 10,
        "Should have exactly 10 properties after idempotent copies"
    );

    Ok(())
}

// ============================================================================
// Project membership (the Project property) tests
// ============================================================================

/// Set a task property to one entity reference, the way property writes store it.
async fn set_task_reference(
    pool: &Pool<Postgres>,
    task_id: &str,
    property_definition_id: Uuid,
    entity_id: &str,
    entity_type: &str,
) -> anyhow::Result<()> {
    sqlx::query!(
        r#"
        INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)
        VALUES (
            gen_random_uuid(), $1, 'TASK', $2,
            jsonb_build_object(
                'type', 'EntityReference',
                'value', jsonb_build_array(jsonb_build_object(
                    'entity_id', $3::text, 'entity_type', $4::text
                ))
            )
        )
        ON CONFLICT (entity_id, entity_type, property_definition_id)
        DO UPDATE SET values = EXCLUDED.values
        "#,
        task_id,
        property_definition_id,
        entity_id,
        entity_type,
    )
    .execute(pool)
    .await?;
    Ok(())
}

#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn project_membership_reads_the_project_property(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = PgSystemPropertiesRepository::new(pool.clone());
    let first = Uuid::now_v7();
    let second = Uuid::now_v7();
    let project = SystemPropertyKey::PROJECT_UUID;
    set_task_reference(&pool, "task-b", project, &first.to_string(), "INITIATIVE").await?;
    set_task_reference(&pool, "task-a", project, &first.to_string(), "INITIATIVE").await?;
    set_task_reference(&pool, "moved", project, &first.to_string(), "INITIATIVE").await?;
    set_task_reference(&pool, "moved", project, &second.to_string(), "INITIATIVE").await?;
    set_task_reference(
        &pool,
        "elsewhere",
        project,
        &second.to_string(),
        "INITIATIVE",
    )
    .await?;
    // Another property referencing the project, and a non-project reference, are not
    // membership.
    set_task_reference(
        &pool,
        "companies",
        SystemPropertyKey::COMPANIES_UUID,
        &first.to_string(),
        "INITIATIVE",
    )
    .await?;
    set_task_reference(
        &pool,
        "not-a-project",
        project,
        &first.to_string(),
        "DOCUMENT",
    )
    .await?;
    // A second reference in the array, an extra key, and an empty array. Containment
    // keeps the first two and drops the empty array, same as whole-value containment.
    sqlx::query!(
        r#"
        INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)
        VALUES (
            gen_random_uuid(), 'two', 'TASK', $1,
            jsonb_build_object('type', 'EntityReference', 'value', jsonb_build_array(
                jsonb_build_object('entity_id', $2::text, 'entity_type', 'INITIATIVE'),
                jsonb_build_object('entity_id', $3::text, 'entity_type', 'INITIATIVE')
            ))
        ), (
            gen_random_uuid(), 'extra', 'TASK', $1,
            jsonb_build_object('type', 'EntityReference', 'value', jsonb_build_array(
                jsonb_build_object(
                    'entity_id', $2::text,
                    'entity_type', 'INITIATIVE',
                    'specific_message_id', 'x'
                )
            ))
        ), (
            gen_random_uuid(), 'empty', 'TASK', $1,
            '{"type": "EntityReference", "value": []}'::jsonb
        )
        "#,
        project,
        first.to_string(),
        second.to_string(),
    )
    .execute(&pool)
    .await?;

    assert_eq!(
        repo.project_task_ids(first).await?,
        ["extra", "task-a", "task-b", "two"]
    );
    let mut projects = repo
        .task_projects(&[
            "task-a".to_string(),
            "moved".to_string(),
            "companies".to_string(),
            "not-a-project".to_string(),
            "unassigned".to_string(),
        ])
        .await?;
    projects.sort();
    assert_eq!(
        projects,
        [
            ("moved".to_string(), second.to_string()),
            ("task-a".to_string(), first.to_string()),
        ]
    );

    Ok(())
}