Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use macro_user_id::user_id::MacroUserIdStr;
use sqlx::{Pool, Postgres, Row};
///! Tests for the team_repo implementation for teams
use super::*;
use crate::domain::model::SeatPlan;
mod delete_team;
mod invite_link;
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_get_stripe_customer_id(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
let stripe_customer_id = team_repo
.get_stripe_customer_id(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)
.await?;
let expected_stripe_customer_id = stripe::CustomerId::from_str("cus_1234").unwrap();
assert_eq!(stripe_customer_id, Some(expected_stripe_customer_id));
let stripe_customer_id = team_repo
.get_stripe_customer_id(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)
.await?;
assert!(stripe_customer_id.is_none());
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_has_user_trialed(pool: Pool<Postgres>) -> anyhow::Result<()> {
sqlx::query("UPDATE macro_user SET has_trialed = FALSE WHERE email = '[email protected]'")
.execute(&pool)
.await?;
let team_repo = TeamRepositoryImpl::new(pool);
let has_trialed = team_repo
.has_user_trialed(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)
.await?;
assert!(has_trialed);
let has_trialed = team_repo
.has_user_trialed(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)
.await?;
assert!(!has_trialed);
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_get_team_subscription_id(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
let subscription_id = team_repo
.get_team_subscription_id(¯o_uuid::string_to_uuid(
"11111111-1111-1111-1111-111111111111",
)?)
.await?;
assert_eq!(
subscription_id.map(|s| s.to_string()),
Some("sub_1".to_string())
);
let subscription_id = team_repo
.get_team_subscription_id(¯o_uuid::string_to_uuid(
"22222222-2222-2222-2222-222222222222",
)?)
.await?;
assert!(subscription_id.is_none());
let err = team_repo
.get_team_subscription_id(¯o_uuid::string_to_uuid(
"63333333-3333-3333-3333-333333333333",
)?)
.await
.err()
.unwrap();
assert!(err.to_string().contains("does not exist"));
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_get_team_payment_status(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let paying = team_repo.get_team_payment_status(&team_id).await?;
assert!(!paying);
sqlx::query!(
r#"
UPDATE team
SET paying = TRUE
WHERE id = $1
"#,
&team_id,
)
.execute(&pool)
.await?;
let paying = team_repo.get_team_payment_status(&team_id).await?;
assert!(paying);
let missing_team_id = macro_uuid::string_to_uuid("63333333-3333-3333-3333-333333333333")?;
let err = team_repo
.get_team_payment_status(&missing_team_id)
.await
.err()
.unwrap();
assert!(err.to_string().contains("does not exist"));
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_get_team_enterprise_status(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let enterprise = team_repo.get_team_enterprise_status(&team_id).await?;
assert!(!enterprise);
sqlx::query!("UPDATE team SET enterprise = TRUE WHERE id = $1", &team_id)
.execute(&pool)
.await?;
let enterprise = team_repo.get_team_enterprise_status(&team_id).await?;
assert!(enterprise);
let missing_team_id = macro_uuid::string_to_uuid("63333333-3333-3333-3333-333333333333")?;
let error = team_repo
.get_team_enterprise_status(&missing_team_id)
.await
.expect_err("a missing team should return an error");
assert!(matches!(error, TeamError::TeamDoesNotExist));
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_create_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let result = team_repo
.create_team(
&user_id,
"Product Team",
"PRODUCT_TEAM",
Some(&"sub_test".parse().unwrap()),
SeatPlan::Premium,
Some("user.com"),
)
.await?;
assert!(!result.id.to_string().is_empty());
assert_eq!(result.auto_join_domain(), Some("user.com"));
assert_eq!(result.name, "Product Team");
assert_eq!(result.slug, "PRODUCT_TEAM");
assert_eq!(result.owner_id.0.as_ref(), "macro|[email protected]");
assert!(!result.enterprise());
// Create team with too large a name
let err = team_repo
.create_team(&user_id, "12345678901234567890123456789012345678901234567890123456789000000000000000000000000000000000000000000000", "MACRO", Some(&"sub_test".parse().unwrap()), SeatPlan::Premium, None)
.await
.err()
.unwrap();
assert!(err.to_string().contains("team name is invalid"));
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_move_github_app_installation_to_team_moves_existing_user_rows(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let unrelated_user_id = "macro|[email protected]";
let existing_team_id = "22222222-2222-2222-2222-222222222222";
sqlx::query(
r#"
INSERT INTO github_app_installation (id, source_id, source_type)
VALUES
('installation-one', $1, 'user'::github_app_installation_source_type),
('installation-two', $1, 'user'::github_app_installation_source_type),
('other-user-installation', $2, 'user'::github_app_installation_source_type),
('existing-team-installation', $3, 'team'::github_app_installation_source_type)
"#,
)
.bind(user_id.as_ref())
.bind(unrelated_user_id)
.bind(existing_team_id)
.execute(&pool)
.await?;
let team = team_repo
.create_team(
&user_id,
"GitHub Owner Team",
"GITHUB_OWNER_TEAM",
Some(&"sub_test".parse().unwrap()),
SeatPlan::Premium,
None,
)
.await?;
let team_id = team.id().to_string();
team_repo
.move_github_app_installation_to_team_if_exists(&user_id, team.id())
.await?;
let remaining_user_row_count = sqlx::query(
r#"
SELECT COUNT(*) AS count
FROM github_app_installation
WHERE source_id = $1
AND source_type = 'user'::github_app_installation_source_type
"#,
)
.bind(user_id.as_ref())
.fetch_one(&pool)
.await?
.try_get::<i64, _>("count")?;
assert_eq!(remaining_user_row_count, 0);
let moved_rows = sqlx::query(
r#"
SELECT id, source_id, source_type::text AS source_type
FROM github_app_installation
WHERE source_id = $1
AND source_type = 'team'::github_app_installation_source_type
ORDER BY id
"#,
)
.bind(&team_id)
.fetch_all(&pool)
.await?
.into_iter()
.map(|row| {
Ok((
row.try_get::<String, _>("id")?,
row.try_get::<String, _>("source_id")?,
row.try_get::<String, _>("source_type")?,
))
})
.collect::<Result<Vec<_>, sqlx::Error>>()?;
assert_eq!(
moved_rows,
vec![
(
"installation-one".to_string(),
team_id.clone(),
"team".to_string()
),
("installation-two".to_string(), team_id, "team".to_string()),
]
);
let unrelated_rows = sqlx::query(
r#"
SELECT id, source_id, source_type::text AS source_type
FROM github_app_installation
WHERE id IN ('existing-team-installation', 'other-user-installation')
ORDER BY id
"#,
)
.fetch_all(&pool)
.await?
.into_iter()
.map(|row| {
Ok((
row.try_get::<String, _>("id")?,
row.try_get::<String, _>("source_id")?,
row.try_get::<String, _>("source_type")?,
))
})
.collect::<Result<Vec<_>, sqlx::Error>>()?;
assert_eq!(
unrelated_rows,
vec![
(
"existing-team-installation".to_string(),
existing_team_id.to_string(),
"team".to_string()
),
(
"other-user-installation".to_string(),
unrelated_user_id.to_string(),
"user".to_string()
),
]
);
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_move_github_app_installation_to_team_noops_when_user_has_no_rows(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let unrelated_user_id = "macro|[email protected]";
sqlx::query(
r#"
INSERT INTO github_app_installation (id, source_id, source_type)
VALUES ('other-user-installation', $1, 'user'::github_app_installation_source_type)
"#,
)
.bind(unrelated_user_id)
.execute(&pool)
.await?;
let team = team_repo
.create_team(
&user_id,
"GitHub Owner Team",
"GITHUB_OWNER_TEAM",
Some(&"sub_test".parse().unwrap()),
SeatPlan::Premium,
None,
)
.await?;
team_repo
.move_github_app_installation_to_team_if_exists(&user_id, team.id())
.await?;
let team_row_count = sqlx::query(
r#"
SELECT COUNT(*) AS count
FROM github_app_installation
WHERE source_id = $1
"#,
)
.bind(team.id().to_string())
.fetch_one(&pool)
.await?
.try_get::<i64, _>("count")?;
assert_eq!(team_row_count, 0);
let unrelated_row = sqlx::query(
r#"
SELECT source_id, source_type::text AS source_type
FROM github_app_installation
WHERE id = 'other-user-installation'
"#,
)
.fetch_one(&pool)
.await?;
assert_eq!(
unrelated_row.try_get::<String, _>("source_id")?,
unrelated_user_id
);
assert_eq!(unrelated_row.try_get::<String, _>("source_type")?, "user");
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_invite_users_to_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let invited = team_repo
.invite_users_to_team(&team_id, &user_id, invites, false)
.await?;
assert_eq!(invited.len(), 1);
assert_eq!(invited[0].email.as_ref(), "[email protected]");
let invites = vec![
Email::parse_from_str("[email protected]")?.lowercase(),
Email::parse_from_str("[email protected]")?.lowercase(),
];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let invited = team_repo
.invite_users_to_team(&team_id, &user_id, invites, false)
.await?;
assert!(invited.is_empty());
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_get_new_invites_filters_existing_invites(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let invites = vec![
Email::parse_from_str("[email protected]")?.lowercase(),
Email::parse_from_str("[email protected]")?.lowercase(),
];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let new_invites = team_repo.get_new_invites(&team_id, invites).await?;
assert_eq!(new_invites.len(), 1);
assert_eq!(new_invites[0].as_ref(), "[email protected]");
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_get_new_invites_filters_existing_team_members(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let invites = vec![
Email::parse_from_str("[email protected]")?.lowercase(),
Email::parse_from_str("[email protected]")?.lowercase(),
];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let new_invites = team_repo.get_new_invites(&team_id, invites).await?;
assert_eq!(new_invites.len(), 1);
assert_eq!(new_invites[0].as_ref(), "[email protected]");
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_get_new_invites_keeps_invites_scoped_to_team(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let other_team_id = macro_uuid::string_to_uuid("22222222-2222-2222-2222-222222222222")?;
sqlx::query!(
r#"
INSERT INTO team_invite (id, team_id, email, team_role, invited_by, created_at, last_sent_at)
VALUES ($1, $2, '[email protected]', 'member', 'macro|[email protected]', NOW(), NOW())
"#,
macro_uuid::generate_uuid_v7(),
other_team_id,
)
.execute(&pool)
.await?;
let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let new_invites = team_repo.get_new_invites(&team_id, invites).await?;
assert_eq!(new_invites.len(), 1);
assert_eq!(new_invites[0].as_ref(), "[email protected]");
Ok(())
}
/// Re-inviting an already-invited user inside the invite email's rate-limit
/// window should not return them (rate limited), so the result should be empty.
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_invite_existing_user_within_rate_limit(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
// [email protected] already has an invite with last_sent_at = NOW() in the fixture
let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let invited = team_repo
.invite_users_to_team(&team_id, &user_id, invites, false)
.await?;
// Rate limit blocks re-send, no new invite created either
assert!(invited.is_empty());
Ok(())
}
/// A resend minutes after the last email would be dropped by the email's
/// rate limit, so the repository must not offer it for sending.
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_invite_existing_user_inside_email_rate_limit(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
sqlx::query!(
r#"UPDATE team_invite SET last_sent_at = NOW() - INTERVAL '30 minutes' WHERE team_id = $1 AND email = '[email protected]'"#,
&team_id,
)
.execute(&pool)
.await?;
let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let invited = team_repo
.invite_users_to_team(&team_id, &user_id, invites, false)
.await?;
assert!(invited.is_empty());
Ok(())
}
/// Re-inviting an already-invited user after the invite email's rate-limit
/// window has passed should return them (re-sent).
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_invite_existing_user_after_rate_limit(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
// Push last_sent_at back past the invite email's rate-limit window
sqlx::query!(
r#"UPDATE team_invite SET last_sent_at = NOW() - INTERVAL '3 days' WHERE team_id = $1 AND email = '[email protected]'"#,
&team_id,
)
.execute(&pool)
.await?;
let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let invited = team_repo
.invite_users_to_team(&team_id, &user_id, invites, false)
.await?;
assert_eq!(invited.len(), 1);
assert_eq!(invited[0].email.as_ref(), "[email protected]");
Ok(())
}
/// Inviting a mix of new users and existing users (past rate limit) should
/// return both.
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_invite_mix_new_and_existing(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
// Push existing invite past the rate limit window
sqlx::query!(
r#"UPDATE team_invite SET last_sent_at = NOW() - INTERVAL '3 days' WHERE team_id = $1 AND email = '[email protected]'"#,
&team_id,
)
.execute(&pool)
.await?;
let invites = vec![
Email::parse_from_str("[email protected]")?.lowercase(),
Email::parse_from_str("[email protected]")?.lowercase(),
];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let invited = team_repo
.invite_users_to_team(&team_id, &user_id, invites, false)
.await?;
assert_eq!(invited.len(), 2);
let emails: Vec<&str> = invited.iter().map(|i| i.email.as_ref()).collect();
assert!(emails.contains(&"[email protected]"));
assert!(emails.contains(&"[email protected]"));
Ok(())
}
/// Re-inviting updates last_sent_at (via mark_invites_sent) so a second
/// immediate re-invite is rate limited.
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_reinvite_updates_last_sent_at(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
// Push past rate limit
sqlx::query!(
r#"UPDATE team_invite SET last_sent_at = NOW() - INTERVAL '3 days' WHERE team_id = $1 AND email = '[email protected]'"#,
&team_id,
)
.execute(&pool)
.await?;
// First re-invite should succeed
let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let invited = team_repo
.invite_users_to_team(&team_id, &user_id, invites, false)
.await?;
assert_eq!(invited.len(), 1);
// Mark the invite as sent (simulating successful notification delivery)
let sent_ids: Vec<uuid::Uuid> = invited.iter().map(|i| i.team_invite_id).collect();
team_repo.mark_invites_sent(&sent_ids).await?;
// Second immediate re-invite should be rate limited
let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let invited = team_repo
.invite_users_to_team(&team_id, &user_id, invites, false)
.await?;
assert!(invited.is_empty());
Ok(())
}
/// invite_users_to_team does NOT update last_sent_at by itself; without a
/// subsequent mark_invites_sent call, the invite remains eligible for resend.
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_resend_without_mark_sent_stays_eligible(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
// Push past rate limit
sqlx::query!(
r#"UPDATE team_invite SET last_sent_at = NOW() - INTERVAL '3 days' WHERE team_id = $1 AND email = '[email protected]'"#,
&team_id,
)
.execute(&pool)
.await?;
// First re-invite returns the invite
let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let invited = team_repo
.invite_users_to_team(&team_id, &user_id, invites, false)
.await?;
assert_eq!(invited.len(), 1);
// Do NOT call mark_invites_sent (simulating failed notification delivery)
// Second re-invite should still return the invite because last_sent_at was not updated
let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let invited = team_repo
.invite_users_to_team(&team_id, &user_id, invites, false)
.await?;
assert_eq!(invited.len(), 1);
Ok(())
}
/// mark_invites_sent updates last_sent_at for the specified invite IDs.
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_mark_invites_sent(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let invite_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
// Push last_sent_at back so it's past the rate limit
sqlx::query!(
r#"UPDATE team_invite SET last_sent_at = NOW() - INTERVAL '3 days' WHERE id = $1"#,
&invite_id,
)
.execute(&pool)
.await?;
// Verify the invite is past rate limit by reading last_sent_at
let before = sqlx::query!(
r#"SELECT last_sent_at FROM team_invite WHERE id = $1"#,
&invite_id,
)
.fetch_one(&pool)
.await?;
team_repo.mark_invites_sent(&[invite_id]).await?;
let after = sqlx::query!(
r#"SELECT last_sent_at FROM team_invite WHERE id = $1"#,
&invite_id,
)
.fetch_one(&pool)
.await?;
// last_sent_at should have been updated to a more recent timestamp
assert!(after.last_sent_at > before.last_sent_at);
// The invite should now be rate limited
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let invited = team_repo
.invite_users_to_team(&team_id, &user_id, invites, false)
.await?;
assert!(invited.is_empty());
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_remove_user_from_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
team_repo.remove_user_from_team(&team_id, &user_id).await?;
// Try to remove user that isn't on team
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let err = team_repo
.remove_user_from_team(&team_id, &user_id)
.await
.err()
.unwrap();
assert!(err.to_string().contains("not in the team"));
// Try to remove owner
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let err = team_repo
.remove_user_from_team(&team_id, &user_id)
.await
.err()
.unwrap();
assert!(err.to_string().contains("Cannot remove owner"));
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_get_team_invite_by_id(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
let invite_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let team_invite = team_repo.get_team_invite_by_id(&invite_id).await?;
assert_eq!(team_invite.email.as_ref(), "[email protected]");
let invite_id = macro_uuid::string_to_uuid("33333333-3333-3333-3333-333333333333")?;
let err = team_repo
.get_team_invite_by_id(&invite_id)
.await
.err()
.unwrap();
assert!(err.to_string().contains("The team invite does not exist"));
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_delete_team_invite(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
// delete invite that exists
team_repo
.delete_team_invite(
&team_id,
¯o_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?,
)
.await?;
// delete invite that does not exist
let err = team_repo
.delete_team_invite(
&team_id,
¯o_uuid::string_to_uuid("33333333-3333-3333-3333-333333333333")?,
)
.await
.err()
.unwrap();
println!("{}", err.to_string());
assert!(err.to_string().contains("The team invite does not exist"));
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_update_team_subscription(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let subscription_id = stripe::SubscriptionId::from_str("sub_1")?;
team_repo
.update_team_subscription(&team_id, &subscription_id)
.await?;
let team = sqlx::query!(
r#"
SELECT subscription_id as "subscription_id!"
FROM team
WHERE id = $1
"#,
&team_id,
)
.fetch_one(&pool)
.await?;
assert_eq!(team.subscription_id, "sub_1");
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_update_team_payment_status(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
team_repo.update_team_payment_status(&team_id, true).await?;
let row = sqlx::query!(
r#"
SELECT paying
FROM team
WHERE id = $1
"#,
&team_id,
)
.fetch_one(&pool)
.await?;
assert!(row.paying);
team_repo
.update_team_payment_status(&team_id, false)
.await?;
let row = sqlx::query!(
r#"
SELECT paying
FROM team
WHERE id = $1
"#,
&team_id,
)
.fetch_one(&pool)
.await?;
assert!(!row.paying);
let missing_team_id = macro_uuid::string_to_uuid("63333333-3333-3333-3333-333333333333")?;
let err = team_repo
.update_team_payment_status(&missing_team_id, true)
.await
.err()
.unwrap();
assert!(err.to_string().contains("does not exist"));
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_delete_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let team_source_id = team_id.to_string();
let other_team_source_id = "22222222-2222-2222-2222-222222222222";
sqlx::query!(
r#"
INSERT INTO github_app_installation (id, source_id, source_type)
VALUES
('deleted-team-installation', $1, 'team'::github_app_installation_source_type),
('same-source-user-installation', $1, 'user'::github_app_installation_source_type),
('other-team-installation', $2, 'team'::github_app_installation_source_type)
"#,
&team_source_id,
other_team_source_id,
)
.execute(&pool)
.await?;
team_repo
.delete_team(&ClearedTeam::assume_cleared(team_id, Vec::new()))
.await?;
let team = sqlx::query!(
r#"
SELECT id as id
FROM team
WHERE id = $1
"#,
&team_id,
)
.fetch_optional(&pool)
.await?;
assert!(team.is_none());
let deleted_installation = sqlx::query!(
r#"
SELECT id
FROM github_app_installation
WHERE id = 'deleted-team-installation'
"#,
)
.fetch_optional(&pool)
.await?;
assert!(deleted_installation.is_none());
let remaining_installations = sqlx::query!(
r#"
SELECT id, source_id, source_type::text AS "source_type!"
FROM github_app_installation
WHERE id IN ('other-team-installation', 'same-source-user-installation')
ORDER BY id
"#,
)
.fetch_all(&pool)
.await?
.into_iter()
.map(|row| (row.id, row.source_id, row.source_type))
.collect::<Vec<_>>();
assert_eq!(
remaining_installations,
vec![
(
"other-team-installation".to_string(),
other_team_source_id.to_string(),
"team".to_string(),
),
(
"same-source-user-installation".to_string(),
team_source_id,
"user".to_string(),
),
]
);
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_get_all_team_members(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let members = team_repo.get_all_team_members(&team_id).await?;
assert_eq!(members.len(), 2);
let results = vec![
("macro|[email protected]", TeamRole::Owner),
("macro|[email protected]", TeamRole::Member),
];
assert_eq!(
members
.iter()
.map(|m| (m.user_id.as_ref(), m.role))
.collect::<Vec<_>>(),
results
);
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_accept_team_invite(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
let team_invite_id = macro_uuid::string_to_uuid("22222222-2222-2222-2222-222222222222")?;
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let accepted_invite = team_repo
.accept_team_invite(&team_invite_id, &user_id)
.await?;
let team_member = accepted_invite.member;
assert_eq!(team_member.user_id.as_ref(), "macro|[email protected]");
assert_eq!(team_member.role, TeamRole::Member);
let team_invite_id = macro_uuid::string_to_uuid("33333333-3333-3333-3333-333333333333")?;
let err = team_repo
.accept_team_invite(&team_invite_id, &user_id)
.await
.err()
.unwrap();
assert!(err.to_string().contains("The team does not exist"));
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_rollback_accept_team_invite(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let team_invite_id = macro_uuid::string_to_uuid("22222222-2222-2222-2222-222222222222")?;
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
// A rolled-back agent invite must stay one, or the retry never joins.
sqlx::query!(
"UPDATE team_invite SET is_agent = TRUE WHERE id = $1",
team_invite_id
)
.execute(&pool)
.await?;
let accepted_invite = team_repo
.accept_team_invite(&team_invite_id, &user_id)
.await?;
team_repo
.rollback_accept_team_invite(&accepted_invite)
.await?;
let member = sqlx::query(
r#"
SELECT 1
FROM team_user
WHERE team_id = $1 AND user_id = $2
"#,
)
.bind(team_id)
.bind(user_id.as_ref())
.fetch_optional(&pool)
.await?;
assert!(member.is_none());
let invite = sqlx::query(
r#"
SELECT email, team_role, is_agent
FROM team_invite
WHERE id = $1
"#,
)
.bind(team_invite_id)
.fetch_one(&pool)
.await?;
assert!(invite.try_get::<bool, _>("is_agent")?);
assert_eq!(invite.try_get::<String, _>("email")?, "[email protected]");
assert_eq!(
invite.try_get::<TeamRole, _>("team_role")?,
TeamRole::Member
);
let team = sqlx::query(r#"SELECT seat_count FROM team WHERE id = $1"#)
.bind(team_id)
.fetch_one(&pool)
.await?;
assert_eq!(team.try_get::<i32, _>("seat_count")?, 3);
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_rollback_remove_user_from_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
team_repo
.patch_team_user_role(&team_id, &user_id, TeamRole::Admin)
.await?;
let removed_member = team_repo.remove_user_from_team(&team_id, &user_id).await?;
assert_eq!(removed_member.role, TeamRole::Admin);
team_repo
.rollback_remove_user_from_team(&removed_member)
.await?;
let member = team_repo.get_team_member(&team_id, &user_id).await?;
assert_eq!(member.role, TeamRole::Admin);
let team = sqlx::query(r#"SELECT seat_count FROM team WHERE id = $1"#)
.bind(team_id)
.fetch_one(&pool)
.await?;
assert_eq!(team.try_get::<i32, _>("seat_count")?, 3);
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_is_user_member_of_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
// [email protected] is an owner on team1
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let is_member = team_repo.is_user_member_of_team(&user_id).await?;
assert!(is_member);
// [email protected] is a member of team1
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let is_member = team_repo.is_user_member_of_team(&user_id).await?;
assert!(is_member);
// [email protected] is not in any team
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let is_member = team_repo.is_user_member_of_team(&user_id).await?;
assert!(!is_member);
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_get_team_members(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let members = team_repo.get_team_members(&team_id).await?;
assert_eq!(members.len(), 2);
let expected = vec!["macro|[email protected]", "macro|[email protected]"];
let mut results = members
.iter()
.map(|m| m.user_id.as_ref())
.collect::<Vec<&str>>();
results.sort();
assert_eq!(results, expected);
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_bump_seat_count_positive(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let mut transaction = pool.begin().await?;
TeamRepositoryImpl::bump_seat_count(&mut transaction, &team_id, 2).await?;
transaction.commit().await?;
let row = sqlx::query!(r#"SELECT seat_count FROM team WHERE id = $1"#, &team_id,)
.fetch_one(&pool)
.await?;
assert_eq!(row.seat_count, 5); // 3 + 2
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_bump_seat_count_negative(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let mut transaction = pool.begin().await?;
TeamRepositoryImpl::bump_seat_count(&mut transaction, &team_id, -1).await?;
transaction.commit().await?;
let row = sqlx::query!(r#"SELECT seat_count FROM team WHERE id = $1"#, &team_id,)
.fetch_one(&pool)
.await?;
assert_eq!(row.seat_count, 2); // 3 - 1
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_get_team_seat_count(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let seat_count = team_repo.get_team_seat_count(&team_id).await?;
assert_eq!(seat_count, 3);
let missing_team_id = macro_uuid::string_to_uuid("63333333-3333-3333-3333-333333333333")?;
let err = team_repo
.get_team_seat_count(&missing_team_id)
.await
.err()
.unwrap();
assert!(err.to_string().contains("does not exist"));
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_get_team_plan(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let plan = team_repo.get_team_plan(&team_id).await?;
assert_eq!(plan, None);
team_repo
.patch_team_plan(&team_id, TeamPlan::SeriesA)
.await?;
let plan = team_repo.get_team_plan(&team_id).await?;
assert_eq!(plan, Some(TeamPlan::SeriesA));
let missing_team_id = macro_uuid::string_to_uuid("63333333-3333-3333-3333-333333333333")?;
let err = team_repo
.get_team_plan(&missing_team_id)
.await
.err()
.unwrap();
assert!(err.to_string().contains("does not exist"));
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_patch_team_plan(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
team_repo.patch_team_plan(&team_id, TeamPlan::Seed).await?;
let row = sqlx::query!(
r#"SELECT plan::text AS "plan!" FROM team WHERE id = $1"#,
&team_id,
)
.fetch_one(&pool)
.await?;
assert_eq!(row.plan, "seed");
team_repo
.patch_team_plan(&team_id, TeamPlan::Growth)
.await?;
let row = sqlx::query!(
r#"SELECT plan::text AS "plan!" FROM team WHERE id = $1"#,
&team_id,
)
.fetch_one(&pool)
.await?;
assert_eq!(row.plan, "growth");
let missing_team_id = macro_uuid::string_to_uuid("63333333-3333-3333-3333-333333333333")?;
let err = team_repo
.patch_team_plan(&missing_team_id, TeamPlan::Idea)
.await
.err()
.unwrap();
assert!(err.to_string().contains("does not exist"));
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_get_team_by_id_hydrates_enterprise_status(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
sqlx::query!("UPDATE team SET enterprise = TRUE WHERE id = $1", &team_id)
.execute(&pool)
.await?;
let team = team_repo.get_team_by_id(&team_id).await?.team;
assert_eq!(team.name(), "team1");
assert_eq!(team.slug(), "MACRO");
assert!(team.enterprise());
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_get_user_teams_hydrates_enterprise_status(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
sqlx::query!("UPDATE team SET enterprise = TRUE WHERE id = $1", &team_id)
.execute(&pool)
.await?;
let teams = team_repo.get_user_teams(&user_id).await?;
let team = teams
.iter()
.find(|team| team.id() == &team_id)
.expect("updated team should be returned for the user");
assert!(team.enterprise());
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_patch_team_normalizes_slug_to_screaming_snake_case(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let req = PatchTeamRequest {
name: Some("New Name".to_string()),
slug: Some("my-team slug".to_string()),
user_role_updates: None,
default_link_share: None,
language: None,
};
team_repo.patch_team(&team_id, &req).await?;
let row = sqlx::query(r#"SELECT name, slug FROM team WHERE id = $1"#)
.bind(team_id)
.fetch_one(&pool)
.await?;
assert_eq!(row.try_get::<String, _>("name")?, "New Name");
assert_eq!(row.try_get::<String, _>("slug")?, "MY_TEAM_SLUG");
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_patch_team_rejects_invalid_slug_without_updating_name(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let req = PatchTeamRequest {
name: Some("Should Not Apply".to_string()),
slug: Some("bad.slug".to_string()),
user_role_updates: None,
default_link_share: None,
language: None,
};
let err = team_repo.patch_team(&team_id, &req).await.err().unwrap();
assert!(matches!(err, TeamError::BadRequest(_)));
let row = sqlx::query(r#"SELECT name, slug FROM team WHERE id = $1"#)
.bind(team_id)
.fetch_one(&pool)
.await?;
assert_eq!(row.try_get::<String, _>("name")?, "team1");
assert_eq!(row.try_get::<String, _>("slug")?, "MACRO");
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_patch_team_rejects_too_long_slug(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let req = PatchTeamRequest {
name: None,
slug: Some("THIS_SLUG_IS_WAY_TOO_LONG".to_string()),
user_role_updates: None,
default_link_share: None,
language: None,
};
let err = team_repo.patch_team(&team_id, &req).await.err().unwrap();
assert!(matches!(err, TeamError::BadRequest(_)));
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_patch_team_default_link_share_round_trip(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
// Existing teams default to TEAM via the column default.
let team = team_repo.get_team_by_id(&team_id).await?;
assert_eq!(team.team.default_link_share(), Some(LinkShare::Team));
// Providing a value updates it.
let req = PatchTeamRequest {
name: None,
slug: None,
user_role_updates: None,
default_link_share: Some(Some(LinkShare::Public)),
language: None,
};
team_repo.patch_team(&team_id, &req).await?;
let team = team_repo.get_team_by_id(&team_id).await?;
assert_eq!(team.team.default_link_share(), Some(LinkShare::Public));
// Omitting the field leaves it unchanged.
let req = PatchTeamRequest {
name: Some("Renamed".to_string()),
slug: None,
user_role_updates: None,
default_link_share: None,
language: None,
};
team_repo.patch_team(&team_id, &req).await?;
let team = team_repo.get_team_by_id(&team_id).await?;
assert_eq!(team.team.default_link_share(), Some(LinkShare::Public));
// An explicit null turns default link sharing off.
let req = PatchTeamRequest {
name: None,
slug: None,
user_role_updates: None,
default_link_share: Some(None),
language: None,
};
team_repo.patch_team(&team_id, &req).await?;
let team = team_repo.get_team_by_id(&team_id).await?;
assert_eq!(team.team.default_link_share(), None);
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_get_team_member(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
// Get existing member
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let member = team_repo.get_team_member(&team_id, &user_id).await?;
assert_eq!(member.user_id.as_ref(), "macro|[email protected]");
assert_eq!(member.team_id, team_id);
assert_eq!(member.role, TeamRole::Member);
// Get owner
let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let member = team_repo.get_team_member(&team_id, &owner_id).await?;
assert_eq!(member.user_id.as_ref(), "macro|[email protected]");
assert_eq!(member.role, TeamRole::Owner);
// Get non-existent member
let missing_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let err = team_repo
.get_team_member(&team_id, &missing_id)
.await
.err()
.unwrap();
assert!(err.to_string().contains("does not exist"));
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_patch_team_user_role(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
// Promote to Admin
team_repo
.patch_team_user_role(&team_id, &user_id, TeamRole::Admin)
.await?;
let member = team_repo.get_team_member(&team_id, &user_id).await?;
assert_eq!(member.role, TeamRole::Admin);
// Demote back to Member
team_repo
.patch_team_user_role(&team_id, &user_id, TeamRole::Member)
.await?;
let member = team_repo.get_team_member(&team_id, &user_id).await?;
assert_eq!(member.role, TeamRole::Member);
// Patch role for non-existent member
let missing_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let err = team_repo
.patch_team_user_role(&team_id, &missing_id, TeamRole::Admin)
.await
.err()
.unwrap();
assert!(err.to_string().contains("member not found"));
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_toggle_auto_join_domain(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
// First toggle sets the domain of the team owner (macro|[email protected]).
let domain = team_repo.toggle_auto_join_domain(&team_id).await?;
assert_eq!(domain.as_deref(), Some("user.com"));
let stored: Option<String> =
sqlx::query_scalar("SELECT auto_join_domain FROM team WHERE id = $1")
.bind(team_id)
.fetch_one(&pool)
.await?;
assert_eq!(stored.as_deref(), Some("user.com"));
// The domain is surfaced on the Team model (read by GET /team).
let team = team_repo.get_team_by_id(&team_id).await?.team;
assert_eq!(team.auto_join_domain(), Some("user.com"));
// Second toggle unsets it.
let domain = team_repo.toggle_auto_join_domain(&team_id).await?;
assert_eq!(domain, None);
let stored: Option<String> =
sqlx::query_scalar("SELECT auto_join_domain FROM team WHERE id = $1")
.bind(team_id)
.fetch_one(&pool)
.await?;
assert_eq!(stored, None);
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_toggle_auto_join_domain_rejects_generic_domain(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let team_id = macro_uuid::string_to_uuid("33333333-3333-3333-3333-333333333333")?;
sqlx::query(
"INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ('a5555555-5555-5555-5555-555555555555', '[email protected]', '[email protected]', 'cus_gmail_owner')",
)
.execute(&pool)
.await?;
sqlx::query(
r#"INSERT INTO "User" (id, email, name, macro_user_id) VALUES ('macro|[email protected]', '[email protected]', 'Gmail Owner', 'a5555555-5555-5555-5555-555555555555')"#,
)
.execute(&pool)
.await?;
sqlx::query(
"INSERT INTO team (id, name, owner_id) VALUES ($1, 'gmail team', 'macro|[email protected]')",
)
.bind(team_id)
.execute(&pool)
.await?;
let team_repo = TeamRepositoryImpl::new(pool.clone());
let err = team_repo
.toggle_auto_join_domain(&team_id)
.await
.err()
.unwrap();
assert!(matches!(
&err,
ToggleAutoJoinDomainError::GenericDomainNotAllowed(domain) if domain.as_str() == "gmail.com"
));
// The rejected toggle must not have set anything.
let stored: Option<String> =
sqlx::query_scalar("SELECT auto_join_domain FROM team WHERE id = $1")
.bind(team_id)
.fetch_one(&pool)
.await?;
assert_eq!(stored, None);
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_toggle_auto_join_domain_missing_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
let missing_team_id = macro_uuid::string_to_uuid("63333333-3333-3333-3333-333333333333")?;
let err = team_repo
.toggle_auto_join_domain(&missing_team_id)
.await
.err()
.unwrap();
assert!(err.to_string().contains("does not exist"));
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_get_team_id_by_domain(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
// No team has an auto-join domain yet.
let found = team_repo
.get_team_id_by_domain(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)
.await?;
assert_eq!(found, None);
team_repo.toggle_auto_join_domain(&team_id).await?;
let found = team_repo
.get_team_id_by_domain(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)
.await?;
assert_eq!(found, Some(team_id));
// Domain matching is case-insensitive on the user's email domain.
let found = team_repo
.get_team_id_by_domain(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)
.await?;
assert_eq!(found, Some(team_id));
// Unrelated domains do not match.
let found = team_repo
.get_team_id_by_domain(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)
.await?;
assert_eq!(found, None);
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_add_user_to_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let seat_count_before = team_repo.get_team_seat_count(&team_id).await?;
let invites_before = team_repo.get_user_team_invites(&user_id).await?;
assert!(
invites_before
.iter()
.any(|invite| invite.team_id == team_id)
);
let member = team_repo
.add_user_to_team(&team_id, &user_id)
.await?
.expect("user should have been added");
assert_eq!(member.team_id, team_id);
assert_eq!(member.user_id.as_ref(), user_id.as_ref());
assert_eq!(member.role, TeamRole::Member);
let role = team_repo.get_team_role(&team_id, &user_id).await?;
assert_eq!(role, Some(TeamRole::Member));
let seat_count = team_repo.get_team_seat_count(&team_id).await?;
assert_eq!(seat_count, seat_count_before + 1);
let invites_after = team_repo.get_user_team_invites(&user_id).await?;
assert!(!invites_after.iter().any(|invite| invite.team_id == team_id));
// Adding again is a no-op: no member returned, no extra seat counted.
let member = team_repo.add_user_to_team(&team_id, &user_id).await?;
assert!(member.is_none());
let seat_count = team_repo.get_team_seat_count(&team_id).await?;
assert_eq!(seat_count, seat_count_before + 1);
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn test_allow_non_admin_invites_defaults_true_and_toggles(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
let team_id = uuid::Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
// Teams default to allowing non-admin invites.
assert!(team_repo.get_team_allow_non_admin_invites(&team_id).await?);
// Toggling flips it off, and the getter agrees.
assert!(!team_repo.toggle_allow_non_admin_invites(&team_id).await?);
assert!(!team_repo.get_team_allow_non_admin_invites(&team_id).await?);
// Toggling again flips it back on.
assert!(team_repo.toggle_allow_non_admin_invites(&team_id).await?);
assert!(team_repo.get_team_allow_non_admin_invites(&team_id).await?);
// Missing teams surface TeamDoesNotExist from both methods.
let missing = uuid::Uuid::parse_str("99999999-9999-9999-9999-999999999999")?;
assert!(matches!(
team_repo.get_team_allow_non_admin_invites(&missing).await,
Err(TeamError::TeamDoesNotExist)
));
assert!(matches!(
team_repo.toggle_allow_non_admin_invites(&missing).await,
Err(TeamError::TeamDoesNotExist)
));
Ok(())
}
// -- Invite reminders --
const TEAM_1: &str = "11111111-1111-1111-1111-111111111111";
/// Sets the fixture invite to `[email protected]` as `days_old` days old, last
/// emailed `last_sent_days_ago` days ago, with `reminders_sent` reminders.
///
/// `last_sent_at` is `TIMESTAMP(3)`, which rounds to the nearest millisecond,
/// so it is truncated first. Rounded up, an invite aged to exactly its due
/// time is still up to 0.5ms short of it if the claim's `NOW()` comes that soon.
async fn age_invite(
pool: &Pool<Postgres>,
days_old: i32,
last_sent_days_ago: i32,
reminders_sent: i16,
) -> anyhow::Result<()> {
let aged_exactly: bool = sqlx::query_scalar(
r#"
UPDATE team_invite
SET created_at = NOW() - make_interval(days => $1),
last_sent_at = date_trunc('milliseconds', NOW() - make_interval(days => $2)),
reminders_sent = $3
WHERE email = '[email protected]'
RETURNING last_sent_at <= NOW() - make_interval(days => $2)
"#,
)
.bind(days_old)
.bind(last_sent_days_ago)
.bind(reminders_sent)
.fetch_one(pool)
.await?;
assert!(
aged_exactly,
"last_sent_at must not round past its due time"
);
Ok(())
}
/// Puts team1 in good standing; the fixture leaves it not paying.
async fn mark_team_1_paying(pool: &Pool<Postgres>) -> anyhow::Result<()> {
sqlx::query("UPDATE team SET paying = true WHERE id = $1::uuid")
.bind(TEAM_1)
.execute(pool)
.await?;
Ok(())
}
async fn claimed_emails(team_repo: &TeamRepositoryImpl) -> anyhow::Result<Vec<(String, u8)>> {
Ok(team_repo
.claim_due_invite_reminders(100)
.await?
.into_iter()
.map(|r| (r.email, r.reminder_number))
.collect())
}
/// Three days after the invite email, the first reminder is claimed once.
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn first_invite_reminder_is_due_after_three_days(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
mark_team_1_paying(&pool).await?;
age_invite(&pool, 3, 3, 0).await?;
let claimed = team_repo.claim_due_invite_reminders(100).await?;
assert_eq!(claimed.len(), 1);
let reminder = &claimed[0];
assert_eq!(reminder.email, "[email protected]");
assert_eq!(reminder.reminder_number, 1);
assert_eq!(reminder.team_name, "team1");
assert_eq!(reminder.invited_by, "macro|[email protected]");
assert!(reminder.paying && reminder.has_subscription && !reminder.enterprise);
// Claiming counted the reminder and restarted the clock.
assert!(claimed_emails(&team_repo).await?.is_empty());
let (reminders_sent, recently_sent): (i16, bool) = sqlx::query_as(
"SELECT reminders_sent, last_sent_at > NOW() - INTERVAL '1 minute' FROM team_invite WHERE email = '[email protected]'",
)
.fetch_one(&pool)
.await?;
assert_eq!((reminders_sent, recently_sent), (1, true));
Ok(())
}
/// Two days after the invite email, nothing is due yet.
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn invite_reminder_is_not_due_before_three_days(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
mark_team_1_paying(&pool).await?;
age_invite(&pool, 2, 2, 0).await?;
assert!(claimed_emails(&team_repo).await?.is_empty());
Ok(())
}
/// The second reminder waits four days after the first, and there is no third.
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn second_invite_reminder_is_the_last(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
mark_team_1_paying(&pool).await?;
age_invite(&pool, 6, 3, 1).await?;
assert!(claimed_emails(&team_repo).await?.is_empty());
age_invite(&pool, 7, 4, 1).await?;
assert_eq!(
claimed_emails(&team_repo).await?,
vec![("[email protected]".to_string(), 2)]
);
age_invite(&pool, 13, 6, 2).await?;
assert!(claimed_emails(&team_repo).await?.is_empty());
Ok(())
}
/// Invites older than 14 days are never reminded, so a deploy does not
/// email people about invites from long ago.
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn old_invites_are_not_reminded(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
mark_team_1_paying(&pool).await?;
age_invite(&pool, 15, 15, 0).await?;
assert!(claimed_emails(&team_repo).await?.is_empty());
Ok(())
}
/// No reminder for an invitee who already joined, one whose inviter left the
/// team, or one the invitee could not accept because the team stopped paying.
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn invite_reminders_skip_invites_that_cannot_lead_anywhere(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
age_invite(&pool, 5, 5, 0).await?;
// team1 has a subscription but is not paying.
assert!(claimed_emails(&team_repo).await?.is_empty());
mark_team_1_paying(&pool).await?;
// The invitee (here user3, who has an account) joined some other way
// and the invite row stayed.
sqlx::query("DELETE FROM team_invite WHERE email = '[email protected]'")
.execute(&pool)
.await?;
sqlx::query("UPDATE team_invite SET email = '[email protected]' WHERE email = '[email protected]'")
.execute(&pool)
.await?;
sqlx::query("INSERT INTO team_user (team_id, user_id, team_role) VALUES ($1::uuid, 'macro|[email protected]', 'member')")
.bind(TEAM_1)
.execute(&pool)
.await?;
assert!(claimed_emails(&team_repo).await?.is_empty());
sqlx::query("DELETE FROM team_user WHERE user_id = 'macro|[email protected]'")
.execute(&pool)
.await?;
assert_eq!(claimed_emails(&team_repo).await?.len(), 1);
sqlx::query(
"UPDATE team_invite SET reminders_sent = 0, last_sent_at = NOW() - INTERVAL '5 days'",
)
.execute(&pool)
.await?;
// The inviter is no longer on the team.
sqlx::query("UPDATE team_invite SET invited_by = 'macro|[email protected]'")
.execute(&pool)
.await?;
assert!(claimed_emails(&team_repo).await?.is_empty());
Ok(())
}
/// Free teams and enterprise teams get reminders too.
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn free_and_enterprise_teams_get_invite_reminders(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
age_invite(&pool, 5, 5, 0).await?;
sqlx::query("UPDATE team SET enterprise = true WHERE id = $1::uuid")
.bind(TEAM_1)
.execute(&pool)
.await?;
let claimed = team_repo.claim_due_invite_reminders(100).await?;
assert_eq!(claimed.len(), 1);
assert!(claimed[0].enterprise);
age_invite(&pool, 5, 5, 0).await?;
sqlx::query("UPDATE team SET enterprise = false, subscription_id = NULL WHERE id = $1::uuid")
.bind(TEAM_1)
.execute(&pool)
.await?;
let claimed = team_repo.claim_due_invite_reminders(100).await?;
assert_eq!(claimed.len(), 1);
assert!(!claimed[0].paying && !claimed[0].has_subscription);
Ok(())
}
/// A sweep claims at most `limit` invites, oldest first.
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn invite_reminder_claims_respect_the_limit(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool.clone());
mark_team_1_paying(&pool).await?;
sqlx::query(
"UPDATE team_invite SET created_at = NOW() - INTERVAL '6 days', last_sent_at = NOW() - INTERVAL '6 days' WHERE email = '[email protected]'",
)
.execute(&pool)
.await?;
age_invite(&pool, 5, 5, 0).await?;
let first = team_repo.claim_due_invite_reminders(1).await?;
assert_eq!(first.len(), 1);
assert_eq!(first[0].email, "[email protected]");
assert_eq!(
claimed_emails(&team_repo).await?,
vec![("[email protected]".to_string(), 1)]
);
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
)]
async fn agent_invites_are_visible_to_the_invitee(pool: Pool<Postgres>) -> anyhow::Result<()> {
let macro_user_id = uuid::Uuid::new_v4();
sqlx::query!(
r#"INSERT INTO "macro_user" (id, username, email, stripe_customer_id)
VALUES ($1, '[email protected]', '[email protected]', 'cus_owner')"#,
macro_user_id,
)
.execute(&pool)
.await?;
sqlx::query!(
r#"INSERT INTO "User" ("id", "email", "macro_user_id")
VALUES ('macro|[email protected]', '[email protected]', $1)"#,
macro_user_id,
)
.execute(&pool)
.await?;
let team_repo = TeamRepositoryImpl::new(pool);
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let invited = team_repo
.invite_users_to_team(&team_id, &user_id, invites, true)
.await?;
assert!(invited[0].is_agent);
let invitee = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let pending = team_repo.get_user_team_invites(&invitee).await?;
assert_eq!(pending.len(), 1);
assert!(pending[0].is_agent);
Ok(())
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn get_user_display_name_joins_the_set_name_parts(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
for statement in [
r#"INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES
('b1111111-1111-1111-1111-111111111111', '[email protected]', '[email protected]', 'cus_full'),
('b2222222-2222-2222-2222-222222222222', '[email protected]', '[email protected]', 'cus_first'),
('b3333333-3333-3333-3333-333333333333', '[email protected]', '[email protected]', 'cus_unset'),
('b4444444-4444-4444-4444-444444444444', '[email protected]', '[email protected]', 'cus_none')"#,
r#"INSERT INTO "User" (id, email, macro_user_id) VALUES
('macro|[email protected]', '[email protected]', 'b1111111-1111-1111-1111-111111111111'),
('macro|[email protected]', '[email protected]', 'b2222222-2222-2222-2222-222222222222'),
('macro|[email protected]', '[email protected]', 'b3333333-3333-3333-3333-333333333333'),
('macro|[email protected]', '[email protected]', 'b4444444-4444-4444-4444-444444444444')"#,
r#"INSERT INTO macro_user_info (macro_user_id, first_name, last_name) VALUES
('b1111111-1111-1111-1111-111111111111', 'Ada', 'Lovelace'),
('b2222222-2222-2222-2222-222222222222', 'Grace', 'N/A'),
('b3333333-3333-3333-3333-333333333333', 'N/A', NULL)"#,
] {
sqlx::query(statement).execute(&pool).await?;
}
let team_repo = TeamRepositoryImpl::new(pool);
let mut names = Vec::new();
for user in [
"macro|[email protected]",
"macro|[email protected]",
"macro|[email protected]",
"macro|[email protected]",
"macro|[email protected]",
] {
let user = MacroUserIdStr::parse_from_str(user)?;
names.push(team_repo.get_user_display_name(&user).await?);
}
assert_eq!(
names,
[
Some("Ada Lovelace".to_string()),
Some("Grace".to_string()),
None,
None,
None,
]
);
Ok(())
}