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.

feat(referral): setup referral completion handling in stripe webhook (#2026)

Will Hutchinsonf33552ed940a
diff --git a/rust/cloud-storage/authentication_service/src/api/webhooks/user/stripe_webhook.rs b/rust/cloud-storage/authentication_service/src/api/webhooks/user/stripe_webhook.rs
index 2f41ef2697..d6a996aa16 100644
--- a/rust/cloud-storage/authentication_service/src/api/webhooks/user/stripe_webhook.rs
+++ b/rust/cloud-storage/authentication_service/src/api/webhooks/user/stripe_webhook.rs
@@ -8,8 +8,10 @@ use axum::{
http::{HeaderMap, StatusCode},
response::{IntoResponse, Json, Response},
};
+use macro_user_id::cowlike::CowLike;
use macro_user_id::email::Email;
use model::response::ErrorResponse;
+use referral::domain::ports::ReferralService;
use roles_and_permissions::domain::port::UserRolesAndPermissionsService;
use stripe_webhook::{EventObject, EventType};
use teams::domain::team_repo::TeamService;
@@ -230,6 +232,13 @@ async fn handle_customer_subscription_event(
);
}
+ // Check if this user was referred and process the referral
+ if subscription_status == "active"
+ && let Err(e) = check_and_process_referral(ctx, &email).await
+ {
+ tracing::error!(error=?e, "failed to process referral on subscription created");
+ }
+
ctx.user_roles_and_permissions_service
.update_user_roles_and_permissions_for_subscription(email, subscription_status.try_into()?)
.await?;
@@ -237,6 +246,38 @@ async fn handle_customer_subscription_event(
Ok(())
}
+/// Checks if the subscribing user was referred and, if so, processes the referral
+/// to credit the referrer.
+#[tracing::instrument(skip(ctx, email), err)]
+async fn check_and_process_referral(
+ ctx: &ApiContext,
+ email: &Email<macro_user_id::lowercased::Lowercase<'_>>,
+) -> anyhow::Result<()> {
+ let (macro_user_id, user_id_str) =
+ macro_db_client::user::get::get_user_macro_user_id_and_id_by_email(&ctx.db, email.as_ref())
+ .await?;
+
+ let Some(referral_code) = ctx
+ .referral_service
+ .get_referred_by(&macro_user_id)
+ .await
+ .map_err(|e| anyhow::anyhow!(e))?
+ else {
+ return Ok(());
+ };
+
+ let user_id = macro_user_id::user_id::MacroUserIdStr::parse_from_str(&user_id_str)
+ .expect("user id from db should be valid")
+ .into_owned();
+
+ ctx.referral_service
+ .process_referral(&user_id.0, &referral_code)
+ .await
+ .map_err(|e| anyhow::anyhow!(e))?;
+
+ Ok(())
+}
+
/// Handles team subscription events.
/// NOTE: We use strs here because there is a mismatch between stripe crate and
/// stripe_webhook crate for these types. *sigh*
diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rs
index 44868bfad3..a9bafdbd84 100644
--- a/rust/cloud-storage/authentication_service/src/main.rs
+++ b/rust/cloud-storage/authentication_service/src/main.rs
@@ -221,7 +221,7 @@ async fn main() -> anyhow::Result<()> {
let referral_service = ReferralServiceImpl::new(
PgReferralRepo::new(db.clone()),
- StripeDiscountClient::new(stripe_client.clone(), 500),
+ StripeDiscountClient::new(stripe_client.clone(), 10000 /*100$ credit, in cents*/),
);
api::setup_and_serve(
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-f2c563a84ecf4b347e19eed2770c9593db5cf4bba24c234e9179f741a920d4d5.json b/rust/cloud-storage/macro_db_client/.sqlx/query-f2c563a84ecf4b347e19eed2770c9593db5cf4bba24c234e9179f741a920d4d5.json
new file mode 100644
index 0000000000..b9194ba12f
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-f2c563a84ecf4b347e19eed2770c9593db5cf4bba24c234e9179f741a920d4d5.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \"macro_user_id\" as \"macro_user_id!\", \"id\"\n FROM \"User\"\n WHERE \"email\" = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "macro_user_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "f2c563a84ecf4b347e19eed2770c9593db5cf4bba24c234e9179f741a920d4d5"
+}
diff --git a/rust/cloud-storage/macro_db_client/src/user/get/mod.rs b/rust/cloud-storage/macro_db_client/src/user/get/mod.rs
index 775717cb75..42db92d3de 100644
--- a/rust/cloud-storage/macro_db_client/src/user/get/mod.rs
+++ b/rust/cloud-storage/macro_db_client/src/user/get/mod.rs
@@ -1,3 +1,6 @@
+#[cfg(test)]
+mod test;
+
pub mod get_user_by_email;
pub mod get_user_organization;
pub mod get_user_permissions;
@@ -188,6 +191,25 @@ pub async fn get_user_profile(
Ok(user_info)
}
+/// Gets the user's macro_user_id (UUID) and id (MacroUserIdStr) by email
+#[tracing::instrument(skip(db), err)]
+pub async fn get_user_macro_user_id_and_id_by_email(
+ db: &sqlx::Pool<sqlx::Postgres>,
+ email: &str,
+) -> Result<(uuid::Uuid, String), sqlx::Error> {
+ sqlx::query!(
+ r#"
+ SELECT "macro_user_id" as "macro_user_id!", "id"
+ FROM "User"
+ WHERE "email" = $1
+ "#,
+ email
+ )
+ .map(|row| (row.macro_user_id, row.id))
+ .fetch_one(db)
+ .await
+}
+
/// Gets all users emails
#[tracing::instrument(skip(db))]
pub async fn get_user_emails(
diff --git a/rust/cloud-storage/macro_db_client/src/user/get/test.rs b/rust/cloud-storage/macro_db_client/src/user/get/test.rs
new file mode 100644
index 0000000000..9850b5d88e
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/src/user/get/test.rs
@@ -0,0 +1,23 @@
+use sqlx::{Pool, Postgres};
+
+use super::get_user_macro_user_id_and_id_by_email;
+
+#[sqlx::test(fixtures(path = "../../../fixtures", scripts("users")))]
+async fn test_get_user_macro_user_id_and_id_by_email_success(pool: Pool<Postgres>) {
+ let (macro_user_id, id) = get_user_macro_user_id_and_id_by_email(&pool, "[email protected]")
+ .await
+ .unwrap();
+
+ assert_eq!(
+ macro_user_id,
+ uuid::Uuid::parse_str("a1111111-1111-1111-1111-111111111111").unwrap()
+ );
+ assert_eq!(id, "macro|[email protected]");
+}
+
+#[sqlx::test(fixtures(path = "../../../fixtures", scripts("users")))]
+async fn test_get_user_macro_user_id_and_id_by_email_not_found(pool: Pool<Postgres>) {
+ let result = get_user_macro_user_id_and_id_by_email(&pool, "[email protected]").await;
+
+ assert!(matches!(result, Err(sqlx::Error::RowNotFound)));
+}
diff --git a/rust/cloud-storage/referral/.sqlx/query-c5196bb88afe2d67ce0a4fe7eb2c23db0321cc59a5abd6f7f714b0333ca87613.json b/rust/cloud-storage/referral/.sqlx/query-c5196bb88afe2d67ce0a4fe7eb2c23db0321cc59a5abd6f7f714b0333ca87613.json
new file mode 100644
index 0000000000..34d7bb06c4
--- /dev/null
+++ b/rust/cloud-storage/referral/.sqlx/query-c5196bb88afe2d67ce0a4fe7eb2c23db0321cc59a5abd6f7f714b0333ca87613.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT referrer_id FROM referral_tracking WHERE referred_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "referrer_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "c5196bb88afe2d67ce0a4fe7eb2c23db0321cc59a5abd6f7f714b0333ca87613"
+}
diff --git a/rust/cloud-storage/referral/src/domain/ports.rs b/rust/cloud-storage/referral/src/domain/ports.rs
index f53291ba17..e3947b744a 100644
--- a/rust/cloud-storage/referral/src/domain/ports.rs
+++ b/rust/cloud-storage/referral/src/domain/ports.rs
@@ -36,6 +36,12 @@ pub trait ReferralRepo: Send + Sync + 'static {
referral_code: &ReferralCode,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
+ /// Gets the referral code of the user who referred the given user, if any
+ fn get_referred_by(
+ &self,
+ referred_user_id: &uuid::Uuid,
+ ) -> impl Future<Output = Result<Option<ReferralCode>, Self::Err>> + Send;
+
/// Gets the referrs customer id using their code
fn get_referrers_customer_id(
&self,
@@ -75,6 +81,12 @@ pub trait ReferralService: Send + Sync + 'static {
referral_code: &ReferralCode,
) -> impl Future<Output = Result<(), ReferralError>> + Send;
+ /// Gets the referral code of the user who referred the given user, if any
+ fn get_referred_by(
+ &self,
+ referred_user_id: &uuid::Uuid,
+ ) -> impl Future<Output = Result<Option<ReferralCode>, ReferralError>> + Send;
+
/// Processes a referral
/// - tracks the referral
/// - assigns the discount to the referrers' stripe
diff --git a/rust/cloud-storage/referral/src/domain/service.rs b/rust/cloud-storage/referral/src/domain/service.rs
index 617c9a0203..e0a45fcdc5 100644
--- a/rust/cloud-storage/referral/src/domain/service.rs
+++ b/rust/cloud-storage/referral/src/domain/service.rs
@@ -49,6 +49,17 @@ impl<R: ReferralRepo, Dc: DiscountClient> ReferralService for ReferralServiceImp
.map_err(|e| ReferralError::Internal(e.into()))
}
+ #[tracing::instrument(skip(self), err)]
+ async fn get_referred_by(
+ &self,
+ referred_user_id: &uuid::Uuid,
+ ) -> Result<Option<ReferralCode>, ReferralError> {
+ self.repo
+ .get_referred_by(referred_user_id)
+ .await
+ .map_err(|e| ReferralError::Internal(e.into()))
+ }
+
#[tracing::instrument(skip(self), err)]
async fn process_referral<'a>(
&self,
diff --git a/rust/cloud-storage/referral/src/inbound/axum_router/test.rs b/rust/cloud-storage/referral/src/inbound/axum_router/test.rs
index 7300f8a37c..b536c370be 100644
--- a/rust/cloud-storage/referral/src/inbound/axum_router/test.rs
+++ b/rust/cloud-storage/referral/src/inbound/axum_router/test.rs
@@ -34,6 +34,13 @@ impl ReferralService for MockReferralService {
Ok(())
}
+ async fn get_referred_by(
+ &self,
+ _referred_user_id: &uuid::Uuid,
+ ) -> Result<Option<ReferralCode>, ReferralError> {
+ Ok(None)
+ }
+
async fn process_referral<'a>(
&self,
_referred_user_id: &macro_user_id::user_id::MacroUserId<
diff --git a/rust/cloud-storage/referral/src/outbound/pg_referral_repo.rs b/rust/cloud-storage/referral/src/outbound/pg_referral_repo.rs
index f4abf79239..3b4e7b04ef 100644
--- a/rust/cloud-storage/referral/src/outbound/pg_referral_repo.rs
+++ b/rust/cloud-storage/referral/src/outbound/pg_referral_repo.rs
@@ -86,6 +86,22 @@ impl ReferralRepo for PgReferralRepo {
Ok(())
}
+ #[tracing::instrument(skip(self), err)]
+ async fn get_referred_by(
+ &self,
+ referred_user_id: &uuid::Uuid,
+ ) -> Result<Option<ReferralCode>, Self::Err> {
+ let referrer_id: Option<uuid::Uuid> = sqlx::query!(
+ "SELECT referrer_id FROM referral_tracking WHERE referred_id = $1",
+ referred_user_id
+ )
+ .map(|r| r.referrer_id)
+ .fetch_optional(&self.pool)
+ .await?;
+
+ Ok(referrer_id.map(|id| ReferralCode(self.short_uuid_converter.from_uuid(&id))))
+ }
+
#[tracing::instrument(skip(self), err)]
async fn complete_referral<'a>(
&self,
diff --git a/rust/cloud-storage/referral/src/outbound/pg_referral_repo/test.rs b/rust/cloud-storage/referral/src/outbound/pg_referral_repo/test.rs
index af271ef733..decffb4535 100644
--- a/rust/cloud-storage/referral/src/outbound/pg_referral_repo/test.rs
+++ b/rust/cloud-storage/referral/src/outbound/pg_referral_repo/test.rs
@@ -280,3 +280,46 @@ async fn test_complete_referral_not_tracked(pool: Pool<Postgres>) {
assert!(matches!(result, Err(sqlx::Error::RowNotFound)));
}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("referral_users"))
+)]
+async fn test_get_referred_by_found(pool: Pool<Postgres>) {
+ let repo = PgReferralRepo::new(pool);
+
+ // First track the referral so there's a row
+ let referred_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+ let code = referrer_referral_code();
+ repo.track_referral(&referred_user_id.0, &code)
+ .await
+ .unwrap();
+
+ // Now look up who referred this user
+ let referred_uuid = uuid::Uuid::parse_str("cccccccc-cccc-cccc-cccc-cccccccccccc").unwrap();
+ let result = repo.get_referred_by(&referred_uuid).await.unwrap();
+
+ assert!(result.is_some());
+ let returned_code = result.unwrap();
+
+ // The returned code should decode back to the referrer's UUID
+ let converter = ShortUuidConverter::default();
+ let decoded = converter.to_uuid(&returned_code.0).unwrap();
+ assert_eq!(decoded.to_string(), REFERRER_UUID);
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("referral_users"))
+)]
+async fn test_get_referred_by_not_found(pool: Pool<Postgres>) {
+ let repo = PgReferralRepo::new(pool);
+
+ // Query with a UUID that has no referral_tracking row
+ let unknown_uuid = uuid::Uuid::parse_str("dddddddd-dddd-dddd-dddd-dddddddddddd").unwrap();
+ let result = repo.get_referred_by(&unknown_uuid).await.unwrap();
+
+ assert!(result.is_none());
+}