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: teams checkout support (#3366)

Will Hutchinson242514bac74c
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 3c37d1c150..5fdb696e6b 100644
--- a/js/app/packages/service-clients/service-auth/generated/client.ts
+++ b/js/app/packages/service-clients/service-auth/generated/client.ts
@@ -48,6 +48,7 @@ import type {
SsoRequiredResponse,
StripeSessionResponse,
Team,
+ TeamCheckoutSessionRequest,
TeamInvitesResponse,
TeamWithMembers,
UserLinkResponse,
@@ -1930,6 +1931,66 @@ export const patchTeam = async (
} as patchTeamResponse;
};
+/**
+ * @summary Creates a new team.
+ */
+export type createTeamCheckoutSessionResponse200 = {
+ data: Team;
+ status: 200;
+};
+
+export type createTeamCheckoutSessionResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
+export type createTeamCheckoutSessionResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type createTeamCheckoutSessionResponseSuccess =
+ createTeamCheckoutSessionResponse200 & {
+ headers: Headers;
+ };
+export type createTeamCheckoutSessionResponseError = (
+ | createTeamCheckoutSessionResponse400
+ | createTeamCheckoutSessionResponse500
+) & {
+ headers: Headers;
+};
+
+export type createTeamCheckoutSessionResponse =
+ | createTeamCheckoutSessionResponseSuccess
+ | createTeamCheckoutSessionResponseError;
+
+export const getCreateTeamCheckoutSessionUrl = () => {
+ return `/team/checkout`;
+};
+
+export const createTeamCheckoutSession = async (
+ teamCheckoutSessionRequest: TeamCheckoutSessionRequest,
+ options?: RequestInit
+): Promise<createTeamCheckoutSessionResponse> => {
+ const res = await fetch(getCreateTeamCheckoutSessionUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(teamCheckoutSessionRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: createTeamCheckoutSessionResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as createTeamCheckoutSessionResponse;
+};
+
/**
* @summary Invites a user to a team.
*/
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 28619a6fff..065db87880 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
@@ -67,6 +67,13 @@ export * from './ssoRequiredResponse';
export * from './stripeProductTier';
export * from './stripeSessionResponse';
export * from './team';
+export * from './teamCheckoutSessionMetadata';
+export * from './teamCheckoutSessionMetadataFbc';
+export * from './teamCheckoutSessionMetadataFbp';
+export * from './teamCheckoutSessionMetadataGaClientId';
+export * from './teamCheckoutSessionRequest';
+export * from './teamCheckoutSessionRequestDiscount';
+export * from './teamCheckoutSessionResponse';
export * from './teamInviteDetails';
export * from './teamInvitesResponse';
export * from './teamMember';
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionMetadata.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionMetadata.ts
new file mode 100644
index 0000000000..b76bef98d2
--- /dev/null
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionMetadata.ts
@@ -0,0 +1,21 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { TeamCheckoutSessionMetadataFbc } from './teamCheckoutSessionMetadataFbc';
+import type { TeamCheckoutSessionMetadataFbp } from './teamCheckoutSessionMetadataFbp';
+import type { TeamCheckoutSessionMetadataGaClientId } from './teamCheckoutSessionMetadataGaClientId';
+
+/**
+ * Team checkout session metadata
+ */
+export interface TeamCheckoutSessionMetadata {
+ /** Meta (Facebook) click ID from _fbc cookie */
+ fbc?: TeamCheckoutSessionMetadataFbc;
+ /** Meta (Facebook) browser ID from _fbp cookie */
+ fbp?: TeamCheckoutSessionMetadataFbp;
+ /** Google Analytics client ID for conversion tracking */
+ ga_client_id?: TeamCheckoutSessionMetadataGaClientId;
+}
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionMetadataFbc.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionMetadataFbc.ts
new file mode 100644
index 0000000000..f96c81b35f
--- /dev/null
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionMetadataFbc.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Meta (Facebook) click ID from _fbc cookie
+ */
+export type TeamCheckoutSessionMetadataFbc = string | null;
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionMetadataFbp.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionMetadataFbp.ts
new file mode 100644
index 0000000000..2eb97fe534
--- /dev/null
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionMetadataFbp.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Meta (Facebook) browser ID from _fbp cookie
+ */
+export type TeamCheckoutSessionMetadataFbp = string | null;
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionMetadataGaClientId.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionMetadataGaClientId.ts
new file mode 100644
index 0000000000..04e8dba770
--- /dev/null
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionMetadataGaClientId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Google Analytics client ID for conversion tracking
+ */
+export type TeamCheckoutSessionMetadataGaClientId = string | null;
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionRequest.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionRequest.ts
new file mode 100644
index 0000000000..20fe411cab
--- /dev/null
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionRequest.ts
@@ -0,0 +1,26 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { TeamCheckoutSessionMetadata } from './teamCheckoutSessionMetadata';
+import type { TeamCheckoutSessionRequestDiscount } from './teamCheckoutSessionRequestDiscount';
+import type { TeamPlan } from './teamPlan';
+
+/**
+ * Team checkout session request
+ */
+export interface TeamCheckoutSessionRequest {
+ /** The URL to redirect to if checkout is cancelled */
+ cancel_url: string;
+ /** Optional discount/promo code to apply */
+ discount?: TeamCheckoutSessionRequestDiscount;
+ /** Tracking metadata for conversion attribution */
+ metadata?: TeamCheckoutSessionMetadata;
+ /** The URL to redirect to on successful checkout */
+ success_url: string;
+ /** The team plan the user wants to purchase for their team */
+ team_plan: TeamPlan;
+}
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionRequestDiscount.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionRequestDiscount.ts
new file mode 100644
index 0000000000..a359cb1f8f
--- /dev/null
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionRequestDiscount.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Optional discount/promo code to apply
+ */
+export type TeamCheckoutSessionRequestDiscount = string | null;
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionResponse.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionResponse.ts
new file mode 100644
index 0000000000..69c57a1465
--- /dev/null
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionResponse.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Team checkout session response
+ */
+export interface TeamCheckoutSessionResponse {
+ /** The checkout url */
+ url: string;
+}
diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.json
index 8ad68b3546..8de4509c25 100644
--- a/js/app/packages/service-clients/service-auth/openapi.json
+++ b/js/app/packages/service-clients/service-auth/openapi.json
@@ -1603,6 +1603,55 @@
}
}
},
+ "/team/checkout": {
+ "post": {
+ "tags": ["teams::inbound::axum_router::create_team_checkout_session"],
+ "summary": "Creates a new team.",
+ "operationId": "create_team_checkout_session",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TeamCheckoutSessionRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Team"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/team/invite": {
"post": {
"tags": ["teams::inbound::axum_router::invite_to_team"],
@@ -3683,6 +3732,62 @@
}
}
},
+ "TeamCheckoutSessionMetadata": {
+ "type": "object",
+ "description": "Team checkout session metadata",
+ "properties": {
+ "fbc": {
+ "type": ["string", "null"],
+ "description": "Meta (Facebook) click ID from _fbc cookie"
+ },
+ "fbp": {
+ "type": ["string", "null"],
+ "description": "Meta (Facebook) browser ID from _fbp cookie"
+ },
+ "ga_client_id": {
+ "type": ["string", "null"],
+ "description": "Google Analytics client ID for conversion tracking"
+ }
+ }
+ },
+ "TeamCheckoutSessionRequest": {
+ "type": "object",
+ "description": "Team checkout session request",
+ "required": ["success_url", "cancel_url", "team_plan"],
+ "properties": {
+ "cancel_url": {
+ "type": "string",
+ "description": "The URL to redirect to if checkout is cancelled"
+ },
+ "discount": {
+ "type": ["string", "null"],
+ "description": "Optional discount/promo code to apply"
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/TeamCheckoutSessionMetadata",
+ "description": "Tracking metadata for conversion attribution"
+ },
+ "success_url": {
+ "type": "string",
+ "description": "The URL to redirect to on successful checkout"
+ },
+ "team_plan": {
+ "$ref": "#/components/schemas/TeamPlan",
+ "description": "The team plan the user wants to purchase for their team"
+ }
+ }
+ },
+ "TeamCheckoutSessionResponse": {
+ "type": "object",
+ "description": "Team checkout session response",
+ "required": ["url"],
+ "properties": {
+ "url": {
+ "type": "string",
+ "description": "The checkout url"
+ }
+ }
+ },
"TeamInviteDetails": {
"type": "object",
"description": "Detailed information about a team invite",
diff --git a/js/bun.lock b/js/bun.lock
index abb76fa624..e2ec2551a9 100644
--- a/js/bun.lock
+++ b/js/bun.lock
@@ -839,7 +839,7 @@
"@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],
- "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#6152009", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-6152009", "sha512-XLN+niDA9BkzrxiZqBjYf+DL4TLoMIcI80ypCowacVfrfAjWt0qLwLkzWVUXjD7k3v0DB/G+BP4OLJNkGygHIw=="],
+ "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#6152009", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-6152009"],
"@inquirer/external-editor": ["@inquirer/[email protected]", "", { "dependencies": { "chardet": "^2.1.1", "iconv-lite": "^0.7.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-RWbSrDiYmO4LbejWY7ttpxczuwQyZLBUyygsA9Nsv95hpzUWwnNTVQmAq3xuh7vNwCp07UTmE5i11XAEExx4RA=="],
@@ -2565,7 +2565,7 @@
"pathval": ["[email protected]", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="],
- "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6", "sha512-HDFaPbCxLG2GHpf1smUG97nku5aPGBGaCcIbK05dGdp07TBLUlDcXsM4WcE82mO5W4RBPIBVYobX5N/6M6NFrA=="],
+ "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6"],
"performance-now": ["[email protected]", "", {}, "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow=="],
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index d15376291d..2e4443d8d3 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -11265,6 +11265,7 @@ dependencies = [
"thiserror 2.0.17",
"tokio",
"tracing",
+ "url",
"utoipa",
"uuid",
]
diff --git a/rust/cloud-storage/authentication_service/src/api/swagger.rs b/rust/cloud-storage/authentication_service/src/api/swagger.rs
index e41ef6d674..baa5b77424 100644
--- a/rust/cloud-storage/authentication_service/src/api/swagger.rs
+++ b/rust/cloud-storage/authentication_service/src/api/swagger.rs
@@ -1,8 +1,9 @@
use model::authentication::login::request::{AppleLoginRequest, PasswordRequest};
use teams::domain::model::{
- PatchTeamPlanRequest, PatchTeamRequest, PatchTeamUserRole, Team, TeamInviteDetails, TeamMember,
- TeamPlan, TeamRole, TeamWithMembers,
+ PatchTeamPlanRequest, PatchTeamRequest, PatchTeamUserRole, Team, TeamCheckoutSessionRequest,
+ TeamInviteDetails, TeamMember, TeamPlan, TeamRole, TeamWithMembers,
};
+use teams::inbound::axum_router::create_team_checkout_session::TeamCheckoutSessionResponse;
use teams::inbound::axum_router::get_team_invites::TeamInvitesResponse as TeamTeamInvitesResponse;
use teams::inbound::axum_router::get_user_invites::TeamInvitesResponse as UserTeamInvitesResponse;
use teams::inbound::axum_router::{
@@ -126,6 +127,7 @@ use model::user::{
teams::inbound::axum_router::get_user_teams::handler::<crate::api::context::TeamsServiceType>,
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>,
+ teams::inbound::axum_router::create_team_checkout_session::handler::<crate::api::context::TeamServiceType>,
/// /referral
referral::inbound::axum_router::get_referral_code_handler::<crate::api::context::ReferralServiceType>,
@@ -194,6 +196,8 @@ use model::user::{
PatchTeamUserRole,
TeamTeamInvitesResponse,
UserTeamInvitesResponse,
+ TeamCheckoutSessionRequest,
+ TeamCheckoutSessionResponse,
// Mobile welcome email
mobile_welcome_email::SendMobileWelcomeEmailRequest,
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 4d78a2f7d1..f23e7b82b1 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
@@ -10,8 +10,8 @@ use axum::{
http::{HeaderMap, StatusCode},
response::{IntoResponse, Json, Response},
};
-use macro_user_id::cowlike::CowLike;
use macro_user_id::email::Email;
+use macro_user_id::{cowlike::CowLike, lowercased::Lowercase};
use miniserde::json::Value as JsonValue;
use model::response::ErrorResponse;
use referral::domain::ports::ReferralService;
@@ -252,6 +252,7 @@ async fn handle_customer_subscription_event(
subscription_id,
subscription_status,
&team_id,
+ &email,
SubscriptionTrackingData {
ga_client_id: ga_client_id.clone(),
fbp: fbp.clone(),
@@ -439,17 +440,19 @@ async fn check_and_process_referral(
/// NOTE: We use strs here because there is a mismatch between stripe crate and
/// stripe_webhook crate for these types. *sigh*
#[tracing::instrument(skip(ctx, tracking_data), err, ret)]
-async fn handle_team_subscription_event(
+async fn handle_team_subscription_event<'a>(
ctx: &ApiContext,
subscription_id: &str,
subscription_status: &str,
team_id: &uuid::Uuid,
+ email: &Email<Lowercase<'a>>,
tracking_data: SubscriptionTrackingData,
) -> anyhow::Result<()> {
tracing::trace!("handling team subscription");
if subscription_status == "trialing" {
- anyhow::bail!("unexpected trialing status for team subscription");
+ // set has_trialed in macro_user table
+ macro_db_client::user::patch::update_macro_user_has_trialed(&ctx.db, email, true).await?;
}
match subscription_status {
diff --git a/rust/cloud-storage/teams/Cargo.toml b/rust/cloud-storage/teams/Cargo.toml
index 83e18f66c2..556608d3ab 100644
--- a/rust/cloud-storage/teams/Cargo.toml
+++ b/rust/cloud-storage/teams/Cargo.toml
@@ -16,7 +16,7 @@ axum = [
]
default = ["axum", "inbound", "outbound", "ports"]
inbound = ["axum", "ports"]
-outbound = ["dep:sqlx", "ports"]
+outbound = ["dep:sqlx", "dep:url", "ports"]
ports = [
"dep:model-entity",
"dep:model_notifications",
@@ -62,6 +62,7 @@ notification = { path = "../notification", optional = true, default-features = f
# Outbound dependencies
sqlx = { workspace = true, optional = true }
+url = { workspace = true, optional = true }
[dev-dependencies]
macro_db_migrator = { path = "../macro_db_migrator" }
diff --git a/rust/cloud-storage/teams/src/domain/customer_repo.rs b/rust/cloud-storage/teams/src/domain/customer_repo.rs
index 8ad9843868..0cdc47865f 100644
--- a/rust/cloud-storage/teams/src/domain/customer_repo.rs
+++ b/rust/cloud-storage/teams/src/domain/customer_repo.rs
@@ -2,7 +2,9 @@
use macro_user_id::user_id::MacroUserIdStr;
-use crate::domain::model::{CreateSubscriptionArgs, CustomerError, TeamPlan};
+use crate::domain::model::{
+ CreateSubscriptionArgs, CustomerError, TeamCheckoutSessionRequest, TeamPlan,
+};
/// The CustomerRepository defines a set of actions to perform on customer data
pub trait CustomerRepository: Clone + Send + Sync + 'static {
@@ -39,4 +41,13 @@ pub trait CustomerRepository: Clone + Send + Sync + 'static {
current_team_plan: Option<TeamPlan>,
team_plan: TeamPlan,
) -> impl Future<Output = Result<(), CustomerError>> + Send;
+
+ /// Creates the team plan checkout session
+ /// Returns the checkout url
+ fn create_team_checkout_session(
+ &self,
+ team_id: &uuid::Uuid,
+ customer_id: stripe::CustomerId,
+ req: &TeamCheckoutSessionRequest,
+ ) -> impl Future<Output = Result<String, CustomerError>> + Send;
}
diff --git a/rust/cloud-storage/teams/src/domain/model.rs b/rust/cloud-storage/teams/src/domain/model.rs
index 7f653bdc4e..0c7366a18a 100644
--- a/rust/cloud-storage/teams/src/domain/model.rs
+++ b/rust/cloud-storage/teams/src/domain/model.rs
@@ -161,6 +161,35 @@ pub struct PatchTeamUserRole {
pub role: TeamRole,
}
+/// Team checkout session metadata
+#[derive(Debug, Default, serde::Deserialize)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+pub struct TeamCheckoutSessionMetadata {
+ /// Google Analytics client ID for conversion tracking
+ pub ga_client_id: Option<String>,
+ /// Meta (Facebook) browser ID from _fbp cookie
+ pub fbp: Option<String>,
+ /// Meta (Facebook) click ID from _fbc cookie
+ pub fbc: Option<String>,
+}
+
+/// Team checkout session request
+#[derive(Debug, serde::Deserialize)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+pub struct TeamCheckoutSessionRequest {
+ /// The URL to redirect to on successful checkout
+ pub success_url: String,
+ /// The URL to redirect to if checkout is cancelled
+ pub cancel_url: String,
+ /// Optional discount/promo code to apply
+ pub discount: Option<String>,
+ /// Tracking metadata for conversion attribution
+ #[serde(default)]
+ pub metadata: TeamCheckoutSessionMetadata,
+ /// The team plan the user wants to purchase for their team
+ pub team_plan: TeamPlan,
+}
+
/// The Team struct
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
@@ -371,6 +400,9 @@ pub enum CustomerError {
/// The subscription is not active
#[error("Subscription is not active")]
SubscriptionNotActive,
+ /// Invalid promotion code
+ #[error("Invalid promotion code {0}")]
+ InvalidPromotionCode(String),
/// Storage layer error
#[error("Storage layer error {0}")]
StorageLayerError(#[from] anyhow::Error),
@@ -454,3 +486,23 @@ pub enum RestorePermissionsForTeamMembersError {
#[error("Underlying user roles and permissions error")]
AddRolesToUserError(#[from] UserRolesAndPermissionsError),
}
+
+/// Error when creating team checkout
+#[derive(Debug, thiserror::Error)]
+pub enum TeamCheckoutError {
+ /// Team already has a plan
+ #[error("Team already has a plan")]
+ TeamAlreadyHasPlanError,
+ /// Missing customer id
+ #[error("User does not have a customer id")]
+ MissingCustomerId,
+ /// Underlying team error
+ #[error("{0}")]
+ TeamError(#[from] TeamError),
+ /// Underlying customer error
+ #[error("{0}")]
+ CustomerError(#[from] CustomerError),
+ /// Customer already has a subscription
+ #[error("User already has an active subscription")]
+ AlreadySubscribed,
+}
diff --git a/rust/cloud-storage/teams/src/domain/team_repo.rs b/rust/cloud-storage/teams/src/domain/team_repo.rs
index 2ae3c362f5..dcc9e83c4e 100644
--- a/rust/cloud-storage/teams/src/domain/team_repo.rs
+++ b/rust/cloud-storage/teams/src/domain/team_repo.rs
@@ -10,8 +10,9 @@ use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStr
use crate::domain::model::{
AcceptedTeamInvite, CreateTeamError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError,
PatchTeamPlanRequest, PatchTeamRequest, RemoveTeamInviteError, RemoveUserFromTeamError,
- RestorePermissionsForTeamMembersError, RevokePermissionsForTeamMembersError, Team, TeamError,
- TeamInvite, TeamInviteDetails, TeamMember, TeamPlan, TeamRole, TeamWithMembers,
+ RestorePermissionsForTeamMembersError, RevokePermissionsForTeamMembersError, Team,
+ TeamCheckoutError, TeamCheckoutSessionRequest, TeamError, TeamInvite, TeamInviteDetails,
+ TeamMember, TeamPlan, TeamRole, TeamWithMembers,
};
/// The TeamChannelsRepository defines a set of actions related to team channels
@@ -351,4 +352,13 @@ pub trait TeamService: Clone + Send + Sync + 'static {
entity_access_receipt: EntityAccessReceipt<OwnerTeamRole>,
req: &PatchTeamPlanRequest,
) -> impl Future<Output = Result<(), TeamError>> + Send;
+
+ /// Creates a checkout session for the initial team purchase
+ /// This should only be called if the team currently is not on a plan
+ /// Returns the checkout session url
+ fn create_checkout_session(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<OwnerTeamRole>,
+ req: &TeamCheckoutSessionRequest,
+ ) -> impl Future<Output = Result<String, TeamCheckoutError>> + Send;
}
diff --git a/rust/cloud-storage/teams/src/domain/team_service.rs b/rust/cloud-storage/teams/src/domain/team_service.rs
index a2488c6d0b..0ecb0b2fe2 100644
--- a/rust/cloud-storage/teams/src/domain/team_service.rs
+++ b/rust/cloud-storage/teams/src/domain/team_service.rs
@@ -27,7 +27,8 @@ use crate::domain::{
CreateTeamError, CustomerError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError,
PatchTeamPlanRequest, PatchTeamRequest, RemoveTeamInviteError, RemoveUserFromTeamError,
RestorePermissionsForTeamMembersError, RevokePermissionsForTeamMembersError, Team,
- TeamError, TeamInvite, TeamInviteDetails, TeamMember, TeamPlan, TeamRole, TeamWithMembers,
+ TeamCheckoutError, TeamCheckoutSessionRequest, TeamError, TeamInvite, TeamInviteDetails,
+ TeamMember, TeamPlan, TeamRole, TeamWithMembers,
},
team_repo::{TeamChannelsRepository, TeamRepository, TeamService},
};
@@ -648,4 +649,47 @@ where
Ok(())
}
+
+ #[tracing::instrument(skip(self), err)]
+ async fn create_checkout_session(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<OwnerTeamRole>,
+ req: &TeamCheckoutSessionRequest,
+ ) -> Result<String, TeamCheckoutError> {
+ let team_id =
+ macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();
+
+ let team_plan = self.team_repository.get_team_plan(&team_id).await?;
+
+ if team_plan.is_some() {
+ return Err(TeamCheckoutError::TeamAlreadyHasPlanError);
+ }
+
+ let user_id = entity_access_receipt
+ .get_authenticated_user()
+ .map_err(TeamError::AccessError)?;
+
+ let stripe_customer_id: stripe::CustomerId =
+ match self.team_repository.get_stripe_customer_id(user_id).await? {
+ Some(customer_id) => customer_id,
+ None => return Err(TeamCheckoutError::MissingCustomerId),
+ };
+
+ // If the user has an active subscription id error out
+ if self
+ .customer_repository
+ .get_subscription_id_for_customer(&stripe_customer_id)
+ .await
+ .is_ok()
+ {
+ return Err(TeamCheckoutError::AlreadySubscribed);
+ }
+
+ let url = self
+ .customer_repository
+ .create_team_checkout_session(&team_id, stripe_customer_id, req)
+ .await?;
+
+ Ok(url)
+ }
}
diff --git a/rust/cloud-storage/teams/src/domain/team_service/test.rs b/rust/cloud-storage/teams/src/domain/team_service/test.rs
index bfdf5da8ea..2f942ae1ab 100644
--- a/rust/cloud-storage/teams/src/domain/team_service/test.rs
+++ b/rust/cloud-storage/teams/src/domain/team_service/test.rs
@@ -416,6 +416,15 @@ impl CustomerRepository for MockCustomerRepository {
) -> impl Future<Output = Result<(), CustomerError>> + Send {
async { unimplemented!() }
}
+
+ fn create_team_checkout_session(
+ &self,
+ _team_id: &uuid::Uuid,
+ _customer_id: stripe::CustomerId,
+ _req: &TeamCheckoutSessionRequest,
+ ) -> impl Future<Output = Result<String, CustomerError>> + Send {
+ async { unimplemented!() }
+ }
}
// -- Mock TeamChannelsRepository --
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/create_team_checkout_session.rs b/rust/cloud-storage/teams/src/inbound/axum_router/create_team_checkout_session.rs
new file mode 100644
index 0000000000..f3a097415f
--- /dev/null
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/create_team_checkout_session.rs
@@ -0,0 +1,71 @@
+use axum::{
+ Json,
+ extract::State,
+ http::StatusCode,
+ response::{IntoResponse, Response},
+};
+use entity_access::{
+ domain::{models::OwnerTeamRole, ports::EntityAccessService},
+ inbound::axum_extractors::MacroUserTeamExtractor,
+};
+use model_error_response::ErrorResponse;
+
+use crate::domain::{
+ model::{Team, TeamCheckoutError, TeamCheckoutSessionRequest},
+ team_repo::TeamService,
+};
+
+use super::TeamRouterState;
+
+impl IntoResponse for TeamCheckoutError {
+ fn into_response(self) -> Response {
+ let status = match self {
+ TeamCheckoutError::TeamAlreadyHasPlanError
+ | TeamCheckoutError::MissingCustomerId
+ | TeamCheckoutError::AlreadySubscribed => StatusCode::BAD_REQUEST,
+ TeamCheckoutError::TeamError(_) | TeamCheckoutError::CustomerError(_) => {
+ StatusCode::INTERNAL_SERVER_ERROR
+ }
+ };
+
+ (
+ status,
+ Json(ErrorResponse {
+ message: self.to_string().into(),
+ }),
+ )
+ .into_response()
+ }
+}
+
+/// Team checkout session response
+#[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
+pub struct TeamCheckoutSessionResponse {
+ /// The checkout url
+ pub url: String,
+}
+
+/// Creates a new team.
+#[utoipa::path(
+ post,
+ path = "/team/checkout",
+ operation_id = "create_team_checkout_session",
+ responses(
+ (status = 200, body = Team),
+ (status = 400, body = model_error_response::ErrorResponse),
+ (status = 500, body = model_error_response::ErrorResponse),
+ ),
+)]
+#[tracing::instrument(skip_all, err)]
+pub async fn handler<T: TeamService, Eas: EntityAccessService>(
+ access: MacroUserTeamExtractor<OwnerTeamRole, Eas>,
+ State(state): State<TeamRouterState<T, Eas>>,
+ Json(req): Json<TeamCheckoutSessionRequest>,
+) -> Result<Json<TeamCheckoutSessionResponse>, crate::domain::model::TeamCheckoutError> {
+ let url = state
+ .service
+ .create_checkout_session(access.entity_access_receipt, &req)
+ .await?;
+
+ Ok(Json(TeamCheckoutSessionResponse { url }))
+}
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs b/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs
index b5e463c84d..3377335aaf 100644
--- a/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs
@@ -2,6 +2,8 @@
/// Create a new team.
pub mod create_team;
+/// Create team checkout session.
+pub mod create_team_checkout_session;
/// Delete a team.
pub mod delete_team;
/// Delete a team invite.
@@ -92,6 +94,10 @@ where
.route("/", delete(delete_team::handler::<T, Eas>))
.route("/invites", get(get_team_invites::handler::<T, Eas>))
.route("/invite", post(invite_to_team::handler::<T, Eas>))
+ .route(
+ "/checkout",
+ post(create_team_checkout_session::handler::<T, Eas>),
+ )
.route(
"/join/{team_invite_id}",
delete(reject_invitation::handler::<T, Eas>),
diff --git a/rust/cloud-storage/teams/src/outbound/customer_repo.rs b/rust/cloud-storage/teams/src/outbound/customer_repo.rs
index 0ebbf37e0e..c32f7c66fd 100644
--- a/rust/cloud-storage/teams/src/outbound/customer_repo.rs
+++ b/rust/cloud-storage/teams/src/outbound/customer_repo.rs
@@ -2,11 +2,12 @@
use std::{collections::HashMap, sync::Arc};
+use anyhow::Context;
use stripe::{CreateSubscription, CreateSubscriptionItems, UpdateSubscription};
use crate::domain::{
customer_repo::CustomerRepository,
- model::{CreateSubscriptionArgs, CustomerError, TeamPlan},
+ model::{CreateSubscriptionArgs, CustomerError, TeamCheckoutSessionRequest, TeamPlan},
};
/// The stripe price ids for all tiers
@@ -231,4 +232,95 @@ impl CustomerRepository for CustomerRepositoryImpl {
Ok(())
}
+
+ #[tracing::instrument(skip(self), err)]
+ async fn create_team_checkout_session(
+ &self,
+ team_id: &uuid::Uuid,
+ customer_id: stripe::CustomerId,
+ req: &TeamCheckoutSessionRequest,
+ ) -> Result<String, CustomerError> {
+ let promo_code_id = if let Some(discount) = req.discount.as_ref() {
+ let mut list_params = stripe::ListPromotionCodes::new();
+ list_params.code = Some(discount);
+ list_params.active = Some(true);
+ list_params.limit = Some(1);
+
+ let promo_codes = stripe::PromotionCode::list(&self.client, &list_params)
+ .await
+ .context("unable to list promotion codes")?;
+
+ let promo_code = promo_codes
+ .data
+ .into_iter()
+ .next()
+ .ok_or(CustomerError::InvalidPromotionCode(discount.clone()))?;
+
+ Some(promo_code.id)
+ } else {
+ None
+ };
+
+ let mut metadata: HashMap<String, String> = HashMap::new();
+ // Insert team id metadata
+ metadata.insert("team_id".to_string(), team_id.to_string());
+
+ // Insert tracking metadata
+ if let Some(ga_client_id) = req.metadata.ga_client_id.as_ref() {
+ metadata.insert("ga_client_id".to_string(), ga_client_id.clone());
+ }
+
+ if let Some(fbp) = req.metadata.fbp.as_ref() {
+ metadata.insert("fbp".to_string(), fbp.clone());
+ }
+
+ if let Some(fbc) = req.metadata.fbc.as_ref() {
+ metadata.insert("fbc".to_string(), fbc.clone());
+ }
+
+ // Only set subscription_data if we have metadata to include
+ let subscription_data =
+ (!metadata.is_empty()).then_some(stripe::CreateCheckoutSessionSubscriptionData {
+ metadata: Some(metadata),
+ ..Default::default()
+ });
+
+ let price_id = self
+ .team_plan_stripe_price_ids
+ .try_get_price_id_for_team_plan(req.team_plan)?;
+
+ // Create the checkout session
+ let params = stripe::CreateCheckoutSession {
+ customer: Some(customer_id),
+ mode: Some(stripe::CheckoutSessionMode::Subscription),
+ success_url: Some(req.success_url.as_str()),
+ cancel_url: Some(req.cancel_url.as_str()),
+ allow_promotion_codes: promo_code_id.is_none().then_some(true),
+ discounts: promo_code_id.map(|id| {
+ vec![stripe::CreateCheckoutSessionDiscounts {
+ promotion_code: Some(id.to_string()),
+ ..Default::default()
+ }]
+ }),
+ line_items: Some(vec![stripe::CreateCheckoutSessionLineItems {
+ price: Some(price_id.to_string()),
+ quantity: Some(1),
+ ..Default::default()
+ }]),
+ subscription_data,
+ ..Default::default()
+ };
+
+ let session = stripe::CheckoutSession::create(&self.client, params)
+ .await
+ .context("could not create checkout session")?;
+
+ let url = session.url.context("expected url")?;
+
+ // Validate but return the exact URL Stripe gave us — session URLs are signed/opaque
+ // and `Url::parse(...).to_string()` can normalize in ways that break the signature.
+ url::Url::parse(&url).context("expected valid url")?;
+
+ Ok(url)
+ }
}