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
feat(auth-service): get_names_with_email endpoint (#455)
Evan Hutnik1106cf276461
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 2f4f0c776b..fa1b277951 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -4846,6 +4846,7 @@ dependencies = ["models_permissions","models_search","models_team",+ "non_empty","rand 0.9.0","serde","serde_json",diff --git a/rust/cloud-storage/authentication_service/src/api/swagger.rs b/rust/cloud-storage/authentication_service/src/api/swagger.rsindex 5b7068dc3a..409ffa2c6f 100644--- a/rust/cloud-storage/authentication_service/src/api/swagger.rs+++ b/rust/cloud-storage/authentication_service/src/api/swagger.rs@@ -20,6 +20,8 @@ use crate::api::user::get_user_organization::UserOrganizationResponse;use crate::api::user::patch_tutorial::PatchUserTutorialRequest;use crate::api::user::patch_user_group::PatchUserGroupRequest;use crate::api::user::patch_user_onboarding::PatchUserOnboardingRequest;+use crate::api::user::post_get_names::PostGetNamesRequestBody;+use crate::api::user::post_get_names_with_email::GetNamesWithEmailRequestBody;use crate::api::{email, health, jwt, link, login, logout, merge, oauth, oauth2, permissions, session, team, user,};@@ -79,6 +81,7 @@ use model::user::{user::patch_user_group::handler,user::patch_user_onboarding::handler,user::post_get_names::handler_external,+ user::post_get_names_with_email::handler,user::get_user_link_exists::handler,user::get_user_organization::handler,user::get_user_quota::handler,@@ -129,6 +132,8 @@ use model::user::{PutUserNameQueryParams,UserName,UserNames,+ GetNamesWithEmailRequestBody,+ PostGetNamesRequestBody,UserTokensResponse,UserLinkResponse,MacroApiTokenResponse,diff --git a/rust/cloud-storage/authentication_service/src/api/user/mod.rs b/rust/cloud-storage/authentication_service/src/api/user/mod.rsindex 75f22fadd4..5dfca2f5a4 100644--- a/rust/cloud-storage/authentication_service/src/api/user/mod.rs+++ b/rust/cloud-storage/authentication_service/src/api/user/mod.rs@@ -23,6 +23,7 @@ pub(in crate::api) mod patch_tutorial;pub(in crate::api) mod patch_user_group;pub(in crate::api) mod patch_user_onboarding;pub(in crate::api) mod post_get_names;+pub(in crate::api) mod post_get_names_with_email;pub(in crate::api) mod post_profile_pictures;pub(in crate::api) mod put_name;pub(in crate::api) mod put_profile_picture;@@ -48,6 +49,10 @@ fn router_with_auth(state: ApiContext, jwt_args: JwtValidationArgs) -> Router<Ap.route("/name", put(put_name::handler)).route("/name", get(get_name::handler)).route("/get_names", post(post_get_names::handler_external))+ .route(+ "/get_names_with_email",+ post(post_get_names_with_email::handler),+ ).route("/link_exists", get(get_user_link_exists::handler)).route("/tutorial", patch(patch_tutorial::handler)).route(diff --git a/rust/cloud-storage/authentication_service/src/api/user/post_get_names_with_email.rs b/rust/cloud-storage/authentication_service/src/api/user/post_get_names_with_email.rsnew file mode 100644index 0000000000..83ac86499e--- /dev/null+++ b/rust/cloud-storage/authentication_service/src/api/user/post_get_names_with_email.rs@@ -0,0 +1,59 @@+use crate::api::context::ApiContext;+use axum::{+ Extension, Json,+ extract::{self, State},+ http::StatusCode,+};+use macro_db_client::user::get_user_name::get_user_names_with_email;+use macro_user_id::lowercased::Lowercase;+use macro_user_id::user_id::{MacroUserId, MacroUserIdStr};++use model::response::ErrorResponse;+use model::user::{UserContext, UserNames};+use non_empty::NonEmpty;++#[derive(Default, Debug, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]+pub struct GetNamesWithEmailRequestBody {+ #[schema(value_type = Vec<String>)]+ pub user_ids: Vec<MacroUserIdStr<'static>>,+}++/// Gets names for passed user profile ids, falling back to the requesting user's email contact names+#[utoipa::path(+ post,+ path = "/user/get_names_with_email",+ operation_id = "get_user_names_with_email",+ responses(+ (status = 200, body=UserNames),+ (status = 400, body=String),+ (status = 401, body=String),+ (status = 500, body=ErrorResponse),+ ),+)]+#[tracing::instrument(skip(ctx))]+pub async fn handler(+ State(ctx): State<ApiContext>,+ user_context: Extension<UserContext>,+ extract::Json(req): extract::Json<GetNamesWithEmailRequestBody>,+) -> Result<Json<UserNames>, (StatusCode, String)> {+ let user_profile_ids: NonEmpty<Vec<MacroUserId<Lowercase>>> = NonEmpty::new(+ req.user_ids+ .into_iter()+ .map(|id| id.0.lowercase())+ .collect(),+ )+ .map_err(|_| {+ (+ StatusCode::BAD_REQUEST,+ "user_ids cannot be empty".to_string(),+ )+ })?;++ let user_names = get_user_names_with_email(&ctx.db, &user_context.user_id, user_profile_ids)+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "failed to get user names with email");+ (StatusCode::INTERNAL_SERVER_ERROR, e.to_string())+ })?;+ Ok(Json(UserNames { names: user_names }))+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-18fb7105aab4316c3b3b13531513d7885f651652b20ad9b4234b8935bed6958a.json b/rust/cloud-storage/macro_db_client/.sqlx/query-18fb7105aab4316c3b3b13531513d7885f651652b20ad9b4234b8935bed6958a.jsonnew file mode 100644index 0000000000..eea1d123d7--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-18fb7105aab4316c3b3b13531513d7885f651652b20ad9b4234b8935bed6958a.json@@ -0,0 +1,35 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH requested_ids AS (\n SELECT UNNEST($2::text[]) as id\n ),\n user_links AS (\n SELECT id as link_id\n FROM email_links\n WHERE macro_id = $1\n ),\n users_found AS (\n SELECT\n u.id as user_profile_id,\n mui.first_name as mui_first_name,\n mui.last_name as mui_last_name\n FROM requested_ids req\n JOIN \"User\" u ON u.id = req.id\n LEFT JOIN macro_user_info mui ON u.macro_user_id = mui.macro_user_id\n ),\n contacts_requested AS (\n SELECT\n req.id as user_profile_id,\n ec.name as contact_name\n FROM requested_ids req\n CROSS JOIN user_links li\n JOIN email_contacts ec\n ON ec.link_id = li.link_id\n AND ec.email_address = REPLACE(req.id, 'macro|', '')\n AND ec.name IS NOT NULL\n )\n SELECT DISTINCT ON (user_profile_id)\n user_profile_id as \"user_profile_id!\",\n -- user's name in macro takes precedence over email contact name\n COALESCE(\n NULLIF(mui_first_name, 'N/A'),\n -- first word in email contact name is approximation of first name\n SPLIT_PART(contact_name, ' ', 1)\n ) as \"first_name\",\n -- user's name in macro takes precedence over email contact name\n COALESCE(\n NULLIF(mui_last_name, 'N/A'),\n CASE\n -- if there is a space in the email contact name, the rest is the last name\n WHEN POSITION(' ' IN contact_name) > 0\n THEN NULLIF(TRIM(SUBSTRING(contact_name FROM POSITION(' ' IN contact_name) + 1)), '')\n ELSE NULL\n END\n ) as \"last_name\"\n FROM (\n -- Users in User table with contact fallback (in case user hasn't set name in Macro)\n SELECT\n uf.user_profile_id,\n uf.mui_first_name,\n uf.mui_last_name,\n cr.contact_name\n FROM users_found uf\n LEFT JOIN contacts_requested cr ON cr.user_profile_id = uf.user_profile_id\n\n UNION ALL\n\n -- People only in email_contacts (haven't joined Macro yet)\n SELECT\n cr.user_profile_id,\n NULL::text as mui_first_name,\n NULL::text as mui_last_name,\n cr.contact_name\n FROM contacts_requested cr\n WHERE NOT EXISTS (\n SELECT 1\n FROM users_found uf\n WHERE uf.user_profile_id = cr.user_profile_id\n )\n ) combined\n ORDER BY user_profile_id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_profile_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "first_name",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "last_name",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "TextArray"+ ]+ },+ "nullable": [+ null,+ null,+ null+ ]+ },+ "hash": "18fb7105aab4316c3b3b13531513d7885f651652b20ad9b4234b8935bed6958a"+}diff --git a/rust/cloud-storage/macro_db_client/Cargo.toml b/rust/cloud-storage/macro_db_client/Cargo.tomlindex 47a6465280..e4db61c2ff 100644--- a/rust/cloud-storage/macro_db_client/Cargo.toml+++ b/rust/cloud-storage/macro_db_client/Cargo.toml@@ -28,6 +28,7 @@ models_pagination = { path = "../models_pagination" }models_permissions = { path = "../models_permissions" }models_search = { path = "../models_search" }models_team = { path = "../models_team", optional = true }+non_empty = { path = "../non_empty" }rand = { workspace = true, optional = true }serde = { workspace = true }serde_json = { workspace = true }diff --git a/rust/cloud-storage/macro_db_client/fixtures/user_names_with_email.sql b/rust/cloud-storage/macro_db_client/fixtures/user_names_with_email.sqlnew file mode 100644index 0000000000..15401b6918--- /dev/null+++ b/rust/cloud-storage/macro_db_client/fixtures/user_names_with_email.sql@@ -0,0 +1,34 @@+-- Test data for get_user_names_with_email function++-- Create test macro users+INSERT INTO macro_user (id, username, email, stripe_customer_id)+VALUES+ ('11111111-1111-1111-1111-111111111111', 'test_user_1', '[email protected]', 'cus_test1'),+ ('22222222-2222-2222-2222-222222222222', 'test_user_2', '[email protected]', 'cus_test2'),+ ('33333333-3333-3333-3333-333333333333', 'test_user_3', '[email protected]', 'cus_test3');++-- Create macro user info with names+INSERT INTO macro_user_info (macro_user_id, first_name, last_name)+VALUES+ ('11111111-1111-1111-1111-111111111111', 'JohnMacroContact', 'DoeMacroContact'),+ ('22222222-2222-2222-2222-222222222222', 'JaneMacroContact', 'SmithMacroContact'),+ ('33333333-3333-3333-3333-333333333333', 'N/A', 'N/A'); -- User with N/A name to test fallback++-- Create User (profile) entries+INSERT INTO "User" (id, email, macro_user_id, "organizationId", "hasChromeExt", "tutorialComplete", "hasOnboardingDocuments")+VALUES+ ('macro|[email protected]', '[email protected]', '11111111-1111-1111-1111-111111111111', NULL, false, false, false),+ ('macro|[email protected]', '[email protected]', '22222222-2222-2222-2222-222222222222', NULL, false, false, false),+ ('macro|[email protected]', '[email protected]', '33333333-3333-3333-3333-333333333333', NULL, false, false, false),+ ('macro|[email protected]', '[email protected]', NULL, NULL, false, false, false);++-- Create email link for macro user 1 (for email contacts lookup)+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active)+VALUES+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'macro|[email protected]', 'fa_user_1', '[email protected]', 'GMAIL', true);++-- Create email contacts (including one for macro|[email protected] with name, and one not in User table)+INSERT INTO email_contacts (id, link_id, email_address, name)+VALUES+ ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'BobEmailContact JohnsonEmailContact'),+ ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'AliceEmailContact WilliamsEmailContact');\ No newline at end of filediff --git a/rust/cloud-storage/macro_db_client/src/user/get_user_name.rs b/rust/cloud-storage/macro_db_client/src/user/get_user_name.rsindex 4779de42d1..537d97a719 100644--- a/rust/cloud-storage/macro_db_client/src/user/get_user_name.rs+++ b/rust/cloud-storage/macro_db_client/src/user/get_user_name.rs@@ -1,4 +1,10 @@+#[cfg(test)]+mod tests;++use macro_user_id::lowercased::Lowercase;+use macro_user_id::user_id::MacroUserId;use model::user::UserName;+use non_empty::NonEmpty;#[tracing::instrument(skip(db))]pub async fn get_user_name(db: &sqlx::PgPool, macro_user_id: &str) -> anyhow::Result<UserName> {@@ -47,3 +53,101 @@ pub async fn get_user_names(Ok(user_names)}++/// gets macro user names for passed user profile ids, falling back to the user's email contacts if they have any+#[tracing::instrument(skip(db), err)]+pub async fn get_user_names_with_email(+ db: &sqlx::PgPool,+ macro_user_id: &str,+ user_profile_ids: NonEmpty<Vec<MacroUserId<Lowercase<'_>>>>,+) -> anyhow::Result<Vec<UserName>> {+ let user_profile_ids_str: Vec<&str> = user_profile_ids.iter().map(|id| id.as_ref()).collect();++ let user_names = sqlx::query!(+ r#"+ WITH requested_ids AS (+ SELECT UNNEST($2::text[]) as id+ ),+ user_links AS (+ SELECT id as link_id+ FROM email_links+ WHERE macro_id = $1+ ),+ users_found AS (+ SELECT+ u.id as user_profile_id,+ mui.first_name as mui_first_name,+ mui.last_name as mui_last_name+ FROM requested_ids req+ JOIN "User" u ON u.id = req.id+ LEFT JOIN macro_user_info mui ON u.macro_user_id = mui.macro_user_id+ ),+ contacts_requested AS (+ SELECT+ req.id as user_profile_id,+ ec.name as contact_name+ FROM requested_ids req+ CROSS JOIN user_links li+ JOIN email_contacts ec+ ON ec.link_id = li.link_id+ AND ec.email_address = REPLACE(req.id, 'macro|', '')+ AND ec.name IS NOT NULL+ )+ SELECT DISTINCT ON (user_profile_id)+ user_profile_id as "user_profile_id!",+ -- user's name in macro takes precedence over email contact name+ COALESCE(+ NULLIF(mui_first_name, 'N/A'),+ -- first word in email contact name is approximation of first name+ SPLIT_PART(contact_name, ' ', 1)+ ) as "first_name",+ -- user's name in macro takes precedence over email contact name+ COALESCE(+ NULLIF(mui_last_name, 'N/A'),+ CASE+ -- if there is a space in the email contact name, the rest is the last name+ WHEN POSITION(' ' IN contact_name) > 0+ THEN NULLIF(TRIM(SUBSTRING(contact_name FROM POSITION(' ' IN contact_name) + 1)), '')+ ELSE NULL+ END+ ) as "last_name"+ FROM (+ -- Users in User table with contact fallback (in case user hasn't set name in Macro)+ SELECT+ uf.user_profile_id,+ uf.mui_first_name,+ uf.mui_last_name,+ cr.contact_name+ FROM users_found uf+ LEFT JOIN contacts_requested cr ON cr.user_profile_id = uf.user_profile_id++ UNION ALL++ -- People only in email_contacts (haven't joined Macro yet)+ SELECT+ cr.user_profile_id,+ NULL::text as mui_first_name,+ NULL::text as mui_last_name,+ cr.contact_name+ FROM contacts_requested cr+ WHERE NOT EXISTS (+ SELECT 1+ FROM users_found uf+ WHERE uf.user_profile_id = cr.user_profile_id+ )+ ) combined+ ORDER BY user_profile_id+ "#,+ macro_user_id,+ &user_profile_ids_str as &[&str]+ )+ .map(|row| UserName {+ id: row.user_profile_id,+ first_name: row.first_name,+ last_name: row.last_name,+ })+ .fetch_all(db)+ .await?;++ Ok(user_names)+}diff --git a/rust/cloud-storage/macro_db_client/src/user/get_user_name/tests.rs b/rust/cloud-storage/macro_db_client/src/user/get_user_name/tests.rsnew file mode 100644index 0000000000..0b68674701--- /dev/null+++ b/rust/cloud-storage/macro_db_client/src/user/get_user_name/tests.rs@@ -0,0 +1,125 @@+use super::*;+use crate::user::get_user_name::get_user_names_with_email;+use macro_user_id::cowlike::CowLike;+use macro_user_id::user_id::MacroUserId;+use non_empty::NonEmpty;+use sqlx::{Pool, Postgres};++fn parse_user_ids(+ ids: Vec<&str>,+) -> anyhow::Result<NonEmpty<Vec<MacroUserId<macro_user_id::lowercased::Lowercase<'static>>>>> {+ NonEmpty::new(+ ids.into_iter()+ .map(|id| MacroUserId::parse_from_str(id).map(|u| u.lowercase().into_owned()))+ .collect::<Result<Vec<_>, _>>()?,+ )+ .map_err(|e| anyhow::anyhow!("Empty user_ids: {}", e))+}++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("user_names_with_email")))]+async fn test_get_user_names_with_email_basic(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let user_profile_ids = parse_user_ids(vec![+ "macro|[email protected]",+ "macro|[email protected]",+ ])?;++ let mut names =+ get_user_names_with_email(&pool, "macro|[email protected]", user_profile_ids)+ .await?;+ names.sort_by(|a, b| a.id.cmp(&b.id));++ assert_eq!(names.len(), 2);++ // Sorted: macro|[email protected], macro|[email protected]+ assert_eq!(names[0].id, "macro|[email protected]");+ assert_eq!(names[0].first_name, Some("JohnMacroContact".to_string()));+ assert_eq!(names[0].last_name, Some("DoeMacroContact".to_string()));++ assert_eq!(names[1].id, "macro|[email protected]");+ assert_eq!(names[1].first_name, Some("JaneMacroContact".to_string()));+ assert_eq!(names[1].last_name, Some("SmithMacroContact".to_string()));++ Ok(())+}++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("user_names_with_email")))]+async fn test_get_user_names_with_email_fallback_to_contact(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ // User with N/A name should fall back to email contact name+ let user_profile_ids = parse_user_ids(vec!["macro|[email protected]"])?;++ let names =+ get_user_names_with_email(&pool, "macro|[email protected]", user_profile_ids)+ .await?;++ assert_eq!(names.len(), 1);+ assert_eq!(names[0].id, "macro|[email protected]");+ assert_eq!(names[0].first_name, Some("BobEmailContact".to_string()));+ assert_eq!(names[0].last_name, Some("JohnsonEmailContact".to_string()));++ Ok(())+}++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("user_names_with_email")))]+async fn test_get_user_names_with_email_contact_only(pool: Pool<Postgres>) -> anyhow::Result<()> {+ // User not in User table, only in email_contacts+ let user_profile_ids = parse_user_ids(vec!["macro|[email protected]"])?;++ let names =+ get_user_names_with_email(&pool, "macro|[email protected]", user_profile_ids)+ .await?;++ assert_eq!(names.len(), 1);+ assert_eq!(names[0].id, "macro|[email protected]");+ assert_eq!(names[0].first_name, Some("AliceEmailContact".to_string()));+ assert_eq!(names[0].last_name, Some("WilliamsEmailContact".to_string()));++ Ok(())+}++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("user_names_with_email")))]+async fn test_get_user_names_with_email_mixed(pool: Pool<Postgres>) -> anyhow::Result<()> {+ // Mix of users with names, N/A fallback, and contact-only+ let user_profile_ids = parse_user_ids(vec![+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",+ ])?;++ let mut names =+ get_user_names_with_email(&pool, "macro|[email protected]", user_profile_ids)+ .await?;+ names.sort_by(|a, b| a.id.cmp(&b.id));++ assert_eq!(names.len(), 3);++ assert_eq!(names[0].id, "macro|[email protected]");+ assert_eq!(names[0].first_name, Some("AliceEmailContact".to_string()));+ assert_eq!(names[0].last_name, Some("WilliamsEmailContact".to_string()));++ assert_eq!(names[1].id, "macro|[email protected]");+ assert_eq!(names[1].first_name, Some("JohnMacroContact".to_string()));+ assert_eq!(names[1].last_name, Some("DoeMacroContact".to_string()));++ assert_eq!(names[2].id, "macro|[email protected]");+ assert_eq!(names[2].first_name, Some("BobEmailContact".to_string()));+ assert_eq!(names[2].last_name, Some("JohnsonEmailContact".to_string()));++ Ok(())+}++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("user_names_with_email")))]+async fn test_get_user_names_with_email_not_found(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let user_profile_ids = parse_user_ids(vec!["macro|[email protected]"])?;++ let names =+ get_user_names_with_email(&pool, "macro|[email protected]", user_profile_ids)+ .await?;++ // Should return empty list for users that don't exist+ assert_eq!(names.len(), 0);++ Ok(())+}