chore: organization onboarding refactor (#24381)

* feat: redirect to new onboarding flow

* Getting started

* Brand details

* Preview organization brands

* Orgs team pages

* Invite team steps

* Move to global zustand store

* Few darkmdoe fixes

* Wip onboarding + stripe flow

* Default plan state

Server Action for gettting slug satus of org

* Remove onboardingId

* Confirmation prompt

* Update old onboarding flow handlers to handle new fields

* update onboarding hook

* Filter out organization section for none -company emails

* Match placeholders to users domain

* Drop migration

* Wip new onboarding intent

* WIP flow for self-hosted. Same service call just split logic

* WIP

* Add TODO

* Use onboarding user type instead of trpc session

* WIP

* WIP

* pass role and team name from onboarding to save in schema

* Add test to ensure role + name + team are persisted into onboarding table

* migrate roles to enum values

* Update ENUM

* Fix type error

* Redirect if flag is disabled

* Remove web

* WIP

* WIP

* Fix migration

* Fix calls

* User onboarding User types instead of trpc session

* Fix factory tests

* Fix flow for self hoste

* Type error

* More type fixes

* Fix handler tests

* Fix enum return type being different

* Use consistant types across the oganization stuff

* Fix

* Use TEAM_BILLING for e2e test

* Refactor is not company email and add tests

* Fix

* Fix

* Refactor flow to submit after form complete

* Fix flow with billing disabled

* Fix tests

* Apply suggestion from @coderabbitai[bot]

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Rename and move test files

* WIP

* Fix types

* Update repo paths + tests

* Move to service folder

* Fix tests

* Fix types

* Remove old test files

* Restore lock

* Fix path

* Fix tests with new paths and factory logic

* Fix updaetdAt

* WIP onboardingID isolation

* Fix e2e test

* verify test

* Code rabbit

* Rename SelfHostedOnboardongService -> SelfHostedOrganizationOnboardingService

* Fix stores

* Fix type error

* Fix types

* remove tsignore

* Apply suggestion from @coderabbitai[bot]

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* NITS

* Add the logic to auto complete admin org when billing enabled

* Fix store being weird

* We need to return the parsed value

* fixes

* sync from db always

* Add onboardingSgtore tests

* fix test

* remove step and status

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Hariom Balhara <[email protected]>
This commit is contained in:
authored and GitHub committed 2025-10-18 14:13:30 +00:00
1 parent 1eb6ff3e65
commit fa35cc5210
48 files changed
+4959 -1813

No files matched your search

@@ -1,6 +1,7 @@
import { lookup } from "dns";
import { getOrgFullOrigin } from "@calcom/ee/organizations/lib/orgDomains";
import { isNotACompanyEmail } from "@calcom/ee/organizations/lib/server/orgCreationUtils";
import { sendAdminOrganizationNotification, sendOrganizationCreationEmail } from "@calcom/emails";
import { sendEmailVerification } from "@calcom/features/auth/lib/verifyEmail";
import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "@calcom/lib/availability";
@@ -23,47 +24,6 @@ import type { TrpcSessionUser } from "../../../types";
import { BillingPeriod } from "./create.schema";
import type { TCreateInputSchema } from "./create.schema";
/**
* We can only say for sure that the email is not a company email. We can't say for sure if it is a company email.
*/
function isNotACompanyEmail(email: string) {
// A list of popular @domains that can't be used to allow automatic acceptance of memberships to organization
const emailProviders = [
"gmail.com",
"yahoo.com",
"outlook.com",
"hotmail.com",
"aol.com",
"icloud.com",
"mail.com",
"protonmail.com",
"zoho.com",
"yandex.com",
"gmx.com",
"fastmail.com",
"inbox.com",
"me.com",
"hushmail.com",
"live.com",
"rediffmail.com",
"tutanota.com",
"mail.ru",
"usa.com",
"qq.com",
"163.com",
"web.de",
"rocketmail.com",
"excite.com",
"lycos.com",
"outlook.co",
"hotmail.co.uk",
];
const emailParts = email.split("@");
if (emailParts.length < 2) return true;
return emailProviders.includes(emailParts[1]);
}
type CreateOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
@@ -1,4 +1,4 @@
import { createOrganizationFromOnboarding } from "@calcom/features/ee/organizations/lib/server/createOrganizationFromOnboarding";
import { SelfHostedOrganizationOnboardingService } from "@calcom/features/ee/organizations/lib/service/onboarding/SelfHostedOnboardingService";
import { IS_SELF_HOSTED } from "@calcom/lib/constants";
import { OrganizationOnboardingRepository } from "@calcom/lib/server/repository/organizationOnboarding";
@@ -45,24 +45,32 @@ export const createSelfHostedHandler = async ({ input, ctx }: CreateSelfHostedOp
});
}
const { organization } = await createOrganizationFromOnboarding({
organizationOnboarding: {
id: input.onboardingId,
logo: input.logo ?? null,
bio: input.bio ?? null,
invitedMembers: input.invitedMembers ?? [],
teams: input.teams ?? [],
orgOwnerEmail: organizationOnboarding.orgOwnerEmail,
slug: organizationOnboarding.slug,
name: organizationOnboarding.name,
billingPeriod: organizationOnboarding.billingPeriod,
seats: organizationOnboarding.seats,
pricePerSeat: organizationOnboarding.pricePerSeat,
stripeCustomerId: organizationOnboarding.stripeCustomerId,
isPlatform: organizationOnboarding.isPlatform,
isDomainConfigured: organizationOnboarding.isDomainConfigured,
organizationId: organizationOnboarding.organizationId,
},
const userContext = {
id: ctx.user.id,
email: ctx.user.email,
role: ctx.user.role as "ADMIN" | "USER",
name: ctx.user.name || undefined,
};
const onboardingService = new SelfHostedOrganizationOnboardingService(userContext);
const { organization } = await onboardingService.createOrganization({
id: input.onboardingId,
logo: input.logo ?? null,
bio: input.bio ?? null,
brandColor: input.brandColor ?? null,
bannerUrl: input.bannerUrl ?? null,
invitedMembers: input.invitedMembers ?? [],
teams: input.teams ?? [],
orgOwnerEmail: organizationOnboarding.orgOwnerEmail,
slug: organizationOnboarding.slug,
name: organizationOnboarding.name,
billingPeriod: organizationOnboarding.billingPeriod,
seats: organizationOnboarding.seats,
pricePerSeat: organizationOnboarding.pricePerSeat,
stripeCustomerId: organizationOnboarding.stripeCustomerId,
isPlatform: organizationOnboarding.isPlatform,
isDomainConfigured: organizationOnboarding.isDomainConfigured,
organizationId: organizationOnboarding.organizationId,
});
await OrganizationOnboardingRepository.markAsComplete(organizationOnboarding.id);
@@ -1,3 +1,12 @@
/**
* @deprecated This endpoint is deprecated. Use `intentToCreateOrg` instead, which now handles
* teams and invites in a single mutation call. This endpoint will be removed in a future release.
*
* Migration guide:
* - Instead of calling `intentToCreateOrg` followed by `createWithPaymentIntent`,
* pass teams and invitedMembers directly to `intentToCreateOrg`
* - The new endpoint returns checkoutUrl directly in the response
*/
import { OrganizationPaymentService } from "@calcom/features/ee/organizations/lib/OrganizationPaymentService";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
@@ -15,8 +24,20 @@ type CreateOptions = {
input: TCreateWithPaymentIntentInputSchema;
};
const log = logger.getSubLogger({ prefix: ["viewer", "organizations", "createWithPaymentIntent"] });
/**
* @deprecated Use intentToCreateOrg with teams and invitedMembers instead
*/
export const createHandler = async ({ input, ctx }: CreateOptions) => {
const paymentService = new OrganizationPaymentService(ctx.user);
log.warn(
"DEPRECATED: createWithPaymentIntent is deprecated. Use intentToCreateOrg with teams and invitedMembers instead."
);
const paymentService = new OrganizationPaymentService({
id: ctx.user.id,
email: ctx.user.email,
role: ctx.user.role,
name: ctx.user.name ?? undefined,
});
const isAdmin = ctx.user.role === "ADMIN";
// Regular user can send onboardingId if the onboarding was started by ADMIN/someone else and they shared the link with them.
// ADMIN flow doesn't send onboardingId
@@ -57,6 +78,8 @@ export const createHandler = async ({ input, ctx }: CreateOptions) => {
...input,
logo: input.logo ?? null,
bio: input.bio ?? null,
brandColor: input.brandColor ?? null,
bannerUrl: input.bannerUrl ?? null,
},
organizationOnboarding
);
@@ -1,3 +1,8 @@
/**
* @deprecated This schema is deprecated. Use ZIntentToCreateOrgInputSchema instead.
* See createWithPaymentIntent.handler.ts for migration guide.
*/
import type { z } from "zod";
import { createOrganizationSchema } from "@calcom/features/ee/organizations/types/schemas";
@@ -7,6 +12,9 @@ export enum BillingPeriod {
ANNUALLY = "ANNUALLY",
}
/**
* @deprecated Use ZIntentToCreateOrgInputSchema instead
*/
export const ZCreateWithPaymentIntentInputSchema = createOrganizationSchema;
export type TCreateWithPaymentIntentInputSchema = z.infer<typeof ZCreateWithPaymentIntentInputSchema>;
@@ -3,7 +3,8 @@ import prismock from "../../../../../../tests/libs/__mocks__/prisma";
import { describe, expect, it, vi, beforeEach } from "vitest";
import { LicenseKeySingleton } from "@calcom/ee/common/server/LicenseKeyService";
import { UserPermissionRole } from "@calcom/prisma/enums";
import { OrganizationPaymentService } from "@calcom/features/ee/organizations/lib/OrganizationPaymentService";
import { BillingPeriod, UserPermissionRole, CreationSource } from "@calcom/prisma/enums";
import { TRPCError } from "@trpc/server";
@@ -15,6 +16,8 @@ vi.mock("@calcom/ee/common/server/LicenseKeyService", () => ({
},
}));
vi.mock("@calcom/features/ee/organizations/lib/OrganizationPaymentService");
const mockInput = {
name: "Test Org",
slug: "test-org",
@@ -23,6 +26,7 @@ const mockInput = {
seats: 5,
pricePerSeat: 20,
isPlatform: false,
creationSource: "WEBAPP",
};
// Helper functions for creating test data
@@ -49,8 +53,37 @@ async function createTestUser(data: {
describe("intentToCreateOrgHandler", () => {
beforeEach(async () => {
vi.resetAllMocks();
// @ts-expect-error reset is a method on Prismock
await prismock.reset();
vi.mocked(OrganizationPaymentService).mockImplementation(() => {
return {
createOrganizationOnboarding: vi.fn().mockImplementation(async (data: any) => {
return await prismock.organizationOnboarding.create({
data: {
id: "onboarding-123",
name: data.name,
slug: data.slug,
orgOwnerEmail: data.orgOwnerEmail,
seats: data.seats ?? 10,
pricePerSeat: data.pricePerSeat ?? 15,
billingPeriod: data.billingPeriod ?? BillingPeriod.MONTHLY,
isComplete: false,
stripeCustomerId: null,
createdById: data.createdByUserId,
teams: data.teams ?? [],
invitedMembers: data.invitedMembers ?? [],
isPlatform: data.isPlatform ?? false,
},
});
}),
createPaymentIntent: vi.fn().mockResolvedValue({
checkoutUrl: "https://stripe.com/checkout/session",
organizationOnboarding: {},
subscription: {},
sessionId: "session-123",
}),
} as any;
});
});
describe("hosted", () => {
@@ -64,7 +97,10 @@ describe("intentToCreateOrgHandler", () => {
});
vi.mocked(LicenseKeySingleton.getInstance).mockResolvedValue({
checkLicense: vi.fn().mockResolvedValue(true),
incrementUsage: vi.fn().mockResolvedValue(undefined),
});
process.env.STRIPE_ORG_PRODUCT_ID = "prod_test123";
process.env.STRIPE_ORG_MONTHLY_PRICE_ID = "price_test123";
});
it("should allow admin user to create org for another user", async () => {
@@ -88,7 +124,7 @@ describe("intentToCreateOrgHandler", () => {
},
});
// Verify the result shape
// Admin creating for different user with no teams/invites triggers handover
expect(result).toEqual({
userId: expect.any(Number),
orgOwnerEmail: mockInput.orgOwnerEmail,
@@ -99,6 +135,9 @@ describe("intentToCreateOrgHandler", () => {
billingPeriod: mockInput.billingPeriod,
isPlatform: mockInput.isPlatform,
organizationOnboardingId: expect.any(String),
checkoutUrl: null,
organizationId: null, // Not created yet - handover flow
handoverUrl: expect.stringContaining("/settings/organizations/new/resume?onboardingId="),
});
// Verify organization onboarding was created
@@ -193,7 +232,7 @@ describe("intentToCreateOrgHandler", () => {
);
});
it("should throw error when organization onboarding already exists", async () => {
it("should throw error when organization onboarding already exists and is complete", async () => {
// Create admin user
const adminUser = await createTestUser({
email: "[email protected]",
@@ -207,7 +246,7 @@ describe("intentToCreateOrgHandler", () => {
emailVerified: new Date(),
});
// Create existing organization onboarding
// Create existing COMPLETE organization onboarding
await prismock.organizationOnboarding.create({
data: {
name: mockInput.name,
@@ -217,6 +256,7 @@ describe("intentToCreateOrgHandler", () => {
seats: mockInput.seats,
pricePerSeat: mockInput.pricePerSeat,
createdById: adminUser.id,
isComplete: true, // Must be complete to throw error
},
});
@@ -249,6 +289,7 @@ describe("intentToCreateOrgHandler", () => {
it("should throw error when license is not valid", async () => {
vi.mocked(LicenseKeySingleton.getInstance).mockResolvedValue({
checkLicense: vi.fn().mockResolvedValue(false),
incrementUsage: vi.fn().mockResolvedValue(undefined),
});
const adminUser = await createTestUser({
email: "[email protected]",
@@ -268,6 +309,7 @@ describe("intentToCreateOrgHandler", () => {
it("should allow admin user to create org for another user", async () => {
vi.mocked(LicenseKeySingleton.getInstance).mockResolvedValue({
checkLicense: vi.fn().mockResolvedValue(true),
incrementUsage: vi.fn().mockResolvedValue(undefined),
});
// Create admin user
const adminUser = await createTestUser({
@@ -289,7 +331,7 @@ describe("intentToCreateOrgHandler", () => {
},
});
// Verify the result shape
// Admin creating for different user with no teams/invites triggers handover (same as hosted)
expect(result).toEqual({
userId: expect.any(Number),
orgOwnerEmail: mockInput.orgOwnerEmail,
@@ -300,6 +342,9 @@ describe("intentToCreateOrgHandler", () => {
billingPeriod: mockInput.billingPeriod,
isPlatform: mockInput.isPlatform,
organizationOnboardingId: expect.any(String),
checkoutUrl: null,
organizationId: null, // Not created yet - handover flow
handoverUrl: expect.stringContaining("/settings/organizations/new/resume?onboardingId="),
});
// Verify organization onboarding was created
@@ -314,5 +359,119 @@ describe("intentToCreateOrgHandler", () => {
expect(organizationOnboarding?.slug).toBe(mockInput.slug);
expect(organizationOnboarding?.orgOwnerEmail).toBe(mockInput.orgOwnerEmail);
});
it("should handle teams and invites in the request", async () => {
vi.mocked(LicenseKeySingleton.getInstance).mockResolvedValue({
checkLicense: vi.fn().mockResolvedValue(true),
incrementUsage: vi.fn().mockResolvedValue(undefined),
});
const adminUser = await createTestUser({
email: "[email protected]",
role: UserPermissionRole.ADMIN,
});
await createTestUser({
email: mockInput.orgOwnerEmail,
completedOnboarding: true,
emailVerified: new Date(),
});
const inputWithTeamsAndInvites = {
...mockInput,
teams: [
{ id: -1, name: "Engineering", isBeingMigrated: false, slug: null },
{ id: -1, name: "Sales", isBeingMigrated: false, slug: null },
],
invitedMembers: [
{ email: "[email protected]", name: "Member 1" },
{ email: "[email protected]", name: "Member 2" },
],
};
const result = await intentToCreateOrgHandler({
input: inputWithTeamsAndInvites,
ctx: {
user: adminUser,
},
});
expect(result.organizationOnboardingId).toBeDefined();
const organizationOnboarding = await prismock.organizationOnboarding.findFirst({
where: {
slug: mockInput.slug,
},
});
expect(organizationOnboarding).toBeDefined();
expect(organizationOnboarding?.teams).toEqual(inputWithTeamsAndInvites.teams);
expect(organizationOnboarding?.invitedMembers).toEqual(inputWithTeamsAndInvites.invitedMembers);
});
it("should preserve teamName, teamId, and role in invites payload", async () => {
vi.mocked(LicenseKeySingleton.getInstance).mockResolvedValue({
checkLicense: vi.fn().mockResolvedValue(true),
incrementUsage: vi.fn().mockResolvedValue(undefined),
});
const adminUser = await createTestUser({
email: "[email protected]",
role: UserPermissionRole.ADMIN,
});
await createTestUser({
email: mockInput.orgOwnerEmail,
completedOnboarding: true,
emailVerified: new Date(),
});
// This matches the exact payload from the frontend
const inputWithTeamsAndInvites = {
...mockInput,
teams: [
{ id: -1, name: "New", isBeingMigrated: false, slug: null },
{ id: -1, name: "team", isBeingMigrated: false, slug: null },
],
invitedMembers: [
{ email: "[email protected]", teamName: "new", teamId: -1, role: "ADMIN" },
{ email: "[email protected]", teamName: "team", teamId: -1, role: "ADMIN" },
],
};
const result = await intentToCreateOrgHandler({
input: inputWithTeamsAndInvites,
ctx: {
user: adminUser,
},
});
expect(result.organizationOnboardingId).toBeDefined();
const organizationOnboarding = await prismock.organizationOnboarding.findFirst({
where: {
slug: mockInput.slug,
},
});
expect(organizationOnboarding).toBeDefined();
expect(organizationOnboarding?.teams).toEqual(inputWithTeamsAndInvites.teams);
// Verify invitedMembers are stored with all fields including teamName, teamId, and role
expect(organizationOnboarding?.invitedMembers).toBeDefined();
expect(organizationOnboarding?.invitedMembers).toHaveLength(2);
const invitedMembers = organizationOnboarding?.invitedMembers as any[];
expect(invitedMembers[0]).toMatchObject({
email: "[email protected]",
teamName: "new",
teamId: -1,
role: "ADMIN",
});
expect(invitedMembers[1]).toMatchObject({
email: "[email protected]",
teamName: "team",
teamId: -1,
role: "ADMIN",
});
});
});
});
@@ -1,5 +1,5 @@
import { LicenseKeySingleton } from "@calcom/ee/common/server/LicenseKeyService";
import { OrganizationPaymentService } from "@calcom/features/ee/organizations/lib/OrganizationPaymentService";
import { OrganizationOnboardingFactory } from "@calcom/ee/organizations/lib/service/onboarding/OrganizationOnboardingFactory";
import {
assertCanCreateOrg,
findUserToBeOrgOwner,
@@ -27,7 +27,7 @@ type CreateOptions = {
};
export const intentToCreateOrgHandler = async ({ input, ctx }: CreateOptions) => {
const { slug, name, orgOwnerEmail, seats, pricePerSeat, billingPeriod, isPlatform } = input;
const { slug, name, orgOwnerEmail, isPlatform } = input;
log.debug(
"Starting organization creation intent",
safeStringify({ slug, name, orgOwnerEmail, isPlatform })
@@ -41,7 +41,6 @@ export const intentToCreateOrgHandler = async ({ input, ctx }: CreateOptions) =>
if (!hasValidLicense) {
throw new TRPCError({
code: "BAD_REQUEST",
// TODO: We need to send translation keys from here and frontend should translate it
message: "License is not valid",
});
}
@@ -75,9 +74,24 @@ export const intentToCreateOrgHandler = async ({ input, ctx }: CreateOptions) =>
}
log.debug("Found organization owner", safeStringify({ orgOwnerId: orgOwner.id, email: orgOwner.email }));
let organizationOnboarding = await OrganizationOnboardingRepository.findByOrgOwnerEmail(orgOwner.email);
const organizationOnboarding = await OrganizationOnboardingRepository.findByOrgOwnerEmail(orgOwner.email);
// If onboarding exists and is incomplete, this is a resume flow (e.g., admin handover)
// Allow proceeding with the existing onboarding record
if (organizationOnboarding) {
throw new Error("organization_onboarding_already_exists");
if (organizationOnboarding.isComplete) {
// Organization already created - shouldn't create another one
throw new Error("organization_onboarding_already_exists");
}
// Incomplete onboarding exists - this is expected for resume/handover flows
log.debug(
"Found incomplete onboarding record - proceeding with resume flow",
safeStringify({ onboardingId: organizationOnboarding.id, slug })
);
// Use existing onboarding ID for the resume flow
input.onboardingId = organizationOnboarding.id;
}
await assertCanCreateOrg({
@@ -87,24 +101,16 @@ export const intentToCreateOrgHandler = async ({ input, ctx }: CreateOptions) =>
restrictBasedOnMinimumPublishedTeams: !IS_USER_ADMIN,
});
const paymentService = new OrganizationPaymentService(ctx.user);
organizationOnboarding = await paymentService.createOrganizationOnboarding({
...input,
createdByUserId: loggedInUser.id,
const onboardingService = OrganizationOnboardingFactory.create({
id: ctx.user.id,
email: ctx.user.email,
role: ctx.user.role,
});
const result = await onboardingService.createOnboardingIntent(input);
log.debug("Organization creation intent successful", safeStringify({ slug, orgOwnerId: orgOwner.id }));
return {
userId: orgOwner.id,
orgOwnerEmail,
name,
slug,
seats,
pricePerSeat,
billingPeriod,
isPlatform,
organizationOnboardingId: organizationOnboarding.id,
};
return result;
};
export default intentToCreateOrgHandler;
@@ -2,12 +2,8 @@ import { z } from "zod";
import { emailSchema } from "@calcom/lib/emailSchema";
import slugify from "@calcom/lib/slugify";
import { CreationSource } from "@calcom/prisma/enums";
export enum BillingPeriod {
MONTHLY = "MONTHLY",
ANNUALLY = "ANNUALLY",
}
import { BillingPeriod, CreationSource } from "@calcom/prisma/enums";
import { orgOnboardingInvitedMembersSchema, orgOnboardingTeamsSchema } from "@calcom/prisma/zod-utils";
export const ZIntentToCreateOrgInputSchema = z.object({
name: z.string(),
@@ -19,6 +15,16 @@ export const ZIntentToCreateOrgInputSchema = z.object({
isPlatform: z.boolean().default(false),
billingPeriod: z.nativeEnum(BillingPeriod).default(BillingPeriod.MONTHLY),
creationSource: z.nativeEnum(CreationSource),
// Brand fields
logo: z.string().nullish(),
bio: z.string().nullish(),
brandColor: z.string().nullish(),
bannerUrl: z.string().nullish(),
// Teams and invites (new)
teams: orgOnboardingTeamsSchema.optional(),
invitedMembers: orgOnboardingInvitedMembersSchema.optional(),
// Optional onboarding ID for resume flows (admin handover)
onboardingId: z.string().optional(),
});
export type TIntentToCreateOrgInputSchema = z.infer<typeof ZIntentToCreateOrgInputSchema>;