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(referrals): implement referral system (#1992)

Will Hutchinson26a12371ac87
diff --git a/js/app/bun.lock b/js/app/bun.lock
index abcbc46fe3..7e2f396114 100644
--- a/js/app/bun.lock
+++ b/js/app/bun.lock
@@ -1,5 +1,6 @@
{
"lockfileVersion": 1,
+ "configVersion": 0,
"workspaces": {
"": {
"name": "@coparse/monorepo",
@@ -373,11 +374,12 @@
},
"overrides": {
- "flatted": ">=3.4.0",
+ "ajv": ">=6.14.0",
"cross-spawn": "7.0.6",
- "rollup": ">=4.59.0",
+ "flatted": ">=3.4.0",
"minimatch": ">=3.1.4",
- "ajv": ">=6.14.0",
+ "rollup": ">=4.59.0",
+ "undici": ">=6.24.0",
},
"packages": {
"@adobe/css-tools": ["@adobe/[email protected]", "", {}, "sha512-Elp+iwUx5rN5+Y8xLt5/GRoG20WGoDCQ/1Fb+1LiGtvwbDavuSk0jhD/eZdckHAuzcDzccnkv+rEjyWfRx18gg=="],
diff --git a/js/app/packages/app/component/auth/EmailForm.tsx b/js/app/packages/app/component/auth/EmailForm.tsx
index cea993e243..2a62bbffbb 100644
--- a/js/app/packages/app/component/auth/EmailForm.tsx
+++ b/js/app/packages/app/component/auth/EmailForm.tsx
@@ -60,6 +60,9 @@ export const sendEmailCode = action(async (formData: FormData) => {
return 'LoggedIn';
}
+ const url = new URL(window.location.href);
+ const referral_code = url.searchParams.get('referral_code');
+
const response = await platformFetch(
`${SERVER_HOSTS['auth-service']}/login/passwordless`,
{
@@ -68,6 +71,7 @@ export const sendEmailCode = action(async (formData: FormData) => {
body: JSON.stringify({
redirect_uri: REDIRECT_URI,
email,
+ ...(referral_code && { referral_code }),
}),
}
);
@@ -79,9 +83,11 @@ export const sendEmailCode = action(async (formData: FormData) => {
if (response.status === 202) {
const body = await response.json();
const idp_id = body.idp_id;
- // form dumb
- const urlEncodedEmail = encodeURIComponent((email ?? '').toString());
- window.location.href = `${SERVER_HOSTS['auth-service']}/login/sso?idp_id=${idp_id}&login_hint=${urlEncodedEmail}`;
+ const ssoUrl = new URL(`${SERVER_HOSTS['auth-service']}/login/sso`);
+ ssoUrl.searchParams.set('idp_id', idp_id);
+ ssoUrl.searchParams.set('login_hint', (email ?? '').toString());
+ if (referral_code) ssoUrl.searchParams.set('referral_code', referral_code);
+ window.location.href = ssoUrl.toString();
return false; // passwordless login flow is not reached
}
diff --git a/js/app/packages/app/component/auth/LoginOptions.tsx b/js/app/packages/app/component/auth/LoginOptions.tsx
index 825ed71686..8babaeb1e2 100644
--- a/js/app/packages/app/component/auth/LoginOptions.tsx
+++ b/js/app/packages/app/component/auth/LoginOptions.tsx
@@ -48,6 +48,12 @@ export function LoginOptions(props: { setStage: Setter<Stage> }) {
const startSsoLogin = async (idp_name: string) => {
const authUrl = new URL(`${SERVER_HOSTS['auth-service']}/login/sso`);
authUrl.searchParams.set('idp_name', idp_name);
+ const referral_code =
+ new URL(window.location.href).searchParams.get('referral_code') ??
+ new URLSearchParams(location.state?.originalLocation?.search).get(
+ 'referral_code'
+ );
+ if (referral_code) authUrl.searchParams.set('referral_code', referral_code);
if (isNativeMobilePlatform()) {
authUrl.searchParams.set('is_mobile', 'true');
}
diff --git a/js/app/packages/core/auth/email.ts b/js/app/packages/core/auth/email.ts
index de5e023e20..886db9a38a 100644
--- a/js/app/packages/core/auth/email.ts
+++ b/js/app/packages/core/auth/email.ts
@@ -13,7 +13,14 @@ function emailAuthUrl(params: EmailAuthParams) {
const idpName = params.idpName ?? GOOGLE_GMAIL_IDP;
const returnUrl = `${window.location.origin}${params.returnPath ?? ROUTER_BASE}`;
- return `${SERVER_HOSTS['auth-service']}/login/sso?idp_name=${idpName}&original_url=${returnUrl}`;
+ const url = new URL(`${SERVER_HOSTS['auth-service']}/login/sso`);
+ url.searchParams.set('idp_name', idpName);
+ url.searchParams.set('original_url', returnUrl);
+ const referral_code = new URL(window.location.href).searchParams.get(
+ 'referral_code'
+ );
+ if (referral_code) url.searchParams.set('referral_code', referral_code);
+ return url.toString();
}
export function redirectToEmailAuth(params: EmailAuthParams) {
diff --git a/js/app/packages/service-clients/service-auth/generated/client.ts b/js/app/packages/service-clients/service-auth/generated/client.ts
index efbc6bb576..8843a93ace 100644
--- a/js/app/packages/service-clients/service-auth/generated/client.ts
+++ b/js/app/packages/service-clients/service-auth/generated/client.ts
@@ -37,6 +37,7 @@ import type {
ProfilePictures,
PutProfilePictureParams,
PutUserNameParams,
+ ReferralCode,
ResendFusionauthVerifyUserEmailRequest,
SsoLoginParams,
SsoRequiredResponse,
@@ -1075,17 +1076,17 @@ export type oauthRedirectResponse200 = {
};
export type oauthRedirectResponse400 = {
- data: string;
+ data: ErrorResponse;
status: 400;
};
export type oauthRedirectResponse401 = {
- data: string;
+ data: ErrorResponse;
status: 401;
};
export type oauthRedirectResponse500 = {
- data: string;
+ data: ErrorResponse;
status: 500;
};
@@ -1308,6 +1309,61 @@ export const getUserPermissions = async (
} as getUserPermissionsResponse;
};
+/**
+ * Returns the authenticated user's referral code.
+ * @summary Handler for `GET /referral-code`.
+ */
+export type getReferralCodeResponse200 = {
+ data: ReferralCode;
+ status: 200;
+};
+
+export type getReferralCodeResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type getReferralCodeResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type getReferralCodeResponseSuccess = getReferralCodeResponse200 & {
+ headers: Headers;
+};
+export type getReferralCodeResponseError = (
+ | getReferralCodeResponse401
+ | getReferralCodeResponse500
+) & {
+ headers: Headers;
+};
+
+export type getReferralCodeResponse =
+ | getReferralCodeResponseSuccess
+ | getReferralCodeResponseError;
+
+export const getGetReferralCodeUrl = () => {
+ return `/referral/code`;
+};
+
+export const getReferralCode = async (
+ options?: RequestInit
+): Promise<getReferralCodeResponse> => {
+ const res = await fetch(getGetReferralCodeUrl(), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: getReferralCodeResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as getReferralCodeResponse;
+};
+
/**
* @summary Refreshes a JWT token
*/
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts b/js/app/packages/service-clients/service-auth/generated/schemas/index.ts
index 0edf4794a1..501a6046e5 100644
--- a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/index.ts
@@ -32,6 +32,7 @@ export * from './macroApiTokenParams';
export * from './macroApiTokenResponse';
export * from './passwordlessCallbackParams';
export * from './passwordlessRequest';
+export * from './passwordlessRequestReferralCode';
export * from './passwordRequest';
export * from './patchTeamRequest';
export * from './patchTeamRequestName';
@@ -47,6 +48,7 @@ export * from './putUserNameParams';
export * from './putUserNameQueryParams';
export * from './putUserNameQueryParamsFirstName';
export * from './putUserNameQueryParamsLastName';
+export * from './referralCode';
export * from './resendFusionauthVerifyUserEmailRequest';
export * from './ssoLoginParams';
export * from './ssoRequiredResponse';
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/passwordlessRequest.ts b/js/app/packages/service-clients/service-auth/generated/schemas/passwordlessRequest.ts
index 6ca9be31cf..d03a6e6905 100644
--- a/js/app/packages/service-clients/service-auth/generated/schemas/passwordlessRequest.ts
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/passwordlessRequest.ts
@@ -4,10 +4,13 @@
* authentication_service
* OpenAPI spec version: 0.1.0
*/
+import type { PasswordlessRequestReferralCode } from './passwordlessRequestReferralCode';
export interface PasswordlessRequest {
/** The email to initiate passwordless authentication for */
email: string;
/** The redirect uri to redirect to after login */
redirect_uri: string;
+ /** The referral code */
+ referral_code?: PasswordlessRequestReferralCode;
}
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/passwordlessRequestReferralCode.ts b/js/app/packages/service-clients/service-auth/generated/schemas/passwordlessRequestReferralCode.ts
new file mode 100644
index 0000000000..632c2ce66a
--- /dev/null
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/passwordlessRequestReferralCode.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The referral code
+ */
+export type PasswordlessRequestReferralCode = string | null;
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/referralCode.ts b/js/app/packages/service-clients/service-auth/generated/schemas/referralCode.ts
new file mode 100644
index 0000000000..6224fd9598
--- /dev/null
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/referralCode.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Wrapper for the referral code to make it type safe
+ */
+export type ReferralCode = string;
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/ssoLoginParams.ts b/js/app/packages/service-clients/service-auth/generated/schemas/ssoLoginParams.ts
index baff85e090..704b601ddc 100644
--- a/js/app/packages/service-clients/service-auth/generated/schemas/ssoLoginParams.ts
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/ssoLoginParams.ts
@@ -26,4 +26,8 @@ export type SsoLoginParams = {
* **OPTIONAL**. If the authentication request is from a mobile device.
*/
is_mobile: string;
+ /**
+ * **OPTIONAL**. If the user opened a link with a referral code.
+ */
+ referral_code: string;
};
diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.json
index fbf69dca10..e87d089449 100644
--- a/js/app/packages/service-clients/service-auth/openapi.json
+++ b/js/app/packages/service-clients/service-auth/openapi.json
@@ -661,6 +661,15 @@
"schema": {
"type": "string"
}
+ },
+ {
+ "name": "referral_code",
+ "in": "query",
+ "description": "**OPTIONAL**. If the user opened a link with a referral code.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
}
],
"responses": {
@@ -909,9 +918,9 @@
"400": {
"description": "",
"content": {
- "text/plain": {
+ "application/json": {
"schema": {
- "type": "string"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
@@ -919,9 +928,9 @@
"401": {
"description": "",
"content": {
- "text/plain": {
+ "application/json": {
"schema": {
- "type": "string"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
@@ -929,9 +938,9 @@
"500": {
"description": "",
"content": {
- "text/plain": {
+ "application/json": {
"schema": {
- "type": "string"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
@@ -1089,6 +1098,46 @@
}
}
},
+ "/referral/code": {
+ "get": {
+ "tags": ["referral"],
+ "summary": "Handler for `GET /referral-code`.",
+ "description": "Returns the authenticated user's referral code.",
+ "operationId": "get_referral_code",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ReferralCode"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/session": {
"post": {
"tags": ["session::session_creation"],
@@ -3199,6 +3248,10 @@
"redirect_uri": {
"type": "string",
"description": "The redirect uri to redirect to after login"
+ },
+ "referral_code": {
+ "type": ["string", "null"],
+ "description": "The referral code"
}
}
},
@@ -3314,6 +3367,10 @@
}
}
},
+ "ReferralCode": {
+ "type": "string",
+ "description": "Wrapper for the referral code to make it type safe"
+ },
"ResendFusionauthVerifyUserEmailRequest": {
"type": "object",
"required": ["email"],
diff --git a/rust/cloud-storage/Caddyfile b/rust/cloud-storage/Caddyfile
deleted file mode 100644
index c8f6200cac..0000000000
--- a/rust/cloud-storage/Caddyfile
+++ /dev/null
@@ -1,14 +0,0 @@
-connection-gateway.local.macro.com {
- tls internal
- reverse_proxy localhost:8080
-}
-
-notification-service.local.macro.com {
- tls internal
- reverse_proxy localhost:8086
-}
-
-comms-service.local.macro.com {
- tls internal
- reverse_proxy localhost:8087
-}
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index e9acafd1fc..125ca03d04 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -604,6 +604,7 @@ dependencies = [
"openssl",
"rand 0.9.0",
"redis",
+ "referral",
"remote_env_var",
"reqwest",
"roles_and_permissions",
@@ -7880,6 +7881,34 @@ dependencies = [
"syn 2.0.98",
]
+[[package]]
+name = "referral"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "async-stripe",
+ "axum",
+ "axum-extra",
+ "chrono",
+ "http-body-util",
+ "macro_db_migrator",
+ "macro_user_id",
+ "macro_uuid",
+ "mockall",
+ "model-error-response",
+ "model_user",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "thiserror 2.0.17",
+ "tokio",
+ "tower 0.5.2",
+ "tracing",
+ "urlencoding",
+ "utoipa",
+ "uuid",
+]
+
[[package]]
name = "regex"
version = "1.12.2"
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index dee00c8d58..1490544dec 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -96,6 +96,7 @@ members = [
"properties",
"properties_db_client",
"properties_service",
+ "referral",
"roles_and_permissions",
"rpc/axum_rpc",
"rpc/axum_rpc_emit",
diff --git a/rust/cloud-storage/authentication_service/Cargo.toml b/rust/cloud-storage/authentication_service/Cargo.toml
index 2841005d12..9ab9aa06c1 100644
--- a/rust/cloud-storage/authentication_service/Cargo.toml
+++ b/rust/cloud-storage/authentication_service/Cargo.toml
@@ -88,6 +88,7 @@ non_empty = { path = "../non_empty" }
notification = { path = "../notification" }
openssl = { workspace = true }
rand = { workspace = true }
+referral = { path = "../referral" }
redis = { workspace = true }
remote_env_var = { path = "../remote_env_var" }
reqwest = { workspace = true }
diff --git a/rust/cloud-storage/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rs
index 96b744f605..70ec0e06c7 100644
--- a/rust/cloud-storage/authentication_service/src/api/context.rs
+++ b/rust/cloud-storage/authentication_service/src/api/context.rs
@@ -13,19 +13,18 @@ use macro_middleware::auth::internal_access::InternalApiSecretKey;
use native_app_service::{domain::service::NativeAppServiceImpl, outbound::DefaultBundleFetcher};
use notification::domain::service::SqsNotificationIngress;
use notification::outbound::queue::SqsIngressQueue;
+use referral::{
+ domain::service::ReferralServiceImpl,
+ outbound::{pg_referral_repo::PgReferralRepo, stripe_discount_client::StripeDiscountClient},
+};
use remote_env_var::LocalOrRemoteSecret;
use roles_and_permissions::{
domain::service::UserRolesAndPermissionsServiceImpl, outbound::pgpool::MacroDB,
};
use sqlx::PgPool;
-use teams::{
- domain::team_service::TeamServiceImpl, outbound::customer_repo::CustomerRepositoryImpl,
- outbound::team_repo::TeamRepositoryImpl,
-};
pub(crate) type NotificationIngressType = SqsNotificationIngress<SqsIngressQueue>;
-#[expect(dead_code, reason = "used by utoipa in swagger.rs")]
pub(crate) type TeamsServiceType = teams::domain::team_service::TeamServiceImpl<
teams::outbound::team_repo::TeamRepositoryImpl,
teams::outbound::customer_repo::CustomerRepositoryImpl,
@@ -33,6 +32,8 @@ pub(crate) type TeamsServiceType = teams::domain::team_service::TeamServiceImpl<
NotificationIngressType,
>;
+pub(crate) type ReferralServiceType = ReferralServiceImpl<PgReferralRepo, StripeDiscountClient>;
+
pub(crate) type GithubLinkServiceType =
GithubLinkServiceImpl<PgGithubRepo, GithubOauthImpl, GithubAuthImpl>;
@@ -55,15 +56,9 @@ pub(crate) struct ApiContext {
pub stripe_webhook_secret: LocalOrRemoteSecret<StripeWebhookSecretKey>,
pub user_roles_and_permissions_service:
Arc<UserRolesAndPermissionsServiceImpl<MacroDB, MacroDB>>, // Note: since FromRef doesn't support generics we have to specify the concrete types here
- pub teams_service: Arc<
- TeamServiceImpl<
- TeamRepositoryImpl,
- CustomerRepositoryImpl,
- UserRolesAndPermissionsServiceImpl<MacroDB, MacroDB>,
- NotificationIngressType,
- >,
- >,
+ pub teams_service: Arc<TeamsServiceType>,
pub native_app_service: Arc<NativeAppServiceImpl<DefaultBundleFetcher>>,
+ pub referral_service: Arc<ReferralServiceType>,
}
env_var! {
diff --git a/rust/cloud-storage/authentication_service/src/api/login/passwordless.rs b/rust/cloud-storage/authentication_service/src/api/login/passwordless.rs
index ba4254a581..ccac693d4d 100644
--- a/rust/cloud-storage/authentication_service/src/api/login/passwordless.rs
+++ b/rust/cloud-storage/authentication_service/src/api/login/passwordless.rs
@@ -9,11 +9,13 @@ use std::borrow::Cow;
use crate::{api::context::ApiContext, generate_password::generate_random_password};
use fusionauth::error::FusionAuthClientError;
+use macro_user_id::user_id::MacroUserId;
use model::{
authentication::login::{request::PasswordlessRequest, response::SsoRequiredResponse},
- response::EmptyResponse,
+ response::{EmptyResponse, ErrorResponse},
tracking::IPContext,
};
+use referral::domain::{models::ReferralCode, ports::ReferralService};
/// Initiates a passwordless login
#[utoipa::path(
@@ -108,6 +110,34 @@ pub async fn handler(
})?;
tracing::trace!(fusionauth_user_id, "created new fusionauth user");
+
+ if let Some(referral_code) = req.referral_code {
+ tracing::trace!(referral_code, "referral code found");
+ let macro_user_id = format!("macro|{}", req.email.to_lowercase());
+ let referrerd_user_id = MacroUserId::parse_from_str(&macro_user_id)
+ .map_err(|_| {
+ (
+ StatusCode::BAD_REQUEST,
+ Json(ErrorResponse {
+ message: "invalid macro user id",
+ }),
+ )
+ .into_response()
+ })?
+ .lowercase();
+
+ // initiates tracking the referral
+ let _ = ctx
+ .referral_service
+ .track_referral(
+ &referrerd_user_id,
+ &ReferralCode(referral_code.clone()),
+ )
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, "unable to track referral");
+ });
+ }
}
_ => {
tracing::error!(error=?e, email=%lowercase_email, "unable to get user id");
diff --git a/rust/cloud-storage/authentication_service/src/api/login/sso.rs b/rust/cloud-storage/authentication_service/src/api/login/sso.rs
index 1cf7d4b8de..f7bb6a7381 100644
--- a/rust/cloud-storage/authentication_service/src/api/login/sso.rs
+++ b/rust/cloud-storage/authentication_service/src/api/login/sso.rs
@@ -13,11 +13,12 @@ use utoipa::ToSchema;
#[cfg(test)]
mod tests;
-#[derive(serde::Serialize, serde::Deserialize, ToSchema, Debug, Default)]
+#[derive(Clone, serde::Serialize, serde::Deserialize, ToSchema, Debug, Default)]
pub struct SsoState {
#[schema(value_type = Option<String>)]
pub original_url: Option<Url>,
pub is_mobile: bool,
+ pub referral_code: Option<String>,
}
#[derive(Debug, serde::Deserialize)]
@@ -30,6 +31,8 @@ pub(crate) struct LoginQueryParams {
original_url: Option<UrlEncoded<Url>>,
#[serde(default)]
is_mobile: bool,
+ /// Optional referral code
+ referral_code: Option<String>,
}
/// Initiates an SSO login
@@ -43,6 +46,7 @@ pub(crate) struct LoginQueryParams {
("login_hint" = String, Query, description = "**OPTIONAL**. The user's email."),
("original_url" = String, Query, description = "**OPTIONAL**. The original url you came from."),
("is_mobile" = String, Query, description = "**OPTIONAL**. If the authentication request is from a mobile device."),
+ ("referral_code" = String, Query, description = "**OPTIONAL**. If the user opened a link with a referral code."),
),
responses(
(status = 200),
@@ -61,6 +65,7 @@ pub async fn handler(
login_hint,
original_url,
is_mobile,
+ referral_code,
}) = query;
if idp_name.is_none() && idp_id.is_none() {
@@ -124,10 +129,13 @@ pub async fn handler(
let state = SsoState {
is_mobile,
original_url: original_url.map(|x| x.0),
+ referral_code,
};
// Only include state if it has a value
- let sso_state = (state.is_mobile || state.original_url.is_some()).then_some(state);
+ let sso_state =
+ (state.is_mobile || state.original_url.is_some() || state.referral_code.is_some())
+ .then_some(state);
// Generate code
let sso_url = ctx
diff --git a/rust/cloud-storage/authentication_service/src/api/login/sso/tests.rs b/rust/cloud-storage/authentication_service/src/api/login/sso/tests.rs
index c6a0346bf2..584538b6b6 100644
--- a/rust/cloud-storage/authentication_service/src/api/login/sso/tests.rs
+++ b/rust/cloud-storage/authentication_service/src/api/login/sso/tests.rs
@@ -24,7 +24,8 @@ async fn it_works_with_no_params() {
idp_id: None,
login_hint: None,
original_url: None,
- is_mobile: false
+ is_mobile: false,
+ referral_code: None,
})
);
}
@@ -47,7 +48,8 @@ async fn it_works_with_mobile() {
idp_id: None,
login_hint: None,
original_url: None,
- is_mobile: true
+ is_mobile: true,
+ referral_code: None,
})
);
}
@@ -70,7 +72,9 @@ async fn it_works_with_mobile_false() {
idp_id: None,
login_hint: None,
original_url: None,
- is_mobile: false
+ is_mobile: false,
+
+ referral_code: None,
})
);
}
@@ -88,7 +92,7 @@ async fn it_fails_with_mobile_garbage() {
#[tokio::test]
async fn it_works_with_everything() {
- let request = Request::builder().uri("https://example.com?is_mobile=true&idp_name=testing&idp_id=something&login_hint=myhint&original_url=https%3A%2F%2Fexample.com").body(Body::from(())).unwrap();
+ let request = Request::builder().uri("https://example.com?is_mobile=true&idp_name=testing&referral_code=code&idp_id=something&login_hint=myhint&original_url=https%3A%2F%2Fexample.com").body(Body::from(())).unwrap();
let extracted = Query::<LoginQueryParams>::from_request(request, &())
.await
@@ -99,12 +103,14 @@ async fn it_works_with_everything() {
idp_id: Some(idp_id),
login_hint: Some(login_hint),
original_url: Some(original_url),
- is_mobile: true
+ is_mobile: true,
+ referral_code: Some(code),
}) => {
assert_eq!(idp_name, "testing");
assert_eq!(idp_id, "something");
assert_eq!(login_hint, "myhint");
assert_eq!(original_url.0.as_str(), "https://example.com/");
+ assert_eq!(code, "code");
});
}
@@ -121,7 +127,8 @@ async fn it_works_with_macro_scheme() {
idp_id: None,
login_hint: None,
original_url: Some(original_url),
- is_mobile: true
+ is_mobile: true,
+ referral_code: _
}) => {
assert_eq!(idp_name, "google");
assert_eq!(original_url.0.as_str(), "macro://app/login");
@@ -141,7 +148,8 @@ async fn it_works_with_double_encoded_scheme() {
idp_id: None,
login_hint: None,
original_url: Some(original_url),
- is_mobile: true
+ is_mobile: true,
+ referral_code: _
}) => {
assert_eq!(idp_name, "google");
assert_eq!(original_url.0.as_str(), "https://example.com/");
diff --git a/rust/cloud-storage/authentication_service/src/api/mod.rs b/rust/cloud-storage/authentication_service/src/api/mod.rs
index ba20b68627..f2a1f3e3b6 100644
--- a/rust/cloud-storage/authentication_service/src/api/mod.rs
+++ b/rust/cloud-storage/authentication_service/src/api/mod.rs
@@ -110,6 +110,24 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {
)),
),
)
+ .nest(
+ "/referral",
+ referral::inbound::axum_router::referral_router(
+ referral::inbound::axum_router::ReferralRouterState {
+ service: state.referral_service.clone(),
+ },
+ )
+ .layer(
+ ServiceBuilder::new()
+ .layer(axum::middleware::from_fn(
+ macro_middleware::tracking::attach_ip_context_handler,
+ ))
+ .layer(axum::middleware::from_fn_with_state(
+ state.jwt_args.clone(),
+ macro_middleware::auth::decode_jwt::handler,
+ )),
+ ),
+ )
.nest("/jwt", jwt::router(state.jwt_args.clone()))
.nest("/session", session::router())
.nest(
diff --git a/rust/cloud-storage/authentication_service/src/api/oauth/oauth_redirect.rs b/rust/cloud-storage/authentication_service/src/api/oauth/oauth_redirect.rs
index aa4b997897..19ee9efda2 100644
--- a/rust/cloud-storage/authentication_service/src/api/oauth/oauth_redirect.rs
+++ b/rust/cloud-storage/authentication_service/src/api/oauth/oauth_redirect.rs
@@ -12,8 +12,10 @@ use axum::{
http::{HeaderValue, StatusCode},
response::{IntoResponse, Response},
};
+use macro_auth::middleware::decode_jwt::decode_macro_access_token_allow_expired;
use maud::{DOCTYPE, Markup, html};
use model::response::ErrorResponse;
+use referral::domain::{models::ReferralCode, ports::ReferralService};
use reqwest::{Url, header::CONTENT_TYPE};
use serde::Deserialize;
use serde_utils::JsonEncoded;
@@ -38,12 +40,13 @@ pub(crate) struct OAuthCbParams {
operation_id = "oauth_redirect",
responses(
(status = 200),
- (status = 400, body=String),
- (status = 401, body=String),
- (status = 500, body=String),
+ (status = 400, body=ErrorResponse),
+ (status = 401, body=ErrorResponse),
+ (status = 500, body=ErrorResponse),
)
)]
#[tracing::instrument(skip(ctx, cookies, params))]
+#[axum::debug_handler]
pub async fn handler(
State(ctx): State<ApiContext>,
cookies: Cookies,
@@ -74,12 +77,35 @@ pub async fn handler(
.map_err(InnerErr::MacroCacheErr)
};
- let redirect_url = get_redirect_url(params, write_db)
+ let state: Option<SsoState> = if let Some(state) = params.state {
+ Some(
+ state
+ .decode()
+ .map_err(|e| InnerErr::Serde(e).into_response())?,
+ )
+ } else {
+ None
+ };
+
+ let redirect_url = get_redirect_url(&state, write_db)
.await
.map_err(IntoResponse::into_response)?;
tracing::trace!("redirect url {redirect_url}");
+ if let Some(state) = state.as_ref()
+ && let Some(referral_code) = state.referral_code.as_ref()
+ {
+ let user_id = decode_macro_access_token_allow_expired(&access_token, &ctx.jwt_args)
+ .map_err(|_| InnerErr::InvalidJwtError.into_response())?;
+
+ let _ = ctx
+ .referral_service
+ .track_referral(&user_id, &ReferralCode(referral_code.clone()))
+ .await
+ .inspect_err(|e| tracing::error!(error=?e, "unable to complete referral for user"));
+ }
+
// Set cookies
cookies.add(create_access_token_cookie(&access_token));
cookies.add(create_refresh_token_cookie(&refresh_token));
@@ -91,6 +117,8 @@ pub async fn handler(
enum InnerErr {
#[error("{0}")]
Serde(#[from] serde_json::Error),
+ #[error("invalid jwt")]
+ InvalidJwtError,
#[error("Macro Cache Err {0}")]
MacroCacheErr(anyhow::Error),
#[error("Failed to parse url {0}")]
@@ -100,6 +128,13 @@ enum InnerErr {
impl IntoResponse for InnerErr {
fn into_response(self) -> Response {
match self {
+ InnerErr::InvalidJwtError => (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "failed to deserialize jwt",
+ }),
+ )
+ .into_response(),
InnerErr::Serde(_error) => (
StatusCode::BAD_REQUEST,
Json(ErrorResponse {
@@ -132,19 +167,20 @@ struct SessionCode(String);
#[tracing::instrument(ret, err, skip(write_db))]
async fn get_redirect_url(
- params: OAuthCbParams,
+ state: &Option<SsoState>,
write_db: impl AsyncFnOnce(&SessionCode) -> Result<(), InnerErr>,
) -> Result<Url, InnerErr> {
- let Some(state) = params.state else {
+ let Some(state) = state else {
return Ok(default_redirect_url());
};
- let state = state.decode()?;
-
// Generate the session code if necessary
let session_code = state.is_mobile.then(generate_session_code).map(SessionCode);
let res = update_url_with_session_code(
- state.original_url.unwrap_or_else(default_redirect_url),
+ state
+ .original_url
+ .clone()
+ .unwrap_or_else(default_redirect_url),
session_code.as_ref(),
write_db,
)
diff --git a/rust/cloud-storage/authentication_service/src/api/oauth/oauth_redirect/tests.rs b/rust/cloud-storage/authentication_service/src/api/oauth/oauth_redirect/tests.rs
index 063eba140e..26f70a10af 100644
--- a/rust/cloud-storage/authentication_service/src/api/oauth/oauth_redirect/tests.rs
+++ b/rust/cloud-storage/authentication_service/src/api/oauth/oauth_redirect/tests.rs
@@ -1,6 +1,5 @@
-use axum::{body::to_bytes, extract::FromRequestParts, http::Request};
+use axum::{extract::FromRequestParts, http::Request};
use cool_asserts::assert_matches;
-use serde_utils::Container;
use super::*;
@@ -8,6 +7,7 @@ use super::*;
async fn it_should_deserialize_query_params() {
let sso_state = SsoState {
original_url: Some("https://example.com".parse().unwrap()),
+ referral_code: Some("test".to_string()),
is_mobile: true,
};
@@ -30,8 +30,9 @@ async fn it_should_deserialize_query_params() {
assert_matches!(data, OAuthCbParams { code, state: Some(container) } => {
assert_eq!(code, "test123");
- assert_matches!(container.decode().unwrap(), SsoState { original_url: Some(url), is_mobile: true } => {
+ assert_matches!(container.decode().unwrap(), SsoState { original_url: Some(url), is_mobile: true, referral_code: Some(code) } => {
assert_eq!(url.as_str(), "https://example.com/");
+ assert_eq!(code.as_str(), "test");
})
});
}
@@ -56,14 +57,7 @@ impl DummyCb {
#[tokio::test]
async fn no_state_is_default_url() {
let mut dummy = DummyCb::default();
- let res = get_redirect_url(
- OAuthCbParams {
- code: "code".into(),
- state: None,
- },
- async |x| dummy.cb(x).await,
- )
- .await;
+ let res = get_redirect_url(&None, async |x| dummy.cb(x).await).await;
assert_eq!(dummy.called, 0);
assert_eq!(res.unwrap(), default_redirect_url());
}
@@ -72,16 +66,11 @@ async fn no_state_is_default_url() {
async fn it_writes_session_code_to_db() {
let mut dummy = DummyCb::default();
let res = get_redirect_url(
- OAuthCbParams {
- code: "code".into(),
- state: Some(
- Container::new(&SsoState {
- original_url: Some("https://example.com".parse().unwrap()),
- is_mobile: true,
- })
- .unwrap(),
- ),
- },
+ &Some(SsoState {
+ original_url: Some("https://example.com".parse().unwrap()),
+ is_mobile: true,
+ referral_code: None,
+ }),
async |x| dummy.cb(x).await,
)
.await
diff --git a/rust/cloud-storage/authentication_service/src/api/oauth/passwordless_callback.rs b/rust/cloud-storage/authentication_service/src/api/oauth/passwordless_callback.rs
index 397d57cbe5..5a648ab1e6 100644
--- a/rust/cloud-storage/authentication_service/src/api/oauth/passwordless_callback.rs
+++ b/rust/cloud-storage/authentication_service/src/api/oauth/passwordless_callback.rs
@@ -27,7 +27,7 @@ pub struct Params {
operation_id = "passwordless_callback",
params(
("code" = String, Path, description = "Code"),
- ("email" = String, Query, description = "Email")
+ ("email" = String, Query, description = "Email"),
),
responses(
(status = 200, body = UserTokensResponse),
diff --git a/rust/cloud-storage/authentication_service/src/api/swagger.rs b/rust/cloud-storage/authentication_service/src/api/swagger.rs
index 5b735c8aaf..33aedc2271 100644
--- a/rust/cloud-storage/authentication_service/src/api/swagger.rs
+++ b/rust/cloud-storage/authentication_service/src/api/swagger.rs
@@ -122,6 +122,9 @@ use model::user::{
teams::inbound::axum_router::remove_user_from_team::handler::<crate::api::context::TeamsServiceType>,
teams::inbound::axum_router::delete_team_invite::handler::<crate::api::context::TeamsServiceType>,
+ /// /referral
+ referral::inbound::axum_router::get_referral_code_handler::<crate::api::context::ReferralServiceType>,
+
/// /merge
merge::create_merge_request::handler,
merge::verify_merge_request::handler,
@@ -178,6 +181,9 @@ use model::user::{
TeamTeamInvitesResponse,
UserTeamInvitesResponse,
+ // Referral
+ referral::domain::models::ReferralCode,
+
// Merge
CreateAccountMergeRequest,
),
diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rs
index 102d197822..44868bfad3 100644
--- a/rust/cloud-storage/authentication_service/src/main.rs
+++ b/rust/cloud-storage/authentication_service/src/main.rs
@@ -28,6 +28,11 @@ use teams::{
outbound::{customer_repo::CustomerRepositoryImpl, team_repo::TeamRepositoryImpl},
};
+use referral::{
+ domain::service::ReferralServiceImpl,
+ outbound::{pg_referral_repo::PgReferralRepo, stripe_discount_client::StripeDiscountClient},
+};
+
use crate::api::context::{
ApiContext, MacroApiTokenContext, MacroApiTokenExpirySeconds, MacroApiTokenIssuer,
MacroApiTokenPrivateSecretKey, StripeWebhookSecretKey,
@@ -214,6 +219,11 @@ async fn main() -> anyhow::Result<()> {
},
);
+ let referral_service = ReferralServiceImpl::new(
+ PgReferralRepo::new(db.clone()),
+ StripeDiscountClient::new(stripe_client.clone(), 500),
+ );
+
api::setup_and_serve(
ApiContext {
db,
@@ -239,6 +249,7 @@ async fn main() -> anyhow::Result<()> {
stripe_webhook_secret,
user_roles_and_permissions_service: Arc::new(user_roles_and_permissions_service),
teams_service: Arc::new(teams_service_impl),
+ referral_service: Arc::new(referral_service),
native_app_service: Arc::new(NativeAppServiceImpl {
bundle_fetcher: DefaultBundleFetcher::default(),
environment: config.environment,
diff --git a/rust/cloud-storage/hx b/rust/cloud-storage/hx
deleted file mode 100644
index 6f0fd4c396..0000000000
--- a/rust/cloud-storage/hx
+++ /dev/null
@@ -1 +0,0 @@
-advisories ok, bans FAILED, licenses ok, sources ok
diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfile
index 60e9ce2e52..ced148a20d 100644
--- a/rust/cloud-storage/justfile
+++ b/rust/cloud-storage/justfile
@@ -85,6 +85,7 @@ setup_test_envs:
echo "DATABASE_URL={{ MACRODB }}" >> ./macro_project_utils/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./entity_access/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./github/.env
+ echo "DATABASE_URL={{ MACRODB }}" >> ./referral/.env
setup_macrodb:
just macro_db_client/create_db
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260317134548_referral_tracking.sql b/rust/cloud-storage/macro_db_client/migrations/20260317134548_referral_tracking.sql
new file mode 100644
index 0000000000..494f9a8542
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260317134548_referral_tracking.sql
@@ -0,0 +1,18 @@
+-- Add migration script here
+CREATE TABLE public.referral_tracking
+(
+ id UUID NOT NULL,
+ referrer_id UUID NOT NULL,
+ referred_id UUID NOT NULL,
+ status TEXT NOT NULL,
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,
+
+ CONSTRAINT referral_tracking_pkey PRIMARY KEY (id)
+);
+
+CREATE INDEX idx_referral_tracking_referrer_id
+ ON referral_tracking (referrer_id);
+
+
+CREATE UNIQUE INDEX idx_referral_tracking_referred_id
+ ON referral_tracking (referred_id);
diff --git a/rust/cloud-storage/macro_uuid/src/lib.rs b/rust/cloud-storage/macro_uuid/src/lib.rs
index 1d9eb1fd94..717c317b88 100644
--- a/rust/cloud-storage/macro_uuid/src/lib.rs
+++ b/rust/cloud-storage/macro_uuid/src/lib.rs
@@ -12,6 +12,7 @@ pub fn string_to_uuid(s: &str) -> Result<Uuid> {
// Flickr's base58 alphabet as used in short-uuid
const FLICKR_BASE58: &str = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
+#[derive(Clone)]
pub struct ShortUuidConverter {
alphabet: String,
base: u128,
diff --git a/rust/cloud-storage/model/src/authentication/login/request.rs b/rust/cloud-storage/model/src/authentication/login/request.rs
index 0bdcc71196..a7de5ed320 100644
--- a/rust/cloud-storage/model/src/authentication/login/request.rs
+++ b/rust/cloud-storage/model/src/authentication/login/request.rs
@@ -6,6 +6,8 @@ pub struct PasswordlessRequest {
pub email: String,
/// The redirect uri to redirect to after login
pub redirect_uri: String,
+ /// The referral code
+ pub referral_code: Option<String>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema)]
diff --git a/rust/cloud-storage/referral/.sqlx/query-13ef9a0dd33e56d64232964dc11b44b0a333958a67d89dfcb1db9dd523a1b837.json b/rust/cloud-storage/referral/.sqlx/query-13ef9a0dd33e56d64232964dc11b44b0a333958a67d89dfcb1db9dd523a1b837.json
new file mode 100644
index 0000000000..46afde0329
--- /dev/null
+++ b/rust/cloud-storage/referral/.sqlx/query-13ef9a0dd33e56d64232964dc11b44b0a333958a67d89dfcb1db9dd523a1b837.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT macro_user_id FROM \"User\" WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "macro_user_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "13ef9a0dd33e56d64232964dc11b44b0a333958a67d89dfcb1db9dd523a1b837"
+}
diff --git a/rust/cloud-storage/referral/.sqlx/query-54155d1cfe6997b0dfe33cf72d9f3e2a1bf3af9a8fb1487fd32fb3f833641046.json b/rust/cloud-storage/referral/.sqlx/query-54155d1cfe6997b0dfe33cf72d9f3e2a1bf3af9a8fb1487fd32fb3f833641046.json
new file mode 100644
index 0000000000..50fcaa7372
--- /dev/null
+++ b/rust/cloud-storage/referral/.sqlx/query-54155d1cfe6997b0dfe33cf72d9f3e2a1bf3af9a8fb1487fd32fb3f833641046.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT macro_user_id FROM \"User\"\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "macro_user_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "54155d1cfe6997b0dfe33cf72d9f3e2a1bf3af9a8fb1487fd32fb3f833641046"
+}
diff --git a/rust/cloud-storage/referral/.sqlx/query-a1936db1ca47241996be534e0e64bb36b63fabbaf3e826459537e089ed3c19a7.json b/rust/cloud-storage/referral/.sqlx/query-a1936db1ca47241996be534e0e64bb36b63fabbaf3e826459537e089ed3c19a7.json
new file mode 100644
index 0000000000..8a9fd5ece9
--- /dev/null
+++ b/rust/cloud-storage/referral/.sqlx/query-a1936db1ca47241996be534e0e64bb36b63fabbaf3e826459537e089ed3c19a7.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT stripe_customer_id FROM macro_user\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "stripe_customer_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "a1936db1ca47241996be534e0e64bb36b63fabbaf3e826459537e089ed3c19a7"
+}
diff --git a/rust/cloud-storage/referral/.sqlx/query-ae72806caeef15e9e4a57b0564601480bcbfd0f0195ef75f197d02f52b843778.json b/rust/cloud-storage/referral/.sqlx/query-ae72806caeef15e9e4a57b0564601480bcbfd0f0195ef75f197d02f52b843778.json
new file mode 100644
index 0000000000..7f8c7057a9
--- /dev/null
+++ b/rust/cloud-storage/referral/.sqlx/query-ae72806caeef15e9e4a57b0564601480bcbfd0f0195ef75f197d02f52b843778.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE referral_tracking\n SET status = 'complete'\n WHERE referrer_id = $1 and referred_id = $2",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "ae72806caeef15e9e4a57b0564601480bcbfd0f0195ef75f197d02f52b843778"
+}
diff --git a/rust/cloud-storage/referral/.sqlx/query-debef3a27b832b3600037a6304558a23c2407f742e67e7c06553929f4405478e.json b/rust/cloud-storage/referral/.sqlx/query-debef3a27b832b3600037a6304558a23c2407f742e67e7c06553929f4405478e.json
new file mode 100644
index 0000000000..d7dc0f11fd
--- /dev/null
+++ b/rust/cloud-storage/referral/.sqlx/query-debef3a27b832b3600037a6304558a23c2407f742e67e7c06553929f4405478e.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT 1 as exists FROM macro_user WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists",
+ "type_info": "Int4"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "debef3a27b832b3600037a6304558a23c2407f742e67e7c06553929f4405478e"
+}
diff --git a/rust/cloud-storage/referral/.sqlx/query-f7350272860b713193c09bbd784418605ec3f0f9f090344882fcac7d251bfdba.json b/rust/cloud-storage/referral/.sqlx/query-f7350272860b713193c09bbd784418605ec3f0f9f090344882fcac7d251bfdba.json
new file mode 100644
index 0000000000..ba4b6efa55
--- /dev/null
+++ b/rust/cloud-storage/referral/.sqlx/query-f7350272860b713193c09bbd784418605ec3f0f9f090344882fcac7d251bfdba.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO referral_tracking (id, referrer_id, referred_id, status, created_at) VALUES ($1, $2, $3, 'incomplete', NOW())",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f7350272860b713193c09bbd784418605ec3f0f9f090344882fcac7d251bfdba"
+}
diff --git a/rust/cloud-storage/referral/Cargo.toml b/rust/cloud-storage/referral/Cargo.toml
new file mode 100644
index 0000000000..3fd1b25777
--- /dev/null
+++ b/rust/cloud-storage/referral/Cargo.toml
@@ -0,0 +1,56 @@
+[package]
+edition = "2024"
+name = "referral"
+publish = false
+version = "0.1.0"
+
+[features]
+axum = [
+ "dep:axum",
+ "dep:axum-extra",
+ "dep:model-error-response",
+ "dep:model_user",
+ "dep:utoipa",
+]
+default = ["axum", "inbound", "outbound", "ports"]
+inbound = ["axum", "ports"]
+outbound = ["dep:async-stripe", "dep:sqlx", "ports"]
+ports = []
+
+[dependencies]
+# Core
+anyhow = { workspace = true }
+chrono = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+thiserror = { workspace = true }
+tracing = { workspace = true }
+uuid = { workspace = true }
+
+# Domain models
+macro_user_id = { path = "../macro_user_id" }
+macro_uuid = { path = "../macro_uuid" }
+
+# Axum dependencies (for inbound)
+axum = { workspace = true, optional = true }
+axum-extra = { workspace = true, optional = true }
+model-error-response = { path = "../model-error-response", optional = true }
+model_user = { path = "../model_user", optional = true, features = ["axum"] }
+utoipa = { workspace = true, optional = true }
+
+async-stripe = { workspace = true, default-features = false, features = [
+ "billing",
+ "checkout",
+ "runtime-tokio-hyper",
+], optional = true } # Outbound dependencies
+sqlx = { workspace = true, optional = true }
+urlencoding = { workspace = true }
+
+[dev-dependencies]
+
+http-body-util = { workspace = true }
+macro_db_migrator = { path = "../macro_db_migrator" }
+mockall = { workspace = true }
+serde_json = { workspace = true }
+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
+tower = { workspace = true }
diff --git a/rust/cloud-storage/referral/fixtures/referral_users.sql b/rust/cloud-storage/referral/fixtures/referral_users.sql
new file mode 100644
index 0000000000..8d3d827034
--- /dev/null
+++ b/rust/cloud-storage/referral/fixtures/referral_users.sql
@@ -0,0 +1,13 @@
+-- Referrer: macro_user + User
+INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES
+ ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'::uuid, 'referrer', '[email protected]', 'cus_referrer');
+
+INSERT INTO "User" (id, email, macro_user_id) VALUES
+ ('macro|[email protected]', '[email protected]', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'::uuid);
+
+-- Referred: macro_user + User
+INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES
+ ('cccccccc-cccc-cccc-cccc-cccccccccccc'::uuid, 'referred', '[email protected]', 'cus_referred');
+
+INSERT INTO "User" (id, email, macro_user_id) VALUES
+ ('macro|[email protected]', '[email protected]', 'cccccccc-cccc-cccc-cccc-cccccccccccc'::uuid);
diff --git a/rust/cloud-storage/referral/justfile b/rust/cloud-storage/referral/justfile
new file mode 100644
index 0000000000..d7f13030d3
--- /dev/null
+++ b/rust/cloud-storage/referral/justfile
@@ -0,0 +1,9 @@
+DATABASE_URL := "postgres://user:password@localhost:5432/macrodb"
+
+mod sqlx '../sqlx.just'
+
+prepare_db:
+ just sqlx::prepare_db {{ DATABASE_URL }}
+
+check:
+ cargo check --all-features
diff --git a/rust/cloud-storage/referral/src/domain.rs b/rust/cloud-storage/referral/src/domain.rs
new file mode 100644
index 0000000000..a947d9653b
--- /dev/null
+++ b/rust/cloud-storage/referral/src/domain.rs
@@ -0,0 +1,9 @@
+//! Domain layer: models, ports (trait interfaces), and service implementation.
+
+pub mod models;
+
+#[cfg(feature = "ports")]
+pub mod ports;
+
+#[cfg(feature = "ports")]
+pub mod service;
diff --git a/rust/cloud-storage/referral/src/domain/models.rs b/rust/cloud-storage/referral/src/domain/models.rs
new file mode 100644
index 0000000000..494c6e19de
--- /dev/null
+++ b/rust/cloud-storage/referral/src/domain/models.rs
@@ -0,0 +1,38 @@
+//! Domain models for the referral crate.
+
+use macro_uuid::ShortUuidConverter;
+
+/// Wrapper for the referral code to make it type safe
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+pub struct ReferralCode(pub String);
+
+/// Errors that can occur during referral operations.
+#[derive(Debug, thiserror::Error)]
+pub enum ReferralError {
+ /// The requested referral code was not found.
+ #[error("referral not found: {0}")]
+ NotFound(String),
+ /// The user is not authorized to perform this action.
+ #[error("unauthorized")]
+ Unauthorized,
+ /// A bad request was made.
+ #[error("bad request: {0}")]
+ BadRequest(String),
+ /// The referral code was invalid
+ #[error("invalid referral code: {0}")]
+ InvalidReferralCode(String),
+ /// An internal error occurred.
+ #[error("{0}")]
+ Internal(#[from] anyhow::Error),
+}
+
+/// Converts the referral code (short uuid) to the full uuid
+pub(crate) fn referral_code_to_uuid(
+ referral_code: &ReferralCode,
+) -> Result<uuid::Uuid, ReferralError> {
+ let short_uuid_converter = ShortUuidConverter::default();
+ short_uuid_converter
+ .to_uuid(&referral_code.0)
+ .map_err(|_| ReferralError::InvalidReferralCode(referral_code.0.clone()))
+}
diff --git a/rust/cloud-storage/referral/src/domain/ports.rs b/rust/cloud-storage/referral/src/domain/ports.rs
new file mode 100644
index 0000000000..f53291ba17
--- /dev/null
+++ b/rust/cloud-storage/referral/src/domain/ports.rs
@@ -0,0 +1,86 @@
+//! Port definitions for the referral domain.
+//!
+//! These traits define the contracts that adapters must implement.
+
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+
+use crate::domain::models::{ReferralCode, ReferralError};
+
+/// Repository for accessing referral data from the database.
+///
+/// All methods perform database operations — SQL queries are written
+/// directly in the outbound adapter implementation.
+#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]
+pub trait ReferralRepo: Send + Sync + 'static {
+ /// The error type returned by repository operations.
+ type Err: Into<anyhow::Error> + Send + std::fmt::Debug;
+
+ /// Gets the referral code for the user
+ /// This is generated from the users FusionAuth user id
+ fn get_referral_code_for_user<'a>(
+ &self,
+ user_id: &MacroUserId<Lowercase<'a>>,
+ ) -> impl Future<Output = Result<ReferralCode, Self::Err>> + Send;
+
+ /// Tracks a referral
+ fn track_referral<'a>(
+ &self,
+ referred_user_id: &MacroUserId<Lowercase<'a>>,
+ referral_code: &ReferralCode,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Completes a referral
+ fn complete_referral<'a>(
+ &self,
+ referred_user_id: &MacroUserId<Lowercase<'a>>,
+ referral_code: &ReferralCode,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Gets the referrs customer id using their code
+ fn get_referrers_customer_id(
+ &self,
+ referral_code: &ReferralCode,
+ ) -> impl Future<Output = Result<String, Self::Err>> + Send;
+}
+
+/// Repository to handle applying discounts to the referrer when a referral is
+/// completed
+#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]
+pub trait DiscountClient: Send + Sync + 'static {
+ /// The error type returned by repository operations.
+ type Err: Into<anyhow::Error> + Send + std::fmt::Debug;
+
+ /// Applies the discount to the referrer
+ fn apply_discount(
+ &self,
+ referrer_customer_id: &str,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+}
+
+/// Service interface for referral operations.
+///
+/// Orchestrates business logic using the repository and external services.
+pub trait ReferralService: Send + Sync + 'static {
+ /// Gets the referral code for the user
+ fn get_referral_code_for_user<'a>(
+ &self,
+ user_id: &MacroUserId<Lowercase<'a>>,
+ ) -> impl Future<Output = Result<ReferralCode, ReferralError>> + Send;
+
+ /// Starts tracking the referral
+ /// The referral is completed when the user pays through stripe
+ fn track_referral<'a>(
+ &self,
+ referred_user_id: &MacroUserId<Lowercase<'a>>,
+ referral_code: &ReferralCode,
+ ) -> impl Future<Output = Result<(), ReferralError>> + Send;
+
+ /// Processes a referral
+ /// - tracks the referral
+ /// - assigns the discount to the referrers' stripe
+ fn process_referral<'a>(
+ &self,
+ referred_user_id: &MacroUserId<Lowercase<'a>>,
+ referral_code: &ReferralCode,
+ ) -> impl Future<Output = Result<(), ReferralError>> + Send;
+}
diff --git a/rust/cloud-storage/referral/src/domain/service.rs b/rust/cloud-storage/referral/src/domain/service.rs
new file mode 100644
index 0000000000..eadf5081a4
--- /dev/null
+++ b/rust/cloud-storage/referral/src/domain/service.rs
@@ -0,0 +1,79 @@
+//! Referral service implementation.
+
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+
+use crate::domain::{
+ models::{ReferralCode, ReferralError},
+ ports::{DiscountClient, ReferralRepo, ReferralService},
+};
+
+/// The concrete referral service implementation.
+pub struct ReferralServiceImpl<R: ReferralRepo, Dc: DiscountClient> {
+ /// referral repo
+ repo: R,
+ /// discount client
+ discount_client: Dc,
+}
+
+impl<R: ReferralRepo, Dc: DiscountClient> ReferralServiceImpl<R, Dc> {
+ /// Create a new referral service.
+ pub fn new(repo: R, discount_client: Dc) -> Self {
+ Self {
+ repo,
+ discount_client,
+ }
+ }
+}
+
+impl<R: ReferralRepo, Dc: DiscountClient> ReferralService for ReferralServiceImpl<R, Dc> {
+ #[tracing::instrument(skip(self), err)]
+ async fn get_referral_code_for_user<'a>(
+ &self,
+ user_id: &MacroUserId<Lowercase<'a>>,
+ ) -> Result<ReferralCode, ReferralError> {
+ self.repo
+ .get_referral_code_for_user(user_id)
+ .await
+ .map_err(|e| ReferralError::Internal(e.into()))
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn track_referral<'a>(
+ &self,
+ referred_user_id: &MacroUserId<Lowercase<'a>>,
+ referral_code: &ReferralCode,
+ ) -> Result<(), ReferralError> {
+ self.repo
+ .track_referral(referred_user_id, referral_code)
+ .await
+ .map_err(|e| ReferralError::Internal(e.into()))?;
+ todo!()
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn process_referral<'a>(
+ &self,
+ referred_user_id: &MacroUserId<Lowercase<'a>>,
+ referral_code: &ReferralCode,
+ ) -> Result<(), ReferralError> {
+ // NOTE: This will error if the referral code is invalid and we cannot find a
+ // user from the referral code
+ let customer_id = self
+ .repo
+ .get_referrers_customer_id(referral_code)
+ .await
+ .map_err(|e| ReferralError::Internal(e.into()))?;
+
+ self.repo
+ .complete_referral(referred_user_id, referral_code)
+ .await
+ .map_err(|e| ReferralError::Internal(e.into()))?;
+
+ self.discount_client
+ .apply_discount(&customer_id)
+ .await
+ .map_err(|e| ReferralError::Internal(e.into()))?;
+
+ Ok(())
+ }
+}
diff --git a/rust/cloud-storage/referral/src/inbound.rs b/rust/cloud-storage/referral/src/inbound.rs
new file mode 100644
index 0000000000..c06c5ac715
--- /dev/null
+++ b/rust/cloud-storage/referral/src/inbound.rs
@@ -0,0 +1,4 @@
+//! Inbound handlers for referral crate
+
+#[cfg(feature = "axum")]
+pub mod axum_router;
diff --git a/rust/cloud-storage/referral/src/inbound/axum_router.rs b/rust/cloud-storage/referral/src/inbound/axum_router.rs
new file mode 100644
index 0000000000..6828cf563b
--- /dev/null
+++ b/rust/cloud-storage/referral/src/inbound/axum_router.rs
@@ -0,0 +1,63 @@
+//! Axum router for referral endpoints.
+//!
+//! Provides routes:
+//! - `GET /code` — get the authenticated user's referral code
+
+#[cfg(test)]
+mod test;
+
+mod get_referral_code;
+
+use std::sync::Arc;
+
+use axum::{Json, Router, http::StatusCode, response::IntoResponse};
+use model_error_response::ErrorResponse;
+
+use crate::domain::models::ReferralError;
+use crate::domain::ports::ReferralService;
+
+pub use get_referral_code::*;
+
+impl IntoResponse for ReferralError {
+ fn into_response(self) -> axum::response::Response {
+ let status_code = match &self {
+ ReferralError::NotFound(_) => StatusCode::NOT_FOUND,
+ ReferralError::Unauthorized => StatusCode::UNAUTHORIZED,
+ ReferralError::BadRequest(_) => StatusCode::BAD_REQUEST,
+ ReferralError::InvalidReferralCode(_) => StatusCode::BAD_REQUEST,
+ ReferralError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+
+ if status_code.is_server_error() {
+ tracing::error!(error=?self, "internal server error");
+ }
+
+ let message = self.to_string();
+ (status_code, Json(ErrorResponse { message: &message })).into_response()
+ }
+}
+
+/// Router state containing the referral service.
+pub struct ReferralRouterState<T> {
+ /// The referral service implementation.
+ pub service: Arc<T>,
+}
+
+impl<T> Clone for ReferralRouterState<T> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ }
+ }
+}
+
+/// Build the referral router with all endpoints.
+pub fn referral_router<T, S>(state: ReferralRouterState<T>) -> Router<S>
+where
+ T: ReferralService,
+ S: Send + Sync + 'static,
+{
+ Router::new()
+ .route("/code", axum::routing::get(get_referral_code_handler::<T>))
+ .with_state(state)
+}
diff --git a/rust/cloud-storage/referral/src/inbound/axum_router/get_referral_code.rs b/rust/cloud-storage/referral/src/inbound/axum_router/get_referral_code.rs
new file mode 100644
index 0000000000..20fcadd7a1
--- /dev/null
+++ b/rust/cloud-storage/referral/src/inbound/axum_router/get_referral_code.rs
@@ -0,0 +1,35 @@
+//! Handler for `GET /code`.
+
+use axum::{Json, extract::State};
+use model_user::axum_extractor::MacroUserExtractor;
+
+use super::ReferralRouterState;
+use crate::domain::models::{ReferralCode, ReferralError};
+use crate::domain::ports::ReferralService;
+
+/// Handler for `GET /referral-code`.
+///
+/// Returns the authenticated user's referral code.
+#[utoipa::path(
+ tag = "referral",
+ get,
+ path = "/referral/code",
+ operation_id = "get_referral_code",
+ responses(
+ (status = 200, body = ReferralCode),
+ (status = 401, body = model_error_response::ErrorResponse),
+ (status = 500, body = model_error_response::ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(state, user_context), err)]
+pub async fn get_referral_code_handler<T: ReferralService>(
+ State(state): State<ReferralRouterState<T>>,
+ user_context: MacroUserExtractor,
+) -> Result<Json<ReferralCode>, ReferralError> {
+ let code = state
+ .service
+ .get_referral_code_for_user(&user_context.macro_user_id)
+ .await?;
+
+ Ok(Json(code))
+}
diff --git a/rust/cloud-storage/referral/src/inbound/axum_router/test.rs b/rust/cloud-storage/referral/src/inbound/axum_router/test.rs
new file mode 100644
index 0000000000..7300f8a37c
--- /dev/null
+++ b/rust/cloud-storage/referral/src/inbound/axum_router/test.rs
@@ -0,0 +1,124 @@
+use std::sync::Arc;
+
+use axum::{Extension, http::StatusCode};
+use http_body_util::BodyExt;
+use model_user::UserContext;
+use tower::ServiceExt;
+
+use crate::domain::models::{ReferralCode, ReferralError};
+use crate::domain::ports::ReferralService;
+use crate::inbound::axum_router::{ReferralRouterState, referral_router};
+
+struct MockReferralService {
+ result: Result<ReferralCode, ReferralError>,
+}
+
+impl ReferralService for MockReferralService {
+ async fn get_referral_code_for_user<'a>(
+ &self,
+ _user_id: &macro_user_id::user_id::MacroUserId<macro_user_id::lowercased::Lowercase<'a>>,
+ ) -> Result<ReferralCode, ReferralError> {
+ match &self.result {
+ Ok(code) => Ok(code.clone()),
+ Err(_) => Err(ReferralError::Internal(anyhow::anyhow!("mock error"))),
+ }
+ }
+
+ async fn track_referral<'a>(
+ &self,
+ _referred_user_id: &macro_user_id::user_id::MacroUserId<
+ macro_user_id::lowercased::Lowercase<'a>,
+ >,
+ _referral_code: &ReferralCode,
+ ) -> Result<(), ReferralError> {
+ Ok(())
+ }
+
+ async fn process_referral<'a>(
+ &self,
+ _referred_user_id: &macro_user_id::user_id::MacroUserId<
+ macro_user_id::lowercased::Lowercase<'a>,
+ >,
+ _referral_code: &ReferralCode,
+ ) -> Result<(), ReferralError> {
+ Ok(())
+ }
+}
+
+fn test_user_context() -> UserContext {
+ UserContext {
+ user_id: "macro|[email protected]".to_string(),
+ fusion_user_id: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb".to_string(),
+ permissions: None,
+ organization_id: None,
+ }
+}
+
+fn build_router(service: MockReferralService) -> axum::Router {
+ let state = ReferralRouterState {
+ service: Arc::new(service),
+ };
+ referral_router(state).layer(Extension(test_user_context()))
+}
+
+#[tokio::test]
+async fn test_get_referral_code_success() {
+ let service = MockReferralService {
+ result: Ok(ReferralCode("test-code".to_string())),
+ };
+ let app = build_router(service);
+
+ let request = axum::http::Request::builder()
+ .uri("/code")
+ .method("GET")
+ .body(axum::body::Body::empty())
+ .unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+
+ let body = response.into_body().collect().await.unwrap().to_bytes();
+ let code: ReferralCode = serde_json::from_slice(&body).unwrap();
+ assert_eq!(code.0, "test-code");
+}
+
+#[tokio::test]
+async fn test_get_referral_code_internal_error() {
+ let service = MockReferralService {
+ result: Err(ReferralError::Internal(anyhow::anyhow!("db error"))),
+ };
+ let app = build_router(service);
+
+ let request = axum::http::Request::builder()
+ .uri("/code")
+ .method("GET")
+ .body(axum::body::Body::empty())
+ .unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
+}
+
+#[tokio::test]
+async fn test_get_referral_code_unauthenticated() {
+ let service = MockReferralService {
+ result: Ok(ReferralCode("test-code".to_string())),
+ };
+ let state = ReferralRouterState {
+ service: Arc::new(service),
+ };
+ // No user context extension — should fail auth
+ let app: axum::Router = referral_router(state);
+
+ let request = axum::http::Request::builder()
+ .uri("/code")
+ .method("GET")
+ .body(axum::body::Body::empty())
+ .unwrap();
+
+ let response = app.oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+}
diff --git a/rust/cloud-storage/referral/src/lib.rs b/rust/cloud-storage/referral/src/lib.rs
new file mode 100644
index 0000000000..48553a8efe
--- /dev/null
+++ b/rust/cloud-storage/referral/src/lib.rs
@@ -0,0 +1,19 @@
+//! Referral hexagonal architecture crate.
+//!
+//! Encapsulates referral CRUD operations using a ports-and-adapters pattern.
+//!
+//! # Architecture
+//!
+//! - **domain**: Contains domain models, ports (traits), and the service implementation
+//! - **outbound**: Contains adapters for external dependencies (PostgreSQL)
+//! - **inbound**: Contains adapters for incoming requests (Axum handlers)
+
+#![deny(missing_docs)]
+
+pub mod domain;
+
+#[cfg(feature = "inbound")]
+pub mod inbound;
+
+#[cfg(feature = "outbound")]
+pub mod outbound;
diff --git a/rust/cloud-storage/referral/src/outbound.rs b/rust/cloud-storage/referral/src/outbound.rs
new file mode 100644
index 0000000000..126cfd9cc2
--- /dev/null
+++ b/rust/cloud-storage/referral/src/outbound.rs
@@ -0,0 +1,4 @@
+//! Outbound handlers for referral crate
+
+pub mod pg_referral_repo;
+pub mod stripe_discount_client;
diff --git a/rust/cloud-storage/referral/src/outbound/pg_referral_repo.rs b/rust/cloud-storage/referral/src/outbound/pg_referral_repo.rs
new file mode 100644
index 0000000000..f4abf79239
--- /dev/null
+++ b/rust/cloud-storage/referral/src/outbound/pg_referral_repo.rs
@@ -0,0 +1,151 @@
+//! PostgreSQL implementation of the [`ReferralRepo`] port.
+
+#[cfg(test)]
+mod test;
+
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use macro_uuid::ShortUuidConverter;
+use sqlx::PgPool;
+
+use crate::domain::{
+ models::{ReferralCode, referral_code_to_uuid},
+ ports::ReferralRepo,
+};
+
+/// PostgreSQL-backed referral repo
+#[derive(Clone)]
+pub struct PgReferralRepo {
+ /// The postgres pool
+ pool: PgPool,
+ /// Short uuid converter
+ short_uuid_converter: ShortUuidConverter,
+}
+impl PgReferralRepo {
+ /// Create a new repository backed by the given connection pool.
+ pub fn new(pool: PgPool) -> Self {
+ Self {
+ pool,
+ short_uuid_converter: ShortUuidConverter::default(),
+ }
+ }
+}
+
+impl ReferralRepo for PgReferralRepo {
+ type Err = sqlx::Error;
+
+ #[tracing::instrument(skip(self), err)]
+ async fn get_referral_code_for_user<'a>(
+ &self,
+ user_id: &MacroUserId<Lowercase<'a>>,
+ ) -> Result<ReferralCode, Self::Err> {
+ let fusion_user_id = sqlx::query!(
+ r#"
+ SELECT macro_user_id FROM "User"
+ WHERE id = $1
+ "#,
+ user_id.as_ref()
+ )
+ .map(|r| r.macro_user_id)
+ .fetch_one(&self.pool)
+ .await?;
+
+ // convert to referral code
+ Ok(ReferralCode(
+ self.short_uuid_converter.from_uuid(&fusion_user_id),
+ ))
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn track_referral<'a>(
+ &self,
+ referred_user_id: &MacroUserId<Lowercase<'a>>,
+ referral_code: &ReferralCode,
+ ) -> Result<(), Self::Err> {
+ let referrer_id =
+ referral_code_to_uuid(referral_code).map_err(|e| sqlx::Error::Decode(Box::new(e)))?;
+
+ // make sure this user exists
+ sqlx::query!(
+ "SELECT 1 as exists FROM macro_user WHERE id = $1",
+ &referrer_id
+ )
+ .fetch_one(&self.pool)
+ .await?;
+
+ let referred_id = sqlx::query!(
+ r#"SELECT macro_user_id FROM "User" WHERE id = $1"#,
+ referred_user_id.as_ref()
+ )
+ .map(|s| s.macro_user_id)
+ .fetch_one(&self.pool)
+ .await?;
+
+ let tracking_id = macro_uuid::generate_uuid_v7();
+ sqlx::query!("INSERT INTO referral_tracking (id, referrer_id, referred_id, status, created_at) VALUES ($1, $2, $3, 'incomplete', NOW())", &tracking_id, &referrer_id, &referred_id).execute(&self.pool).await?;
+
+ Ok(())
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn complete_referral<'a>(
+ &self,
+ referred_user_id: &MacroUserId<Lowercase<'a>>,
+ referral_code: &ReferralCode,
+ ) -> Result<(), Self::Err> {
+ let referrer_id =
+ referral_code_to_uuid(referral_code).map_err(|e| sqlx::Error::Decode(Box::new(e)))?;
+
+ // make sure this user exists
+ sqlx::query!(
+ "SELECT 1 as exists FROM macro_user WHERE id = $1",
+ &referrer_id
+ )
+ .fetch_one(&self.pool)
+ .await?;
+
+ let referred_id = sqlx::query!(
+ r#"SELECT macro_user_id FROM "User" WHERE id = $1"#,
+ referred_user_id.as_ref()
+ )
+ .map(|s| s.macro_user_id)
+ .fetch_one(&self.pool)
+ .await?;
+
+ let result = sqlx::query!(
+ r#"
+ UPDATE referral_tracking
+ SET status = 'complete'
+ WHERE referrer_id = $1 and referred_id = $2"#,
+ &referrer_id,
+ &referred_id
+ )
+ .execute(&self.pool)
+ .await?;
+
+ if result.rows_affected() == 0 {
+ return Err(sqlx::Error::RowNotFound);
+ }
+
+ Ok(())
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn get_referrers_customer_id(
+ &self,
+ referral_code: &ReferralCode,
+ ) -> Result<String, Self::Err> {
+ let fusion_user_id =
+ referral_code_to_uuid(referral_code).map_err(|e| sqlx::Error::Decode(Box::new(e)))?;
+
+ sqlx::query!(
+ r#"
+ SELECT stripe_customer_id FROM macro_user
+ WHERE id = $1
+ "#,
+ fusion_user_id,
+ )
+ .map(|s| s.stripe_customer_id)
+ .fetch_one(&self.pool)
+ .await
+ }
+}
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
new file mode 100644
index 0000000000..af271ef733
--- /dev/null
+++ b/rust/cloud-storage/referral/src/outbound/pg_referral_repo/test.rs
@@ -0,0 +1,282 @@
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use macro_uuid::ShortUuidConverter;
+use sqlx::{Pool, Postgres};
+
+use crate::domain::models::ReferralCode;
+use crate::domain::ports::ReferralRepo;
+use crate::outbound::pg_referral_repo::PgReferralRepo;
+
+const REFERRER_UUID: &str = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb";
+const REFERRER_STRIPE_ID: &str = "cus_referrer";
+
+fn referrer_referral_code() -> ReferralCode {
+ let converter = ShortUuidConverter::default();
+ let uuid = uuid::Uuid::parse_str(REFERRER_UUID).unwrap();
+ ReferralCode(converter.from_uuid(&uuid))
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("referral_users"))
+)]
+async fn test_get_referral_code_for_user(pool: Pool<Postgres>) {
+ let repo = PgReferralRepo::new(pool);
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+
+ let code = repo.get_referral_code_for_user(&user_id.0).await.unwrap();
+
+ // Round-trip: the returned code should decode back to the referrer's macro_user_id
+ let converter = ShortUuidConverter::default();
+ let decoded = converter.to_uuid(&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_referral_code_for_nonexistent_user(pool: Pool<Postgres>) {
+ let repo = PgReferralRepo::new(pool);
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+
+ let result = repo.get_referral_code_for_user(&user_id.0).await;
+
+ assert!(matches!(result, Err(sqlx::Error::RowNotFound)));
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("referral_users"))
+)]
+async fn test_get_referrers_customer_id(pool: Pool<Postgres>) {
+ let repo = PgReferralRepo::new(pool);
+
+ let code = referrer_referral_code();
+ let customer_id = repo.get_referrers_customer_id(&code).await.unwrap();
+
+ assert_eq!(customer_id, REFERRER_STRIPE_ID);
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("referral_users"))
+)]
+async fn test_get_referrers_customer_id_invalid_code(pool: Pool<Postgres>) {
+ let repo = PgReferralRepo::new(pool);
+
+ let code = ReferralCode("!!!invalid!!!".to_string());
+ let result = repo.get_referrers_customer_id(&code).await;
+
+ assert!(result.is_err());
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("referral_users"))
+)]
+async fn test_get_referrers_customer_id_nonexistent_user(pool: Pool<Postgres>) {
+ let repo = PgReferralRepo::new(pool);
+
+ // Valid short UUID format but no matching macro_user row
+ let converter = ShortUuidConverter::default();
+ let fake_uuid = uuid::Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap();
+ let code = ReferralCode(converter.from_uuid(&fake_uuid));
+
+ let result = repo.get_referrers_customer_id(&code).await;
+
+ assert!(matches!(result, Err(sqlx::Error::RowNotFound)));
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("referral_users"))
+)]
+async fn test_track_referral(pool: Pool<Postgres>) {
+ let repo = PgReferralRepo::new(pool.clone());
+
+ 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();
+
+ // Verify a row was inserted into referral_tracking
+ let row = sqlx::query!("SELECT referrer_id, referred_id FROM referral_tracking LIMIT 1")
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+
+ assert_eq!(row.referrer_id.to_string(), REFERRER_UUID);
+ assert_eq!(
+ row.referred_id.to_string(),
+ "cccccccc-cccc-cccc-cccc-cccccccccccc"
+ );
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("referral_users"))
+)]
+async fn test_track_referral_invalid_code(pool: Pool<Postgres>) {
+ let repo = PgReferralRepo::new(pool);
+
+ let referred_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+ let code = ReferralCode("!!!invalid!!!".to_string());
+
+ let result = repo.track_referral(&referred_user_id.0, &code).await;
+
+ assert!(result.is_err());
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("referral_users"))
+)]
+async fn test_track_referral_nonexistent_referrer(pool: Pool<Postgres>) {
+ let repo = PgReferralRepo::new(pool);
+
+ let referred_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+
+ // Valid short UUID but no matching macro_user
+ let converter = ShortUuidConverter::default();
+ let fake_uuid = uuid::Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap();
+ let code = ReferralCode(converter.from_uuid(&fake_uuid));
+
+ let result = repo.track_referral(&referred_user_id.0, &code).await;
+
+ assert!(matches!(result, Err(sqlx::Error::RowNotFound)));
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("referral_users"))
+)]
+async fn test_track_referral_nonexistent_referred_user(pool: Pool<Postgres>) {
+ let repo = PgReferralRepo::new(pool);
+
+ let referred_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+ let code = referrer_referral_code();
+
+ let result = repo.track_referral(&referred_user_id.0, &code).await;
+
+ assert!(matches!(result, Err(sqlx::Error::RowNotFound)));
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("referral_users"))
+)]
+async fn test_complete_referral(pool: Pool<Postgres>) {
+ let repo = PgReferralRepo::new(pool.clone());
+
+ let referred_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+ let code = referrer_referral_code();
+
+ // First track the referral
+ repo.track_referral(&referred_user_id.0, &code)
+ .await
+ .unwrap();
+
+ // Then complete it
+ repo.complete_referral(&referred_user_id.0, &code)
+ .await
+ .unwrap();
+
+ // Verify the status was updated
+ let row = sqlx::query!("SELECT status FROM referral_tracking LIMIT 1")
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+
+ assert_eq!(row.status, "complete");
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("referral_users"))
+)]
+async fn test_complete_referral_invalid_code(pool: Pool<Postgres>) {
+ let repo = PgReferralRepo::new(pool);
+
+ let referred_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+ let code = ReferralCode("!!!invalid!!!".to_string());
+
+ let result = repo.complete_referral(&referred_user_id.0, &code).await;
+
+ assert!(result.is_err());
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("referral_users"))
+)]
+async fn test_complete_referral_nonexistent_referrer(pool: Pool<Postgres>) {
+ let repo = PgReferralRepo::new(pool);
+
+ let referred_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+
+ let converter = ShortUuidConverter::default();
+ let fake_uuid = uuid::Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap();
+ let code = ReferralCode(converter.from_uuid(&fake_uuid));
+
+ let result = repo.complete_referral(&referred_user_id.0, &code).await;
+
+ assert!(matches!(result, Err(sqlx::Error::RowNotFound)));
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("referral_users"))
+)]
+async fn test_complete_referral_nonexistent_referred_user(pool: Pool<Postgres>) {
+ let repo = PgReferralRepo::new(pool);
+
+ let referred_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+ let code = referrer_referral_code();
+
+ let result = repo.complete_referral(&referred_user_id.0, &code).await;
+
+ assert!(matches!(result, Err(sqlx::Error::RowNotFound)));
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("referral_users"))
+)]
+async fn test_complete_referral_not_tracked(pool: Pool<Postgres>) {
+ let repo = PgReferralRepo::new(pool);
+
+ let referred_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+ let code = referrer_referral_code();
+
+ // Complete without tracking first — no rows exist to update
+ let result = repo.complete_referral(&referred_user_id.0, &code).await;
+
+ assert!(matches!(result, Err(sqlx::Error::RowNotFound)));
+}
diff --git a/rust/cloud-storage/referral/src/outbound/stripe_discount_client.rs b/rust/cloud-storage/referral/src/outbound/stripe_discount_client.rs
new file mode 100644
index 0000000000..6952480671
--- /dev/null
+++ b/rust/cloud-storage/referral/src/outbound/stripe_discount_client.rs
@@ -0,0 +1,61 @@
+//! Stripe adapter for applying discounts.
+
+use anyhow::{Context, bail};
+
+use crate::domain::ports::DiscountClient;
+
+/// Stripe implementation of the discount client
+#[derive(Clone)]
+pub struct StripeDiscountClient {
+ /// inner stripe client
+ stripe_client: stripe::Client,
+ /// the amount a single discount is worth, in cents
+ discount_amount_in_cents: i64,
+}
+
+impl StripeDiscountClient {
+ /// Create a new stripe discount client
+ pub fn new(stripe_client: stripe::Client, discount_amount: i64) -> Self {
+ Self {
+ stripe_client,
+ discount_amount_in_cents: discount_amount,
+ }
+ }
+}
+
+impl DiscountClient for StripeDiscountClient {
+ type Err = anyhow::Error;
+
+ #[tracing::instrument(skip(self), err)]
+ async fn apply_discount(&self, referrer_customer_id: &str) -> Result<(), Self::Err> {
+ let customer_id: stripe::CustomerId = referrer_customer_id
+ .parse()
+ .context("invalid stripe customer id format")?;
+
+ let customer = stripe::Customer::retrieve(&self.stripe_client, &customer_id, &[])
+ .await
+ .inspect_err(|e| tracing::error!(error=?e, "failed to retrieve stripe customer"))
+ .context("stripe customer not found or could not be retrieved")?;
+
+ if customer.deleted {
+ bail!("stripe customer '{referrer_customer_id}' has been deleted");
+ }
+
+ // Negative amount = credit applied to the customer's balance
+ let params = stripe::CreateCustomerBalanceTransaction {
+ amount: -self.discount_amount_in_cents,
+ currency: stripe::Currency::USD,
+ description: Some("Referral credit"),
+ metadata: None,
+ };
+
+ stripe::Customer::create_balance_transaction(&self.stripe_client, &customer_id, params)
+ .await
+ .inspect_err(
+ |e| tracing::error!(error=?e, "failed to create balance transaction for customer"),
+ )
+ .context("failed to apply referral credit to stripe customer balance")?;
+
+ Ok(())
+ }
+}