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(pricing): update to new subscription model (#3448)

Will Hutchinson53dcf052df08
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 5fdb696e6b..e586878630 100644
--- a/js/app/packages/service-clients/service-auth/generated/client.ts
+++ b/js/app/packages/service-clients/service-auth/generated/client.ts
@@ -8,6 +8,7 @@ import type {
AppleLoginRequest,
CreateAccountMergeRequest,
CreateCheckoutSessionRequest,
+ CreateCheckoutSessionV2Request,
CreateInProgressLinkResponse,
CreatePortalSessionRequest,
CreateTeamRequest,
@@ -30,7 +31,6 @@ import type {
PasswordlessRequest,
PasswordRequest,
PatchSubscriptionTierRequest,
- PatchTeamPlanRequest,
PatchTeamRequest,
PatchUserGroupRequest,
PatchUserOnboardingRequest,
@@ -48,7 +48,6 @@ import type {
SsoRequiredResponse,
StripeSessionResponse,
Team,
- TeamCheckoutSessionRequest,
TeamInvitesResponse,
TeamWithMembers,
UserLinkResponse,
@@ -1931,66 +1930,6 @@ 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.
*/
@@ -2312,75 +2251,6 @@ export const rejectInvitation = async (
} as rejectInvitationResponse;
};
-/**
- * @summary Updates a team plan.
- */
-export type patchTeamPlanResponse200 = {
- data: void;
- status: 200;
-};
-
-export type patchTeamPlanResponse400 = {
- data: ErrorResponse;
- status: 400;
-};
-
-export type patchTeamPlanResponse401 = {
- data: ErrorResponse;
- status: 401;
-};
-
-export type patchTeamPlanResponse404 = {
- data: ErrorResponse;
- status: 404;
-};
-
-export type patchTeamPlanResponse500 = {
- data: ErrorResponse;
- status: 500;
-};
-
-export type patchTeamPlanResponseSuccess = patchTeamPlanResponse200 & {
- headers: Headers;
-};
-export type patchTeamPlanResponseError = (
- | patchTeamPlanResponse400
- | patchTeamPlanResponse401
- | patchTeamPlanResponse404
- | patchTeamPlanResponse500
-) & {
- headers: Headers;
-};
-
-export type patchTeamPlanResponse =
- | patchTeamPlanResponseSuccess
- | patchTeamPlanResponseError;
-
-export const getPatchTeamPlanUrl = () => {
- return `/team/plan`;
-};
-
-export const patchTeamPlan = async (
- patchTeamPlanRequest: PatchTeamPlanRequest,
- options?: RequestInit
-): Promise<patchTeamPlanResponse> => {
- const res = await fetch(getPatchTeamPlanUrl(), {
- ...options,
- method: 'PATCH',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(patchTeamPlanRequest),
- });
-
- const body = [204, 205, 304].includes(res.status) ? null : await res.text();
-
- const data: patchTeamPlanResponse['data'] = body ? JSON.parse(body) : {};
- return {
- data,
- status: res.status,
- headers: res.headers,
- } as patchTeamPlanResponse;
-};
-
/**
* @summary Removes a user from a team.
*/
@@ -3490,7 +3360,7 @@ export const getUserQuota = async (
};
/**
- * @summary Creates a Stripe checkout session for the user to subscribe.
+ * @summary **LEGACY DO NOT USE** Creates a Stripe checkout session for the user to subscribe.
*/
export type createCheckoutSessionResponse200 = {
data: StripeSessionResponse;
@@ -3561,6 +3431,78 @@ export const createCheckoutSession = async (
} as createCheckoutSessionResponse;
};
+/**
+ * @summary Creates a Stripe checkout session for the user to subscribe.
+ */
+export type createCheckoutSessionV2Response200 = {
+ data: StripeSessionResponse;
+ status: 200;
+};
+
+export type createCheckoutSessionV2Response400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
+export type createCheckoutSessionV2Response404 = {
+ data: ErrorResponse;
+ status: 404;
+};
+
+export type createCheckoutSessionV2Response409 = {
+ data: ErrorResponse;
+ status: 409;
+};
+
+export type createCheckoutSessionV2Response500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type createCheckoutSessionV2ResponseSuccess =
+ createCheckoutSessionV2Response200 & {
+ headers: Headers;
+ };
+export type createCheckoutSessionV2ResponseError = (
+ | createCheckoutSessionV2Response400
+ | createCheckoutSessionV2Response404
+ | createCheckoutSessionV2Response409
+ | createCheckoutSessionV2Response500
+) & {
+ headers: Headers;
+};
+
+export type createCheckoutSessionV2Response =
+ | createCheckoutSessionV2ResponseSuccess
+ | createCheckoutSessionV2ResponseError;
+
+export const getCreateCheckoutSessionV2Url = () => {
+ return `/user/stripe/checkoutv2`;
+};
+
+export const createCheckoutSessionV2 = async (
+ createCheckoutSessionV2Request: CreateCheckoutSessionV2Request,
+ options?: RequestInit
+): Promise<createCheckoutSessionV2Response> => {
+ const res = await fetch(getCreateCheckoutSessionV2Url(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(createCheckoutSessionV2Request),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: createCheckoutSessionV2Response['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as createCheckoutSessionV2Response;
+};
+
/**
* @summary Creates a Stripe billing portal session.
*/
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/createCheckoutSessionV2Request.ts b/js/app/packages/service-clients/service-auth/generated/schemas/createCheckoutSessionV2Request.ts
new file mode 100644
index 0000000000..2bd30db6c9
--- /dev/null
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/createCheckoutSessionV2Request.ts
@@ -0,0 +1,23 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { CheckoutSessionMetadata } from './checkoutSessionMetadata';
+import type { CreateCheckoutSessionV2RequestDiscount } from './createCheckoutSessionV2RequestDiscount';
+
+/**
+ * Request body for creating a Stripe checkout session
+ */
+export interface CreateCheckoutSessionV2Request {
+ /** The URL to redirect to if checkout is cancelled */
+ cancelUrl: string;
+ /** Optional discount/promo code to apply */
+ discount?: CreateCheckoutSessionV2RequestDiscount;
+ /** Tracking metadata for conversion attribution */
+ metadata?: CheckoutSessionMetadata;
+ /** The URL to redirect to on successful checkout */
+ successUrl: string;
+}
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionRequestDiscount.ts b/js/app/packages/service-clients/service-auth/generated/schemas/createCheckoutSessionV2RequestDiscount.ts
similarity index 72%
rename from js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionRequestDiscount.ts
rename to js/app/packages/service-clients/service-auth/generated/schemas/createCheckoutSessionV2RequestDiscount.ts
index a359cb1f8f..b2f1add032 100644
--- a/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionRequestDiscount.ts
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/createCheckoutSessionV2RequestDiscount.ts
@@ -8,4 +8,4 @@
/**
* Optional discount/promo code to apply
*/
-export type TeamCheckoutSessionRequestDiscount = string | null;
+export type CreateCheckoutSessionV2RequestDiscount = string | null;
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 9ac98b1df1..4d1c342bcc 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
@@ -14,6 +14,8 @@ export * from './checkoutSessionMetadataGaClientId';
export * from './createAccountMergeRequest';
export * from './createCheckoutSessionRequest';
export * from './createCheckoutSessionRequestDiscount';
+export * from './createCheckoutSessionV2Request';
+export * from './createCheckoutSessionV2RequestDiscount';
export * from './createInProgressLinkResponse';
export * from './createPortalSessionRequest';
export * from './createTeamRequest';
@@ -41,7 +43,6 @@ export * from './passwordlessRequest';
export * from './passwordlessRequestReferralCode';
export * from './passwordRequest';
export * from './patchSubscriptionTierRequest';
-export * from './patchTeamPlanRequest';
export * from './patchTeamRequest';
export * from './patchTeamRequestName';
export * from './patchTeamRequestSlug';
@@ -68,13 +69,6 @@ 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/patchTeamPlanRequest.ts b/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamPlanRequest.ts
deleted file mode 100644
index 52bdf1f609..0000000000
--- a/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamPlanRequest.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * authentication_service
- * OpenAPI spec version: 0.1.0
- */
-import type { TeamPlan } from './teamPlan';
-
-/**
- * Request to update the team plan
- */
-export interface PatchTeamPlanRequest {
- /** The new team plan */
- team_plan: TeamPlan;
-}
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
deleted file mode 100644
index b76bef98d2..0000000000
--- a/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionMetadata.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-/**
- * 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
deleted file mode 100644
index f96c81b35f..0000000000
--- a/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionMetadataFbc.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * 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
deleted file mode 100644
index 2eb97fe534..0000000000
--- a/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionMetadataFbp.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * 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
deleted file mode 100644
index 04e8dba770..0000000000
--- a/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionMetadataGaClientId.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * 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
deleted file mode 100644
index 20fe411cab..0000000000
--- a/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionRequest.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- * 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/teamCheckoutSessionResponse.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionResponse.ts
deleted file mode 100644
index 69c57a1465..0000000000
--- a/js/app/packages/service-clients/service-auth/generated/schemas/teamCheckoutSessionResponse.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-/**
- * 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 abf5cac5da..fae4733dc2 100644
--- a/js/app/packages/service-clients/service-auth/openapi.json
+++ b/js/app/packages/service-clients/service-auth/openapi.json
@@ -1603,55 +1603,6 @@
}
}
},
- "/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"],
@@ -1933,68 +1884,6 @@
}
}
},
- "/team/plan": {
- "patch": {
- "tags": ["teams::inbound::axum_router::patch_team_plan"],
- "summary": "Updates a team plan.",
- "operationId": "patch_team_plan",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/PatchTeamPlanRequest"
- }
- }
- },
- "required": true
- },
- "responses": {
- "200": {
- "description": ""
- },
- "400": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ErrorResponse"
- }
- }
- }
- },
- "401": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ErrorResponse"
- }
- }
- }
- },
- "404": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ErrorResponse"
- }
- }
- }
- },
- "500": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ErrorResponse"
- }
- }
- }
- }
- }
- }
- },
"/team/remove/{remove_user_id}": {
"delete": {
"tags": ["teams::inbound::axum_router::remove_user_from_team"],
@@ -2890,7 +2779,7 @@
"/user/stripe/checkout": {
"post": {
"tags": ["user::stripe::create_checkout_session"],
- "summary": "Creates a Stripe checkout session for the user to subscribe.",
+ "summary": "**LEGACY DO NOT USE** Creates a Stripe checkout session for the user to subscribe.",
"operationId": "create_checkout_session",
"requestBody": {
"content": {
@@ -2956,6 +2845,75 @@
}
}
},
+ "/user/stripe/checkoutv2": {
+ "post": {
+ "tags": ["user::stripe::create_checkout_session_v2"],
+ "summary": "Creates a Stripe checkout session for the user to subscribe.",
+ "operationId": "create_checkout_session_v2",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateCheckoutSessionV2Request"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/StripeSessionResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/user/stripe/portal": {
"post": {
"tags": ["user::stripe::create_portal_session"],
@@ -3210,6 +3168,29 @@
}
}
},
+ "CreateCheckoutSessionV2Request": {
+ "type": "object",
+ "description": "Request body for creating a Stripe checkout session",
+ "required": ["successUrl", "cancelUrl"],
+ "properties": {
+ "cancelUrl": {
+ "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/CheckoutSessionMetadata",
+ "description": "Tracking metadata for conversion attribution"
+ },
+ "successUrl": {
+ "type": "string",
+ "description": "The URL to redirect to on successful checkout"
+ }
+ }
+ },
"CreateInProgressLinkResponse": {
"type": "object",
"required": ["link_id"],
@@ -3504,17 +3485,6 @@
}
}
},
- "PatchTeamPlanRequest": {
- "type": "object",
- "description": "Request to update the team plan",
- "required": ["team_plan"],
- "properties": {
- "team_plan": {
- "$ref": "#/components/schemas/TeamPlan",
- "description": "The new team plan"
- }
- }
- },
"PatchTeamRequest": {
"type": "object",
"description": "Request to update a team",
@@ -3739,62 +3709,6 @@
}
}
},
- "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 34867994c4..ac5170a339 100644
--- a/js/bun.lock
+++ b/js/bun.lock
@@ -824,7 +824,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=="],
@@ -2544,7 +2544,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/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rs
index 07dedbc1f0..38a028834f 100644
--- a/rust/cloud-storage/authentication_service/src/api/context.rs
+++ b/rust/cloud-storage/authentication_service/src/api/context.rs
@@ -82,6 +82,8 @@ pub(crate) struct ApiContext {
pub rate_limit_service: RateLimiter,
/// The stripe price ids
pub legacy_stripe_price_ids: LegacyStripePriceIds,
+ /// The stripe price id
+ pub stripe_price_id: String,
}
env_var! {
diff --git a/rust/cloud-storage/authentication_service/src/api/swagger.rs b/rust/cloud-storage/authentication_service/src/api/swagger.rs
index baa5b77424..c72c76897b 100644
--- a/rust/cloud-storage/authentication_service/src/api/swagger.rs
+++ b/rust/cloud-storage/authentication_service/src/api/swagger.rs
@@ -1,9 +1,8 @@
use model::authentication::login::request::{AppleLoginRequest, PasswordRequest};
use teams::domain::model::{
- PatchTeamPlanRequest, PatchTeamRequest, PatchTeamUserRole, Team, TeamCheckoutSessionRequest,
- TeamInviteDetails, TeamMember, TeamPlan, TeamRole, TeamWithMembers,
+ PatchTeamRequest, PatchTeamUserRole, Team, 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::{
@@ -28,6 +27,7 @@ use crate::api::user::patch_user_onboarding::PatchUserOnboardingRequest;
use crate::api::user::post_get_names::PostGetNamesRequestBody;
use crate::api::user::post_get_names_with_email::GetNamesWithEmailRequestBody;
use crate::api::user::stripe::create_checkout_session::CreateCheckoutSessionRequest;
+use crate::api::user::stripe::create_checkout_session_v2::CreateCheckoutSessionV2Request;
use crate::api::user::stripe::create_portal_session::CreatePortalSessionRequest;
use crate::api::user::stripe::patch_subscription_tier::PatchSubscriptionTierRequest;
use crate::api::user::stripe::{StripeProductTier, StripeSessionResponse};
@@ -100,6 +100,7 @@ use model::user::{
user::get_legacy_user_permissions::handler,
user::patch_tutorial::handler,
user::stripe::create_checkout_session::create_checkout_session,
+ user::stripe::create_checkout_session_v2::create_checkout_session,
user::stripe::create_portal_session::create_portal_session,
user::stripe::patch_subscription_tier::patch_subscription_tier,
@@ -121,13 +122,11 @@ use model::user::{
teams::inbound::axum_router::invite_to_team::handler::<crate::api::context::TeamsServiceType>,
teams::inbound::axum_router::get_team_invites::handler::<crate::api::context::TeamsServiceType>,
teams::inbound::axum_router::patch_team::handler::<crate::api::context::TeamsServiceType>,
- teams::inbound::axum_router::patch_team_plan::handler::<crate::api::context::TeamsServiceType>,
teams::inbound::axum_router::reject_invitation::handler::<crate::api::context::TeamsServiceType>,
teams::inbound::axum_router::get_user_invites::handler::<crate::api::context::TeamsServiceType>,
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>,
@@ -174,6 +173,7 @@ use model::user::{
// Stripe
StripeProductTier,
CreateCheckoutSessionRequest,
+ CreateCheckoutSessionV2Request,
CreatePortalSessionRequest,
PatchSubscriptionTierRequest,
StripeSessionResponse,
@@ -192,12 +192,9 @@ use model::user::{
CreateTeamRequest,
InviteToTeamRequest,
PatchTeamRequest,
- PatchTeamPlanRequest,
PatchTeamUserRole,
TeamTeamInvitesResponse,
UserTeamInvitesResponse,
- TeamCheckoutSessionRequest,
- TeamCheckoutSessionResponse,
// Mobile welcome email
mobile_welcome_email::SendMobileWelcomeEmailRequest,
diff --git a/rust/cloud-storage/authentication_service/src/api/user/mod.rs b/rust/cloud-storage/authentication_service/src/api/user/mod.rs
index 0274ba84e2..c19a38e339 100644
--- a/rust/cloud-storage/authentication_service/src/api/user/mod.rs
+++ b/rust/cloud-storage/authentication_service/src/api/user/mod.rs
@@ -6,7 +6,7 @@ use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use tower::ServiceBuilder;
use tower_cookies::CookieManagerLayer;
-use crate::api::ApiContext;
+use crate::api::{ApiContext, context::EntityAccessServiceType};
// needs to be public in api crate for swagger
pub(in crate::api) mod create_user;
@@ -61,6 +61,14 @@ fn router_with_auth(state: ApiContext, jwt_args: JwtValidationArgs) -> Router<Ap
"/stripe/checkout",
post(stripe::create_checkout_session::create_checkout_session),
)
+ .route(
+ "/stripe/checkoutv2",
+ post(
+ stripe::create_checkout_session_v2::create_checkout_session::<
+ EntityAccessServiceType,
+ >,
+ ),
+ )
.route(
"/stripe/portal",
post(stripe::create_portal_session::create_portal_session),
diff --git a/rust/cloud-storage/authentication_service/src/api/user/stripe/create_checkout_session.rs b/rust/cloud-storage/authentication_service/src/api/user/stripe/create_checkout_session.rs
index 2365787afd..f82ead3af0 100644
--- a/rust/cloud-storage/authentication_service/src/api/user/stripe/create_checkout_session.rs
+++ b/rust/cloud-storage/authentication_service/src/api/user/stripe/create_checkout_session.rs
@@ -37,7 +37,7 @@ pub struct CreateCheckoutSessionRequest {
pub tier: StripeProductTier,
}
-/// Creates a Stripe checkout session for the user to subscribe.
+/// **LEGACY DO NOT USE** Creates a Stripe checkout session for the user to subscribe.
#[utoipa::path(
post,
path = "/user/stripe/checkout",
diff --git a/rust/cloud-storage/authentication_service/src/api/user/stripe/create_checkout_session_v2.rs b/rust/cloud-storage/authentication_service/src/api/user/stripe/create_checkout_session_v2.rs
new file mode 100644
index 0000000000..b911ce9126
--- /dev/null
+++ b/rust/cloud-storage/authentication_service/src/api/user/stripe/create_checkout_session_v2.rs
@@ -0,0 +1,163 @@
+use axum::{Json, extract::State};
+use entity_access::domain::models::OwnerTeamRole;
+use entity_access::domain::ports::EntityAccessService;
+use entity_access::inbound::axum_extractors::OptionalMacroUserTeamExtractor;
+use model_user::axum_extractor::MacroUserExtractor;
+use serde::Deserialize;
+use utoipa::ToSchema;
+
+use super::{StripeOperationError, StripeSessionResponse};
+use crate::api::context::ApiContext;
+use crate::api::user::stripe::create_checkout_session::CheckoutSessionMetadata;
+use model::response::ErrorResponse;
+
+/// Request body for creating a Stripe checkout session
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateCheckoutSessionV2Request {
+ /// 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: CheckoutSessionMetadata,
+}
+
+/// Creates a Stripe checkout session for the user to subscribe.
+#[utoipa::path(
+ post,
+ path = "/user/stripe/checkoutv2",
+ operation_id = "create_checkout_session_v2",
+ request_body = CreateCheckoutSessionV2Request,
+ responses(
+ (status = 200, body = StripeSessionResponse),
+ (status = 400, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 409, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(ctx, user, optional_team), err, fields(user_id = %user.macro_user_id))]
+pub async fn create_checkout_session<Eas: EntityAccessService>(
+ State(ctx): State<ApiContext>,
+ user: MacroUserExtractor,
+ optional_team: OptionalMacroUserTeamExtractor<OwnerTeamRole, Eas>,
+ Json(req): Json<CreateCheckoutSessionV2Request>,
+) -> Result<Json<StripeSessionResponse>, StripeOperationError> {
+ // Get the stripe customer ID from the database
+ let stripe_customer_id =
+ macro_db_client::user::get::get_stripe_customer_id_by_user_id(&ctx.db, &user.macro_user_id)
+ .await?
+ .ok_or(StripeOperationError::MissingStripeId)?;
+
+ let customer_id: stripe::CustomerId = stripe_customer_id.parse()?;
+
+ // Check if user already has an active subscription
+ let mut list_subscriptions = stripe::ListSubscriptions::new();
+ list_subscriptions.customer = Some(customer_id.clone());
+ list_subscriptions.limit = Some(10);
+
+ let subscriptions = stripe::Subscription::list(&ctx.stripe_client, &list_subscriptions).await?;
+
+ let has_active_subscription = subscriptions.data.iter().any(|sub| {
+ matches!(
+ sub.status,
+ stripe::SubscriptionStatus::Active | stripe::SubscriptionStatus::Trialing
+ )
+ });
+
+ if has_active_subscription {
+ tracing::warn!(
+ customer_id = %customer_id,
+ "User attempted to create checkout session but already has an active subscription"
+ );
+ return Err(StripeOperationError::AlreadySubscribed);
+ }
+
+ // If a discount code is provided, look up the promotion code ID
+ let promo_code_id = if let Some(ref discount) = req.discount {
+ 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(&ctx.stripe_client, &list_params).await?;
+
+ let promo_code = promo_codes
+ .data
+ .into_iter()
+ .next()
+ .ok_or(StripeOperationError::PromoCodeNotFound)?;
+
+ Some(promo_code.id)
+ } else {
+ None
+ };
+
+ // Build subscription metadata from optional tracking fields
+ let mut metadata = std::collections::HashMap::new();
+
+ // If the user is the owner of a team, we need to insert team metadata into subscription
+ if let Some(team) = optional_team.entity_access_receipt {
+ let team_id = team.entity().entity_id.clone();
+ metadata.insert("team_id".to_string(), team_id);
+
+ metadata.insert("owner_id".to_string(), user.macro_user_id.to_string());
+ }
+
+ if let Some(ga_client_id) = req.metadata.ga_client_id {
+ metadata.insert("ga_client_id".to_string(), ga_client_id);
+ }
+ if let Some(fbp) = req.metadata.fbp {
+ metadata.insert("fbp".to_string(), fbp);
+ }
+ if let Some(fbc) = req.metadata.fbc {
+ metadata.insert("fbc".to_string(), fbc);
+ }
+
+ // 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 = ctx.stripe_price_id;
+
+ // 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(&ctx.stripe_client, params).await?;
+
+ let url = session
+ .url
+ .ok_or(StripeOperationError::UnexpectedStripeResponse)?;
+
+ // 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).map_err(|_| StripeOperationError::UnexpectedStripeResponse)?;
+
+ Ok(Json(StripeSessionResponse { url }))
+}
diff --git a/rust/cloud-storage/authentication_service/src/api/user/stripe/mod.rs b/rust/cloud-storage/authentication_service/src/api/user/stripe/mod.rs
index 16a2920977..9f0c9122c7 100644
--- a/rust/cloud-storage/authentication_service/src/api/user/stripe/mod.rs
+++ b/rust/cloud-storage/authentication_service/src/api/user/stripe/mod.rs
@@ -1,4 +1,5 @@
pub mod create_checkout_session;
+pub mod create_checkout_session_v2;
pub mod create_portal_session;
pub mod patch_subscription_tier;
mod shared;
diff --git a/rust/cloud-storage/authentication_service/src/config.rs b/rust/cloud-storage/authentication_service/src/config.rs
index eb8b579258..197d8c6c36 100644
--- a/rust/cloud-storage/authentication_service/src/config.rs
+++ b/rust/cloud-storage/authentication_service/src/config.rs
@@ -95,8 +95,8 @@ pub struct Config {
/// The legacy stripe price ids
pub legacy_stripe_price_ids: LegacyStripePriceIds,
- /// The team stripe price ids
- pub team_stripe_price_ids: TeamStripePriceIds,
+ /// The stripe price id
+ pub stripe_price_id: String,
}
env_var! {
@@ -111,35 +111,12 @@ env_var! {
}
}
-#[derive(Clone)]
-pub struct TeamStripePriceIds {
- /// The idea price id
- pub idea: String,
- /// The pre-seed price id
- pub pre_seed: String,
- /// The seed price id
- pub seed: String,
- /// The series-a price id
- pub series_a: String,
-}
-
-impl From<Environment> for TeamStripePriceIds {
- fn from(value: Environment) -> Self {
- // SAFETY: stripe price ids are not sensitive information so hard coding them here is simpler
- match value {
- Environment::Production => Self {
- idea: "price_1TX2JjJaD7zvQeOBv2MDjxUC".to_string(),
- pre_seed: "price_1TX2K5JaD7zvQeOBKbFKDQZr".to_string(),
- seed: "price_1TX2KJJaD7zvQeOBJljvtVoL".to_string(),
- series_a: "price_1TX2KVJaD7zvQeOByIRkVPdS".to_string(),
- },
- Environment::Develop | Environment::Local => Self {
- idea: "price_1TX2GiJaD7zvQeOBACos6om2".to_string(),
- pre_seed: "price_1TX2GxJaD7zvQeOBgueJpOTi".to_string(),
- seed: "price_1TX2HDJaD7zvQeOBXl4Xlc0c".to_string(),
- series_a: "price_1TX2HUJaD7zvQeOBMWwI4FFK".to_string(),
- },
- }
+/// Grab the stripe product price id using the environment
+fn get_stripe_price_id_from_environment(environment: Environment) -> String {
+ // SAFETY: stripe price ids are not sensitive information so hard coding them here is simpler
+ match environment {
+ Environment::Production => "price_1TZY5FJaD7zvQeOBMldBpUHg".to_string(),
+ Environment::Develop | Environment::Local => "price_1TZY5uJaD7zvQeOBRu9a5v8P".to_string(),
}
}
@@ -218,7 +195,7 @@ impl Config {
let legacy_stripe_price_ids = LegacyStripePriceIds::new()?;
- let team_stripe_price_ids = TeamStripePriceIds::from(environment);
+ let stripe_price_id = get_stripe_price_id_from_environment(environment);
Ok(Config {
base_url,
@@ -252,7 +229,7 @@ impl Config {
posthog_api_key,
posthog_host,
legacy_stripe_price_ids,
- team_stripe_price_ids,
+ stripe_price_id,
})
}
}
diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rs
index e7f676221a..fed2c79987 100644
--- a/rust/cloud-storage/authentication_service/src/main.rs
+++ b/rust/cloud-storage/authentication_service/src/main.rs
@@ -241,29 +241,8 @@ async fn main() -> anyhow::Result<()> {
);
let teams_repo_impl = TeamRepositoryImpl::new(db.clone());
- let customer_repo_impl = CustomerRepositoryImpl::new(
- stripe_client.clone(),
- teams::outbound::customer_repo::TeamStripePriceIds {
- idea: config.team_stripe_price_ids.idea,
- pre_seed: config.team_stripe_price_ids.pre_seed,
- seed: config.team_stripe_price_ids.seed,
- series_a: config.team_stripe_price_ids.series_a,
- },
- teams::outbound::customer_repo::LegacyStripePriceIds {
- haiku: config
- .legacy_stripe_price_ids
- .stripe_price_id_haiku
- .to_string(),
- sonnet: config
- .legacy_stripe_price_ids
- .stripe_price_id_sonnet
- .to_string(),
- opus: config
- .legacy_stripe_price_ids
- .stripe_price_id_opus
- .to_string(),
- },
- );
+ let customer_repo_impl =
+ CustomerRepositoryImpl::new(stripe_client.clone(), config.stripe_price_id.clone());
let team_channels_repo_impl = TeamChannelsRepositoryImpl::new(db.clone());
let notification_ingress_service = Arc::new(notification_ingress_service);
@@ -344,6 +323,7 @@ async fn main() -> anyhow::Result<()> {
}),
analytics_client: Arc::new(analytics_client),
legacy_stripe_price_ids: config.legacy_stripe_price_ids,
+ stripe_price_id: config.stripe_price_id,
},
config.port,
)
diff --git a/rust/cloud-storage/teams/src/domain/customer_repo.rs b/rust/cloud-storage/teams/src/domain/customer_repo.rs
index 7d8945a427..008dd81099 100644
--- a/rust/cloud-storage/teams/src/domain/customer_repo.rs
+++ b/rust/cloud-storage/teams/src/domain/customer_repo.rs
@@ -2,9 +2,7 @@
use macro_user_id::user_id::MacroUserIdStr;
-use crate::domain::model::{
- CreateSubscriptionArgs, CustomerError, TeamCheckoutSessionRequest, TeamPlan,
-};
+use crate::domain::model::CustomerError;
/// The CustomerRepository defines a set of actions to perform on customer data
pub trait CustomerRepository: Clone + Send + Sync + 'static {
@@ -22,33 +20,25 @@ pub trait CustomerRepository: Clone + Send + Sync + 'static {
customer_id: &stripe::CustomerId,
) -> impl Future<Output = Result<stripe::SubscriptionId, CustomerError>> + Send;
- /// Create a new subscription for a customer
- fn create_subscription(
- &self,
- args: CreateSubscriptionArgs,
- ) -> impl Future<Output = Result<stripe::SubscriptionId, CustomerError>> + Send;
-
- /// Cancels a subscription immediately.
- fn cancel_subscription(
+ /// Increment the seat count on a subscription by the provided amount.
+ fn increment_seat_count(
&self,
subscription_id: &stripe::SubscriptionId,
+ amount: u64,
) -> impl Future<Output = Result<(), CustomerError>> + Send;
- /// Update the plan for the team
- fn update_team_plan(
+ /// Decrement the seat count on a subscription by the provided amount.
+ ///
+ /// Implementations must not let the resulting seat count drop below one.
+ fn decrement_seat_count(
&self,
subscription_id: &stripe::SubscriptionId,
- current_team_plan: Option<TeamPlan>,
- team_plan: TeamPlan,
+ amount: u64,
) -> impl Future<Output = Result<(), CustomerError>> + Send;
- /// Creates the team plan checkout session
- /// Returns the checkout url
- fn create_team_checkout_session(
+ /// Cancels a subscription immediately.
+ fn cancel_subscription(
&self,
- team_id: &uuid::Uuid,
- customer_id: stripe::CustomerId,
- req: &TeamCheckoutSessionRequest,
- has_trialed: bool,
- ) -> impl Future<Output = Result<String, CustomerError>> + Send;
+ subscription_id: &stripe::SubscriptionId,
+ ) -> impl Future<Output = Result<(), CustomerError>> + Send;
}
diff --git a/rust/cloud-storage/teams/src/domain/model.rs b/rust/cloud-storage/teams/src/domain/model.rs
index 56b7629a30..e1670f54ad 100644
--- a/rust/cloud-storage/teams/src/domain/model.rs
+++ b/rust/cloud-storage/teams/src/domain/model.rs
@@ -430,6 +430,9 @@ pub enum CustomerError {
/// Invalid promotion code
#[error("Invalid promotion code {0}")]
InvalidPromotionCode(String),
+ /// No subscription line item matched the configured Stripe price id.
+ #[error("No matching line item")]
+ NoMatchingLineItem,
/// Storage layer error
#[error("Storage layer error {0}")]
StorageLayerError(#[from] anyhow::Error),
diff --git a/rust/cloud-storage/teams/src/domain/team_repo.rs b/rust/cloud-storage/teams/src/domain/team_repo.rs
index 9e92536e52..e92efef31e 100644
--- a/rust/cloud-storage/teams/src/domain/team_repo.rs
+++ b/rust/cloud-storage/teams/src/domain/team_repo.rs
@@ -9,10 +9,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,
- TeamCheckoutError, TeamCheckoutSessionRequest, TeamError, TeamInvite, TeamInviteDetails,
- TeamMember, TeamMembers, TeamPlan, TeamRole, TeamWithMembers,
+ PatchTeamRequest, RemoveTeamInviteError, RemoveUserFromTeamError,
+ RestorePermissionsForTeamMembersError, RevokePermissionsForTeamMembersError, Team, TeamError,
+ TeamInvite, TeamInviteDetails, TeamMember, TeamMembers, TeamPlan, TeamRole, TeamWithMembers,
};
/// The TeamChannelsRepository defines a set of actions related to team channels
@@ -360,20 +359,4 @@ pub trait TeamService: Clone + Send + Sync + 'static {
) -> impl Future<
Output = Result<HashSet<roles_and_permissions::domain::model::PermissionId>, TeamError>,
> + Send;
-
- /// Updates the teams plan
- fn update_team_plan(
- &self,
- 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 49a3ce254b..fa017bcd4a 100644
--- a/rust/cloud-storage/teams/src/domain/team_service.rs
+++ b/rust/cloud-storage/teams/src/domain/team_service.rs
@@ -26,10 +26,10 @@ use crate::domain::{
customer_repo::CustomerRepository,
model::{
CreateTeamError, CustomerError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError,
- PatchTeamPlanRequest, PatchTeamRequest, RemoveTeamInviteError, RemoveUserFromTeamError,
+ PatchTeamRequest, RemoveTeamInviteError, RemoveUserFromTeamError,
RestorePermissionsForTeamMembersError, RevokePermissionsForTeamMembersError, Team,
- TeamCheckoutError, TeamCheckoutSessionRequest, TeamError, TeamInvite, TeamInviteDetails,
- TeamMember, TeamMembers, TeamPlan, TeamRole, TeamWithMembers,
+ TeamError, TeamInvite, TeamInviteDetails, TeamMember, TeamMembers, TeamRole,
+ TeamWithMembers,
},
team_repo::{TeamChannelsRepository, TeamMembersService, TeamRepository, TeamService},
};
@@ -214,11 +214,19 @@ enum GetTeamSubscriptionError {
}
impl GetTeamSubscriptionError {
- fn into_team_error(self) -> TeamError {
+ fn into_join_team_error(self) -> JoinTeamError {
match self {
- Self::Team(e) => e,
- Self::Customer(e) => TeamError::StorageLayerError(e.into()),
- Self::Storage(e) => TeamError::StorageLayerError(e),
+ Self::Team(e) => JoinTeamError::TeamError(e),
+ Self::Customer(e) => JoinTeamError::CustomerError(e),
+ Self::Storage(e) => JoinTeamError::StorageLayerError(e),
+ }
+ }
+
+ fn into_remove_user_from_team_error(self) -> RemoveUserFromTeamError {
+ match self {
+ Self::Team(e) => RemoveUserFromTeamError::TeamError(e),
+ Self::Customer(e) => RemoveUserFromTeamError::CustomerError(e),
+ Self::Storage(e) => RemoveUserFromTeamError::StorageLayerError(e),
}
}
}
@@ -372,23 +380,114 @@ where
let team_id =
macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();
- self.team_repository
+ let removed_member = self
+ .team_repository
.remove_user_from_team(&team_id, user_id)
.await?;
- self.team_channels_repository
+ let subscription_id = match self.get_team_subscription(&team_id).await {
+ Ok(subscription_id) => subscription_id,
+ Err(e) => {
+ self.team_repository
+ .rollback_remove_user_from_team(&removed_member)
+ .await
+ .inspect_err(|rollback_err| {
+ tracing::error!(
+ error=?rollback_err,
+ "unable to rollback removed team member after getting team subscription failed"
+ );
+ })
+ .ok();
+ return Err(e.into_remove_user_from_team_error());
+ }
+ };
+
+ if let Err(e) = self
+ .customer_repository
+ .decrement_seat_count(&subscription_id, 1)
+ .await
+ {
+ self.team_repository
+ .rollback_remove_user_from_team(&removed_member)
+ .await
+ .inspect_err(|rollback_err| {
+ tracing::error!(
+ error=?rollback_err,
+ "unable to rollback removed team member after decrementing seat count failed"
+ );
+ })
+ .ok();
+ return Err(RemoveUserFromTeamError::CustomerError(e));
+ }
+
+ if let Err(e) = self
+ .team_channels_repository
.remove_team_member_from_channels(&team_id, user_id)
- .await?;
+ .await
+ {
+ self.customer_repository
+ .increment_seat_count(&subscription_id, 1)
+ .await
+ .inspect_err(|rollback_err| {
+ tracing::error!(
+ error=?rollback_err,
+ "unable to rollback customer seat count after removing team member from channels failed"
+ );
+ })
+ .ok();
+ self.team_repository
+ .rollback_remove_user_from_team(&removed_member)
+ .await
+ .inspect_err(|rollback_err| {
+ tracing::error!(
+ error=?rollback_err,
+ "unable to rollback removed team member after removing team member from channels failed"
+ );
+ })
+ .ok();
+ return Err(RemoveUserFromTeamError::TeamError(e));
+ }
let roles_to_remove = vec![RoleId::TeamSubscriber, RoleId::SubOpus];
+ let roles = non_empty::NonEmpty::new(roles_to_remove.as_slice()).unwrap();
- self.user_roles_and_permissions_service
- .dangerous_remove_roles_from_user(
- user_id,
- &non_empty::NonEmpty::new(roles_to_remove.as_slice()).unwrap(),
- )
+ if let Err(e) = self
+ .user_roles_and_permissions_service
+ .dangerous_remove_roles_from_user(user_id, &roles)
.await
- .map_err(RemoveUserFromTeamError::RemoveRolesFromUserError)?;
+ {
+ self.team_channels_repository
+ .add_team_member_to_channels(&team_id, user_id)
+ .await
+ .inspect_err(|rollback_err| {
+ tracing::error!(
+ error=?rollback_err,
+ "unable to rollback team channel membership after removing team member roles failed"
+ );
+ })
+ .ok();
+ self.customer_repository
+ .increment_seat_count(&subscription_id, 1)
+ .await
+ .inspect_err(|rollback_err| {
+ tracing::error!(
+ error=?rollback_err,
+ "unable to rollback customer seat count after removing team member roles failed"
+ );
+ })
+ .ok();
+ self.team_repository
+ .rollback_remove_user_from_team(&removed_member)
+ .await
+ .inspect_err(|rollback_err| {
+ tracing::error!(
+ error=?rollback_err,
+ "unable to rollback removed team member after removing team member roles failed"
+ );
+ })
+ .ok();
+ return Err(RemoveUserFromTeamError::RemoveRolesFromUserError(e));
+ }
// Best-effort: ask the email service to tear down CRM rows
// sourced from this user's email link. Log and swallow failures
@@ -515,18 +614,111 @@ where
let team_member = accepted_invite.member.clone();
+ let subscription_id = match self.get_team_subscription(&team_member.team_id).await {
+ Ok(subscription_id) => subscription_id,
+ Err(e) => {
+ self.team_repository
+ .rollback_accept_team_invite(&accepted_invite)
+ .await
+ .inspect_err(|rollback_err| {
+ tracing::error!(
+ error=?rollback_err,
+ "unable to rollback accepted team invite after getting team subscription failed"
+ );
+ })
+ .ok();
+ return Err(e.into_join_team_error());
+ }
+ };
+
+ if let Err(e) = self
+ .customer_repository
+ .increment_seat_count(&subscription_id, 1)
+ .await
+ {
+ self.team_repository
+ .rollback_accept_team_invite(&accepted_invite)
+ .await
+ .inspect_err(|rollback_err| {
+ tracing::error!(
+ error=?rollback_err,
+ "unable to rollback accepted team invite after incrementing seat count failed"
+ );
+ })
+ .ok();
+ return Err(JoinTeamError::CustomerError(e));
+ }
+
// subscribe the user to professional features from the TeamSubscriber role and the role associated with their tier
let roles_to_add = vec![RoleId::TeamSubscriber, RoleId::SubOpus];
let roles = non_empty::NonEmpty::new(roles_to_add.as_slice()).unwrap();
- self.user_roles_and_permissions_service
+ if let Err(e) = self
+ .user_roles_and_permissions_service
.dangerous_upsert_roles_for_user(user_id, roles)
.await
- .map_err(JoinTeamError::AddRolesToUserError)?;
+ {
+ self.customer_repository
+ .decrement_seat_count(&subscription_id, 1)
+ .await
+ .inspect_err(|rollback_err| {
+ tracing::error!(
+ error=?rollback_err,
+ "unable to rollback customer seat count after adding team member roles failed"
+ );
+ })
+ .ok();
+ self.team_repository
+ .rollback_accept_team_invite(&accepted_invite)
+ .await
+ .inspect_err(|rollback_err| {
+ tracing::error!(
+ error=?rollback_err,
+ "unable to rollback accepted team invite after adding team member roles failed"
+ );
+ })
+ .ok();
+ return Err(JoinTeamError::AddRolesToUserError(e));
+ }
- self.team_channels_repository
+ if let Err(e) = self
+ .team_channels_repository
.add_team_member_to_channels(&team_member.team_id, user_id)
- .await?;
+ .await
+ {
+ let roles = non_empty::NonEmpty::new(roles_to_add.as_slice()).unwrap();
+ self.user_roles_and_permissions_service
+ .dangerous_remove_roles_from_user(user_id, &roles)
+ .await
+ .inspect_err(|rollback_err| {
+ tracing::error!(
+ error=?rollback_err,
+ "unable to rollback team member roles after adding team member to channels failed"
+ );
+ })
+ .ok();
+ self.customer_repository
+ .decrement_seat_count(&subscription_id, 1)
+ .await
+ .inspect_err(|rollback_err| {
+ tracing::error!(
+ error=?rollback_err,
+ "unable to rollback customer seat count after adding team member to channels failed"
+ );
+ })
+ .ok();
+ self.team_repository
+ .rollback_accept_team_invite(&accepted_invite)
+ .await
+ .inspect_err(|rollback_err| {
+ tracing::error!(
+ error=?rollback_err,
+ "unable to rollback accepted team invite after adding team member to channels failed"
+ );
+ })
+ .ok();
+ return Err(JoinTeamError::TeamError(e));
+ }
// Best-effort: ask the email service to seed CRM tables from this
// user's historical sent mail. Log and swallow failures — the join
@@ -681,113 +873,4 @@ where
.await
.map_err(|e| TeamError::StorageLayerError(e.into()))
}
-
- #[tracing::instrument(skip(self), err)]
- async fn update_team_plan(
- &self,
- entity_access_receipt: EntityAccessReceipt<OwnerTeamRole>,
- req: &PatchTeamPlanRequest,
- ) -> Result<(), TeamError> {
- let team_id =
- macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();
-
- let new_team_plan = req.team_plan;
-
- // Ensure the user isn't trying to upgrade to growth plan
- if new_team_plan == TeamPlan::Growth {
- return Err(TeamError::BadRequest(
- "cannot upgrade to growth plan automatically".to_string(),
- ));
- }
-
- let team_seat_count = self.team_repository.get_team_seat_count(&team_id).await?;
-
- let current_team_plan = self.team_repository.get_team_plan(&team_id).await?;
-
- // Check if plans are equal
- if let Some(current_team_plan) = current_team_plan
- && new_team_plan == current_team_plan
- {
- return Err(TeamError::BadRequest(
- "cannot change plan to same plan.".to_string(),
- ));
- }
-
- // Check if the user has the seat capacity to downgrade
- if team_seat_count > new_team_plan.seat_cap() {
- return Err(TeamError::BadRequest(
- "you have too many members to downgrade to this plan".to_string(),
- ));
- }
-
- let subscription_id = match self.get_team_subscription(&team_id).await {
- Ok(subscription_id) => subscription_id,
- Err(e) => return Err(e.into_team_error()),
- };
-
- // Bump plan in db
- self.team_repository
- .patch_team_plan(&team_id, new_team_plan)
- .await?;
-
- if let Err(e) = self
- .customer_repository
- .update_team_plan(&subscription_id, current_team_plan, new_team_plan)
- .await
- {
- if let Some(team_plan) = current_team_plan {
- self.team_repository
- .patch_team_plan(&team_id, team_plan)
- .await?;
- }
- return Err(TeamError::StorageLayerError(e.into()));
- }
-
- 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 has_trialed = self.team_repository.has_user_trialed(user_id).await?;
-
- 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, has_trialed)
- .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 dc05c5494c..7295a9690c 100644
--- a/rust/cloud-storage/teams/src/domain/team_service/test.rs
+++ b/rust/cloud-storage/teams/src/domain/team_service/test.rs
@@ -37,9 +37,9 @@ use super::*;
use crate::domain::{
customer_repo::CustomerRepository,
model::{
- AcceptedTeamInvite, CreateSubscriptionArgs, CustomerError, PatchTeamRequest,
- PatchTeamUserRole, RemoveTeamInviteError, RemoveUserFromTeamError, Team, TeamError,
- TeamInvite, TeamInviteDetails, TeamMember, TeamPlan, TeamRole, TeamWithMembers,
+ AcceptedTeamInvite, CustomerError, PatchTeamRequest, PatchTeamUserRole,
+ RemoveTeamInviteError, RemoveUserFromTeamError, Team, TeamError, TeamInvite,
+ TeamInviteDetails, TeamInviteSnapshot, TeamMember, TeamPlan, TeamRole, TeamWithMembers,
},
team_repo::{TeamChannelsRepository, TeamRepository},
};
@@ -385,7 +385,25 @@ impl TeamRepository for MockTeamRepository {
// -- Mock CustomerRepository --
#[derive(Clone)]
-struct MockCustomerRepository;
+struct MockCustomerRepository {
+ subscription_id: stripe::SubscriptionId,
+ increment_calls: Arc<Mutex<Vec<(String, u64)>>>,
+ decrement_calls: Arc<Mutex<Vec<(String, u64)>>>,
+ fail_increment: bool,
+ fail_decrement: bool,
+}
+
+impl Default for MockCustomerRepository {
+ fn default() -> Self {
+ Self {
+ subscription_id: "sub_test".parse().unwrap(),
+ increment_calls: Arc::new(Mutex::new(Vec::new())),
+ decrement_calls: Arc::new(Mutex::new(Vec::new())),
+ fail_increment: false,
+ fail_decrement: false,
+ }
+ }
+}
impl CustomerRepository for MockCustomerRepository {
fn convert_subscription_to_team(
@@ -401,70 +419,123 @@ impl CustomerRepository for MockCustomerRepository {
&self,
_: &stripe::CustomerId,
) -> impl Future<Output = Result<stripe::SubscriptionId, CustomerError>> + Send {
- async { unimplemented!() }
- }
-
- fn create_subscription(
- &self,
- _: CreateSubscriptionArgs,
- ) -> impl Future<Output = Result<stripe::SubscriptionId, CustomerError>> + Send {
- async { unimplemented!() }
+ let subscription_id = self.subscription_id.clone();
+ async move { Ok(subscription_id) }
}
- fn cancel_subscription(
+ fn increment_seat_count(
&self,
- _: &stripe::SubscriptionId,
+ subscription_id: &stripe::SubscriptionId,
+ amount: u64,
) -> impl Future<Output = Result<(), CustomerError>> + Send {
- async { unimplemented!() }
+ self.increment_calls
+ .lock()
+ .unwrap()
+ .push((subscription_id.to_string(), amount));
+ let fail = self.fail_increment;
+ async move {
+ if fail {
+ Err(CustomerError::StorageLayerError(anyhow::anyhow!(
+ "increment failed"
+ )))
+ } else {
+ Ok(())
+ }
+ }
}
- fn update_team_plan(
+ fn decrement_seat_count(
&self,
- _subscription_id: &stripe::SubscriptionId,
- _current_team_plan: Option<TeamPlan>,
- _team_plan: TeamPlan,
+ subscription_id: &stripe::SubscriptionId,
+ amount: u64,
) -> impl Future<Output = Result<(), CustomerError>> + Send {
- async { unimplemented!() }
+ self.decrement_calls
+ .lock()
+ .unwrap()
+ .push((subscription_id.to_string(), amount));
+ let fail = self.fail_decrement;
+ async move {
+ if fail {
+ Err(CustomerError::StorageLayerError(anyhow::anyhow!(
+ "decrement failed"
+ )))
+ } else {
+ Ok(())
+ }
+ }
}
- fn create_team_checkout_session(
+ fn cancel_subscription(
&self,
- _team_id: &uuid::Uuid,
- _customer_id: stripe::CustomerId,
- _req: &TeamCheckoutSessionRequest,
- _has_trialed: bool,
- ) -> impl Future<Output = Result<String, CustomerError>> + Send {
+ _: &stripe::SubscriptionId,
+ ) -> impl Future<Output = Result<(), CustomerError>> + Send {
async { unimplemented!() }
}
}
// -- Mock TeamChannelsRepository --
-#[derive(Clone)]
-struct MockTeamChannelsRepository;
+#[derive(Clone, Default)]
+struct MockTeamChannelsRepository {
+ add_calls: Arc<Mutex<Vec<(uuid::Uuid, String)>>>,
+ remove_calls: Arc<Mutex<Vec<(uuid::Uuid, String)>>>,
+ fail_add: bool,
+ fail_remove: bool,
+}
impl TeamChannelsRepository for MockTeamChannelsRepository {
fn add_team_member_to_channels(
&self,
- _: &uuid::Uuid,
- _: &MacroUserIdStr<'_>,
+ team_id: &uuid::Uuid,
+ user_id: &MacroUserIdStr<'_>,
) -> impl Future<Output = Result<(), TeamError>> + Send {
- async { unimplemented!() }
+ self.add_calls
+ .lock()
+ .unwrap()
+ .push((*team_id, user_id.as_ref().to_string()));
+ let fail = self.fail_add;
+ async move {
+ if fail {
+ Err(TeamError::StorageLayerError(anyhow::anyhow!(
+ "add channels failed"
+ )))
+ } else {
+ Ok(())
+ }
+ }
}
fn remove_team_member_from_channels(
&self,
- _: &uuid::Uuid,
- _: &MacroUserIdStr<'_>,
+ team_id: &uuid::Uuid,
+ user_id: &MacroUserIdStr<'_>,
) -> impl Future<Output = Result<(), TeamError>> + Send {
- async { unimplemented!() }
+ self.remove_calls
+ .lock()
+ .unwrap()
+ .push((*team_id, user_id.as_ref().to_string()));
+ let fail = self.fail_remove;
+ async move {
+ if fail {
+ Err(TeamError::StorageLayerError(anyhow::anyhow!(
+ "remove channels failed"
+ )))
+ } else {
+ Ok(())
+ }
+ }
}
}
// -- Mock UserRolesAndPermissionsService --
-#[derive(Clone)]
-struct MockUserRolesAndPermissionsService;
+#[derive(Clone, Default)]
+struct MockUserRolesAndPermissionsService {
+ upsert_calls: Arc<Mutex<Vec<(String, Vec<RoleId>)>>>,
+ remove_calls: Arc<Mutex<Vec<(String, Vec<RoleId>)>>>,
+ fail_upsert: bool,
+ fail_remove: bool,
+}
impl UserRolesAndPermissionsService for MockUserRolesAndPermissionsService {
fn get_user_roles(
@@ -493,18 +564,44 @@ impl UserRolesAndPermissionsService for MockUserRolesAndPermissionsService {
fn dangerous_upsert_roles_for_user(
&self,
- _: &MacroUserIdStr<'_>,
- _: non_empty::NonEmpty<&[RoleId]>,
+ user_id: &MacroUserIdStr<'_>,
+ role_ids: non_empty::NonEmpty<&[RoleId]>,
) -> impl Future<Output = Result<(), UserRolesAndPermissionsError>> + Send {
- async { unimplemented!() }
+ self.upsert_calls
+ .lock()
+ .unwrap()
+ .push((user_id.as_ref().to_string(), role_ids.inner().to_vec()));
+ let fail = self.fail_upsert;
+ async move {
+ if fail {
+ Err(UserRolesAndPermissionsError::StorageLayerError(
+ anyhow::anyhow!("upsert roles failed"),
+ ))
+ } else {
+ Ok(())
+ }
+ }
}
fn dangerous_remove_roles_from_user(
&self,
- _: &MacroUserIdStr<'_>,
- _: &non_empty::NonEmpty<&[RoleId]>,
+ user_id: &MacroUserIdStr<'_>,
+ role_ids: &non_empty::NonEmpty<&[RoleId]>,
) -> impl Future<Output = Result<(), UserRolesAndPermissionsError>> + Send {
- async { unimplemented!() }
+ self.remove_calls
+ .lock()
+ .unwrap()
+ .push((user_id.as_ref().to_string(), role_ids.inner().to_vec()));
+ let fail = self.fail_remove;
+ async move {
+ if fail {
+ Err(UserRolesAndPermissionsError::StorageLayerError(
+ anyhow::anyhow!("remove roles failed"),
+ ))
+ } else {
+ Ok(())
+ }
+ }
}
}
@@ -567,6 +664,34 @@ fn make_invite(email: &str, invite_id: uuid::Uuid, team_id: uuid::Uuid) -> TeamI
}
}
+fn make_accepted_invite(
+ team_id: uuid::Uuid,
+ invite_id: uuid::Uuid,
+ user_id: &MacroUserIdStr<'_>,
+) -> AcceptedTeamInvite<'static> {
+ AcceptedTeamInvite {
+ member: TeamMember {
+ team_id,
+ user_id: user_id.clone().into_owned(),
+ role: TeamRole::Member,
+ },
+ invite: TeamInviteSnapshot {
+ id: invite_id,
+ team_id,
+ email: Email::parse_from_str(user_id.email_part().as_ref())
+ .unwrap()
+ .into_owned()
+ .lowercase(),
+ team_role: TeamRole::Member,
+ invited_by: MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned(),
+ created_at: chrono::Utc::now(),
+ last_sent_at: chrono::Utc::now(),
+ },
+ }
+}
+
fn build_service(
invites: Vec<TeamInvite<'static>>,
fail_indices: HashSet<usize>,
@@ -576,9 +701,9 @@ fn build_service(
let notification_ingress = Arc::new(MockNotificationIngress::new(fail_indices));
let service = TeamServiceImpl::new(
team_repo,
- MockCustomerRepository,
- MockTeamChannelsRepository,
- MockUserRolesAndPermissionsService,
+ MockCustomerRepository::default(),
+ MockTeamChannelsRepository::default(),
+ MockUserRolesAndPermissionsService::default(),
notification_ingress.clone(),
NoOpCrmEnqueuer,
);
@@ -735,9 +860,9 @@ fn build_service_with_team(
let notification_ingress = Arc::new(MockNotificationIngress::new(HashSet::new()));
let service = TeamServiceImpl::new(
team_repo,
- MockCustomerRepository,
- MockTeamChannelsRepository,
- MockUserRolesAndPermissionsService,
+ MockCustomerRepository::default(),
+ MockTeamChannelsRepository::default(),
+ MockUserRolesAndPermissionsService::default(),
notification_ingress,
NoOpCrmEnqueuer,
);
@@ -906,3 +1031,325 @@ async fn test_patch_team_empty_role_updates() {
assert_eq!(name_calls.len(), 1);
assert_eq!(name_calls[0], (team_id, Some("New Name".to_string()), None));
}
+
+#[tokio::test]
+async fn test_join_team_increments_customer_seat_count() {
+ let team_id = uuid::Uuid::from_u128(1);
+ let invite_id = uuid::Uuid::from_u128(2);
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let subscription_id: stripe::SubscriptionId = "sub_test".parse().unwrap();
+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));
+
+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls);
+ team_repo.accepted_invite = Some(make_accepted_invite(team_id, invite_id, &user_id));
+ team_repo.team_subscription_id = Some(subscription_id.clone());
+ let rollback_accept_calls = team_repo.rollback_accept_calls.clone();
+
+ let customer_repo = MockCustomerRepository {
+ subscription_id: subscription_id.clone(),
+ ..Default::default()
+ };
+ let increment_calls = customer_repo.increment_calls.clone();
+ let decrement_calls = customer_repo.decrement_calls.clone();
+
+ let channels_repo = MockTeamChannelsRepository::default();
+ let add_channel_calls = channels_repo.add_calls.clone();
+ let roles_service = MockUserRolesAndPermissionsService::default();
+ let upsert_role_calls = roles_service.upsert_calls.clone();
+
+ let service = TeamServiceImpl::new(
+ team_repo,
+ customer_repo,
+ channels_repo,
+ roles_service,
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ NoOpCrmEnqueuer,
+ );
+
+ service.join_team(&invite_id, &user_id).await.unwrap();
+
+ assert_eq!(
+ *increment_calls.lock().unwrap(),
+ vec![(subscription_id.to_string(), 1)]
+ );
+ assert!(decrement_calls.lock().unwrap().is_empty());
+ assert_eq!(*rollback_accept_calls.lock().unwrap(), 0);
+ assert_eq!(
+ *add_channel_calls.lock().unwrap(),
+ vec![(team_id, user_id.as_ref().to_string())]
+ );
+ assert_eq!(upsert_role_calls.lock().unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn test_join_team_rolls_back_accept_when_customer_increment_fails() {
+ let team_id = uuid::Uuid::from_u128(1);
+ let invite_id = uuid::Uuid::from_u128(2);
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let subscription_id: stripe::SubscriptionId = "sub_test".parse().unwrap();
+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));
+
+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls);
+ team_repo.accepted_invite = Some(make_accepted_invite(team_id, invite_id, &user_id));
+ team_repo.team_subscription_id = Some(subscription_id.clone());
+ let rollback_accept_calls = team_repo.rollback_accept_calls.clone();
+
+ let customer_repo = MockCustomerRepository {
+ subscription_id: subscription_id.clone(),
+ fail_increment: true,
+ ..Default::default()
+ };
+ let increment_calls = customer_repo.increment_calls.clone();
+ let channels_repo = MockTeamChannelsRepository::default();
+ let add_channel_calls = channels_repo.add_calls.clone();
+ let roles_service = MockUserRolesAndPermissionsService::default();
+ let upsert_role_calls = roles_service.upsert_calls.clone();
+
+ let service = TeamServiceImpl::new(
+ team_repo,
+ customer_repo,
+ channels_repo,
+ roles_service,
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ NoOpCrmEnqueuer,
+ );
+
+ let err = service.join_team(&invite_id, &user_id).await.err().unwrap();
+
+ assert!(matches!(err, JoinTeamError::CustomerError(_)));
+ assert_eq!(
+ *increment_calls.lock().unwrap(),
+ vec![(subscription_id.to_string(), 1)]
+ );
+ assert_eq!(*rollback_accept_calls.lock().unwrap(), 1);
+ assert!(add_channel_calls.lock().unwrap().is_empty());
+ assert!(upsert_role_calls.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn test_remove_user_from_team_decrements_customer_seat_count() {
+ let team_id = uuid::Uuid::from_u128(1);
+ let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let member_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let subscription_id: stripe::SubscriptionId = "sub_test".parse().unwrap();
+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));
+
+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls);
+ team_repo.removed_member = Some(TeamMember {
+ team_id,
+ user_id: member_id.clone().into_owned(),
+ role: TeamRole::Member,
+ });
+ team_repo.team_subscription_id = Some(subscription_id.clone());
+ let rollback_remove_calls = team_repo.rollback_remove_calls.clone();
+
+ let customer_repo = MockCustomerRepository {
+ subscription_id: subscription_id.clone(),
+ ..Default::default()
+ };
+ let increment_calls = customer_repo.increment_calls.clone();
+ let decrement_calls = customer_repo.decrement_calls.clone();
+
+ let channels_repo = MockTeamChannelsRepository::default();
+ let remove_channel_calls = channels_repo.remove_calls.clone();
+ let roles_service = MockUserRolesAndPermissionsService::default();
+ let remove_role_calls = roles_service.remove_calls.clone();
+
+ let service = TeamServiceImpl::new(
+ team_repo,
+ customer_repo,
+ channels_repo,
+ roles_service,
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ NoOpCrmEnqueuer,
+ );
+
+ service
+ .remove_user_from_team(
+ test_team_receipt::<OwnerTeamRole>(team_id, &owner_id),
+ &member_id,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ *decrement_calls.lock().unwrap(),
+ vec![(subscription_id.to_string(), 1)]
+ );
+ assert!(increment_calls.lock().unwrap().is_empty());
+ assert_eq!(*rollback_remove_calls.lock().unwrap(), 0);
+ assert_eq!(
+ *remove_channel_calls.lock().unwrap(),
+ vec![(team_id, member_id.as_ref().to_string())]
+ );
+ assert_eq!(remove_role_calls.lock().unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn test_remove_user_from_team_rolls_back_remove_when_customer_decrement_fails() {
+ let team_id = uuid::Uuid::from_u128(1);
+ let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let member_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let subscription_id: stripe::SubscriptionId = "sub_test".parse().unwrap();
+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));
+
+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls);
+ team_repo.removed_member = Some(TeamMember {
+ team_id,
+ user_id: member_id.clone().into_owned(),
+ role: TeamRole::Member,
+ });
+ team_repo.team_subscription_id = Some(subscription_id.clone());
+ let rollback_remove_calls = team_repo.rollback_remove_calls.clone();
+
+ let customer_repo = MockCustomerRepository {
+ subscription_id: subscription_id.clone(),
+ fail_decrement: true,
+ ..Default::default()
+ };
+ let decrement_calls = customer_repo.decrement_calls.clone();
+ let channels_repo = MockTeamChannelsRepository::default();
+ let remove_channel_calls = channels_repo.remove_calls.clone();
+ let roles_service = MockUserRolesAndPermissionsService::default();
+ let remove_role_calls = roles_service.remove_calls.clone();
+
+ let service = TeamServiceImpl::new(
+ team_repo,
+ customer_repo,
+ channels_repo,
+ roles_service,
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ NoOpCrmEnqueuer,
+ );
+
+ let err = service
+ .remove_user_from_team(
+ test_team_receipt::<OwnerTeamRole>(team_id, &owner_id),
+ &member_id,
+ )
+ .await
+ .err()
+ .unwrap();
+
+ assert!(matches!(err, RemoveUserFromTeamError::CustomerError(_)));
+ assert_eq!(
+ *decrement_calls.lock().unwrap(),
+ vec![(subscription_id.to_string(), 1)]
+ );
+ assert_eq!(*rollback_remove_calls.lock().unwrap(), 1);
+ assert!(remove_channel_calls.lock().unwrap().is_empty());
+ assert!(remove_role_calls.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn test_join_team_rolls_back_customer_roles_and_accept_when_channel_add_fails() {
+ let team_id = uuid::Uuid::from_u128(1);
+ let invite_id = uuid::Uuid::from_u128(2);
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let subscription_id: stripe::SubscriptionId = "sub_test".parse().unwrap();
+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));
+
+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls);
+ team_repo.accepted_invite = Some(make_accepted_invite(team_id, invite_id, &user_id));
+ team_repo.team_subscription_id = Some(subscription_id.clone());
+ let rollback_accept_calls = team_repo.rollback_accept_calls.clone();
+
+ let customer_repo = MockCustomerRepository {
+ subscription_id: subscription_id.clone(),
+ ..Default::default()
+ };
+ let increment_calls = customer_repo.increment_calls.clone();
+ let decrement_calls = customer_repo.decrement_calls.clone();
+ let channels_repo = MockTeamChannelsRepository {
+ fail_add: true,
+ ..Default::default()
+ };
+ let roles_service = MockUserRolesAndPermissionsService::default();
+ let upsert_role_calls = roles_service.upsert_calls.clone();
+ let remove_role_calls = roles_service.remove_calls.clone();
+
+ let service = TeamServiceImpl::new(
+ team_repo,
+ customer_repo,
+ channels_repo,
+ roles_service,
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ NoOpCrmEnqueuer,
+ );
+
+ let err = service.join_team(&invite_id, &user_id).await.err().unwrap();
+
+ assert!(matches!(err, JoinTeamError::TeamError(_)));
+ assert_eq!(
+ *increment_calls.lock().unwrap(),
+ vec![(subscription_id.to_string(), 1)]
+ );
+ assert_eq!(
+ *decrement_calls.lock().unwrap(),
+ vec![(subscription_id.to_string(), 1)]
+ );
+ assert_eq!(*rollback_accept_calls.lock().unwrap(), 1);
+ assert_eq!(upsert_role_calls.lock().unwrap().len(), 1);
+ assert_eq!(remove_role_calls.lock().unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn test_remove_user_from_team_rolls_back_customer_and_remove_when_channel_remove_fails() {
+ let team_id = uuid::Uuid::from_u128(1);
+ let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let member_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let subscription_id: stripe::SubscriptionId = "sub_test".parse().unwrap();
+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));
+
+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls);
+ team_repo.removed_member = Some(TeamMember {
+ team_id,
+ user_id: member_id.clone().into_owned(),
+ role: TeamRole::Member,
+ });
+ team_repo.team_subscription_id = Some(subscription_id.clone());
+ let rollback_remove_calls = team_repo.rollback_remove_calls.clone();
+
+ let customer_repo = MockCustomerRepository {
+ subscription_id: subscription_id.clone(),
+ ..Default::default()
+ };
+ let increment_calls = customer_repo.increment_calls.clone();
+ let decrement_calls = customer_repo.decrement_calls.clone();
+ let channels_repo = MockTeamChannelsRepository {
+ fail_remove: true,
+ ..Default::default()
+ };
+ let roles_service = MockUserRolesAndPermissionsService::default();
+ let remove_role_calls = roles_service.remove_calls.clone();
+
+ let service = TeamServiceImpl::new(
+ team_repo,
+ customer_repo,
+ channels_repo,
+ roles_service,
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ NoOpCrmEnqueuer,
+ );
+
+ let err = service
+ .remove_user_from_team(
+ test_team_receipt::<OwnerTeamRole>(team_id, &owner_id),
+ &member_id,
+ )
+ .await
+ .err()
+ .unwrap();
+
+ assert!(matches!(err, RemoveUserFromTeamError::TeamError(_)));
+ assert_eq!(
+ *decrement_calls.lock().unwrap(),
+ vec![(subscription_id.to_string(), 1)]
+ );
+ assert_eq!(
+ *increment_calls.lock().unwrap(),
+ vec![(subscription_id.to_string(), 1)]
+ );
+ assert_eq!(*rollback_remove_calls.lock().unwrap(), 1);
+ assert!(remove_role_calls.lock().unwrap().is_empty());
+}
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
deleted file mode 100644
index f3a097415f..0000000000
--- a/rust/cloud-storage/teams/src/inbound/axum_router/create_team_checkout_session.rs
+++ /dev/null
@@ -1,71 +0,0 @@
-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 3377335aaf..c623c6b685 100644
--- a/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs
@@ -2,8 +2,6 @@
/// 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.
@@ -22,8 +20,6 @@ pub mod invite_to_team;
pub mod join_team;
/// Update a team.
pub mod patch_team;
-/// Update team plan.
-pub mod patch_team_plan;
/// Reject a team invitation.
pub mod reject_invitation;
/// Remove a user from a team.
@@ -90,14 +86,9 @@ where
.route("/user/invites", get(get_user_invites::handler::<T, Eas>))
.route("/", get(get_team::handler::<T, Eas>))
.route("/", patch(patch_team::handler::<T, Eas>))
- .route("/plan", patch(patch_team_plan::handler::<T, Eas>))
.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/inbound/axum_router/patch_team_plan.rs b/rust/cloud-storage/teams/src/inbound/axum_router/patch_team_plan.rs
deleted file mode 100644
index d522ab4088..0000000000
--- a/rust/cloud-storage/teams/src/inbound/axum_router/patch_team_plan.rs
+++ /dev/null
@@ -1,40 +0,0 @@
-use axum::{Json, extract::State};
-use entity_access::{
- domain::{models::OwnerTeamRole, ports::EntityAccessService},
- inbound::axum_extractors::MacroUserTeamExtractor,
-};
-use model_error_response::ErrorResponse;
-
-use crate::domain::{
- model::{PatchTeamPlanRequest, TeamError},
- team_repo::TeamService,
-};
-
-use super::TeamRouterState;
-
-/// Updates a team plan.
-#[utoipa::path(
- patch,
- path = "/team/plan",
- operation_id = "patch_team_plan",
- request_body = PatchTeamPlanRequest,
- responses(
- (status = 200),
- (status = 400, body = ErrorResponse),
- (status = 401, body = ErrorResponse),
- (status = 404, body = ErrorResponse),
- (status = 500, body = 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<PatchTeamPlanRequest>,
-) -> Result<(), TeamError> {
- state
- .service
- .update_team_plan(access.entity_access_receipt, &req)
- .await?;
- Ok(())
-}
diff --git a/rust/cloud-storage/teams/src/outbound/customer_repo.rs b/rust/cloud-storage/teams/src/outbound/customer_repo.rs
index ff835509c7..3c571820d8 100644
--- a/rust/cloud-storage/teams/src/outbound/customer_repo.rs
+++ b/rust/cloud-storage/teams/src/outbound/customer_repo.rs
@@ -3,101 +3,110 @@
use std::{collections::HashMap, sync::Arc};
use anyhow::Context;
-use stripe::{CreateSubscription, CreateSubscriptionItems, UpdateSubscription};
+use stripe::UpdateSubscription;
-use crate::domain::{
- customer_repo::CustomerRepository,
- model::{CreateSubscriptionArgs, CustomerError, TeamCheckoutSessionRequest, TeamPlan},
-};
-
-/// The stripe price ids for all tiers
-/// These are legacy stripe price ids for the old tier system
-#[derive(Clone)]
-pub struct LegacyStripePriceIds {
- /// haiku tier price id
- pub haiku: String,
- /// sonnet tier price id
- pub sonnet: String,
- /// opus tier price id
- pub opus: String,
-}
-
-/// Team plan stripe price ids
-/// Note: there is not `growth` plan price id as growth plan is white glove.
-#[derive(Clone)]
-pub struct TeamStripePriceIds {
- /// The idea price id
- pub idea: String,
- /// The pre-seed price id
- pub pre_seed: String,
- /// The seed price id
- pub seed: String,
- /// The series-a price id
- pub series_a: String,
-}
-
-impl TeamStripePriceIds {
- /// Tries to map the stripe price id for a team plan
- fn try_get_price_id_for_team_plan(&self, value: TeamPlan) -> Result<String, CustomerError> {
- let price_id = match value {
- TeamPlan::Idea => self.idea.clone(),
- TeamPlan::PreSeed => self.pre_seed.clone(),
- TeamPlan::Seed => self.seed.clone(),
- TeamPlan::SeriesA => self.series_a.clone(),
- TeamPlan::Growth => return Err(anyhow::anyhow!("no price id for growth plan").into()),
- };
-
- Ok(price_id)
- }
-}
+use crate::domain::{customer_repo::CustomerRepository, model::CustomerError};
/// The CustomerRepositoryImpl struct is a wrapper around a stripe::Client connected to stripe.
#[derive(Clone)]
pub struct CustomerRepositoryImpl {
/// The underlying stripe::Client connected to stripe.
client: Arc<stripe::Client>,
- /// The team plan stripe price ids
- team_plan_stripe_price_ids: TeamStripePriceIds,
- /// The legacy stripe price ids
- legacy_stripe_price_ids: LegacyStripePriceIds,
+ /// The stripe price id for the per-seat subscription item.
+ stripe_price_id: String,
}
impl CustomerRepositoryImpl {
/// Creates a new instance of CustomerRepositoryImpl
- pub fn new(
- stripe_client: stripe::Client,
- team_plan_stripe_price_ids: TeamStripePriceIds,
- legacy_stripe_price_ids: LegacyStripePriceIds,
- ) -> Self {
+ pub fn new(stripe_client: stripe::Client, stripe_price_id: String) -> Self {
Self {
client: Arc::new(stripe_client),
- team_plan_stripe_price_ids,
- legacy_stripe_price_ids,
+ stripe_price_id,
}
}
+
+ async fn get_seat_subscription_item(
+ &self,
+ subscription_id: &stripe::SubscriptionId,
+ ) -> Result<(String, u64), CustomerError> {
+ let subscription = stripe::Subscription::retrieve(&self.client, subscription_id, &[])
+ .await
+ .map_err(|e| CustomerError::StorageLayerError(e.into()))?;
+
+ if subscription.status != stripe::SubscriptionStatus::Active {
+ return Err(CustomerError::SubscriptionNotActive);
+ }
+
+ let item = subscription
+ .items
+ .data
+ .iter()
+ .find(|item| {
+ item.price
+ .as_ref()
+ .map(|price| price.id == self.stripe_price_id)
+ .unwrap_or(false)
+ })
+ .ok_or(CustomerError::NoMatchingLineItem)?;
+
+ Ok((item.id.to_string(), item.quantity.unwrap_or(1)))
+ }
+
+ async fn update_seat_subscription_item(
+ &self,
+ subscription_id: &stripe::SubscriptionId,
+ subscription_item_id: String,
+ quantity: u64,
+ ) -> Result<(), CustomerError> {
+ let update_params = UpdateSubscription {
+ items: Some(vec![stripe::UpdateSubscriptionItems {
+ id: Some(subscription_item_id),
+ quantity: Some(quantity),
+ ..Default::default()
+ }]),
+ proration_behavior: Some(
+ stripe::generated::billing::subscription::SubscriptionProrationBehavior::AlwaysInvoice,
+ ),
+ ..Default::default()
+ };
+
+ stripe::Subscription::update(&self.client, subscription_id, update_params)
+ .await
+ .map_err(|e| CustomerError::StorageLayerError(e.into()))?;
+
+ Ok(())
+ }
}
impl CustomerRepository for CustomerRepositoryImpl {
#[tracing::instrument(skip(self), err)]
- async fn create_subscription(
+ async fn increment_seat_count(
&self,
- args: CreateSubscriptionArgs,
- ) -> Result<stripe::SubscriptionId, CustomerError> {
- // Create the subscription
- let mut params = CreateSubscription::new(args.customer_id);
- params.items = Some(vec![CreateSubscriptionItems {
- price: Some(self.legacy_stripe_price_ids.haiku.clone()),
- quantity: Some(args.quantity),
- ..Default::default()
- }]);
-
- params.metadata = args.metadata;
+ subscription_id: &stripe::SubscriptionId,
+ amount: u64,
+ ) -> Result<(), CustomerError> {
+ let (subscription_item_id, current_quantity) =
+ self.get_seat_subscription_item(subscription_id).await?;
+ let quantity = current_quantity
+ .checked_add(amount)
+ .context("seat count overflow")?;
- let subscription = stripe::Subscription::create(&self.client, params)
+ self.update_seat_subscription_item(subscription_id, subscription_item_id, quantity)
.await
- .map_err(|e| CustomerError::StorageLayerError(e.into()))?;
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn decrement_seat_count(
+ &self,
+ subscription_id: &stripe::SubscriptionId,
+ amount: u64,
+ ) -> Result<(), CustomerError> {
+ let (subscription_item_id, current_quantity) =
+ self.get_seat_subscription_item(subscription_id).await?;
+ let quantity = current_quantity.saturating_sub(amount).max(1);
- Ok(subscription.id)
+ self.update_seat_subscription_item(subscription_id, subscription_item_id, quantity)
+ .await
}
#[tracing::instrument(skip(self), err)]
@@ -156,176 +165,4 @@ impl CustomerRepository for CustomerRepositoryImpl {
.map(|sub| sub.id)
.ok_or(CustomerError::SubscriptionNotActive)
}
-
- #[tracing::instrument(skip(self), err)]
- async fn update_team_plan(
- &self,
- subscription_id: &stripe::SubscriptionId,
- current_plan: Option<TeamPlan>,
- team_plan: TeamPlan,
- ) -> Result<(), CustomerError> {
- // Get new plan price id
- let new_plan_price_id = self
- .team_plan_stripe_price_ids
- .try_get_price_id_for_team_plan(team_plan)?;
-
- let subscription = stripe::Subscription::retrieve(&self.client, subscription_id, &[])
- .await
- .map_err(|e| CustomerError::StorageLayerError(e.into()))?;
-
- if subscription.status != stripe::SubscriptionStatus::Active {
- return Err(CustomerError::SubscriptionNotActive);
- }
-
- let mut items = Vec::with_capacity(2);
-
- if let Some(current_team_plan) = current_plan {
- let old_plan_price_id = self
- .team_plan_stripe_price_ids
- .try_get_price_id_for_team_plan(current_team_plan)?;
-
- // The old item must exist
- let old_item = subscription
- .items
- .data
- .iter()
- .find(|item| {
- item.price
- .as_ref()
- .map(|p| p.id == old_plan_price_id)
- .unwrap_or(false)
- })
- .ok_or_else(|| {
- CustomerError::StorageLayerError(anyhow::anyhow!(
- "No subscription item found for old tier {:?}",
- current_team_plan
- ))
- })?;
-
- // delete the current price id
- items.push(stripe::UpdateSubscriptionItems {
- id: Some(old_item.id.to_string()),
- deleted: Some(true),
- ..Default::default()
- });
- }
-
- // Add the new item
- items.push(stripe::UpdateSubscriptionItems {
- price: Some(new_plan_price_id.to_string()),
- quantity: Some(1),
- ..Default::default()
- });
-
- // Single atomic update — one prorated invoice for both changes
- let update_params = UpdateSubscription {
- items: Some(items),
- proration_behavior: Some(
- stripe::generated::billing::subscription::SubscriptionProrationBehavior::AlwaysInvoice,
- ),
- ..Default::default()
- };
-
- stripe::Subscription::update(&self.client, subscription_id, update_params)
- .await
- .map_err(|e| CustomerError::StorageLayerError(e.into()))?;
-
- Ok(())
- }
-
- #[tracing::instrument(skip(self), err)]
- async fn create_team_checkout_session(
- &self,
- team_id: &uuid::Uuid,
- customer_id: stripe::CustomerId,
- req: &TeamCheckoutSessionRequest,
- has_trialed: bool,
- ) -> 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());
- }
-
- let subscription_metadata = (!metadata.is_empty()).then_some(metadata);
-
- // Only set subscription_data if we have metadata or a trial to include.
- let subscription_data = (subscription_metadata.is_some() || !has_trialed).then_some(
- stripe::CreateCheckoutSessionSubscriptionData {
- metadata: subscription_metadata,
- trial_period_days: (!has_trialed).then_some(60),
- ..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)
- }
}