Skip to content

The open alternative to Salesforce, designed for AI.

feat(billing) : store the ?partner= sign-up attribution on the Stripe customer (#27836)

Etienne834620408b05
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index 5b4db26be02..c09faf57514 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -4353,6 +4353,7 @@ type SignUp {
input SignUpInNewWorkspaceInput {
displayName: String
+ partner: String
subdomain: String
}
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index b690e5304de..940828a2468 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -7435,7 +7435,7 @@ export interface SignUpGenqlSelection{
__scalar?: boolean | number
}
-export interface SignUpInNewWorkspaceInput {displayName?: (Scalars['String'] | null),subdomain?: (Scalars['String'] | null)}
+export interface SignUpInNewWorkspaceInput {displayName?: (Scalars['String'] | null),partner?: (Scalars['String'] | null),subdomain?: (Scalars['String'] | null)}
export interface SkillGenqlSelection{
applicationId?: boolean | number
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index bb11378dd0c..b5ae1061df3 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -11639,6 +11639,9 @@ export default {
"displayName": [
1
],
+ "partner": [
+ 1
+ ],
"subdomain": [
1
],
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index df1477136a3..0c0ed941ee3 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -6441,6 +6441,7 @@ export type SignUp = {
export type SignUpInNewWorkspaceInput = {
displayName?: InputMaybe<Scalars['String']['input']>;
+ partner?: InputMaybe<Scalars['String']['input']>;
subdomain?: InputMaybe<Scalars['String']['input']>;
};
diff --git a/packages/twenty-front/src/modules/app/hooks/__tests__/useInitializeQueryParamState.test.tsx b/packages/twenty-front/src/modules/app/hooks/__tests__/useInitializeQueryParamState.test.tsx
new file mode 100644
index 00000000000..c6df279779c
--- /dev/null
+++ b/packages/twenty-front/src/modules/app/hooks/__tests__/useInitializeQueryParamState.test.tsx
@@ -0,0 +1,74 @@
+import { act, renderHook } from '@testing-library/react';
+import { Provider as JotaiProvider } from 'jotai';
+import Cookies from 'js-cookie';
+import { type ReactNode } from 'react';
+
+import { useInitializeQueryParamState } from '@/app/hooks/useInitializeQueryParamState';
+import {
+ jotaiStore,
+ resetJotaiStore,
+} from '@/ui/utilities/state/jotai/jotaiStore';
+
+const Wrapper = ({ children }: { children: ReactNode }) => (
+ <JotaiProvider store={jotaiStore}>{children}</JotaiProvider>
+);
+
+const initializeQueryParamStateAt = (url: string) => {
+ window.history.pushState({}, '', url);
+
+ const { result } = renderHook(() => useInitializeQueryParamState(), {
+ wrapper: Wrapper,
+ });
+
+ act(() => {
+ result.current.initializeQueryParamState();
+ });
+};
+
+describe('useInitializeQueryParamState', () => {
+ beforeEach(() => {
+ resetJotaiStore();
+ });
+
+ afterEach(() => {
+ Cookies.remove('partner');
+ window.history.pushState({}, '', '/');
+ });
+
+ it('should store the normalized partner in the cookie', () => {
+ initializeQueryParamStateAt('/welcome?partner=%20Acme%20');
+
+ expect(Cookies.get('partner')).toBe(JSON.stringify({ partner: 'acme' }));
+ });
+
+ it('should not re-render the caller when it stores the partner', () => {
+ window.history.pushState({}, '', '/welcome?partner=acme');
+
+ let renderCount = 0;
+
+ const { result } = renderHook(
+ () => {
+ renderCount++;
+
+ return useInitializeQueryParamState();
+ },
+ { wrapper: Wrapper },
+ );
+
+ const renderCountBeforeInitialization = renderCount;
+
+ act(() => {
+ result.current.initializeQueryParamState();
+ });
+
+ expect(renderCount).toBe(renderCountBeforeInitialization);
+ });
+
+ it('should keep the stored partner when the new one is invalid', () => {
+ Cookies.set('partner', JSON.stringify({ partner: 'acme' }));
+
+ initializeQueryParamStateAt('/welcome?partner=%3Cx%3E');
+
+ expect(Cookies.get('partner')).toBe(JSON.stringify({ partner: 'acme' }));
+ });
+});
diff --git a/packages/twenty-front/src/modules/app/hooks/useInitializeQueryParamState.ts b/packages/twenty-front/src/modules/app/hooks/useInitializeQueryParamState.ts
index 510f2f530ac..74bb5684e54 100644
--- a/packages/twenty-front/src/modules/app/hooks/useInitializeQueryParamState.ts
+++ b/packages/twenty-front/src/modules/app/hooks/useInitializeQueryParamState.ts
@@ -1,11 +1,13 @@
import { useCallback } from 'react';
import { billingCheckoutSessionState } from '@/auth/states/billingCheckoutSessionState';
+import { partnerCookieState } from '@/auth/states/partnerCookieState';
import { returnToPathState } from '@/auth/states/returnToPathState';
import { type BillingCheckoutSession } from '@/auth/types/BillingCheckoutSession';
import { isValidReturnToPath } from '@/auth/utils/isValidReturnToPath';
import { BILLING_CHECKOUT_SESSION_DEFAULT_VALUE } from '@/settings/billing/constants/BillingCheckoutSessionDefaultValue';
import { useStore } from 'jotai';
+import { isDefined, normalizePartner } from 'twenty-shared/utils';
import { isDeeplyEqual } from '~/utils/isDeeplyEqual';
export const useInitializeQueryParamState = () => {
@@ -50,6 +52,13 @@ export const useInitializeQueryParamState = () => {
store.set(returnToPathState.atom, value);
}
},
+ partner: (value: string) => {
+ const partner = normalizePartner(value);
+
+ if (isDefined(partner)) {
+ store.set(partnerCookieState.atom, { partner });
+ }
+ },
};
const queryParams = new URLSearchParams(window.location.search);
diff --git a/packages/twenty-front/src/modules/auth/sign-in-up/hooks/useSignUpInNewWorkspace.ts b/packages/twenty-front/src/modules/auth/sign-in-up/hooks/useSignUpInNewWorkspace.ts
index 82a65142eda..29fab9af7ce 100644
--- a/packages/twenty-front/src/modules/auth/sign-in-up/hooks/useSignUpInNewWorkspace.ts
+++ b/packages/twenty-front/src/modules/auth/sign-in-up/hooks/useSignUpInNewWorkspace.ts
@@ -1,8 +1,10 @@
import { useAuth } from '@/auth/hooks/useAuth';
+import { partnerCookieState } from '@/auth/states/partnerCookieState';
import { useUploadNewWorkspaceLogo } from '@/auth/sign-in-up/hooks/useUploadNewWorkspaceLogo';
import { isMultiWorkspaceEnabledState } from '@/client-config/states/isMultiWorkspaceEnabledState';
import { useRedirectToWorkspaceDomain } from '@/domain-manager/hooks/useRedirectToWorkspaceDomain';
import { getToastOptionsFromError } from '@/error-handler/utils/getToastOptionsFromError';
+import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { CombinedGraphQLErrors } from '@apollo/client/errors';
import { useMutation } from '@apollo/client/react';
@@ -26,6 +28,7 @@ export const useSignUpInNewWorkspace = () => {
SignUpInNewWorkspaceDocument,
);
const { uploadNewWorkspaceLogo } = useUploadNewWorkspaceLogo();
+ const [partnerCookie, setPartnerCookie] = useAtomState(partnerCookieState);
const createWorkspace = async ({
displayName,
@@ -38,10 +41,14 @@ export const useSignUpInNewWorkspace = () => {
} = {}): Promise<boolean> => {
try {
const { data } = await signUpInNewWorkspaceMutation({
- variables: { input: { displayName, subdomain } },
+ variables: {
+ input: { displayName, subdomain, partner: partnerCookie?.partner },
+ },
});
assertIsDefinedOrThrow(data?.signUpInNewWorkspace);
+ setPartnerCookie(null);
+
const workspaceId = data.signUpInNewWorkspace.workspace.id;
if (isDefined(logo)) {
diff --git a/packages/twenty-front/src/modules/auth/states/partnerCookieState.ts b/packages/twenty-front/src/modules/auth/states/partnerCookieState.ts
new file mode 100644
index 00000000000..d1c76ed220f
--- /dev/null
+++ b/packages/twenty-front/src/modules/auth/states/partnerCookieState.ts
@@ -0,0 +1,16 @@
+import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';
+import { isDefined, normalizePartner } from 'twenty-shared/utils';
+
+export const partnerCookieState = createAtomState<{ partner: string } | null>({
+ key: 'partnerCookie',
+ defaultValue: null,
+ useCookieStorage: {
+ cookieKey: 'partner',
+ attributes: {
+ expires: 30,
+ },
+ validateInitFn: (payload) =>
+ isDefined(payload.partner) &&
+ normalizePartner(payload.partner) === payload.partner,
+ },
+});
diff --git a/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.ts b/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.ts
index 7dec8578bb6..dd19c581cc7 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.ts
@@ -710,7 +710,11 @@ export class AuthResolver {
const { user, workspace } = await this.signInUpService.signUpOnNewWorkspace(
{ type: 'existingUser', existingUser: fullUser },
- { displayName: input?.displayName, subdomain: input?.subdomain },
+ {
+ displayName: input?.displayName,
+ subdomain: input?.subdomain,
+ partner: input?.partner,
+ },
);
const loginToken = await this.loginTokenService.generateLoginToken(
diff --git a/packages/twenty-server/src/engine/core-modules/auth/dto/sign-up-in-new-workspace.input.ts b/packages/twenty-server/src/engine/core-modules/auth/dto/sign-up-in-new-workspace.input.ts
index ac9b885cf1c..f0cd57ede27 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/dto/sign-up-in-new-workspace.input.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/dto/sign-up-in-new-workspace.input.ts
@@ -1,6 +1,7 @@
import { Field, InputType } from '@nestjs/graphql';
-import { IsOptional, IsString, MaxLength } from 'class-validator';
+import { IsOptional, IsString, Matches, MaxLength } from 'class-validator';
+import { PARTNER_PATTERN } from 'twenty-shared/constants';
@InputType()
export class SignUpInNewWorkspaceInput {
@@ -14,4 +15,10 @@ export class SignUpInNewWorkspaceInput {
@IsString()
@IsOptional()
subdomain?: string;
+
+ @Field(() => String, { nullable: true })
+ @IsString()
+ @IsOptional()
+ @Matches(PARTNER_PATTERN)
+ partner?: string;
}
diff --git a/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts b/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts
index 609ca2e3795..c4ad4114599 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts
@@ -639,7 +639,7 @@ export class SignInUpService {
async signUpOnNewWorkspace(
userData: ExistingUserOrPartialUserWithPicture['userData'],
- options?: { displayName?: string; subdomain?: string },
+ options?: { displayName?: string; subdomain?: string; partner?: string },
) {
const email =
userData.type === 'newUserWithPicture'
@@ -810,6 +810,7 @@ export class SignInUpService {
userEmail: email,
workspaceId: workspace.id,
workspaceDisplayName: workspace.displayName,
+ partner: options?.partner,
});
}
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing.service.ts
index e20e9c1748a..609ed686281 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing.service.ts
@@ -39,10 +39,12 @@ export class BillingService {
userEmail,
workspaceId,
workspaceDisplayName,
+ partner,
}: {
userEmail: string;
workspaceId: string;
workspaceDisplayName: string | undefined;
+ partner?: string;
}): Promise<void> {
const existingBillingCustomer =
await this.billingCustomerRepository.findOne(workspaceId, { where: {} });
@@ -51,11 +53,12 @@ export class BillingService {
return;
}
- await this.stripeCustomerService.createStripeCustomer(
+ await this.stripeCustomerService.createStripeCustomer({
userEmail,
workspaceId,
- workspaceDisplayName,
- );
+ customerName: workspaceDisplayName,
+ partner,
+ });
}
async hasWorkspaceAnySubscription(workspaceId: string) {
diff --git a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-checkout.service.ts b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-checkout.service.ts
index 74606a245de..e890ef92428 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-checkout.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-checkout.service.ts
@@ -202,11 +202,11 @@ export class StripeCheckoutService {
}
const stripeCustomer =
- await this.stripeCustomerService.createStripeCustomer(
- user.email,
- workspace.id,
- workspace.displayName,
- );
+ await this.stripeCustomerService.createStripeCustomer({
+ userEmail: user.email,
+ workspaceId: workspace.id,
+ customerName: workspace.displayName,
+ });
return stripeCustomer.id;
}
diff --git a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-customer.service.ts b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-customer.service.ts
index 15c610c7228..66437793488 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-customer.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-customer.service.ts
@@ -2,6 +2,7 @@
import { Injectable, Logger } from '@nestjs/common';
+import { isNonEmptyString } from '@sniptt/guards';
import { isDefined } from 'twenty-shared/utils';
import type Stripe from 'stripe';
@@ -98,16 +99,23 @@ export class StripeCustomerService {
});
}
- async createStripeCustomer(
- userEmail: string,
- workspaceId: string,
- customerName: string | undefined,
- ) {
+ async createStripeCustomer({
+ userEmail,
+ workspaceId,
+ customerName,
+ partner,
+ }: {
+ userEmail: string;
+ workspaceId: string;
+ customerName: string | undefined;
+ partner?: string;
+ }) {
const customer = await this.stripe.customers.create({
name: customerName,
email: userEmail,
metadata: {
workspaceId,
+ ...(isNonEmptyString(partner) ? { partner } : {}),
},
});
diff --git a/packages/twenty-shared/src/constants/PartnerPattern.ts b/packages/twenty-shared/src/constants/PartnerPattern.ts
new file mode 100644
index 00000000000..99d8860cebb
--- /dev/null
+++ b/packages/twenty-shared/src/constants/PartnerPattern.ts
@@ -0,0 +1 @@
+export const PARTNER_PATTERN = /^[a-z0-9](?:[a-z0-9_-]{0,62}[a-z0-9])?$/;
diff --git a/packages/twenty-shared/src/constants/index.ts b/packages/twenty-shared/src/constants/index.ts
index 335f340c0a2..e5adaa44c80 100644
--- a/packages/twenty-shared/src/constants/index.ts
+++ b/packages/twenty-shared/src/constants/index.ts
@@ -64,6 +64,7 @@ export { MULTI_ITEM_FIELD_DEFAULT_MAX_VALUES } from './MultiItemFieldDefaultMaxV
export { MULTI_ITEM_FIELD_MIN_MAX_VALUES } from './MultiItemFieldMinMaxValues';
export { MUTATION_MAX_MERGE_RECORDS } from './MutationMaxMergeRecords';
export { OBJECTS_WITH_CHANNEL_VISIBILITY_CONSTRAINTS } from './ObjectsWithChannelVisibilityConstraints';
+export { PARTNER_PATTERN } from './PartnerPattern';
export { PermissionFlagType } from './PermissionFlagType';
export { PermissionsOnAllObjectRecords } from './PermissionsOnAllObjectRecords';
export { POLLED_MESSAGE_CHANNEL_TYPES } from './PolledMessageChannelTypes';
diff --git a/packages/twenty-shared/src/utils/index.ts b/packages/twenty-shared/src/utils/index.ts
index b5b12cdcb66..00b1d409478 100644
--- a/packages/twenty-shared/src/utils/index.ts
+++ b/packages/twenty-shared/src/utils/index.ts
@@ -355,6 +355,7 @@ export { isValidTwentySubdomain } from './validation/isValidTwentySubdomain';
export { isValidUuid } from './validation/isValidUuid';
export { isValidVariable } from './validation/isValidVariable';
export { normalizeLocale } from './validation/normalizeLocale';
+export { normalizePartner } from './validation/normalizePartner';
export { getCountryCodesForCallingCode } from './validation/phones-value/getCountryCodesForCallingCode';
export { isValidCountryCode } from './validation/phones-value/isValidCountryCode';
export {
diff --git a/packages/twenty-shared/src/utils/validation/__tests__/normalizePartner.test.ts b/packages/twenty-shared/src/utils/validation/__tests__/normalizePartner.test.ts
new file mode 100644
index 00000000000..2fa494617e7
--- /dev/null
+++ b/packages/twenty-shared/src/utils/validation/__tests__/normalizePartner.test.ts
@@ -0,0 +1,30 @@
+import { normalizePartner } from '@/utils/validation/normalizePartner';
+
+describe('normalizePartner', () => {
+ it('should trim and lowercase a valid partner', () => {
+ expect(normalizePartner(' Acme ')).toBe('acme');
+ });
+
+ it('should accept letters, digits, hyphens and underscores', () => {
+ expect(normalizePartner('acme-eu_2')).toBe('acme-eu_2');
+ });
+
+ it('should accept 1 and 64 characters', () => {
+ expect(normalizePartner('a')).toBe('a');
+ expect(normalizePartner('a'.repeat(64))).toBe('a'.repeat(64));
+ });
+
+ it('should reject more than 64 characters', () => {
+ expect(normalizePartner('a'.repeat(65))).toBeUndefined();
+ });
+
+ it('should reject a value starting or ending with a separator', () => {
+ expect(normalizePartner('-acme')).toBeUndefined();
+ expect(normalizePartner('acme_')).toBeUndefined();
+ });
+
+ it('should reject other characters', () => {
+ expect(normalizePartner('<x>')).toBeUndefined();
+ expect(normalizePartner('acme.com')).toBeUndefined();
+ });
+});
diff --git a/packages/twenty-shared/src/utils/validation/normalizePartner.ts b/packages/twenty-shared/src/utils/validation/normalizePartner.ts
new file mode 100644
index 00000000000..d5c4df09b98
--- /dev/null
+++ b/packages/twenty-shared/src/utils/validation/normalizePartner.ts
@@ -0,0 +1,12 @@
+import { PARTNER_PATTERN } from '@/constants/PartnerPattern';
+import { isString } from '@sniptt/guards';
+
+export const normalizePartner = (value: unknown): string | undefined => {
+ if (!isString(value)) {
+ return undefined;
+ }
+
+ const partner = value.trim().toLowerCase();
+
+ return PARTNER_PATTERN.test(partner) ? partner : undefined;
+};