Scheduling infrastructure for absolutely everyone.
feat: Organization onboarding improvement - Payment before creation of org but onboarding doesn't require payment (#18990)
sean-brydon837349e3d3fa
diff --git a/.env.example b/.env.exampleindex 89e0c3eeeee..f7535e36e20 100644--- a/.env.example+++ b/.env.example@@ -192,7 +192,10 @@ NEXT_PUBLIC_IS_PREMIUM_NEW_PLAN=0NEXT_PUBLIC_STRIPE_PREMIUM_NEW_PLAN_PRICE=STRIPE_TEAM_MONTHLY_PRICE_ID=STRIPE_TEAM_PRODUCT_ID=+# It is a price ID in the product with id STRIPE_ORG_PRODUCT_IDSTRIPE_ORG_MONTHLY_PRICE_ID=+STRIPE_ORG_PRODUCT_ID=+STRIPE_WEBHOOK_SECRET=STRIPE_WEBHOOK_SECRET_APPS=STRIPE_PRIVATE_KEY=@@ -285,7 +288,7 @@ NEXT_PUBLIC_AVAILABILITY_SCHEDULE_INTERVAL=# use organizationsORGANIZATIONS_ENABLED=NEXT_PUBLIC_ORGANIZATIONS_MIN_SELF_SERVE_SEATS=30-NEXT_PUBLIC_ORGANIZATIONS_SELF_SERVE_PRICE=3700 # $37.00 per seat+NEXT_PUBLIC_ORGANIZATIONS_SELF_SERVE_PRICE_NEW=37 # $37.00 per seat# This variable should only be set to 1 or true if you want to autolink external provider sign-ups with# existing organizations based on email domain addressdiff --git a/PR_TODO.md b/PR_TODO.mddeleted file mode 100644index dde9bb02beb..00000000000--- a/PR_TODO.md+++ /dev/null@@ -1,9 +0,0 @@-- [x] Refactor individual calendar links functions to create the variables and just use the variables in the string literal instead of functions being called in the string literal-- [x] Must ensure during review that logically there is no change in the functionality of booking-single-view.tsx---- Testing-- [x] Verify Google Calendar, Ics, Office 365 - Compare with Production- - [x] Event Description, Booking title, Booking location, Start time, End time - All correct- - [x] Recurring event?- - [x] Dynamic Group booking?\ No newline at end of filediff --git a/apps/web/app/(use-page-wrapper)/settings/organizations/[id]/about/page.tsx b/apps/web/app/(use-page-wrapper)/settings/organizations/new/about/page.tsxsimilarity index 87%rename from apps/web/app/(use-page-wrapper)/settings/organizations/[id]/about/page.tsxrename to apps/web/app/(use-page-wrapper)/settings/organizations/new/about/page.tsxindex 991e556f155..ba189104c84 100644--- a/apps/web/app/(use-page-wrapper)/settings/organizations/[id]/about/page.tsx+++ b/apps/web/app/(use-page-wrapper)/settings/organizations/new/about/page.tsx@@ -3,11 +3,10 @@ import type { PageProps } from "app/_types";import { _generateMetadata } from "app/_utils";import { cookies, headers } from "next/headers";-import { getServerSideProps } from "@calcom/features/ee/organizations/pages/organization";-import { buildLegacyCtx } from "@lib/buildLegacyCtx";+import { getServerSideProps } from "@lib/settings/organizations/new/getServerSideProps";-import LegacyPage, { LayoutWrapper } from "~/settings/organizations/[id]/about-view";+import LegacyPage, { LayoutWrapper } from "~/settings/organizations/new/about-view";export const generateMetadata = async () =>await _generateMetadata(diff --git a/apps/web/app/(use-page-wrapper)/settings/organizations/[id]/add-teams/page.tsx b/apps/web/app/(use-page-wrapper)/settings/organizations/new/add-teams/page.tsxsimilarity index 86%rename from apps/web/app/(use-page-wrapper)/settings/organizations/[id]/add-teams/page.tsxrename to apps/web/app/(use-page-wrapper)/settings/organizations/new/add-teams/page.tsxindex 937dbccd394..21c90a94304 100644--- a/apps/web/app/(use-page-wrapper)/settings/organizations/[id]/add-teams/page.tsx+++ b/apps/web/app/(use-page-wrapper)/settings/organizations/new/add-teams/page.tsx@@ -3,11 +3,10 @@ import type { PageProps } from "app/_types";import { _generateMetadata } from "app/_utils";import { cookies, headers } from "next/headers";-import { getServerSideProps } from "@calcom/features/ee/organizations/pages/organization";-import { buildLegacyCtx } from "@lib/buildLegacyCtx";+import { getServerSideProps } from "@lib/settings/organizations/new/getServerSideProps";-import LegacyPage, { LayoutWrapper } from "~/settings/organizations/[id]/add-teams-view";+import LegacyPage, { LayoutWrapper } from "~/settings/organizations/new/add-teams-view";export const generateMetadata = async () =>await _generateMetadata(diff --git a/apps/web/app/(use-page-wrapper)/settings/organizations/new/handover/page.tsx b/apps/web/app/(use-page-wrapper)/settings/organizations/new/handover/page.tsxnew file mode 100644index 00000000000..d5b06be4564--- /dev/null+++ b/apps/web/app/(use-page-wrapper)/settings/organizations/new/handover/page.tsx@@ -0,0 +1,29 @@+import { withAppDirSsr } from "app/WithAppDirSsr";+import type { PageProps } from "app/_types";+import { _generateMetadata } from "app/_utils";+import { cookies } from "next/headers";+import { headers } from "next/headers";++import { buildLegacyCtx } from "@lib/buildLegacyCtx";+import { getServerSideProps } from "@lib/settings/organizations/new/getServerSideProps";++import LegacyPage, { LayoutWrapper } from "~/settings/organizations/new/onboarding-handover";++export const generateMetadata = async () =>+ await _generateMetadata(+ (t) => t("handover_onboarding_page_title"),+ (t) => t("handover_onboarding_page_description")+ );++const getData = withAppDirSsr(getServerSideProps);++const ServerPage = async ({ params, searchParams }: PageProps) => {+ await getData(buildLegacyCtx(headers(), cookies(), params, searchParams));+ return (+ <LayoutWrapper>+ <LegacyPage />+ </LayoutWrapper>+ );+};++export default ServerPage;diff --git a/apps/web/app/(use-page-wrapper)/settings/organizations/[id]/onboard-members/page.tsx b/apps/web/app/(use-page-wrapper)/settings/organizations/new/onboard-members/page.tsxsimilarity index 86%rename from apps/web/app/(use-page-wrapper)/settings/organizations/[id]/onboard-members/page.tsxrename to apps/web/app/(use-page-wrapper)/settings/organizations/new/onboard-members/page.tsxindex 09fcf81c55c..d6aff7cb959 100644--- a/apps/web/app/(use-page-wrapper)/settings/organizations/[id]/onboard-members/page.tsx+++ b/apps/web/app/(use-page-wrapper)/settings/organizations/new/onboard-members/page.tsx@@ -3,11 +3,10 @@ import type { PageProps } from "app/_types";import { _generateMetadata } from "app/_utils";import { cookies, headers } from "next/headers";-import { getServerSideProps } from "@calcom/features/ee/organizations/pages/organization";-import { buildLegacyCtx } from "@lib/buildLegacyCtx";+import { getServerSideProps } from "@lib/settings/organizations/new/getServerSideProps";-import LegacyPage, { LayoutWrapper } from "~/settings/organizations/[id]/onboard-members-view";+import LegacyPage, { LayoutWrapper } from "~/settings/organizations/new/onboard-members-view";export const generateMetadata = async () =>await _generateMetadata(diff --git a/apps/web/app/(use-page-wrapper)/settings/organizations/new/page.tsx b/apps/web/app/(use-page-wrapper)/settings/organizations/new/page.tsxindex fbbffd2a725..96da7ee4729 100644--- a/apps/web/app/(use-page-wrapper)/settings/organizations/new/page.tsx+++ b/apps/web/app/(use-page-wrapper)/settings/organizations/new/page.tsx@@ -7,7 +7,6 @@ import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequirimport { buildLegacyCtx } from "@lib/buildLegacyCtx";import { getServerSideProps } from "@lib/settings/organizations/new/getServerSideProps";-import { type inferSSRProps } from "@lib/types/inferSSRProps";import LegacyPage, { LayoutWrapper } from "~/settings/organizations/new/create-new-view";@@ -17,7 +16,11 @@ export const generateMetadata = async () =>(t) => t("organizations_description"));-const getData = withAppDirSsr<inferSSRProps<typeof getServerSideProps>>(getServerSideProps);+type Props = {+ isOrg: boolean;+};++const getData = withAppDirSsr<Props>(getServerSideProps);const ServerPage = async ({ params, searchParams }: PageProps) => {await getData(buildLegacyCtx(headers(), cookies(), params, searchParams));diff --git a/apps/web/app/(use-page-wrapper)/settings/organizations/new/status/page.tsx b/apps/web/app/(use-page-wrapper)/settings/organizations/new/status/page.tsxnew file mode 100644index 00000000000..69967aecd2a--- /dev/null+++ b/apps/web/app/(use-page-wrapper)/settings/organizations/new/status/page.tsx@@ -0,0 +1,28 @@+import { withAppDirSsr } from "app/WithAppDirSsr";+import type { PageProps } from "app/_types";+import { _generateMetadata } from "app/_utils";+import { cookies, headers } from "next/headers";++import { buildLegacyCtx } from "@lib/buildLegacyCtx";+import { getServerSideProps } from "@lib/settings/organizations/new/getServerSideProps";++import LegacyPage, { LayoutWrapper } from "~/settings/organizations/new/payment-status-view";++export const generateMetadata = async () =>+ await _generateMetadata(+ (t) => t("organization_onboarding_status"),+ (t) => t("organization_onboarding_status_description")+ );++const getData = withAppDirSsr(getServerSideProps);++const ServerPage = async ({ params, searchParams }: PageProps) => {+ await getData(buildLegacyCtx(headers(), cookies(), params, searchParams));+ return (+ <LayoutWrapper>+ <LegacyPage />+ </LayoutWrapper>+ );+};++export default ServerPage;diff --git a/apps/web/app/(use-page-wrapper)/settings/platform/new/page.tsx b/apps/web/app/(use-page-wrapper)/settings/platform/new/page.tsxindex 34cd14dc1d7..d338805430c 100644--- a/apps/web/app/(use-page-wrapper)/settings/platform/new/page.tsx+++ b/apps/web/app/(use-page-wrapper)/settings/platform/new/page.tsx@@ -7,17 +7,20 @@ import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequirimport { buildLegacyCtx } from "@lib/buildLegacyCtx";import { getServerSideProps } from "@lib/settings/organizations/new/getServerSideProps";-import { type inferSSRProps } from "@lib/types/inferSSRProps";import LegacyPage, { LayoutWrapper } from "~/settings/platform/new/create-new-view";+type Props = {+ isOrg: boolean;+};+export const generateMetadata = async () =>await _generateMetadata((t) => t("set_up_your_platform_organization"),(t) => t("platform_organization_description"));-const getData = withAppDirSsr<inferSSRProps<typeof getServerSideProps>>(getServerSideProps);+const getData = withAppDirSsr<Props>(getServerSideProps);const ServerPage = async ({ params, searchParams }: PageProps) => {await getData(buildLegacyCtx(headers(), cookies(), params, searchParams));diff --git a/apps/web/lib/settings/organizations/new/getServerSideProps.tsx b/apps/web/lib/settings/organizations/new/getServerSideProps.tsxindex f54bfc2f424..a9ce4fa9511 100644--- a/apps/web/lib/settings/organizations/new/getServerSideProps.tsx+++ b/apps/web/lib/settings/organizations/new/getServerSideProps.tsx@@ -1,22 +1,20 @@-import type { GetServerSidePropsContext } from "next";+import type { GetServerSidePropsResult } from "next";import { getFeatureFlag } from "@calcom/features/flags/server/utils";+import prisma from "@calcom/prisma";-export const getServerSideProps = async (context: GetServerSidePropsContext) => {- const prisma = await import("@calcom/prisma").then((mod) => mod.default);+export const getServerSideProps = async (): Promise<GetServerSidePropsResult<{ isOrg: boolean }>> => {const organizations = await getFeatureFlag(prisma, "organizations");// Check if organizations are enabledif (!organizations) {return {notFound: true,- } as const;+ };}- const querySlug = context.query.slug as string;-return {props: {- querySlug: querySlug ?? null,+ isOrg: true,},};};diff --git a/apps/web/modules/settings/organizations/[id]/onboard-members-view.tsx b/apps/web/modules/settings/organizations/[id]/onboard-members-view.tsxdeleted file mode 100644index e3e0df7e8e6..00000000000--- a/apps/web/modules/settings/organizations/[id]/onboard-members-view.tsx+++ /dev/null@@ -1,28 +0,0 @@-"use client";--import { useRouter } from "next/navigation";--import AddNewTeamMembers from "@calcom/features/ee/teams/components/AddNewTeamMembers";-import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";-import { WizardLayout } from "@calcom/ui";--export const LayoutWrapper = ({ children }: { children: React.ReactNode }) => {- // eslint-disable-next-line react-hooks/rules-of-hooks- const router = useRouter();- // eslint-disable-next-line react-hooks/rules-of-hooks- const query = useCompatSearchParams();-- return (- <WizardLayout- currentStep={4}- maxSteps={5}- isOptionalCallback={() => {- router.push(`/settings/organizations/${query.get("id")}/add-teams`);- }}>- {children}- </WizardLayout>- );-};--const OrgAddNewTeamMembers = () => <AddNewTeamMembers isOrg={true} />;-export default OrgAddNewTeamMembers;diff --git a/packages/features/ee/organizations/components/AddNewTeamsForm.tsx b/apps/web/modules/settings/organizations/new/_components/AddNewTeamsForm.tsxsimilarity index 62%rename from packages/features/ee/organizations/components/AddNewTeamsForm.tsxrename to apps/web/modules/settings/organizations/new/_components/AddNewTeamsForm.tsxindex edb088ded1c..42033e7f6ce 100644--- a/packages/features/ee/organizations/components/AddNewTeamsForm.tsx+++ b/apps/web/modules/settings/organizations/new/_components/AddNewTeamsForm.tsx@@ -1,24 +1,25 @@"use client";-import { useSession } from "next-auth/react";import { useRouter } from "next/navigation";import { useState } from "react";import { Controller, useFieldArray, useForm } from "react-hook-form";import { z } from "zod";-import { IS_TEAM_BILLING_ENABLED_CLIENT } from "@calcom/lib/constants";+import { useOnboarding } from "@calcom/features/ee/organizations/lib/onboardingStore";import { useLocale } from "@calcom/lib/hooks/useLocale";-import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";-import { CreationSource } from "@calcom/prisma/enums";-import { UserPermissionRole } from "@calcom/prisma/enums";import { trpc } from "@calcom/trpc/react";-import { Button, CheckboxField, Form, Icon, showToast, TextField } from "@calcom/ui";+import {+ Button,+ CheckboxField,+ Form,+ Icon,+ TextField,+ SkeletonText,+ SkeletonContainer,+ SkeletonButton,+} from "@calcom/ui";import classNames from "@calcom/ui/classNames";-const querySchema = z.object({- id: z.string().transform((val) => parseInt(val)),-});-const schema = z.object({teams: z.array(z.object({@@ -35,44 +36,58 @@ const schema = z.object({});export const AddNewTeamsForm = () => {- const { data: teams } = trpc.viewer.teams.list.useQuery();- const routerQuery = useRouterQuery();-- const { id: orgId } = querySchema.parse(routerQuery);-- const { data: org } = trpc.viewer.teams.get.useQuery({ teamId: orgId, isOrg: true });-- if (!teams || !org) {- return null;+ const { data: teams, isLoading } = trpc.viewer.teams.listOwnedTeams.useQuery();++ if (isLoading) {+ return (+ <SkeletonContainer as="div" className="space-y-6">+ <div className="space-y-4">+ <SkeletonText className="h-4 w-32" />+ <div className="space-y-2">+ {[...Array(2)].map((_, i) => (+ <div key={i} className="flex items-center space-x-2">+ <SkeletonText className="h-5 w-5" />+ <SkeletonText className="h-8 w-full" />+ </div>+ ))}+ </div>+ </div>+ <div className="space-y-4">+ <SkeletonText className="h-4 w-32" />+ <div className="space-y-2">+ {[...Array(3)].map((_, i) => (+ <SkeletonText key={i} className="h-10 w-full" />+ ))}+ </div>+ </div>+ <SkeletonButton className="w-full" />+ </SkeletonContainer>+ );}- const orgWithRequestedSlug = {- ...org,- requestedSlug: org.metadata.requestedSlug ?? null,- };-- const regularTeams = teams.filter((team) => !team.parentId);- return <AddNewTeamsFormChild org={orgWithRequestedSlug} teams={regularTeams} />;+ return <AddNewTeamsFormChild teams={(teams ?? []).map(({ id, name, slug }) => ({ id, name, slug }))} />;};-const AddNewTeamsFormChild = ({- teams,- org,-}: {- org: { id: number; slug: string | null; requestedSlug: string | null };- teams: { id: number; name: string; slug: string | null }[];-}) => {+const AddNewTeamsFormChild = ({ teams }: { teams: { id: number; name: string; slug: string | null }[] }) => {const { t } = useLocale();const router = useRouter();const [counter, setCounter] = useState(1);+ const { useOnboardingStore } = useOnboarding();+ const { slug: orgSlug, setTeams, teams: teamsFromStore } = useOnboardingStore();+ const teamsToCreateFromStore = teamsFromStore.filter((team) => !team.isBeingMigrated);+ const teamsToMigrateFromStore = teamsFromStore.filter((team) => team.isBeingMigrated);const form = useForm({defaultValues: {- teams: [{ name: "" }],- moveTeams: teams.map((team) => ({- id: team.id,- shouldMove: false,- newSlug: getSuggestedSlug({ teamSlug: team.slug, orgSlug: org.slug || org.requestedSlug }),- })),+ teams: teamsToCreateFromStore.length ? teamsToCreateFromStore : [{ name: "" }],+ moveTeams: teams.map((team) => {+ const teamToMigrateInStore = teamsToMigrateFromStore.find((t) => t.id === team.id);+ return {+ id: team.id,+ shouldMove: !!teamToMigrateInStore,+ newSlug: teamToMigrateInStore?.slug || getSuggestedSlug({ teamSlug: team.slug, orgSlug }),+ name: team.name,+ };+ }),}, // Set initial valuesresolver: async (data) => {try {@@ -91,27 +106,12 @@ const AddNewTeamsFormChild = ({}},});- const session = useSession();- const isAdmin =- session.data?.user?.role === UserPermissionRole.ADMIN ||- session.data?.user?.impersonatedBy?.role === UserPermissionRole.ADMIN;-- const allowWizardCompletionWithoutUpgrading = !IS_TEAM_BILLING_ENABLED_CLIENT || isAdmin;const { register, control, watch, getValues } = form;const { fields, append, remove } = useFieldArray({control,name: "teams",});- const publishOrgMutation = trpc.viewer.organizations.publish.useMutation({- onSuccess(data) {- router.push(data.url);- },- onError: (error) => {- showToast(error.message, "error");- },- });-const handleCounterIncrease = () => {if (counter >= 0 && counter < 5) {setCounter((prevCounter) => prevCounter + 1);@@ -124,40 +124,32 @@ const AddNewTeamsFormChild = ({setCounter((prevCounter) => prevCounter - 1);};- const createTeamsMutation = trpc.viewer.organizations.createTeams.useMutation({- async onSuccess(data) {- if (data.duplicatedSlugs.length) {- showToast(t("duplicated_slugs_warning", { slugs: data.duplicatedSlugs.join(", ") }), "warning");- // Server will return array of duplicated slugs, so we need to wait for user to read the warning- // before pushing to next page- setTimeout(() => handleSuccessRedirect, 3000);- } else {- handleSuccessRedirect();- }-- function handleSuccessRedirect() {- if (allowWizardCompletionWithoutUpgrading) {- router.push(`/event-types`);- return;- }- // mutate onSuccess will take care of routing to the correct place.- publishOrgMutation.mutate();- }- },- onError: (error) => {- showToast(t(error.message), "error");- },- });-const handleFormSubmit = () => {const fields = getValues("teams");const moveTeams = getValues("moveTeams");- createTeamsMutation.mutate({- orgId: org.id,- moveTeams,- teamNames: fields.map((field) => field.name),- creationSource: CreationSource.WEBAPP,++ const teamsBeingMoved = moveTeams.map((team) => {+ return {+ id: team.id,+ isBeingMigrated: team.shouldMove,+ slug: team.newSlug,+ name: team.name,+ };});++ const newTeams = fields+ .map((team) => {+ return {+ id: -1,+ isBeingMigrated: false,+ slug: getSuggestedSlug({ teamSlug: team.name, orgSlug }),+ name: team.name,+ };+ })+ .filter((team) => team.slug !== "");++ setTeams([...teamsBeingMoved, ...newTeams]);+ router.push(`/settings/organizations/new/onboard-members`);};const moveTeams = watch("moveTeams");@@ -233,7 +225,6 @@ const AddNewTeamsFormChild = ({<ButtonStartIcon="plus"color="secondary"- disabled={createTeamsMutation.isPending}onClick={handleCounterIncrease}aria-label={t("add_a_team")}className="my-1"@@ -243,12 +234,11 @@ const AddNewTeamsFormChild = ({)}<ButtonEndIcon="arrow-right"+ type="submit"color="primary"className="mt-6 w-full justify-center"- data-testId="continue_or_checkout"- disabled={createTeamsMutation.isPending || createTeamsMutation.isSuccess}- onClick={handleFormSubmit}>- {allowWizardCompletionWithoutUpgrading ? t("continue") : t("checkout")}+ data-testId="continue_or_checkout">+ {t("continue")}</Button></Form></>diff --git a/apps/web/modules/settings/organizations/new/_components/OnboardMembersView.tsx b/apps/web/modules/settings/organizations/new/_components/OnboardMembersView.tsxnew file mode 100644index 00000000000..c51b1b13654--- /dev/null+++ b/apps/web/modules/settings/organizations/new/_components/OnboardMembersView.tsx@@ -0,0 +1,213 @@+"use client";++import { useSession } from "next-auth/react";+import { useState } from "react";+import { useForm } from "react-hook-form";+import { z } from "zod";++import { useOnboarding } from "@calcom/features/ee/organizations/lib/onboardingStore";+import { useLocale } from "@calcom/lib/hooks/useLocale";+import type { RouterOutputs } from "@calcom/trpc";+import { trpc } from "@calcom/trpc";+import {+ Avatar,+ Badge,+ Button,+ SkeletonContainer,+ SkeletonText,+ SkeletonButton,+ Tooltip,+ TextField,+ showToast,+ Alert,+} from "@calcom/ui";++type TeamMember = RouterOutputs["viewer"]["teams"]["listMembers"]["members"][number];++const AddNewTeamMembers = () => {+ const session = useSession();++ if (session.status === "loading") {+ return <SkeletonContainer>Loading...</SkeletonContainer>;+ }+ return <AddNewTeamMembersForm />;+};++const useCheckout = () => {+ const { t } = useLocale();+ const [serverErrorMessage, setServerErrorMessage] = useState("");+ const mutation = trpc.viewer.organizations.createWithPaymentIntent.useMutation({+ onSuccess: (data) => {+ if (data.checkoutUrl) {+ window.location.href = data.checkoutUrl;+ }+ },+ onError: (error) => {+ setServerErrorMessage(t(error.message));+ },+ });++ return {+ mutation,+ mutate: mutation.mutate,+ isPending: mutation.isPending,+ errorMessage: serverErrorMessage,+ };+};++export const AddNewTeamMembersForm = () => {+ const { t } = useLocale();+ const { useOnboardingStore } = useOnboarding();+ const {+ addInvitedMember,+ removeInvitedMember,+ orgOwnerEmail,+ teams,+ invitedMembers,+ logo,+ bio,+ onboardingId,+ } = useOnboardingStore();+ const checkout = useCheckout();++ const teamIds = teams.filter((team) => team.isBeingMigrated && team.id > 0).map((team) => team.id);++ const results = trpc.useQueries((t) => teamIds.map((teamId) => t.viewer.teams.listMembers({ teamId })));++ const isLoading = results.some((result) => result.isLoading);++ // Combine all members and remove duplicates+ const uniqueMembers = results+ .reduce<TeamMember[]>((acc, result) => {+ if (result.data?.members) {+ return [...acc, ...result.data.members];+ }+ return acc;+ }, [])+ .filter((member, index, self) => index === self.findIndex((m) => m.email === member.email));++ const { register, handleSubmit, reset } = useForm<{ email: string }>();++ const onSubmit = handleSubmit((data) => {+ const parsedEmail = z.string().email().safeParse(data.email);+ if (!parsedEmail.success) {+ return;+ }++ const normalizedEmail = parsedEmail.data.toLowerCase();++ // Check if email exists in either invitedMembers or uniqueMembers+ const isInvited = invitedMembers.some((member) => member.email.toLowerCase() === normalizedEmail);+ const isExisting = uniqueMembers?.some((member) => member.email.toLowerCase() === normalizedEmail);++ if (isInvited || isExisting) {+ showToast(t("member_already_invited"), "error");+ return;+ }++ addInvitedMember({ email: normalizedEmail });+ reset();+ });++ if (isLoading) {+ return (+ <SkeletonContainer as="div" className="space-y-6">+ <SkeletonText className="h-8 w-full" />+ <SkeletonText className="h-8 w-full" />+ <SkeletonButton className="mr-6 h-8 w-20 rounded-md p-5" />+ </SkeletonContainer>+ );+ }++ return (+ <>+ {checkout.errorMessage && (+ <div className="mb-4">+ <Alert severity="error" message={checkout.errorMessage} />+ </div>+ )}+ <div className="space-y-6">+ <div className="flex space-x-3">+ <form onSubmit={onSubmit} className="flex w-full items-end space-x-2">+ <div className="flex-grow">+ <TextField+ label={t("email")}+ type="email"+ {...register("email", { required: true })}+ placeholder="[email protected]"+ />+ </div>+ <Button type="submit" StartIcon="plus" color="secondary">+ {t("add")}+ </Button>+ </form>+ </div>++ {(invitedMembers.length > 0 || uniqueMembers?.length > 0) && (+ <ul+ className="border-subtle divide-subtle max-h-[300px] divide-y overflow-y-auto rounded-md border"+ data-testid="pending-member-list">+ {invitedMembers.map((member) => (+ <li key={member.email} className="flex items-center justify-between px-5 py-2">+ <div className="flex items-center space-x-3">+ <Avatar size="sm" alt={member.email} />+ <div className="flex gap-1">+ <Tooltip content={member.email}>+ <span className="text-subtle max-w-[250px] truncate text-sm">{member.email}</span>+ </Tooltip>+ <Badge variant="gray">{t("pending")}</Badge>+ </div>+ </div>+ <Button+ variant="icon"+ size="sm"+ color="minimal"+ StartIcon="x"+ onClick={() => removeInvitedMember(member.email)}+ />+ </li>+ ))}+ {uniqueMembers?.map((member) => (+ <li key={member.email} className="flex items-center justify-between px-5 py-2">+ <div className="flex items-center space-x-3">+ <Avatar size="sm" alt={member.email} imageSrc={member.avatarUrl} />+ <div className="flex gap-1">+ <Tooltip content={member.email}>+ <span className="text-emphasis text-sm font-medium">{member.name || member.email}</span>+ </Tooltip>+ {/* TODO: We should show the team name here instead of "migrating from team" */}+ <Badge variant="green">{t("migrating_from_team")}</Badge>+ </div>+ </div>+ </li>+ ))}+ </ul>+ )}+ </div>+ <div className="mt-3 mt-6 flex items-center justify-end">+ <Button+ onClick={() => {+ if (!onboardingId) {+ console.error("Org owner email and onboardingId are required", {+ orgOwnerEmail,+ onboardingId,+ });+ return;+ }+ checkout.mutation.mutate({+ logo,+ bio,+ teams,+ invitedMembers,+ onboardingId,+ });+ }}+ loading={checkout.isPending}>+ {t("checkout")}+ </Button>+ </div>+ </>+ );+};++export default AddNewTeamMembers;diff --git a/apps/web/modules/settings/organizations/new/_components/PaymentStatusView.tsx b/apps/web/modules/settings/organizations/new/_components/PaymentStatusView.tsxnew file mode 100644index 00000000000..506b0670ad2--- /dev/null+++ b/apps/web/modules/settings/organizations/new/_components/PaymentStatusView.tsx@@ -0,0 +1,67 @@+"use client";++import { useRouter, useSearchParams } from "next/navigation";+import { useEffect, useState } from "react";++import { useOnboarding } from "@calcom/features/ee/organizations/lib/onboardingStore";+import { useLocale } from "@calcom/lib/hooks/useLocale";+import { trpc } from "@calcom/trpc";+import { Button, Icon } from "@calcom/ui";++const PaymentStatusView = () => {+ const { t } = useLocale();+ const router = useRouter();+ const searchParams = useSearchParams();+ const paymentStatus = searchParams?.get("paymentStatus");+ const paymentError = searchParams?.get("error");+ const { useOnboardingStore } = useOnboarding({+ step: "status",+ });+ const [organizationCreated, setOrganizationCreated] = useState<boolean>(false);+ const { name } = useOnboardingStore();++ const { data: organization } = trpc.viewer.organizations.listCurrent.useQuery(undefined, {+ refetchInterval: 2000, // Poll every 2 seconds until org is created+ enabled: !organizationCreated,+ });++ useEffect(() => {+ if (organization) {+ setOrganizationCreated(true);+ // Organization is created, redirect to next step+ router.push(`/settings/organizations`);+ }+ }, [organization, router, useOnboardingStore]);++ if (paymentStatus === "failed" || paymentError) {+ return (+ <div className="flex min-h-[500px] flex-col items-center justify-center space-y-6 px-4 sm:px-6">+ <div className="flex h-12 w-12 items-center justify-center rounded-full bg-red-100">+ <Icon name="x" className="h-6 w-6 text-red-600" />+ </div>+ <div className="text-center">+ <h1 className="font-cal text-emphasis text-2xl">{t("payment_failed")}</h1>+ <p className="text-default mt-2 text-sm">{paymentError || t("payment_failed_description")}</p>+ </div>+ <Button color="secondary" href="/settings/organizations/new/onboard-members">+ {t("try_again")}+ </Button>+ </div>+ );+ }++ return (+ <div className="flex min-h-[500px] flex-col items-center justify-center space-y-6 px-4 sm:px-6">+ <div className="flex h-12 w-12 items-center justify-center rounded-full bg-green-100">+ <Icon name="check" className="h-6 w-6 text-green-600 dark:text-green-400" />+ </div>+ <div className="text-center">+ <h1 className="font-cal text-emphasis text-2xl">{t("payment_successful")}</h1>+ <p className="text-default mt-2 text-sm">{t("creating_your_organization", { orgName: name })}</p>+ <p className="text-subtle mt-1 text-sm">{t("this_may_take_a_few_seconds")}</p>+ </div>+ </div>+ );+};++export default PaymentStatusView;diff --git a/apps/web/modules/settings/organizations/[id]/about-view.tsx b/apps/web/modules/settings/organizations/new/about-view.tsxsimilarity index 86%rename from apps/web/modules/settings/organizations/[id]/about-view.tsxrename to apps/web/modules/settings/organizations/new/about-view.tsxindex d84565803d3..356936f2528 100644--- a/apps/web/modules/settings/organizations/[id]/about-view.tsx+++ b/apps/web/modules/settings/organizations/new/about-view.tsx@@ -5,7 +5,7 @@ import { WizardLayout } from "@calcom/ui";export const LayoutWrapper = ({ children }: { children: React.ReactNode }) => {return (- <WizardLayout currentStep={3} maxSteps={5}>+ <WizardLayout currentStep={2} maxSteps={5}>{children}</WizardLayout>);diff --git a/apps/web/modules/settings/organizations/new/add-teams-view.tsx b/apps/web/modules/settings/organizations/new/add-teams-view.tsxnew file mode 100644index 00000000000..ea0e11142b7--- /dev/null+++ b/apps/web/modules/settings/organizations/new/add-teams-view.tsx@@ -0,0 +1,15 @@+"use client";++import { WizardLayout } from "@calcom/ui";++import { AddNewTeamsForm } from "./_components/AddNewTeamsForm";++export const LayoutWrapper = ({ children }: { children: React.ReactNode }) => {+ return (+ <WizardLayout currentStep={3} maxSteps={5}>+ {children}+ </WizardLayout>+ );+};++export default AddNewTeamsForm;diff --git a/apps/web/modules/settings/organizations/new/flow.mermaid b/apps/web/modules/settings/organizations/new/flow.mermaidnew file mode 100644index 00000000000..37285431368--- /dev/null+++ b/apps/web/modules/settings/organizations/new/flow.mermaid@@ -0,0 +1,39 @@+graph TD+ Start[Start] --> AboutOrg[About Organization Form]+ AboutOrg -->|Set Name, Logo, Bio| Teams[Add Teams]+ Teams -->|Create/Migrate Teams| Members[Add Team Members]+ Members -->|Add Members & Invite| Payment[Payment]+ Payment -->|Create Payment Intent| StripeCheckout[Stripe Checkout]+ StripeCheckout -->|Success| PaymentSuccess[Payment Success View]+ StripeCheckout -->|Failure| Payment++ subgraph "About Organization"+ AboutOrg -->|Store in onboardingStore| OrgData[Organization Data]+ OrgData -->|"Name, Logo, Bio"| ValidateSlug[Validate Slug]+ end++ subgraph "Teams Setup"+ Teams -->|Store in onboardingStore| TeamData[Teams Data]+ TeamData -->|"Create New/Migrate"| TeamMembers[Team Members]+ end++ subgraph "Members Setup"+ Members -->|Store in onboardingStore| MemberData[Members Data]+ MemberData -->|"Invited/Migrating"| MembersList[Members List]+ end++ subgraph "Payment Process"+ Payment -->|Create Intent| PaymentData[Payment Data]+ PaymentData -->|"Billing Period, Price/Seat"| StripeSession[Stripe Session]+ end++ subgraph "Webhook Handling"+ StripeCheckout -->|invoice.paid| WebhookHandler[Webhook Handler]+ WebhookHandler -->|Process Payment| OrgCreation[Create Organization]+ OrgCreation --> Complete[Complete]+ end++ style Start fill:#f9f,stroke:#333,stroke-width:2px+ style Complete fill:#9f9,stroke:#333,stroke-width:2px+ style StripeCheckout fill:#fdd,stroke:#333,stroke-width:2px+ style WebhookHandler fill:#ddf,stroke:#333,stroke-width:2px\ No newline at end of filediff --git a/apps/web/modules/settings/organizations/new/onboard-members-view.tsx b/apps/web/modules/settings/organizations/new/onboard-members-view.tsxnew file mode 100644index 00000000000..c90e8709e72--- /dev/null+++ b/apps/web/modules/settings/organizations/new/onboard-members-view.tsx@@ -0,0 +1,15 @@+"use client";++import { WizardLayout } from "@calcom/ui";++import AddNewTeamMembers from "./_components/OnboardMembersView";++export const LayoutWrapper = ({ children }: { children: React.ReactNode }) => {+ return (+ <WizardLayout currentStep={4} maxSteps={5}>+ {children}+ </WizardLayout>+ );+};++export default AddNewTeamMembers;diff --git a/apps/web/modules/settings/organizations/new/onboarding-handover.tsx b/apps/web/modules/settings/organizations/new/onboarding-handover.tsxnew file mode 100644index 00000000000..58dd9067a94--- /dev/null+++ b/apps/web/modules/settings/organizations/new/onboarding-handover.tsx@@ -0,0 +1,14 @@+"use client";++import { AdminOnboardingHandover } from "@calcom/features/ee/organizations/components";+import { WizardLayout } from "@calcom/ui";++export const LayoutWrapper = ({ children }: { children: React.ReactNode }) => {+ return (+ <WizardLayout currentStep={2} maxSteps={2}>+ {children}+ </WizardLayout>+ );+};++export default AdminOnboardingHandover;diff --git a/apps/web/modules/settings/organizations/[id]/add-teams-view.tsx b/apps/web/modules/settings/organizations/new/payment-status-view.tsxsimilarity index 65%rename from apps/web/modules/settings/organizations/[id]/add-teams-view.tsxrename to apps/web/modules/settings/organizations/new/payment-status-view.tsxindex ad498b34b5d..d4f130d5253 100644--- a/apps/web/modules/settings/organizations/[id]/add-teams-view.tsx+++ b/apps/web/modules/settings/organizations/new/payment-status-view.tsx@@ -1,8 +1,9 @@"use client";-import { AddNewTeamsForm } from "@calcom/features/ee/organizations/components";import { WizardLayout } from "@calcom/ui";+import PaymentStatusView from "~/settings/organizations/new/_components/PaymentStatusView";+export const LayoutWrapper = ({ children }: { children: React.ReactNode }) => {return (<WizardLayout currentStep={5} maxSteps={5}>@@ -11,4 +12,4 @@ export const LayoutWrapper = ({ children }: { children: React.ReactNode }) => {);};-export default AddNewTeamsForm;+export default PaymentStatusView;diff --git a/apps/web/next.config.js b/apps/web/next.config.jsindex 46bd0e145e6..a9da42d69cb 100644--- a/apps/web/next.config.js+++ b/apps/web/next.config.js@@ -535,6 +535,11 @@ const nextConfig = {},async redirects() {const redirects = [+ {+ source: "/settings/organizations",+ destination: "/settings/organizations/profile",+ permanent: false,+ },{source: "/apps/routing-forms",destination: "/routing/forms",diff --git a/apps/web/package.json b/apps/web/package.jsonindex dbef99c5dd9..0ecbc2874db 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -20,7 +20,8 @@"lint:fix": "eslint . --ext .ts,.js,.tsx,.jsx --fix","lint:report": "eslint . --format json --output-file ../../lint-results/web.json","check-changed-files": "ts-node scripts/ts-check-changed-files.ts",- "translate-locales": "ts-node scripts/check-missing-translations.ts"+ "translate-locales": "ts-node scripts/check-missing-translations.ts",+ "stripe:listen": "stripe listen --forward-to http://localhost:3000/api/stripe/webhook"},"engines": {"yarn": "3.4.1"diff --git a/apps/web/playwright/organization/organization-creation.e2e.ts b/apps/web/playwright/organization/organization-creation.e2e.tsindex af156486aad..f93bb861d93 100644--- a/apps/web/playwright/organization/organization-creation.e2e.ts+++ b/apps/web/playwright/organization/organization-creation.e2e.ts@@ -11,7 +11,6 @@ import type { createEmailsFixture } from "../fixtures/emails";import { test } from "../lib/fixtures";import { fillStripeTestCheckout } from "../lib/testUtils";import { getEmailsReceivedByUser } from "../lib/testUtils";-import { gotoPathAndExpectRedirectToOrgDomain } from "./lib/gotoPathAndExpectRedirectToOrgDomain";async function expectEmailWithSubject(page: Page,@@ -103,7 +102,7 @@ function capitalize(text: string) {}test.describe("Organization", () => {- test("Admin should be able to create an org where an existing user is made an owner", async ({+ test("Admin should be able to do onboarding handover an org where an existing user is made an owner", async ({page,users,emails,@@ -141,113 +140,13 @@ test.describe("Organization", () => {await fillAndSubmitFirstStepAsAdmin(page, orgOwnerEmail, orgName, orgSlug);});- await expectOrganizationCreationEmailToBeSentWithLinks({- page,- emails,- userEmail: orgOwnerEmail,- oldUsername: orgOwnerUsernameOutsideOrg || "",- newUsername: orgOwnerUsernameInOrg,- orgSlug,- });-- await test.step("About the organization", async () => {- // Choosing an avatar- await page.getByTestId("open-upload-avatar-dialog").click();- const fileChooserPromise = page.waitForEvent("filechooser");- await page.getByText("Choose a file...").click();- const fileChooser = await fileChooserPromise;- await fileChooser.setFiles(path.join(__dirname, "../../public/apple-touch-icon.png"));- await page.getByTestId("upload-avatar").click();-- // About text- await page.locator('textarea[name="about"]').fill("This is a testing org");- await page.locator("button[type=submit]").click();-- // Waiting to be in next step URL- await page.waitForURL("/settings/organizations/*/onboard-members");- });-- await test.step("On-board administrators", async () => {- await page.waitForSelector('[data-testid="pending-member-list"]');- await expect(page.getByTestId("pending-member-item")).toHaveCount(1);-- const adminEmail = users.trackEmail({ username: "rick", domain: `example.com` });-- //can add members- await page.getByTestId("new-member-button").click();- await page.locator('[placeholder="email\\@example\\.com"]').fill(adminEmail);- await page.getByTestId("invite-new-member-button").click();- await expect(page.getByTestId("pending-member-item").filter({ hasText: adminEmail })).toBeVisible();- // TODO: Check if invited admin received the invitation email- // await expectInvitationEmailToBeReceived(- // page,- // emails,- // adminEmail,- // `${orgName}'s admin invited you to join the organization ${orgName} on Cal.com`- // );- await expect(page.getByTestId("pending-member-item")).toHaveCount(2);-- // can remove members- await expect(page.getByTestId("pending-member-item")).toHaveCount(2);- const lastRemoveMemberButton = page.getByTestId("remove-member-button").last();- await lastRemoveMemberButton.click();- await expect(page.getByTestId("pending-member-item")).toHaveCount(1);- await page.getByTestId("publish-button").click();- // Waiting to be in next step URL- await page.waitForURL("/settings/organizations/*/add-teams");- });-- await test.step("Create teams", async () => {- // Filling one team- await page.locator('input[name="teams.0.name"]').fill("Marketing");-- // Adding another team- await page.getByTestId("add_a_team").click();- await page.locator('input[name="teams.1.name"]').fill("Sales");-- // Finishing the creation wizard- await page.getByTestId("continue_or_checkout").click();- await page.waitForURL("/event-types");- });-- await test.step("Login as org owner and pay", async () => {- // eslint-disable-next-line playwright/no-skipped-test- test.skip(!IS_TEAM_BILLING_ENABLED, "Skipping paying for org as stripe is disabled");-- await orgOwnerUser.apiLogin();- await page.goto("/event-types");- const upgradeButton = await page.getByTestId("upgrade_org_banner_button");-- await expect(upgradeButton).toBeVisible();- await upgradeButton.click();- // Check that stripe checkout is present- const expectedUrl = "https://checkout.stripe.com";-- await page.waitForURL((url) => url.href.startsWith(expectedUrl));- const url = page.url();-- // Check that the URL matches the expected URL- expect(url).toContain(expectedUrl);-- await fillStripeTestCheckout(page);-- const upgradeButtonHidden = await page.getByTestId("upgrade_org_banner_button");-- await expect(upgradeButtonHidden).toBeHidden();- });-- // Verify that the owner's old username redirect is properly set- await gotoPathAndExpectRedirectToOrgDomain({- page,- org: {- slug: orgSlug,- },- path: `/${orgOwnerUsernameOutsideOrg}`,- expectedPath: `/${orgOwnerUsernameInOrg}`,+ await test.step("Handover", async () => {+ const onboardingUrl = await page.getByTestId("onboarding-url").textContent();+ expect(onboardingUrl).toContain("settings/organizations/new");});});- test("Admin should be able to create an org where the owner doesn't exist yet", async ({+ test.skip("Admin should be able to create an org where the owner doesn't exist yet", async ({page,users,emails,@@ -570,7 +469,7 @@ async function fillAndSubmitFirstStepAsAdmin(await page.locator("input[name=pricePerSeat]").fill("30");await Promise.all([- page.waitForResponse("**/api/trpc/organizations/create**"),+ page.waitForResponse("**/api/trpc/organizations/intentToCreateOrg**"),page.locator("button[type=submit]").click(),]);}diff --git a/apps/web/public/static/locales/en/common.json b/apps/web/public/static/locales/en/common.jsonindex b2289d381a8..8b4ef4be22f 100644--- a/apps/web/public/static/locales/en/common.json+++ b/apps/web/public/static/locales/en/common.json@@ -2939,6 +2939,7 @@"dry_run_mode_active": "You are doing a test booking.","icon_showcase": "Icon showcase","icons_showcase": "Icons showcase",+ "migrating_from_team":"Migrating from team","feature_currently_disabled": "Feature is currently disabled","choose_an_option": "Choose an option","enter_option_value": "Enter option value",@@ -2968,6 +2969,32 @@"asc": "Asc","desc": "Desc","verify_email_change": "Verify email change",+ "organization_slug_taken": "Organization slug is already taken",+ "you_cannot_create_an_organization_as_you_are_already_part_of_an_organization": "You cannot create an organization as you are already a part of an organization",+ "you_need_to_complete_user_onboarding_before_creating_an_organization": "You need to complete user onboarding before creating an organization",+ "use_company_email_to_create_an_organization": "Use company email to create an organization",+ "you_cannot_create_a_platform_organization_as_you_are_already_part_of_a_team": "You cannot create a platform organization as you are already a part of a team",+ "you_need_to_have_minimum_published_teams": "You need to have minimum published teams",+ "you_are_part_of_this_organization_already": "You are part of this organization already",+ "you_are_part_of_another_organization_cannot_create_organization": "You are part of another organization, cannot create a new organization",+ "organization_payment_success": "Organization payment success",+ "organization_payment_success_description": "Your organization has been created successfully",+ "this_may_take_a_few_seconds": "This may take a few seconds...",+ "organization_onboarding_status": "Organization onboarding status",+ "organization_onboarding_status_description": "Organization onboarding status description",+ "payment_failed": "Payment failed",+ "payment_failed_description": "Your payment has failed. Please try again.",+ "creating_your_organization": "Creating your organization",+ "organization_onboarding_already_completed": "Organization onboarding already completed",+ "organization_onboarding_already_exists": "Organization onboarding already exists",+ "organization_onboarding_not_found": "Organization onboarding not found",+ "payment_successful": "Payment successful",+ "handover_onboarding_page_title": "Handover onboarding",+ "handover_onboarding_page_description": "Handover onboarding to the user",+ "organization_already_exists_with_this_slug": "Organization already exists with this slug",+ "you_do_not_have_permission_to_create_an_organization_for_this_email": "You do not have permission to create an organization for this email",+ "you_do_not_have_permission_to_migrate_one_or_more_of_the_teams": "You do not have permission to migrate one or more of the teams",+ "organization_has_subscription_already": "Organization has a subscription already","rr_reset_interval": "Round Robin Reset Interval","interval": "Interval","rr_reset_interval_description": "Determines how often the round robin booking count resets to ensure balanced distribution.",diff --git a/packages/emails/src/templates/OrganizationCreationEmail.tsx b/packages/emails/src/templates/OrganizationCreationEmail.tsxindex b386b66ca4e..d9c6dfc46c5 100644--- a/packages/emails/src/templates/OrganizationCreationEmail.tsx+++ b/packages/emails/src/templates/OrganizationCreationEmail.tsx@@ -36,8 +36,7 @@ export const OrganizationCreationEmail = (marginTop: "32px",lineHeightStep: "24px",}}>- You have been added as an owner of the organization. To publish your new organization, visit{" "}- <a href={`${WEBAPP_URL}/upgrade`}>{WEBAPP_URL}/upgrade</a>+ You have been added as an owner of the organization.</p><pdata-testid="organization-link-info"diff --git a/packages/features/ee/billing/api/webhook/_invoice.paid.org.ts b/packages/features/ee/billing/api/webhook/_invoice.paid.org.tsnew file mode 100644index 00000000000..451091d837c--- /dev/null+++ b/packages/features/ee/billing/api/webhook/_invoice.paid.org.ts@@ -0,0 +1,96 @@+import { z } from "zod";++import { createOrganizationFromOnboarding } from "@calcom/features/ee/organizations/lib/server/createOrganizationFromOnboarding";+import logger from "@calcom/lib/logger";+import { safeStringify } from "@calcom/lib/safeStringify";+import { OrganizationOnboardingRepository } from "@calcom/lib/server/repository/organizationOnboarding";++import type { SWHMap } from "./__handler";++const invoicePaidSchema = z.object({+ object: z.object({+ customer: z.string(),+ subscription: z.string(),+ lines: z.object({+ data: z.array(+ z.object({+ subscription_item: z.string(),+ })+ ),+ }),+ }),+});++async function handlePaymentReceivedForOnboarding({+ organizationOnboarding,+ paymentSubscriptionId,+ paymentSubscriptionItemId,+}: {+ organizationOnboarding: { id: string };+ paymentSubscriptionId: string;+ paymentSubscriptionItemId: string;+}) {+ await OrganizationOnboardingRepository.update(organizationOnboarding.id, {+ stripeSubscriptionId: paymentSubscriptionId,+ stripeSubscriptionItemId: paymentSubscriptionItemId,+ });+}++const handler = async (data: SWHMap["invoice.paid"]["data"]) => {+ const { object: invoice } = invoicePaidSchema.parse(data);+ const subscriptionItemId = invoice.lines.data[0]?.subscription_item;+ const subscriptionId = invoice.subscription;+ logger.debug(+ `Processing invoice paid webhook for customer ${invoice.customer} and subscription ${invoice.subscription}`+ );++ const organizationOnboarding = await OrganizationOnboardingRepository.findByStripeCustomerId(+ invoice.customer+ );++ if (!organizationOnboarding) {+ logger.error(+ `NonRecoverableError: No onboarding record found for stripe customer id: ${invoice.customer}.`+ );++ // Don't throw as we don't want to retry.+ return {+ success: false,+ error: `No onboarding record found for stripe customer id: ${invoice.customer}.`,+ };+ }++ const paymentSubscriptionId = subscriptionId;+ const paymentSubscriptionItemId = subscriptionItemId;++ await handlePaymentReceivedForOnboarding({+ organizationOnboarding,+ paymentSubscriptionId,+ paymentSubscriptionItemId,+ });++ try {+ const { organization } = await createOrganizationFromOnboarding({+ organizationOnboarding,+ paymentSubscriptionId,+ paymentSubscriptionItemId,+ });++ logger.debug(`Marking onboarding as complete for organization ${organization.id}`);+ await OrganizationOnboardingRepository.markAsComplete(organizationOnboarding.id);+ return { success: true };+ } catch (error) {+ if (error instanceof Error) {+ await OrganizationOnboardingRepository.update(organizationOnboarding.id, {+ error: error.message,+ });+ }+ logger.error(+ `Error creating organization from onboarding:${organizationOnboarding.id}`,+ safeStringify({ error: error instanceof Error ? error.message : error })+ );+ throw error;+ }+};++export default handler;diff --git a/packages/features/ee/billing/api/webhook/_invoice.paid.ts b/packages/features/ee/billing/api/webhook/_invoice.paid.tsnew file mode 100644index 00000000000..ff3782609b8--- /dev/null+++ b/packages/features/ee/billing/api/webhook/_invoice.paid.ts@@ -0,0 +1,41 @@+import { HttpCode } from "./__handler";+import type { LazyModule, SWHMap } from "./__handler";+import logger from "@calcom/lib/logger";++type Data = SWHMap["invoice.paid"]["data"];++type Handlers = Record<`prod_${string}`, () => LazyModule<Data>>;++// We can't crash here if STRIPE_ORG_PRODUCT_ID is not set, because not all self-hosters use Organizations and it might break the build on import of this module.+const STRIPE_ORG_PRODUCT_ID = process.env.STRIPE_ORG_PRODUCT_ID || "";++const log = logger.getSubLogger({ prefix: ["stripe-webhook-invoice-paid"] });++const stripeWebhookProductHandler = (handlers: Handlers) => async (data: Data) => {+ const invoice = data.object;+ // Only handle subscription invoices+ if (!invoice.subscription) {+ log.warn("Not a subscription invoice, skipping");+ return { success: true };+ }++ // Get the product ID from the first subscription item+ const firstItem = invoice.lines.data[0];+ const productId = firstItem?.price?.product as string; // prod_xxxxx++ if (!productId) {+ log.error("No product ID found in invoice, skipping");+ return { success: true };+ }++ const handlerGetter = handlers[productId as keyof typeof handlers];+ if (!handlerGetter) throw new HttpCode(202, `No product handler found for product: ${productId}`);+ const handler = (await handlerGetter())?.default;+ // auto catch unsupported Stripe products.+ if (!handler) throw new HttpCode(202, `No product handler found for product: ${productId}`);+ return await handler(data);+};++export default stripeWebhookProductHandler({+ [STRIPE_ORG_PRODUCT_ID]: () => import("./_invoice.paid.org"),+});diff --git a/packages/features/ee/billing/api/webhook/index.ts b/packages/features/ee/billing/api/webhook/index.tsindex aa3eec5305e..c9c8e000ea7 100644--- a/packages/features/ee/billing/api/webhook/index.ts+++ b/packages/features/ee/billing/api/webhook/index.ts@@ -3,16 +3,15 @@ import { defaultResponder } from "@calcom/lib/server/defaultResponder";import { stripeWebhookHandler } from "./__handler";+// We handle each Stripe webhook event type with it's own lazy loaded handler+const handlers = {+ "payment_intent.succeeded": () => import("./_payment_intent.succeeded"),+ "customer.subscription.deleted": () => import("./_customer.subscription.deleted"),+ "invoice.paid": () => import("./_invoice.paid"),+};+export default defaultHandler({- // We only need to handle POST requestsPOST: Promise.resolve({- default: defaultResponder(- // We handle each Stripe webhook event type with it's own lazy loaded handler- stripeWebhookHandler({- "payment_intent.succeeded": () => import("./_payment_intent.succeeded"),- // "customer.subscription.updated": () => import("./_customer.subscription.deleted"),- "customer.subscription.deleted": () => import("./_customer.subscription.deleted"),- })- ),+ default: defaultResponder(stripeWebhookHandler(handlers)),}),});diff --git a/packages/features/ee/billing/billing-service.ts b/packages/features/ee/billing/billing-service.tsindex 8c88de7b3d7..ebbbd9d2d13 100644--- a/packages/features/ee/billing/billing-service.ts+++ b/packages/features/ee/billing/billing-service.ts@@ -9,5 +9,37 @@ export interface BillingService {subscriptionItemId: string;membershipCount: number;}): Promise<void>;++ // Customer management+ createCustomer(args: {+ email: string;+ metadata?: Record<string, string>;+ }): Promise<{ stripeCustomerId: string }>;+ createPaymentIntent(args: {+ customerId: string;+ amount: number;+ metadata?: Record<string, string | number>;+ }): Promise<{ id: string; client_secret: string | null }>;++ // Subscription management+ createSubscriptionCheckout(args: {+ customerId: string;+ successUrl: string;+ cancelUrl: string;+ priceId: string;+ quantity: number;+ metadata?: Record<string, string | number>;+ mode?: "subscription" | "setup" | "payment";+ }): Promise<{ checkoutUrl: string | null; sessionId: string }>;++ // Price management+ createPrice(args: {+ amount: number;+ currency: string;+ interval: "month" | "year";+ nickname?: string;+ productId: string;+ metadata?: Record<string, string | number>;+ }): Promise<{ priceId: string }>;getSubscriptionStatus(subscriptionId: string): Promise<Stripe.Subscription.Status | null>;}diff --git a/packages/features/ee/billing/organizations/index.ts b/packages/features/ee/billing/organizations/index.tsnew file mode 100644index 00000000000..a5c8489acc1--- /dev/null+++ b/packages/features/ee/billing/organizations/index.ts@@ -0,0 +1,10 @@+import { IS_PRODUCTION } from "@calcom/lib/constants";+import { prisma } from "@calcom/prisma";++import { InternalOrganizationBilling } from "./internal-organization-billing";+import { OrganizationBillingRepository } from "./organization-billing.repository";+import { StubOrganizationBilling } from "./stub-organization-billing";++export { OrganizationBillingRepository };++export const OrganizationBilling = IS_PRODUCTION ? InternalOrganizationBilling : StubOrganizationBilling;\ No newline at end of filediff --git a/packages/features/ee/billing/organizations/internal-organization-billing.ts b/packages/features/ee/billing/organizations/internal-organization-billing.tsnew file mode 100644index 00000000000..35a1990e0c5--- /dev/null+++ b/packages/features/ee/billing/organizations/internal-organization-billing.ts@@ -0,0 +1,56 @@+import { stripe } from "@calcom/features/ee/payments/server/stripe";++import { OrganizationBilling } from "./organization-billing";+import { OrganizationBillingRepository } from "./organization-billing.repository";++export class InternalOrganizationBilling extends OrganizationBilling {+ constructor(+ organization: Parameters<typeof OrganizationBilling>[0],+ repository: OrganizationBillingRepository = new OrganizationBillingRepository()+ ) {+ super(organization);+ this.repository = repository;+ }++ async getStripeCustomerId() {+ return this.repository.getStripeCustomerId(this.organization.id);+ }++ async getSubscriptionId() {+ return this.repository.getSubscriptionId(this.organization.id);+ }++ async getSubscriptionItems() {+ const subscriptionId = await this.getSubscriptionId();+ if (!subscriptionId) return [];++ const subscription = await stripe.subscriptions.retrieve(subscriptionId);+ return subscription.items.data.map((item) => ({+ id: item.id,+ quantity: item.quantity ?? 0,+ }));+ }++ async createPaymentIntent({ seats, pricePerSeat }: { seats: number; pricePerSeat: number }) {+ const stripeCustomerId = await this.getStripeCustomerId();+ if (!stripeCustomerId) {+ throw new Error("No stripe customer id found");+ }++ const amount = seats * pricePerSeat;++ return stripe.paymentIntents.create({+ amount,+ currency: "usd",+ customer: stripeCustomerId,+ automatic_payment_methods: {+ enabled: true,+ },+ metadata: {+ organizationId: this.organization.id,+ seats,+ pricePerSeat,+ },+ });+ }+}diff --git a/packages/features/ee/billing/organizations/organization-billing.repository.interface.ts b/packages/features/ee/billing/organizations/organization-billing.repository.interface.tsnew file mode 100644index 00000000000..58d240e8529--- /dev/null+++ b/packages/features/ee/billing/organizations/organization-billing.repository.interface.ts@@ -0,0 +1,8 @@+import type { Team } from "@prisma/client";++export interface OrganizationBillingRepository {+ findById(organizationId: number): Promise<Pick<Team, "id" | "slug" | "name" | "billingPeriod"> | null>;++ getStripeCustomerId(organizationId: number): Promise<string | null>;+ getSubscriptionId(organizationId: number): Promise<string | null>;+}diff --git a/packages/features/ee/billing/organizations/organization-billing.repository.ts b/packages/features/ee/billing/organizations/organization-billing.repository.tsnew file mode 100644index 00000000000..cbf4620be2d--- /dev/null+++ b/packages/features/ee/billing/organizations/organization-billing.repository.ts@@ -0,0 +1,46 @@+import { prisma } from "@calcom/prisma";++import type { OrganizationBillingRepository as IOrganizationBillingRepository } from "./organization-billing.repository.interface";++export class OrganizationBillingRepository implements IOrganizationBillingRepository {+ async findById(organizationId: number) {+ return prisma.team.findUnique({+ where: {+ id: organizationId,+ isOrganization: true,+ },+ select: {+ id: true,+ slug: true,+ name: true,+ billingPeriod: true,+ },+ });+ }++ async getStripeCustomerId(organizationId: number) {+ const organization = await prisma.team.findUnique({+ where: {+ id: organizationId,+ isOrganization: true,+ },+ select: {+ stripeCustomerId: true,+ },+ });+ return organization?.stripeCustomerId ?? null;+ }++ async getSubscriptionId(organizationId: number) {+ const organization = await prisma.team.findUnique({+ where: {+ id: organizationId,+ isOrganization: true,+ },+ select: {+ stripeSubscriptionId: true,+ },+ });+ return organization?.stripeSubscriptionId ?? null;+ }+}diff --git a/packages/features/ee/billing/organizations/organization-billing.ts b/packages/features/ee/billing/organizations/organization-billing.tsnew file mode 100644index 00000000000..5e67184ad1c--- /dev/null+++ b/packages/features/ee/billing/organizations/organization-billing.ts@@ -0,0 +1,16 @@+import type { Team } from "@prisma/client";++import type { OrganizationBillingRepository } from "./organization-billing.repository";++export abstract class OrganizationBilling {+ protected organization: Pick<Team, "id" | "slug" | "name" | "billingPeriod">;+ protected repository: OrganizationBillingRepository;++ constructor(organization: Pick<Team, "id" | "slug" | "name" | "billingPeriod">) {+ this.organization = organization;+ }++ abstract getStripeCustomerId(): Promise<string | null>;+ abstract getSubscriptionId(): Promise<string | null>;+ abstract getSubscriptionItems(): Promise<{ id: string; quantity: number }[]>;+}diff --git a/packages/features/ee/billing/organizations/stub-organization-billing.ts b/packages/features/ee/billing/organizations/stub-organization-billing.tsnew file mode 100644index 00000000000..81ebbda7fd0--- /dev/null+++ b/packages/features/ee/billing/organizations/stub-organization-billing.ts@@ -0,0 +1,32 @@+import { OrganizationBilling } from "./organization-billing";+import { OrganizationBillingRepository } from "./organization-billing.repository";++export class StubOrganizationBilling extends OrganizationBilling {+ constructor(+ organization: Parameters<typeof OrganizationBilling>[0],+ repository: OrganizationBillingRepository = new OrganizationBillingRepository()+ ) {+ super(organization);+ this.repository = repository;+ }++ async getStripeCustomerId() {+ return "cus_stub";+ }++ async getSubscriptionId() {+ return "sub_stub";+ }++ async getSubscriptionItems() {+ return [{ id: "si_stub", quantity: 1 }];+ }++ async createPaymentIntent() {+ return {+ id: "pi_stub",+ client_secret: "pi_stub_secret",+ status: "requires_payment_method",+ };+ }+}diff --git a/packages/features/ee/billing/stripe-billling-service.ts b/packages/features/ee/billing/stripe-billling-service.tsindex b7bc1239685..b9d621a32f4 100644--- a/packages/features/ee/billing/stripe-billling-service.ts+++ b/packages/features/ee/billing/stripe-billling-service.ts@@ -9,12 +9,87 @@ export class StripeBillingService implements BillingService {apiVersion: "2020-08-27",});}++ async createCustomer(args: Parameters<BillingService["createCustomer"]>[0]) {+ const { email, metadata } = args;+ const customer = await this.stripe.customers.create({+ email,+ metadata: {+ email,+ ...metadata,+ },+ });+ return { stripeCustomerId: customer.id };+ }++ async createPaymentIntent(args: Parameters<BillingService["createPaymentIntent"]>[0]) {+ const { customerId, amount, metadata } = args;+ const paymentIntent = await this.stripe.paymentIntents.create({+ customer: customerId,+ amount,+ currency: "usd",+ automatic_payment_methods: {+ enabled: true,+ },+ metadata,+ });++ return {+ id: paymentIntent.id,+ client_secret: paymentIntent.client_secret,+ };+ }++ async createSubscriptionCheckout(args: Parameters<BillingService["createSubscriptionCheckout"]>[0]) {+ const { customerId, successUrl, cancelUrl, priceId, quantity, metadata, mode = "subscription" } = args;++ const session = await this.stripe.checkout.sessions.create({+ customer: customerId,+ success_url: successUrl,+ cancel_url: cancelUrl,+ mode,+ metadata,+ line_items: [+ {+ price: priceId,+ quantity,+ },+ ],+ });++ return {+ checkoutUrl: session.url,+ sessionId: session.id,+ };+ }++ async createPrice(args: Parameters<BillingService["createPrice"]>[0]) {+ const { amount, currency, interval, productId, nickname, metadata } = args;++ const price = await this.stripe.prices.create({+ nickname,+ unit_amount: amount,+ currency,+ recurring: {+ interval,+ },+ product: productId,+ metadata,+ });++ return {+ priceId: price.id,+ };+ }+async handleSubscriptionCreation(subscriptionId: string) {throw new Error("Method not implemented.");}+async handleSubscriptionCancel(subscriptionId: string) {await this.stripe.subscriptions.cancel(subscriptionId);}+async handleSubscriptionUpdate(args: Parameters<BillingService["handleSubscriptionUpdate"]>[0]) {const { subscriptionId, subscriptionItemId, membershipCount } = args;const subscription = await this.stripe.subscriptions.retrieve(subscriptionId);@@ -26,6 +101,7 @@ export class StripeBillingService implements BillingService {items: [{ quantity: membershipCount, id: subscriptionItemId }],});}+async checkoutSessionIsPaid(paymentId: string) {const checkoutSession = await this.stripe.checkout.sessions.retrieve(paymentId);return checkoutSession.payment_status === "paid";diff --git a/packages/features/ee/billing/teams/internal-team-billing.ts b/packages/features/ee/billing/teams/internal-team-billing.tsindex aba14c881db..2fd46f0dac0 100644--- a/packages/features/ee/billing/teams/internal-team-billing.ts+++ b/packages/features/ee/billing/teams/internal-team-billing.ts@@ -1,6 +1,6 @@import type { Prisma } from "@prisma/client";import type { z } from "zod";-+import { safeStringify } from "@calcom/lib/safeStringify";import { getRequestedSlugError } from "@calcom/app-store/stripepayment/lib/team-billing";import { purchaseTeamOrOrgSubscription } from "@calcom/features/ee/teams/lib/payments";import { MINIMUM_NUMBER_OF_ORG_SEATS, WEBAPP_URL } from "@calcom/lib/constants";@@ -12,6 +12,7 @@ import { teamMetadataSchema } from "@calcom/prisma/zod-utils";import billing from "..";import { TeamBillingPublishResponseStatus, type TeamBilling, type TeamBillingInput } from "./team-billing";+import { OrganizationOnboardingRepository } from "@calcom/lib/server/repository/organizationOnboarding";const log = logger.getSubLogger({ prefix: ["TeamBilling"] });@@ -120,13 +121,23 @@ export class InternalTeamBilling implements TeamBilling {async updateQuantity() {try {await this.getOrgIfNeeded();+ const { id: teamId, metadata, isOrganization } = this.team;+const { url } = await this.checkIfTeamPaymentRequired();+ const organizationOnboarding = await OrganizationOnboardingRepository.findByOrganizationId(this.team.id);+ log.debug("updateQuantity", safeStringify({ url, team: this.team }));+/*** If there's no pending checkout URL it means that this team has not been paid.* We cannot update the subscription yet, this will be handled on publish/checkout.+ *+ * An organization can only be created if it is paid for and updateQuantity is called only when we have an organization.+ * For some old organizations, it is possible that they aren't paid for yet, but then they wouldn't have been published as well(i.e. slug would be null and are unusable)+ * So, we can safely assume go forward for organizations.**/- if (!url) return;- const { id: teamId, metadata, isOrganization } = this.team;+ if (!url && !isOrganization) return;++ // TODO: To be read from organizationOnboarding for Organizations later, but considering the fact that certain old organization won't have onboardingconst { subscriptionId, subscriptionItemId, orgSeats } = metadata;// Either it would be custom pricing where minimum number of seats are changed(available in orgSeats) or it would be default MINIMUM_NUMBER_OF_ORG_SEATS// We can't go below this quantity for subscriptiondiff --git a/packages/features/ee/organizations/components/AboutOrganizationForm.tsx b/packages/features/ee/organizations/components/AboutOrganizationForm.tsxindex a62b65eb587..d355189118e 100644--- a/packages/features/ee/organizations/components/AboutOrganizationForm.tsx+++ b/packages/features/ee/organizations/components/AboutOrganizationForm.tsx@@ -1,40 +1,26 @@"use client";import { useRouter } from "next/navigation";-import { useState } from "react";import { Controller, useForm } from "react-hook-form";-import z from "zod";+import { useOnboarding } from "@calcom/features/ee/organizations/lib/onboardingStore";import { useLocale } from "@calcom/lib/hooks/useLocale";-import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";-import { trpc } from "@calcom/trpc/react";-import { Alert, Avatar, Button, Form, Icon, ImageUploader, Label, TextAreaField } from "@calcom/ui";--const querySchema = z.object({- id: z.string(),-});+import { Avatar, Button, Form, Icon, ImageUploader, Label, TextAreaField } from "@calcom/ui";export const AboutOrganizationForm = () => {const { t } = useLocale();const router = useRouter();- const routerQuery = useRouterQuery();- const { id: orgId } = querySchema.parse(routerQuery);- const [serverErrorMessage, setServerErrorMessage] = useState<string | null>(null);- const [image, setImage] = useState("");++ const { useOnboardingStore } = useOnboarding();+ const { setLogo, setBio, bio: bioFromStore, logo: logoFromStore } = useOnboardingStore();const aboutOrganizationFormMethods = useForm<{logo: string;bio: string;- }>();-- const updateOrganizationMutation = trpc.viewer.organizations.update.useMutation({- onSuccess: (data) => {- if (data.update) {- router.push(`/settings/organizations/${orgId}/onboard-members`);- }- },- onError: (err) => {- setServerErrorMessage(err.message);+ }>({+ defaultValues: {+ logo: logoFromStore ?? "",+ bio: bioFromStore ?? "",},});@@ -43,23 +29,16 @@ export const AboutOrganizationForm = () => {<Formform={aboutOrganizationFormMethods}className="space-y-5"- handleSubmit={(v) => {- if (!updateOrganizationMutation.isPending) {- setServerErrorMessage(null);- updateOrganizationMutation.mutate({ ...v, orgId });- }+ handleSubmit={(values) => {+ setLogo(values.logo);+ setBio(values.bio);+ router.push(`/settings/organizations/new/add-teams`);}}>- {serverErrorMessage && (- <div>- <Alert severity="error" message={serverErrorMessage} />- </div>- )}-<div><Controllercontrol={aboutOrganizationFormMethods.control}name="logo"- render={() => (+ render={({ field: { value } }) => (<><Label>{t("organization_logo")}</Label><div className="flex items-center">@@ -67,7 +46,7 @@ export const AboutOrganizationForm = () => {alt=""fallback={<Icon name="plus" className="text-subtle h-6 w-6" />}className="items-center"- imageSrc={image}+ imageSrc={value}size="lg"/><div className="ms-4">@@ -76,10 +55,9 @@ export const AboutOrganizationForm = () => {id="avatar-upload"buttonMsg={t("upload")}handleAvatarChange={(newAvatar: string) => {- setImage(newAvatar);aboutOrganizationFormMethods.setValue("logo", newAvatar);}}- imageSrc={image}+ imageSrc={value}/></div></div>@@ -109,9 +87,8 @@ export const AboutOrganizationForm = () => {<div className="flex"><Button- disabled={- aboutOrganizationFormMethods.formState.isSubmitting || updateOrganizationMutation.isPending- }+ // Form submitted means navigation is happening and new Form would render when that occurs, so keep it in loading state+ loading={aboutOrganizationFormMethods.formState.isSubmitted}color="primary"EndIcon="arrow-right"type="submit"diff --git a/packages/features/ee/organizations/components/AdminOnboardingHandover.tsx b/packages/features/ee/organizations/components/AdminOnboardingHandover.tsxnew file mode 100644index 00000000000..77371a14597--- /dev/null+++ b/packages/features/ee/organizations/components/AdminOnboardingHandover.tsx@@ -0,0 +1,49 @@+"use client";++import { useSession } from "next-auth/react";++import { WEBAPP_URL } from "@calcom/lib/constants";+import { useLocale } from "@calcom/lib/hooks/useLocale";+import { Button, showToast } from "@calcom/ui";++export const AdminOnboardingHandover = () => {+ const { t } = useLocale();+ const session = useSession();+ const isAdmin = session.data?.user.role === "ADMIN";++ if (!isAdmin) {+ return null;+ }++ const onboardingUrl = `${WEBAPP_URL}/settings/organizations/new`;++ return (+ <div className="bg-subtle rounded-md p-4">+ <div className="flex-col items-center gap-2">+ <span className="text-emphasis font-medium">+ User can now continue onboarding with the following link+ </span>+ <div className="mt-2 flex items-center gap-2">+ <code+ data-testid="onboarding-url"+ className="bg-default text-default flex w-full items-center truncate rounded-md px-3 py-2 font-mono text-sm">+ {onboardingUrl}+ </code>+ <Button+ data-testid="copy-onboarding-url"+ type="button"+ variant="icon"+ color="secondary"+ className="h-9 w-9"+ onClick={() => {+ navigator.clipboard.writeText(onboardingUrl);+ showToast(t("link_copied"), "success");+ }}+ StartIcon="clipboard"+ tooltip={t("copy_to_clipboard")}+ />+ </div>+ </div>+ </div>+ );+};diff --git a/packages/features/ee/organizations/components/CreateANewOrganizationForm.tsx b/packages/features/ee/organizations/components/CreateANewOrganizationForm.tsxindex a6286fedb72..05bd69c380d 100644--- a/packages/features/ee/organizations/components/CreateANewOrganizationForm.tsx+++ b/packages/features/ee/organizations/components/CreateANewOrganizationForm.tsx@@ -1,7 +1,7 @@"use client";import type { SessionContextValue } from "next-auth/react";-import { signIn, useSession } from "next-auth/react";+import { useSession } from "next-auth/react";import { useRouter } from "next/navigation";import { useState } from "react";import { Controller, useForm } from "react-hook-form";@@ -10,14 +10,15 @@ import { subdomainSuffix } from "@calcom/features/ee/organizations/lib/orgDomainimport { MINIMUM_NUMBER_OF_ORG_SEATS } from "@calcom/lib/constants";import { useLocale } from "@calcom/lib/hooks/useLocale";import slugify from "@calcom/lib/slugify";-import { telemetryEventTypes, useTelemetry } from "@calcom/lib/telemetry";-import { UserPermissionRole } from "@calcom/prisma/enums";import { CreationSource } from "@calcom/prisma/enums";+import { UserPermissionRole } from "@calcom/prisma/enums";import { trpc } from "@calcom/trpc/react";import type { Ensure } from "@calcom/types/utils";import { Alert, Button, Form, Label, RadioGroup as RadioArea, TextField, ToggleGroup } from "@calcom/ui";import classNames from "@calcom/ui/classNames";+import { useOnboarding } from "../lib/onboardingStore";+function extractDomainFromEmail(email: string) {let out = "";try {@@ -29,9 +30,12 @@ function extractDomainFromEmail(email: string) {export const CreateANewOrganizationForm = () => {const session = useSession();- if (!session.data) {++ const { isLoadingOrgOnboarding } = useOnboarding({ step: "start" });+ if (!session.data || isLoadingOrgOnboarding) {return null;}+return <CreateANewOrganizationFormChild session={session} />;};@@ -40,50 +44,53 @@ enum BillingPeriod {ANNUALLY = "ANNUALLY",}-const CreateANewOrganizationFormChild = ({- session,-}: {- session: Ensure<SessionContextValue, "data">;- isPlatformOrg?: boolean;-}) => {+const CreateANewOrganizationFormChild = ({ session }: { session: Ensure<SessionContextValue, "data"> }) => {const { t } = useLocale();const router = useRouter();- const telemetry = useTelemetry();const [serverErrorMessage, setServerErrorMessage] = useState<string | null>(null);const isAdmin = session.data.user.role === UserPermissionRole.ADMIN;const defaultOrgOwnerEmail = session.data.user.email ?? "";+ const { useOnboardingStore } = useOnboarding({ step: "start" });+ const { slug, name, orgOwnerEmail, billingPeriod, pricePerSeat, seats, onboardingId, reset } =+ useOnboardingStore();+const newOrganizationFormMethods = useForm<{name: string;- seats: number;+ seats: number | null;billingPeriod: BillingPeriod;- pricePerSeat: number;+ pricePerSeat: number | null;slug: string;orgOwnerEmail: string;}>({defaultValues: {- billingPeriod: BillingPeriod.MONTHLY,- slug: !isAdmin ? deriveSlugFromEmail(defaultOrgOwnerEmail) : undefined,- orgOwnerEmail: !isAdmin ? defaultOrgOwnerEmail : undefined,- name: !isAdmin ? deriveOrgNameFromEmail(defaultOrgOwnerEmail) : undefined,+ billingPeriod: billingPeriod ?? BillingPeriod.MONTHLY,+ slug: slug ?? (!isAdmin ? deriveSlugFromEmail(defaultOrgOwnerEmail) : undefined),+ orgOwnerEmail: orgOwnerEmail || (!isAdmin ? defaultOrgOwnerEmail : undefined),+ name: name ?? (!isAdmin ? deriveOrgNameFromEmail(defaultOrgOwnerEmail) : undefined),+ seats: seats ?? null,+ pricePerSeat: pricePerSeat ?? null,},});- const createOrganizationMutation = trpc.viewer.organizations.create.useMutation({+ const intentToCreateOrgMutation = trpc.viewer.organizations.intentToCreateOrg.useMutation({onSuccess: async (data) => {- telemetry.event(telemetryEventTypes.org_created);- // This is necessary so that server token has the updated upId- await session.update({- upId: data.upId,+ // TODO: To be moved to _invoice.paid.org.ts+ // telemetry.event(telemetryEventTypes.org_created);+ reset({+ onboardingId: data.organizationOnboardingId,+ billingPeriod: data.billingPeriod,+ pricePerSeat: data.pricePerSeat ?? null,+ seats: data.seats ?? null,+ orgOwnerEmail: data.orgOwnerEmail,+ name: data.name,+ slug: data.slug,});- if (isAdmin && data.userId !== session.data?.user.id) {- // Impersonate the user chosen as the organization owner(if the admin user isn't the owner himself), so that admin can now configure the organisation on his behalf.- // He won't need to have access to the org directly in this way.- signIn("impersonation-auth", {- username: data.email,- callbackUrl: `/settings/organizations/${data.organizationId}/about`,- });++ if (isAdmin) {+ router.push("/settings/organizations/new/handover");+ } else {+ router.push("/settings/organizations/new/about");}- router.push(`/settings/organizations/${data.organizationId}/about`);},onError: (err) => {if (err.message === "organization_url_taken") {@@ -94,21 +101,24 @@ const CreateANewOrganizationFormChild = ({message: t("problem_registering_domain"),});} else {- setServerErrorMessage(err.message);+ setServerErrorMessage(t(err.message));}},});+ const needToCreateOnboarding = !onboardingId;return (<><Formform={newOrganizationFormMethods}className="space-y-5"id="createOrg"- handleSubmit={(v) => {- if (!createOrganizationMutation.isPending) {+ handleSubmit={async (v) => {+ if (!needToCreateOnboarding) {+ router.push("/settings/organizations/new/about");+ } else if (!intentToCreateOrgMutation.isPending) {setServerErrorMessage(null);- createOrganizationMutation.mutate({ ...v, creationSource: CreationSource.WEBAPP });+ intentToCreateOrgMutation.mutate({ ...v, creationSource: CreationSource.WEBAPP });}}}><div>@@ -167,12 +177,13 @@ const CreateANewOrganizationFormChild = ({defaultValue={value}onChange={(e) => {const email = e?.target.value;- const slug = deriveSlugFromEmail(email);newOrganizationFormMethods.setValue("orgOwnerEmail", email.trim());if (newOrganizationFormMethods.getValues("slug") === "") {+ const slug = deriveSlugFromEmail(email);newOrganizationFormMethods.setValue("slug", slug);}- newOrganizationFormMethods.setValue("name", deriveOrgNameFromEmail(email));+ const name = deriveOrgNameFromEmail(email);+ newOrganizationFormMethods.setValue("name", name);}}autoComplete="off"/>@@ -218,7 +229,6 @@ const CreateANewOrganizationFormChild = ({}}render={({ field: { value } }) => (<TextField- className="mt-2"name="slug"label={t("organization_url")}placeholder="acme"@@ -274,7 +284,7 @@ const CreateANewOrganizationFormChild = ({type="number"addOnSuffix="$"label="Price per seat (optional)"- defaultValue={value}+ defaultValue={value ?? ""}onChange={(e) => {onChange(+e.target.value);}}@@ -305,7 +315,13 @@ const CreateANewOrganizationFormChild = ({</RadioArea.Item><RadioArea.Item className={classNames("bg-default w-full text-sm")} value="ORGANIZATION"><strong className="mb-1 block">{t("organization")}</strong>- <p>{t("organization_price_per_user_month")}</p>+ {pricePerSeat && seats ? (+ <p>{`$${pricePerSeat} per user per month (${seats} seats minimum) ${+ billingPeriod === BillingPeriod.ANNUALLY ? "(billed annually)" : ""+ }`}</p>+ ) : (+ <p>{t("organization_price_per_user_month")}</p>+ )}</RadioArea.Item></RadioArea.Group></div>@@ -314,9 +330,7 @@ const CreateANewOrganizationFormChild = ({<div className="flex space-x-2 rtl:space-x-reverse"><Button- disabled={- newOrganizationFormMethods.formState.isSubmitting || createOrganizationMutation.isPending- }+ loading={newOrganizationFormMethods.formState.isSubmitting || intentToCreateOrgMutation.isPending}color="primary"EndIcon="arrow-right"type="submit"diff --git a/packages/features/ee/organizations/components/index.ts b/packages/features/ee/organizations/components/index.tsindex 32e312bf20d..eb8816ad496 100644--- a/packages/features/ee/organizations/components/index.ts+++ b/packages/features/ee/organizations/components/index.ts@@ -1,3 +1,4 @@export { CreateANewOrganizationForm } from "./CreateANewOrganizationForm";export { AboutOrganizationForm } from "./AboutOrganizationForm";-export { AddNewTeamsForm } from "./AddNewTeamsForm";+export { AddNewTeamsForm } from "@calcom/web/modules/settings/organizations/new/_components/AddNewTeamsForm";+export { AdminOnboardingHandover } from "./AdminOnboardingHandover";diff --git a/packages/features/ee/organizations/lib/OrganizationPaymentService.test.ts b/packages/features/ee/organizations/lib/OrganizationPaymentService.test.tsnew file mode 100644index 00000000000..b516ca3866b--- /dev/null+++ b/packages/features/ee/organizations/lib/OrganizationPaymentService.test.ts@@ -0,0 +1,311 @@+import { describe, expect, it, vi, beforeEach } from "vitest";++import { ORGANIZATION_SELF_SERVE_MIN_SEATS } from "@calcom/lib/constants";+import { prisma } from "@calcom/prisma";+import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";++import { OrganizationPaymentService } from "./OrganizationPaymentService";+import type { IOrganizationPermissionService } from "./OrganizationPermissionService";++vi.stubEnv("STRIPE_ORG_PRODUCT_ID", "STRIPE_ORG_PRODUCT_ID");+vi.stubEnv("STRIPE_ORG_MONTHLY_PRICE_ID", "STRIPE_ORG_MONTHLY_PRICE_ID");+const defaultOrgOnboarding = {+ id: "onboard-id-1",+ name: "Test Org",+ slug: "test-org",+ orgOwnerEmail: "[email protected]",+ billingPeriod: "MONTHLY",+ seats: 5,+ pricePerSeat: 20,+ isComplete: false,+ stripeCustomerId: "mock_stripe_customer_id",+};++vi.mock("@calcom/prisma", () => {+ const prismaMock = {+ organizationOnboarding: {+ findFirst: vi.fn(),+ create: vi.fn(),+ update: vi.fn(),+ },+ membership: {+ findMany: vi.fn(),+ },+ user: {+ findUnique: vi.fn(),+ update: vi.fn(),+ },+ };+ return {+ prisma: prismaMock,+ default: prismaMock,+ };+});++vi.mock("@calcom/features/ee/billing/stripe-billling-service", () => ({+ StripeBillingService: vi.fn().mockImplementation(() => ({+ createCustomer: vi.fn().mockResolvedValue({ id: "mock_customer_id" }),+ createPrice: vi.fn().mockResolvedValue({ id: "mock_price_id", isCustom: false }),+ createSubscription: vi.fn().mockResolvedValue({ id: "mock_subscription_id" }),+ createSubscriptionCheckout: vi.fn().mockResolvedValue({+ checkoutUrl: "https://checkout.stripe.com/mock-checkout-url",+ }),+ })),+}));++describe("OrganizationPaymentService", () => {+ let service: OrganizationPaymentService;+ let mockPermissionService: IOrganizationPermissionService;+ const mockUser: TrpcSessionUser = {+ id: 1,+ email: "[email protected]",+ role: "USER",+ };++ beforeEach(() => {+ vi.clearAllMocks();+ mockPermissionService = {+ hasPermissionToCreateForEmail: vi.fn().mockResolvedValue(true),+ hasPendingOrganizations: vi.fn().mockResolvedValue(false),+ hasPermissionToModifyDefaultPayment: vi.fn().mockReturnValue(false),+ hasPermissionToMigrateTeams: vi.fn().mockResolvedValue(true),+ hasModifiedDefaultPayment: vi.fn().mockReturnValue(false),+ validatePermissions: vi.fn().mockResolvedValue(true),+ };+ service = new OrganizationPaymentService(mockUser, mockPermissionService);+ vi.mocked(prisma.user.findUnique).mockResolvedValue({ metadata: {} } as any);++ // Mock successful organization onboarding creation+ vi.mocked(prisma.organizationOnboarding.create).mockResolvedValue({+ id: 1,+ name: "Test Org",+ slug: "test-org",+ orgOwnerEmail: "[email protected]",+ billingPeriod: "MONTHLY",+ seats: 5,+ pricePerSeat: 20,+ stripeCustomerId: "mock_customer_id",+ isComplete: false,+ } as any);+ });++ describe("createPaymentIntent", () => {+ const baseInput = {+ bio: "BIO",+ logo: "LOGO",+ teams: [{ id: 1, isBeingMigrated: true, name: "Team 1", slug: "team1" }],+ };++ it("should not allow non-admin to modify payment settings", async () => {+ mockPermissionService.validatePermissions.mockRejectedValueOnce(+ new Error("You do not have permission to modify the default payment settings")+ );++ await expect(+ service.createPaymentIntent(+ {+ ...baseInput,+ pricePerSeat: 1000, // Trying to modify price+ },+ defaultOrgOnboarding+ )+ ).rejects.toThrow("You do not have permission to modify the default payment settings");+ });++ it("should use minimum seats when total unique members is less than minimum", async () => {+ // Mock 3 unique members (less than minimum of 5)+ vi.mocked(prisma.membership.findMany).mockImplementation(async () => [+ { userId: 1, user: { email: "[email protected]" } },+ { userId: 2, user: { email: "[email protected]" } },+ { userId: 3, user: { email: "[email protected]" } },+ ]);++ const result = await service.createPaymentIntent(+ {+ ...baseInput,+ invitedMembers: [{ email: "[email protected]" }], // Adding 1 invited member+ },+ defaultOrgOnboarding+ );++ expect(result).toBeDefined();+ const updateCall = vi.mocked(prisma.organizationOnboarding.update).mock.calls[0][0];+ expect(updateCall.where).toEqual({ id: "onboard-id-1" });+ const { updatedAt, ...data } = updateCall.data;+ expect(data).toEqual({+ bio: "BIO",+ logo: "LOGO",+ teams: [+ {+ id: 1,+ isBeingMigrated: true,+ name: "Team 1",+ slug: "team1",+ },+ ],+ invitedMembers: [+ {+ email: "[email protected]",+ },+ ],+ stripeCustomerId: "mock_stripe_customer_id",+ pricePerSeat: defaultOrgOnboarding.pricePerSeat,+ billingPeriod: "MONTHLY",+ seats: Number(ORGANIZATION_SELF_SERVE_MIN_SEATS),+ });+ });++ it("should use total unique members when more than minimum", async () => {+ // Mock 7 unique team members+ vi.mocked(prisma.membership.findMany).mockImplementation(async () =>+ Array.from({ length: 7 }, (_, i) => ({+ userId: i + 1,+ user: { email: `user${i + 1}@example.com` },+ }))+ );++ const result = await service.createPaymentIntent(+ {+ ...baseInput,+ invitedMembers: [+ { email: "[email protected]" },+ { email: "[email protected]" },+ { email: "[email protected]" },+ ], // Adding 3 invited members, total should be 7 as these new invites are pending+ },+ defaultOrgOnboarding+ );++ expect(result).toBeDefined();+ const updateCall = vi.mocked(prisma.organizationOnboarding.update).mock.calls[0][0];+ expect(updateCall.where).toEqual({ id: "onboard-id-1" });+ const { updatedAt, ...data } = updateCall.data;+ expect(data).toEqual({+ bio: "BIO",+ logo: "LOGO",+ teams: [+ {+ id: 1,+ isBeingMigrated: true,+ name: "Team 1",+ slug: "team1",+ },+ ],+ invitedMembers: [+ { email: "[email protected]" },+ { email: "[email protected]" },+ { email: "[email protected]" },+ ],+ stripeCustomerId: "mock_stripe_customer_id",+ pricePerSeat: defaultOrgOnboarding.pricePerSeat,+ billingPeriod: "MONTHLY",+ seats: 10,+ });+ });++ describe("admin overrides", () => {+ beforeEach(() => {+ mockPermissionService.hasPermissionToModifyDefaultPayment.mockReturnValue(true);+ mockPermissionService.hasModifiedDefaultPayment.mockReturnValue(true);+ mockPermissionService.validatePermissions.mockResolvedValue(true);+ // Mock membership count to be 0 for admin override tests+ vi.mocked(prisma.membership.findMany).mockResolvedValue([]);+ });++ it("should allow admin to override minimum seats to a lower value", async () => {+ const customSeats = 3;+ await service.createPaymentIntent(+ {+ ...baseInput,+ seats: customSeats,+ },+ {+ ...defaultOrgOnboarding,+ seats: customSeats,+ }+ );++ expect(vi.mocked(prisma.organizationOnboarding.update)).toHaveBeenCalled();+ const updateCall = vi.mocked(prisma.organizationOnboarding.update).mock.calls[0][0];+ expect(updateCall.where).toEqual({ id: "onboard-id-1" });+ const { updatedAt, ...data } = updateCall.data;+ expect(data).toEqual({+ bio: "BIO",+ logo: "LOGO",+ teams: [+ {+ id: 1,+ isBeingMigrated: true,+ name: "Team 1",+ slug: "team1",+ },+ ],+ stripeCustomerId: "mock_stripe_customer_id",+ pricePerSeat: defaultOrgOnboarding.pricePerSeat,+ billingPeriod: "MONTHLY",+ seats: customSeats,+ });+ });++ it("should allow admin to override price per seat", async () => {+ const customPrice = 1000;+ const result = await service.createPaymentIntent(baseInput, {+ ...defaultOrgOnboarding,+ pricePerSeat: customPrice,+ });++ expect(result).toBeDefined();+ const updateCall = vi.mocked(prisma.organizationOnboarding.update).mock.calls[0][0];+ expect(updateCall.where).toEqual({ id: "onboard-id-1" });+ const { updatedAt, ...data } = updateCall.data;+ expect(data).toEqual({+ bio: "BIO",+ logo: "LOGO",+ teams: [+ {+ id: 1,+ isBeingMigrated: true,+ name: "Team 1",+ slug: "team1",+ },+ ],+ stripeCustomerId: "mock_stripe_customer_id",+ pricePerSeat: customPrice,+ billingPeriod: "MONTHLY",+ seats: 5,+ });+ });++ it("should create custom price in Stripe when admin overrides price", async () => {+ const customPrice = 1500;++ await service.createPaymentIntent(+ {+ ...baseInput,+ pricePerSeat: customPrice,+ },+ {+ ...defaultOrgOnboarding,+ pricePerSeat: customPrice,+ }+ );++ // Verify a custom price was created in Stripe+ expect(vi.mocked(service["billingService"].createPrice)).toHaveBeenCalledWith(+ expect.objectContaining({+ amount: customPrice * 100, // Convert to cents for Stripe+ currency: "usd",+ interval: "month",+ productId: "STRIPE_ORG_PRODUCT_ID",+ nickname: expect.stringContaining("Custom Organization Price"),+ metadata: expect.objectContaining({+ billingPeriod: "MONTHLY",+ organizationOnboardingId: "onboard-id-1",+ pricePerSeat: customPrice,+ }),+ })+ );+ });+ });+ });+});diff --git a/packages/features/ee/organizations/lib/OrganizationPaymentService.ts b/packages/features/ee/organizations/lib/OrganizationPaymentService.tsnew file mode 100644index 00000000000..6e77c2ae38a--- /dev/null+++ b/packages/features/ee/organizations/lib/OrganizationPaymentService.ts@@ -0,0 +1,383 @@+import { StripeBillingService } from "@calcom/features/ee/billing/stripe-billling-service";+import {+ ORGANIZATION_SELF_SERVE_MIN_SEATS,+ ORGANIZATION_SELF_SERVE_PRICE,+ WEBAPP_URL,+} from "@calcom/lib/constants";+import logger from "@calcom/lib/logger";+import { safeStringify } from "@calcom/lib/safeStringify";+import { OrganizationOnboardingRepository } from "@calcom/lib/server/repository/organizationOnboarding";+import { UserRepository } from "@calcom/lib/server/repository/user";+import { prisma } from "@calcom/prisma";+import type { OrganizationOnboarding } from "@calcom/prisma/client";+import type { BillingPeriod } from "@calcom/prisma/enums";+import { userMetadata } from "@calcom/prisma/zod-utils";+import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";++import { TRPCError } from "@trpc/server";++import { OrganizationPermissionService } from "./OrganizationPermissionService";++type OrganizationOnboardingId = string;+const log = logger.getSubLogger({ prefix: ["OrganizationPaymentService"] });+type CreatePaymentIntentInput = {+ logo: string | null;+ bio: string | null;+ teams?: { id: number; isBeingMigrated: boolean; slug: string | null; name: string }[];+ invitedMembers?: { email: string }[];+};++type CreateOnboardingInput = {+ name: string;+ slug: string;+ orgOwnerEmail: string;+ billingPeriod?: BillingPeriod;+ seats?: number | null;+ pricePerSeat?: number | null;+ createdByUserId: number;+};++type PermissionCheckInput = {+ orgOwnerEmail: string;+ teams: { id: number; isBeingMigrated: boolean }[];+ billingPeriod: BillingPeriod;+ seats: number;+ pricePerSeat: number;+ slug: string;+};++type OrganizationOnboardingForPaymentIntent = Pick<+ OrganizationOnboarding,+ | "id"+ | "pricePerSeat"+ | "billingPeriod"+ | "seats"+ | "isComplete"+ | "orgOwnerEmail"+ | "slug"+ | "stripeCustomerId"+>;++type PaymentConfig = {+ billingPeriod: BillingPeriod;+ seats: number;+ pricePerSeat: number;+};++type StripePrice = {+ priceId: string;+ isCustom: boolean;+};++export class OrganizationPaymentService {+ protected billingService: StripeBillingService;+ protected permissionService: OrganizationPermissionService;+ protected user: NonNullable<TrpcSessionUser>;++ constructor(user: NonNullable<TrpcSessionUser>, permissionService?: OrganizationPermissionService) {+ this.billingService = new StripeBillingService();+ this.permissionService = permissionService || new OrganizationPermissionService(user);+ this.user = user;+ }++ protected async getOrCreateStripeCustomerId(email: string) {+ log.debug("getOrCreateStripeCustomerId", safeStringify({ email }));+ const existingCustomer = await prisma.user.findUnique({+ where: { email },+ select: { id: true, metadata: true },+ });++ const parsedMetadata = existingCustomer?.metadata+ ? userMetadata.parse(existingCustomer.metadata)+ : undefined;++ if (parsedMetadata?.stripeCustomerId) {+ return parsedMetadata.stripeCustomerId;+ }++ log.debug("Creating new Stripe customer", safeStringify({ email }));+ const customer = await this.billingService.createCustomer({+ email,+ metadata: {+ email,+ },+ });++ const stripeCustomerId = customer.stripeCustomerId;+ if (existingCustomer && parsedMetadata) {+ await UserRepository.updateStripeCustomerId({+ id: existingCustomer.id,+ stripeCustomerId,+ existingMetadata: parsedMetadata,+ });+ }++ log.debug("Created new Stripe customer", safeStringify({ email, stripeCustomerId }));++ return stripeCustomerId;+ }++ protected normalizePaymentConfig(input: {+ billingPeriod?: BillingPeriod;+ seats?: number | null;+ pricePerSeat?: number | null;+ }): PaymentConfig {+ return {+ billingPeriod: input.billingPeriod || "MONTHLY",+ seats: input.seats || Number(ORGANIZATION_SELF_SERVE_MIN_SEATS),+ pricePerSeat: input.pricePerSeat || Number(ORGANIZATION_SELF_SERVE_PRICE),+ };+ }++ protected async getUniqueTeamMembersCount({+ teamIds,+ invitedMembers,+ }: {+ teamIds: number[];+ invitedMembers?: { email: string }[];+ }) {+ if (!teamIds.length) return 0;++ const memberships = await prisma.membership.findMany({+ where: {+ teamId: {+ in: teamIds,+ },+ },+ select: {+ userId: true,+ user: {+ select: {+ email: true,+ },+ },+ },+ distinct: ["userId"],+ });++ const emailsSet = new Set(memberships.map((membership) => membership.user.email));++ if (invitedMembers) {+ invitedMembers.forEach((member) => {+ emailsSet.add(member.email);+ });+ }++ return emailsSet.size;+ }++ async createOrganizationOnboarding(input: CreateOnboardingInput) {+ if (+ this.permissionService.hasModifiedDefaultPayment(input) &&+ !this.permissionService.hasPermissionToModifyDefaultPayment()+ ) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message: "You do not have permission to modify the default payment settings",+ });+ }++ await this.permissionService.validatePermissions(input);++ // We know admin permissions have been validated in the above step so we can safely normalize the input+ const config = this.normalizePaymentConfig(input);++ // Create new onboarding record if none exists+ return await OrganizationOnboardingRepository.create({+ name: input.name,+ slug: input.slug,+ orgOwnerEmail: input.orgOwnerEmail,+ billingPeriod: config.billingPeriod,+ seats: config.seats,+ pricePerSeat: config.pricePerSeat,+ createdById: input.createdByUserId,+ });+ }++ protected async getOrCreatePrice(+ config: PaymentConfig,+ organizationOnboardingId: OrganizationOnboardingId,+ shouldCreateCustomPrice: boolean+ ): Promise<StripePrice> {+ log.debug(+ "getOrCreatePrice",+ safeStringify({+ config,+ organizationOnboardingId,+ shouldCreateCustomPrice,+ })+ );++ if (!process.env.STRIPE_ORG_PRODUCT_ID || !process.env.STRIPE_ORG_MONTHLY_PRICE_ID) {+ throw new Error("STRIPE_ORG_PRODUCT_ID or STRIPE_ORG_MONTHLY_PRICE_ID is not set");+ }++ const fixedPriceId = process.env.STRIPE_ORG_MONTHLY_PRICE_ID;+ if (!shouldCreateCustomPrice) {+ return {+ priceId: fixedPriceId,+ isCustom: false,+ };+ }++ const { interval, occurrence } = (() => {+ if (config.billingPeriod === "MONTHLY") return { interval: "month" as const, occurrence: 1 };+ if (config.billingPeriod === "ANNUALLY") return { interval: "year" as const, occurrence: 12 };+ throw new Error(`Invalid billing period: ${config.billingPeriod}`);+ })();++ const customPrice = await this.billingService.createPrice({+ amount: config.pricePerSeat * 100 * occurrence,+ productId: process.env.STRIPE_ORG_PRODUCT_ID,+ currency: "usd",+ interval,+ nickname: `Custom Organization Price - ${config.pricePerSeat} per seat`,+ metadata: {+ organizationOnboardingId,+ pricePerSeat: config.pricePerSeat,+ billingPeriod: config.billingPeriod,+ createdAt: new Date().toISOString(),+ },+ });++ return {+ priceId: customPrice.priceId,+ isCustom: true,+ };+ }++ protected async createSubscription(+ stripeCustomerId: string,+ priceId: string,+ config: PaymentConfig,+ organizationOnboardingId: OrganizationOnboardingId,+ params: URLSearchParams+ ) {+ log.debug(+ "Creating subscription",+ safeStringify({+ stripeCustomerId,+ priceId,+ config,+ organizationOnboardingId,+ })+ );+ return this.billingService.createSubscriptionCheckout({+ customerId: stripeCustomerId,+ successUrl: `${WEBAPP_URL}/settings/organizations/new/status?session_id={CHECKOUT_SESSION_ID}&paymentStatus=success&${params.toString()}`,+ cancelUrl: `${WEBAPP_URL}/settings/organizations/new/status?session_id={CHECKOUT_SESSION_ID}&paymentStatus=failed&${params.toString()}`,+ priceId,+ quantity: config.seats,+ metadata: {+ organizationOnboardingId,+ seats: config.seats,+ pricePerSeat: config.pricePerSeat,+ billingPeriod: config.billingPeriod,+ },+ });+ }++ protected async validatePermissions(input: PermissionCheckInput): Promise<boolean> {+ return this.permissionService.validatePermissions(input);+ }++ async createPaymentIntent(+ input: CreatePaymentIntentInput,+ organizationOnboarding: OrganizationOnboardingForPaymentIntent+ ) {+ log.debug("createPaymentIntent", safeStringify(input));++ const { teams: _teams, invitedMembers, logo, bio } = input;++ const teams = _teams?.filter((team) => team.id === -1 || team.isBeingMigrated) || [];+ const teamIds = teams.filter((team) => team.id > 0).map((team) => team.id);++ const { orgOwnerEmail, pricePerSeat, slug, billingPeriod, seats } = organizationOnboarding;++ if (this.user.role === "ADMIN") {+ log.debug("Admin flow, skipping checkout", safeStringify({ organizationOnboarding }));+ return {+ organizationOnboarding,+ subscription: null,+ checkoutUrl: null,+ sessionId: null,+ };+ }++ await this.validatePermissions({+ orgOwnerEmail,+ teams,+ billingPeriod,+ seats,+ pricePerSeat,+ slug,+ });++ const hasModifiedDefaultPayment = this.permissionService.hasModifiedDefaultPayment({+ billingPeriod,+ pricePerSeat,+ seats,+ });++ const paymentConfigFromOnboarding = {+ pricePerSeat,+ billingPeriod,+ seats,+ };++ // Get unique members count from existing teams+ const uniqueMembersCount = await this.getUniqueTeamMembersCount({ teamIds, invitedMembers });++ // Create new config with updated seats if necessary+ const updatedConfig = {+ ...paymentConfigFromOnboarding,+ seats: Math.max(paymentConfigFromOnboarding.seats, uniqueMembersCount),+ };++ log.debug(+ "Creating subscription",+ safeStringify({+ paymentConfigFromOnboarding,+ })+ );++ const { priceId } = await this.getOrCreatePrice(+ updatedConfig,+ organizationOnboarding.id,+ // Whether modified default payment is allowed or not is checked as part of this.createPaymentIntent and onboarding entry is only created after that.+ hasModifiedDefaultPayment+ );++ const stripeCustomerId = organizationOnboarding.stripeCustomerId+ ? organizationOnboarding.stripeCustomerId+ : await this.getOrCreateStripeCustomerId(organizationOnboarding.orgOwnerEmail);++ const subscription = await this.createSubscription(+ stripeCustomerId,+ priceId,+ updatedConfig,+ organizationOnboarding.id,+ new URLSearchParams({+ orgOwnerEmail: organizationOnboarding.orgOwnerEmail,+ })+ );++ log.debug("Updating onboarding");++ await OrganizationOnboardingRepository.update(organizationOnboarding.id, {+ bio: bio ?? null,+ logo: logo ?? null,+ invitedMembers: invitedMembers,+ teams,+ stripeCustomerId,+ ...updatedConfig,+ });++ return {+ organizationOnboarding,+ subscription,+ checkoutUrl: subscription.checkoutUrl,+ sessionId: subscription.sessionId,+ };+ }+}diff --git a/packages/features/ee/organizations/lib/OrganizationPermissionService.test.ts b/packages/features/ee/organizations/lib/OrganizationPermissionService.test.tsnew file mode 100644index 00000000000..3e97b0ef049--- /dev/null+++ b/packages/features/ee/organizations/lib/OrganizationPermissionService.test.ts@@ -0,0 +1,98 @@+import { describe, expect, it, vi, beforeEach } from "vitest";++import { prisma } from "@calcom/prisma";+import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";++import { OrganizationPermissionService } from "./OrganizationPermissionService";++vi.mock("@calcom/prisma", () => ({+ prisma: {+ organizationOnboarding: {+ findUnique: vi.fn(),+ },+ membership: {+ findMany: vi.fn(),+ },+ team: {+ findFirst: vi.fn(),+ },+ },+}));++describe("OrganizationPermissionService", () => {+ let service: OrganizationPermissionService;+ const mockUser: TrpcSessionUser = {+ id: 1,+ email: "[email protected]",+ role: "USER",+ };++ beforeEach(() => {+ vi.clearAllMocks();+ service = new OrganizationPermissionService(mockUser);+ });++ describe("hasPermissionToCreateForEmail", () => {+ it("should allow users to create for their own email", async () => {+ const result = await service.hasPermissionToCreateForEmail("[email protected]");+ expect(result).toBe(true);+ });++ it("should not allow users to create for other emails", async () => {+ const result = await service.hasPermissionToCreateForEmail("[email protected]");+ expect(result).toBe(false);+ });++ it("should allow admins to create for any email", async () => {+ const adminService = new OrganizationPermissionService({ ...mockUser, role: "ADMIN" });+ const result = await adminService.hasPermissionToCreateForEmail("[email protected]");+ expect(result).toBe(true);+ });+ });++ describe("hasPermissionToMigrateTeams", () => {+ it("should return true if user has required permissions for all teams", async () => {+ vi.mocked(prisma.membership.findMany).mockResolvedValue([+ { userId: 1, teamId: 1, role: "OWNER" },+ { userId: 1, teamId: 2, role: "ADMIN" },+ ]);++ const result = await service.hasPermissionToMigrateTeams([1, 2]);+ expect(result).toBe(true);+ });++ it("should return false if user lacks permissions for any team", async () => {+ vi.mocked(prisma.membership.findMany).mockResolvedValue([{ userId: 1, teamId: 1, role: "OWNER" }]);++ const result = await service.hasPermissionToMigrateTeams([1, 2]);+ expect(result).toBe(false);+ });++ it("should return true for empty team list", async () => {+ const result = await service.hasPermissionToMigrateTeams([]);+ expect(result).toBe(true);+ });+ });++ describe("validatePermissions", () => {+ it("should validate all permissions successfully", async () => {+ vi.mocked(prisma.organizationOnboarding.findUnique).mockResolvedValue(null);+ vi.mocked(prisma.membership.findMany).mockResolvedValue([{ userId: 1, teamId: 1, role: "OWNER" }]);++ const result = await service.validatePermissions({+ orgOwnerEmail: "[email protected]",+ teams: [{ id: 1, isBeingMigrated: true }],+ });++ expect(result).toBe(true);+ });++ it("should throw error for unauthorized email", async () => {+ await expect(+ service.validatePermissions({+ orgOwnerEmail: "[email protected]",+ })+ ).rejects.toThrow("you_do_not_have_permission_to_create_an_organization_for_this_email");+ });+ });+});diff --git a/packages/features/ee/organizations/lib/OrganizationPermissionService.ts b/packages/features/ee/organizations/lib/OrganizationPermissionService.tsnew file mode 100644index 00000000000..aacd084112e--- /dev/null+++ b/packages/features/ee/organizations/lib/OrganizationPermissionService.ts@@ -0,0 +1,138 @@+import { ORGANIZATION_SELF_SERVE_MIN_SEATS, ORGANIZATION_SELF_SERVE_PRICE } from "@calcom/lib/constants";+import logger from "@calcom/lib/logger";+import { safeStringify } from "@calcom/lib/safeStringify";+import { OrganizationRepository } from "@calcom/lib/server/repository/organization";+import { prisma } from "@calcom/prisma";+import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";++import { TRPCError } from "@trpc/server";++const log = logger.getSubLogger({ prefix: ["ee", "organizations", "OrganizationPermissionService"] });+type SeatsPrice = {+ seats?: number | null;+ pricePerSeat?: number | null;+};++export interface validatePermissionsIOrganizationPermissionService {+ hasPermissionToCreateForEmail(targetEmail: string): Promise<boolean>;+ hasPendingOrganizations(email: string, slug?: string): Promise<boolean>;+ hasPermissionToModifyDefaultPayment(): boolean;+ hasPermissionToMigrateTeams(teamIds: number[]): Promise<boolean>;+ hasModifiedDefaultPayment(+ input: {+ billingPeriod?: string;+ } & SeatsPrice+ ): boolean;+}++export class OrganizationPermissionService {+ constructor(private readonly user: NonNullable<TrpcSessionUser>) {}++ async hasPermissionToCreateForEmail(targetEmail: string): Promise<boolean> {+ return this.user.email === targetEmail || this.user.role === "ADMIN";+ }++ /**+ * If an onboarding is complete then it also means that org is created already.+ */+ async hasConflictingOrganization({ slug }: { slug: string }): Promise<boolean> {+ return !!(await OrganizationRepository.findBySlug({ slug }));+ }++ async hasCompletedOnboarding(email: string): Promise<boolean> {+ const orgOnboarding = await prisma.organizationOnboarding.findUnique({+ where: {+ orgOwnerEmail: email,+ },+ });++ return !!(orgOnboarding && orgOnboarding.isComplete);+ }++ hasPermissionToModifyDefaultPayment(): boolean {+ return this.user.role === "ADMIN";+ }++ hasModifiedDefaultPayment(data: SeatsPrice & { billingPeriod?: string }): boolean {+ const isBillingPeriodModified =+ data.billingPeriod !== undefined && data.billingPeriod !== null && data.billingPeriod !== "MONTHLY";++ const isSeatsModified =+ data.seats !== undefined && data.seats !== null && data.seats !== ORGANIZATION_SELF_SERVE_MIN_SEATS;++ const isPricePerSeatModified =+ data.pricePerSeat !== undefined &&+ data.pricePerSeat !== null &&+ data.pricePerSeat !== ORGANIZATION_SELF_SERVE_PRICE;++ log.debug(+ "hasModifiedDefaultPayment",+ safeStringify({ isBillingPeriodModified, isSeatsModified, isPricePerSeatModified })+ );+ return isBillingPeriodModified || isSeatsModified || isPricePerSeatModified;+ }++ async hasPermissionToMigrateTeams(teamIds: number[]): Promise<boolean> {+ if (teamIds.length === 0) return true;+ const teamMemberships = await prisma.membership.findMany({+ where: {+ userId: this.user.id,+ teamId: {+ in: teamIds,+ },+ role: {+ in: ["OWNER", "ADMIN"],+ },+ },+ });++ return teamMemberships.length === teamIds.length;+ }++ /**+ * Doesn't validate custom price permission as that is validated before onboarding is created and this method also runs when checkout is to be started+ */+ async validatePermissions(+ input: {+ orgOwnerEmail: string;+ teams?: { id: number; isBeingMigrated: boolean }[];+ billingPeriod?: string;+ slug: string;+ } & SeatsPrice+ ): Promise<boolean> {+ if (!(await this.hasPermissionToCreateForEmail(input.orgOwnerEmail))) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message: "you_do_not_have_permission_to_create_an_organization_for_this_email",+ });+ }++ if (await this.hasConflictingOrganization({ slug: input.slug })) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "organization_already_exists_with_this_slug",+ });+ }++ if (await this.hasCompletedOnboarding(input.orgOwnerEmail)) {+ // TODO: Consider redirecting to success page+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "organization_onboarding_already_completed",+ });+ }++ const teamsToMigrate = input.teams+ ?.filter((team) => team.id > 0 && team.isBeingMigrated)+ .map((team) => team.id);++ if (teamsToMigrate && !(await this.hasPermissionToMigrateTeams(teamsToMigrate))) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message: "you_do_not_have_permission_to_migrate_one_or_more_of_the_teams",+ });+ }++ return true;+ }+}diff --git a/packages/features/ee/organizations/lib/onboardingStore.ts b/packages/features/ee/organizations/lib/onboardingStore.tsnew file mode 100644index 00000000000..aa590d19d6f--- /dev/null+++ b/packages/features/ee/organizations/lib/onboardingStore.ts@@ -0,0 +1,174 @@+import { useSession } from "next-auth/react";+import { useSearchParams, useRouter, usePathname } from "next/navigation";+import { useEffect } from "react";+import { create } from "zustand";+import { persist } from "zustand/middleware";++import { WEBAPP_URL } from "@calcom/lib/constants";+import { UserPermissionRole } from "@calcom/prisma/enums";+import { trpc } from "@calcom/trpc/react";++enum BillingPeriod {+ MONTHLY = "MONTHLY",+ ANNUALLY = "ANNUALLY",+}++interface OnboardingAdminStoreState {+ billingPeriod?: BillingPeriod;+ pricePerSeat?: number | null;+ seats?: number | null;+ orgOwnerEmail?: string;+}++interface OnboardingUserStoreState {+ name: string;+ slug: string;+ logo?: string | null;+ bio?: string | null;+ onboardingId: string | null;+ invitedMembers: { email: string; name?: string }[];+ teams: { id: number; name: string; slug: string | null; isBeingMigrated: boolean }[];+}++interface OnboardingStoreState extends OnboardingAdminStoreState, OnboardingUserStoreState {+ // Actions for admin state+ setBillingPeriod: (billingPeriod: BillingPeriod) => void;+ setPricePerSeat: (price: number | null) => void;+ setSeats: (seats: number | null) => void;+ setOrgOwnerEmail: (email: string) => void;++ // Actions for user state+ setName: (name: string) => void;+ setSlug: (slug: string) => void;+ setLogo: (logo: string) => void;+ setBio: (bio: string) => void;+ addInvitedMember: (member: { email: string; name?: string }) => void;+ removeInvitedMember: (email: string) => void;++ setOnboardingId: (onboardingId: string) => void;++ // Actions for team state+ setTeams: (teams: { id: number; name: string; slug: string | null; isBeingMigrated: boolean }[]) => void;+ // Reset state+ reset: (state?: Partial<OnboardingStoreState>) => void;+}++const initialState: OnboardingAdminStoreState & OnboardingUserStoreState = {+ // User state+ name: "",+ slug: "",+ logo: "",+ bio: "",+ orgOwnerEmail: "",+ seats: null,+ pricePerSeat: null,+ billingPeriod: undefined,+ onboardingId: null,+ invitedMembers: [],+ teams: [],+};++export const useOnboardingStore = create<OnboardingStoreState>()(+ persist(+ (set) => ({+ ...initialState,++ // Admin actions+ setBillingPeriod: (billingPeriod) => set({ billingPeriod }),+ setPricePerSeat: (pricePerSeat) => set({ pricePerSeat }),+ setSeats: (seats) => set({ seats }),+ setOrgOwnerEmail: (orgOwnerEmail) => set({ orgOwnerEmail }),++ // User actions+ setName: (name) => set({ name }),+ setSlug: (slug) => set({ slug }),+ setLogo: (logo) => set({ logo }),+ setBio: (bio) => set({ bio }),+ setOnboardingId: (onboardingId) => set({ onboardingId }),+ addInvitedMember: (member) =>+ set((state) => ({+ invitedMembers: [...state.invitedMembers, member],+ })),+ removeInvitedMember: (email) =>+ set((state) => ({+ invitedMembers: state.invitedMembers.filter((member) => member.email !== email),+ })),++ // Team actions+ setTeams: (teams) => set({ teams }),++ // Reset action+ reset: (state) => {+ if (state) {+ set(state);+ } else {+ set(initialState);+ }+ },+ }),+ {+ name: "org-creation-onboarding",+ }+ )+);++export const useOnboarding = (params?: { step?: "start" | "status" | null }) => {+ const session = useSession();+ const router = useRouter();+ const path = usePathname();+ const isAdmin = session.data?.user?.role === UserPermissionRole.ADMIN;+ const searchParams = useSearchParams();+ const { data: organizationOnboarding, isPending: isLoadingOrgOnboarding } =+ trpc.viewer.organizations.getOrganizationOnboarding.useQuery();+ const { reset, onboardingId } = useOnboardingStore();+ const step = params?.step ?? null;+ useEffect(() => {+ if (isLoadingOrgOnboarding) {+ return;+ }++ if (organizationOnboarding) {+ // Must not keep resetting state on each step change as every step doesn't save at the moment and this would reset user's changes+ if (!window.isOrgOnboardingSynced) {+ window.isOrgOnboardingSynced = true;+ // Must reset with current state of onboarding in DB for the user+ reset({+ onboardingId: organizationOnboarding.id,+ billingPeriod: organizationOnboarding.billingPeriod as BillingPeriod,+ pricePerSeat: organizationOnboarding.pricePerSeat,+ seats: organizationOnboarding.seats,+ orgOwnerEmail: organizationOnboarding.orgOwnerEmail,+ name: organizationOnboarding.name,+ slug: organizationOnboarding.slug,+ bio: organizationOnboarding.bio,+ logo: organizationOnboarding.logo,+ });+ }+ } else {+ // First step doesn't require onboardingId+ const requireOnboardingId = step !== "start";++ // Reset to first step if onboardingId isn't available+ if (!onboardingId && requireOnboardingId) {+ console.warn("No onboardingId found in store, redirecting to /settings/organizations/new");+ router.push("/settings/organizations/new");+ }+ }++ // Admin must start fresh, so that they can create organization with any email and data doesn't mix from different org creations+ if (isAdmin) {+ reset();+ }+ }, [organizationOnboarding, isLoadingOrgOnboarding, isAdmin, onboardingId, reset, step, router]);++ useEffect(() => {+ if (session.status === "loading") {+ return;+ }+ if (!session.data) {+ const searchString = !searchParams ? "" : `${searchParams.toString()}`;+ router.push(`/auth/login?callbackUrl=${WEBAPP_URL}${path}${searchString ? `?${searchString}` : ""}`);+ }+ }, [session, router, path, searchParams]);+ return { useOnboardingStore, isLoadingOrgOnboarding, dbOnboarding: organizationOnboarding };+};diff --git a/packages/features/ee/organizations/lib/server/createOrganizationFromOnboarding.test.ts b/packages/features/ee/organizations/lib/server/createOrganizationFromOnboarding.test.tsnew file mode 100644index 00000000000..de7b1f91a93--- /dev/null+++ b/packages/features/ee/organizations/lib/server/createOrganizationFromOnboarding.test.ts@@ -0,0 +1,405 @@+/**+ * Goal is to e2e test createOrganizationFromOnboarding except inviteMembersWithNoInviterPermissionCheck, createTeamsHandler and createDomain+ * Those are either already tested or should be tested out separately+ */+import prismock from "../../../../../../tests/libs/__mocks__/prisma";++import { describe, expect, it, vi, beforeEach } from "vitest";++import { createDomain } from "@calcom/lib/domainManager/organization";+import { MembershipRole } from "@calcom/prisma/enums";+import { createTeamsHandler } from "@calcom/trpc/server/routers/viewer/organizations/createTeams.handler";+import { inviteMembersWithNoInviterPermissionCheck } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/inviteMember.handler";++import { createOrganizationFromOnboarding } from "./createOrganizationFromOnboarding";++// Mock the external functions+vi.mock("@calcom/features/auth/lib/verifyEmail", () => ({+ sendEmailVerification: vi.fn(),+}));++vi.mock("@calcom/emails/email-manager", () => ({+ sendOrganizationCreationEmail: vi.fn(),+}));++vi.mock("@calcom/trpc/server/routers/viewer/teams/inviteMember/inviteMember.handler", () => ({+ inviteMembersWithNoInviterPermissionCheck: vi.fn(),+}));++vi.mock("@calcom/trpc/server/routers/viewer/organizations/createTeams.handler", () => ({+ createTeamsHandler: vi.fn(),+}));++vi.mock("next-i18next", () => ({+ serverSideTranslations: vi.fn().mockImplementation(async () => {+ return {+ _nextI18Next: {+ initialI18nStore: {+ en: {+ common: {},+ },+ },+ userConfig: {+ i18n: {+ defaultLocale: "en",+ locales: ["en"],+ },+ },+ },+ };+ }),+ i18n: {+ language: "en",+ languages: ["en"],+ defaultLocale: "en",+ getFixedT: () => (key: string) => key,+ },+}));++vi.mock("@calcom/lib/domainManager/organization", () => ({+ createDomain: vi.fn(),+}));++const mockOrganizationOnboarding = {+ name: "Test Org",+ slug: "test-org",+ orgOwnerEmail: "[email protected]",+ billingPeriod: "MONTHLY",+ seats: 5,+ pricePerSeat: 20,+ isComplete: false,+ stripeCustomerId: "mock_stripe_customer_id",+ createdById: 1,+ invitedMembers: [{ email: "[email protected]" }, { email: "[email protected]" }],+ teams: [+ { id: 1, name: "Team To Move", isBeingMigrated: true, slug: "new-team-slug" },+ { id: 2, name: "New Team", isBeingMigrated: false, slug: null },+ ],+ logo: null,+ bio: null,+ organizationId: null,+ isDomainConfigured: false,+ isPlatform: false,+};++// Helper functions for creating test scenarios+async function createTestUser(data: {+ email: string;+ name?: string;+ username?: string;+ metadata?: any;+ onboardingCompleted?: boolean;+ emailVerified?: Date | null;+}) {+ return prismock.user.create({+ data: {+ email: data.email,+ name: data.name || "Test User",+ username: data.username || "testuser",+ metadata: data.metadata || {},+ completedOnboarding: data.onboardingCompleted,+ emailVerified: data.emailVerified,+ },+ });+}++async function createTestOrganization(data: {+ name: string;+ slug: string;+ isOrganization?: boolean;+ metadata?: any;+}) {+ return prismock.team.create({+ data: {+ name: data.name,+ slug: data.slug,+ isOrganization: data.isOrganization ?? true,+ metadata: data.metadata || {},+ },+ });+}++async function createTestTeam(data: { name: string; slug: string }) {+ return prismock.team.create({+ data: {+ name: data.name,+ slug: data.slug,+ isOrganization: false,+ },+ });+}++async function createTestOrganizationOnboarding(+ data?: Partial<typeof mockOrganizationOnboarding> & { organizationId?: number | null }+) {+ console.log("Creating organization onboarding", data);+ return prismock.organizationOnboarding.create({+ data: {+ ...mockOrganizationOnboarding,+ ...data,+ },+ });+}++async function createOnboardingEligibleUserAndOnboarding(data: {+ user?: {+ email: string;+ name?: string;+ username?: string;+ };+ organizationOnboarding?: Partial<typeof mockOrganizationOnboarding> & { organizationId?: number | null };+}) {+ const user = await createTestUser({+ ...data.user,+ onboardingCompleted: true,+ emailVerified: new Date(),+ });+ const organizationOnboarding = await createTestOrganizationOnboarding({+ ...data.organizationOnboarding,+ createdById: user.id,+ });+ return { user, organizationOnboarding };+}++async function createTestMembership(data: { userId: number; teamId: number; role?: MembershipRole }) {+ return prismock.membership.create({+ data: {+ userId: data.userId,+ teamId: data.teamId,+ role: data.role || MembershipRole.MEMBER,+ accepted: true,+ },+ });+}++describe("createOrganizationFromOnboarding", () => {+ beforeEach(async () => {+ vi.resetAllMocks();+ // @ts-expect-error reset is a method on Prismock+ await prismock.reset();+ });++ // Skipped because non-existend user creation support isn't there through onboarding now.+ it.skip("should create an organization with a non-existent user as owner", async () => {+ const organizationOnboarding = await createTestOrganizationOnboarding();++ const { organization, owner } = await createOrganizationFromOnboarding({+ organizationOnboarding,+ paymentSubscriptionId: "mock_subscription_id",+ paymentSubscriptionItemId: "mock_subscription_item_id",+ });++ // Verify organization creation+ expect(organization).toBeDefined();+ expect(organization.name).toBe(organizationOnboarding.name);+ expect(organization.slug).toBe(organizationOnboarding.slug);+ expect(organization.metadata).toEqual({+ orgSeats: 5,+ orgPricePerSeat: 20,+ billingPeriod: "MONTHLY",+ subscriptionId: "mock_subscription_id",+ subscriptionItemId: "mock_subscription_item_id",+ });++ // Verify owner creation+ expect(owner).toBeDefined();+ expect(owner.email).toBe(organizationOnboarding.orgOwnerEmail);+ });++ it("should create an organization with an existing user as owner", async () => {+ const orgOwnerEmail = "[email protected]";+ const existingUser = await createTestUser({+ email: orgOwnerEmail,+ name: "Existing User",+ username: "existinguser",+ onboardingCompleted: true,+ emailVerified: new Date(),+ });++ const organizationOnboarding = await createTestOrganizationOnboarding({+ orgOwnerEmail,+ });++ const { organization, owner } = await createOrganizationFromOnboarding({+ organizationOnboarding,+ paymentSubscriptionId: "mock_subscription_id",+ paymentSubscriptionItemId: "mock_subscription_item_id",+ });++ // Verify organization creation+ expect(organization).toBeDefined();+ expect(organization.name).toBe(organizationOnboarding.name);+ expect(organization.slug).toBe(organizationOnboarding.slug);++ // Verify owner is the existing user+ expect(owner.id).toBe(existingUser.id);+ expect(owner.email).toBe(existingUser.email);++ expect(createDomain).toHaveBeenCalledWith(organization.slug);+ // Verify team creation and member invites still work+ expect(inviteMembersWithNoInviterPermissionCheck).toHaveBeenCalledWith(+ expect.objectContaining({+ orgSlug: organization.slug,+ teamId: organization.id,+ invitations: organizationOnboarding.invitedMembers?.map((member) => ({+ usernameOrEmail: member.email,+ role: MembershipRole.MEMBER,+ })),+ })+ );+ expect(createTeamsHandler).toHaveBeenCalledWith(+ expect.objectContaining({+ input: expect.objectContaining({+ orgId: organization.id,+ teamNames: ["New Team"],+ moveTeams: expect.arrayContaining([expect.objectContaining({ id: 1, newSlug: "new-team-slug" })]),+ }),+ })+ );+ });++ it("should reuse existing organization if organizationId is already set in onboarding. Covers the retry scenario where org got created but then error occurred", async () => {+ const orgName = "Existing Org";+ const orgSlug = "existing-org";+ const existingOrg = await createTestOrganization({+ name: orgName,+ slug: orgSlug,+ });++ const { organizationOnboarding } = await createOnboardingEligibleUserAndOnboarding({+ user: {+ name: "Existing User",+ username: "existinguser",+ email: "[email protected]",+ },+ organizationOnboarding: {+ organizationId: existingOrg.id,+ name: orgName,+ slug: orgSlug,+ },+ });++ const { organization } = await createOrganizationFromOnboarding({+ organizationOnboarding,+ paymentSubscriptionId: "mock_subscription_id",+ paymentSubscriptionItemId: "mock_subscription_item_id",+ });++ // Verify the existing organization was reused+ expect(organization.id).toBe(existingOrg.id);+ });++ it("should throw error if organization with same slug exists", async () => {+ const { organizationOnboarding } = await createOnboardingEligibleUserAndOnboarding({+ user: {+ email: "[email protected]",+ },+ organizationOnboarding: {+ slug: "conflicting-org-with-same-slug",+ },+ });++ await createTestOrganization({+ name: "Conflicting Org with same slug",+ slug: organizationOnboarding.slug,+ });++ await expect(+ createOrganizationFromOnboarding({+ organizationOnboarding,+ paymentSubscriptionId: "mock_subscription_id",+ paymentSubscriptionItemId: "mock_subscription_item_id",+ })+ ).rejects.toThrow("organization_url_taken");+ });++ it("should update stripe customer ID for existing user", async () => {+ const { user: existingUser, organizationOnboarding } = await createOnboardingEligibleUserAndOnboarding({+ user: {+ email: "[email protected]",+ },+ organizationOnboarding: {+ slug: "conflicting-org-with-same-slug",+ },+ });++ await createOrganizationFromOnboarding({+ organizationOnboarding,+ paymentSubscriptionId: "mock_subscription_id",+ paymentSubscriptionItemId: "mock_subscription_item_id",+ });++ // Verify user's stripe customer ID was updated+ const updatedUser = await prismock.user.findUnique({+ where: { id: existingUser.id },+ });++ expect(updatedUser?.metadata).toEqual(+ expect.objectContaining({+ stripeCustomerId: organizationOnboarding.stripeCustomerId,+ })+ );+ });++ it("should create organization in with slug set even if there is a team with same slug of which orgOwner(to-be) is a member", async () => {+ const { organizationOnboarding } = await createOnboardingEligibleUserAndOnboarding({+ user: {+ email: "[email protected]",+ },+ organizationOnboarding: {+ slug: "conflicting-org-with-same-slug",+ },+ });++ const teamWithConflictingSlug = await createTestTeam({+ name: "TestTeamWithConflictingSlug",+ slug: organizationOnboarding.slug,+ });++ // Make the orgOwner a member of the team+ await createTestMembership({+ userId: organizationOnboarding.createdById,+ teamId: teamWithConflictingSlug.id,+ role: MembershipRole.ADMIN,+ });++ const { organization } = await createOrganizationFromOnboarding({+ organizationOnboarding,+ paymentSubscriptionId: "mock_subscription_id",+ paymentSubscriptionItemId: "mock_subscription_item_id",+ });++ expect(organization.slug).toBe(organizationOnboarding.slug);+ });++ it("should not create organization if there is a team with same slug of which orgOwner(to-be) is not a member", async () => {+ const { organizationOnboarding } = await createOnboardingEligibleUserAndOnboarding({+ user: {+ email: "[email protected]",+ },+ organizationOnboarding: {+ slug: "conflicting-org-with-same-slug",+ },+ });++ await createTestTeam({+ name: "TestTeamWithConflictingSlugNotOwnedByOrgOwner",+ slug: organizationOnboarding.slug,+ });++ // Don't make the orgOwner a member of the team+ // await createTestMembership({+ // userId: organizationOnboarding.createdById,+ // teamId: teamWithConflictingSlug.id,+ // role: MembershipRole.ADMIN,+ // });++ await expect(+ createOrganizationFromOnboarding({+ organizationOnboarding,+ paymentSubscriptionId: "mock_subscription_id",+ paymentSubscriptionItemId: "mock_subscription_item_id",+ })+ ).rejects.toThrow("organization_url_taken");+ });+});diff --git a/packages/features/ee/organizations/lib/server/createOrganizationFromOnboarding.ts b/packages/features/ee/organizations/lib/server/createOrganizationFromOnboarding.tsnew file mode 100644index 00000000000..c65acc0e996--- /dev/null+++ b/packages/features/ee/organizations/lib/server/createOrganizationFromOnboarding.ts@@ -0,0 +1,511 @@+import type { TFunction } from "i18next";++import { sendOrganizationCreationEmail } from "@calcom/emails/email-manager";+import { sendEmailVerification } from "@calcom/features/auth/lib/verifyEmail";+import { getOrgFullOrigin } from "@calcom/features/ee/organizations/lib/orgDomains";+import {+ assertCanCreateOrg,+ findUserToBeOrgOwner,+ setupDomain,+} from "@calcom/features/ee/organizations/lib/server/orgCreationUtils";+import { DEFAULT_SCHEDULE } from "@calcom/lib/availability";+import { getAvailabilityFromSchedule } from "@calcom/lib/availability";+import logger from "@calcom/lib/logger";+import { safeStringify } from "@calcom/lib/safeStringify";+import { getTranslation } from "@calcom/lib/server/i18n";+import { OrganizationRepository } from "@calcom/lib/server/repository/organization";+import { OrganizationOnboardingRepository } from "@calcom/lib/server/repository/organizationOnboarding";+import { UserRepository } from "@calcom/lib/server/repository/user";+import { prisma } from "@calcom/prisma";+import type { Prisma } from "@calcom/prisma/client";+import type { Team, User } from "@calcom/prisma/client";+import type { OrganizationOnboarding } from "@calcom/prisma/client";+import { MembershipRole, CreationSource } from "@calcom/prisma/enums";+import {+ userMetadata,+ orgOnboardingInvitedMembersSchema,+ orgOnboardingTeamsSchema,+} from "@calcom/prisma/zod-utils";+import { teamMetadataSchema } from "@calcom/prisma/zod-utils";+import { createTeamsHandler } from "@calcom/trpc/server/routers/viewer/organizations/createTeams.handler";+import { inviteMembersWithNoInviterPermissionCheck } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/inviteMember.handler";++// Onboarding can only be done from webapp currently and so we consider the source for User as WEBAPP+const creationSource = CreationSource.WEBAPP;+const log = logger.getSubLogger({ prefix: ["createOrganizationFromOnboarding"] });+// Types for organization data+type OrganizationData = {+ id: number | null;+ name: string;+ slug: string;+ isOrganizationConfigured: boolean;+ isOrganizationAdminReviewed: boolean;+ autoAcceptEmail: string;+ seats: number | null;+ pricePerSeat: number | null;+ isPlatform: boolean;+ logoUrl: string | null;+ bio: string | null;+ billingPeriod?: "MONTHLY" | "ANNUALLY";+};++type TeamData = {+ id: number;+ name: string;+ isBeingMigrated: boolean;+ slug: string | null;+};++type InvitedMember = {+ email: string;+ name?: string;+};++type OrgOwner = Awaited<ReturnType<typeof findUserToBeOrgOwner>>;++type OrganizationOnboardingArg = Pick<+ OrganizationOnboarding,+ | "id"+ | "organizationId"+ | "name"+ | "slug"+ | "orgOwnerEmail"+ | "seats"+ | "pricePerSeat"+ | "billingPeriod"+ | "invitedMembers"+ | "teams"+ | "isPlatform"+ | "logo"+ | "bio"+ | "stripeCustomerId"+ | "isDomainConfigured"+>;++const invitedMembersSchema = orgOnboardingInvitedMembersSchema;+const teamsSchema = orgOnboardingTeamsSchema;++async function createOrganizationWithExistingUserAsOwner({+ owner,+ orgData,+}: {+ owner: NonNullable<Awaited<ReturnType<typeof findUserToBeOrgOwner>>>;+ orgData: OrganizationData;+}) {+ const orgOwnerTranslation = await getTranslation(owner.locale || "en", "common");+ // We prefer ID which would be available if it is a retry of createOrganizationFromOnboarding and earlier organization was created and connected with Onboarding+ let organization = orgData.id ? await OrganizationRepository.findById({ id: orgData.id }) : null;++ if (organization) {+ log.debug(+ `Reusing existing organization:`,+ safeStringify({+ slug: orgData.slug,+ id: organization.id,+ })+ );+ return { organization };+ }++ const { slugConflictType } = await assertCanCreateOrg({+ slug: orgData.slug,+ isPlatform: orgData.isPlatform,+ orgOwner: owner,+ errorOnUserAlreadyPartOfOrg: false,+ // If it would have been restricted, then it would have been done already in intentToCreateOrgHandler+ // This restriction doesn't apply for admin as we would have validated it already in intentToCreateOrgHandler, we just relax it here as we don't know who created the organization.+ // TODO: If needed, we could start tracking if the onboarding is being done by instance Admin and relax it then only.+ restrictBasedOnMinimumPublishedTeams: false,+ });++ // In this case we create the organization with slug=null. Let the teams migrate and then the conflict would go away.+ const canSetSlug = slugConflictType === "teamUserIsMemberOfExists" ? false : true;++ log.debug(+ `Creating organization for owner ${owner.email} with slug ${orgData.slug} and canSetSlug=${canSetSlug}`+ );++ try {+ const nonOrgUsername = owner.username || "";+ const orgCreationResult = await OrganizationRepository.createWithExistingUserAsOwner({+ orgData: {+ ...orgData,+ ...(canSetSlug ? { slug: orgData.slug } : { slug: null, requestedSlug: orgData.slug }),+ },+ owner: {+ id: owner.id,+ email: owner.email,+ nonOrgUsername,+ },+ });+ organization = orgCreationResult.organization;+ const ownerProfile = orgCreationResult.ownerProfile;++ // Send organization creation email+ if (!orgData.isPlatform) {+ await sendOrganizationCreationEmail({+ language: orgOwnerTranslation,+ from: `${organization.name}'s admin`,+ to: owner.email,+ ownerNewUsername: ownerProfile.username,+ ownerOldUsername: nonOrgUsername,+ orgDomain: getOrgFullOrigin(orgData.slug, { protocol: false }),+ orgName: organization.name,+ prevLink: `${getOrgFullOrigin("", { protocol: true })}/${owner.username || ""}`,+ newLink: `${getOrgFullOrigin(orgData.slug, { protocol: true })}/${ownerProfile.username}`,+ });+ }++ // Set up default availability+ const availability = getAvailabilityFromSchedule(DEFAULT_SCHEDULE);+ await prisma.availability.createMany({+ data: availability.map((schedule) => ({+ days: schedule.days,+ startTime: schedule.startTime,+ endTime: schedule.endTime,+ userId: owner.id,+ })),+ });+ } catch (error) {+ // Catch and log so that redactError doesn't redact the log message+ log.error(+ `RecoverableError: Error creating organization for owner ${owner.email}.`,+ safeStringify(error)+ );+ throw error;+ }++ return { organization };+}++async function createOrganizationWithNonExistentUserAsOwner({+ email,+ orgData,+}: {+ email: string;+ orgData: OrganizationData;+}) {+ let organization = orgData.id+ ? await OrganizationRepository.findById({ id: orgData.id })+ : await OrganizationRepository.findBySlug({ slug: orgData.slug });++ if (organization) {+ log.debug(+ `createOrganizationWithNonExistentUserAsOwner: Reusing existing organization:`,+ safeStringify({ slug: orgData.slug, id: organization.id })+ );+ const owner = await findUserToBeOrgOwner(email);+ if (!owner) {+ throw new Error(`Org exists but owner could not be found for email: ${email}`);+ }+ return { organization, owner };+ }++ const orgCreationResult = await OrganizationRepository.createWithNonExistentOwner({+ orgData,+ owner: {+ email: email,+ },+ creationSource,+ });+ organization = orgCreationResult.organization;+ const { ownerProfile, orgOwner: orgOwnerFromCreation } = orgCreationResult;+ const orgOwner = await findUserToBeOrgOwner(orgOwnerFromCreation.email);+ if (!orgOwner) {+ throw new Error(+ `Just created the owner ${orgOwnerFromCreation.email}, but couldn't find it in the database`+ );+ }++ const translation = await getTranslation(orgOwner.locale ?? "en", "common");++ await sendEmailVerification({+ email: orgOwner.email,+ language: orgOwner.locale ?? "en",+ username: ownerProfile.username || "",+ isPlatform: orgData.isPlatform,+ });++ if (!orgData.isPlatform) {+ await sendOrganizationCreationEmail({+ language: translation,+ from: orgOwner.name ?? `${organization.name}'s admin`,+ to: orgOwner.email,+ ownerNewUsername: ownerProfile.username,+ ownerOldUsername: null,+ orgDomain: getOrgFullOrigin(orgData.slug, { protocol: false }),+ orgName: organization.name,+ prevLink: null,+ newLink: `${getOrgFullOrigin(orgData.slug, { protocol: true })}/${ownerProfile.username}`,+ });+ }++ return {+ organization,+ owner: orgOwner,+ };+}++async function createOrMoveTeamsToOrganization(teams: TeamData[], owner: User, organizationId: number) {+ if (teams.length === 0) return;++ const teamsToCreate = teams.filter((team) => !team.isBeingMigrated).map((team) => team.name);+ const teamsToMove = teams+ .filter((team) => team.isBeingMigrated)+ .map((team) => ({+ id: team.id,+ newSlug: team.slug,+ shouldMove: true,+ }));++ log.debug(+ `Creating ${teamsToCreate} teams and moving ${teamsToMove.map(+ (team) => team.newSlug+ )} teams for organization ${organizationId}`+ );++ await createTeamsHandler({+ ctx: {+ user: {+ ...owner,+ organizationId,+ },+ },+ input: {+ teamNames: teamsToCreate,+ orgId: organizationId,+ moveTeams: teamsToMove,+ creationSource,+ },+ });++ log.debug(+ `Created ${teamsToCreate.length} teams and moved ${teamsToMove.length} teams for organization ${organizationId}`+ );+}++async function inviteMembers(invitedMembers: InvitedMember[], organization: Team) {+ if (invitedMembers.length === 0) return;++ log.debug(`Inviting ${invitedMembers.length} members to organization ${organization.id}`);+ await inviteMembersWithNoInviterPermissionCheck({+ inviterName: null,+ teamId: organization.id,+ language: "en",+ creationSource: CreationSource.WEBAPP,+ orgSlug: organization.slug || null,+ invitations: invitedMembers.map((member) => ({+ usernameOrEmail: member.email,+ role: MembershipRole.MEMBER,+ })),+ });+}++async function ensureStripeCustomerIdIsUpdated({+ owner,+ stripeCustomerId,+}: {+ owner: User;+ stripeCustomerId: string;+}) {+ const parsedMetadata = userMetadata.parse(owner.metadata);++ await UserRepository.updateStripeCustomerId({+ id: owner.id,+ stripeCustomerId: stripeCustomerId,+ existingMetadata: parsedMetadata,+ });+}++/**+ * Temporary till we adapt all other code reading from metadata about stripeSubscriptionId and stripeSubscriptionItemId+ */+async function backwardCompatibilityForSubscriptionDetails({+ organization,+ paymentSubscriptionId,+ paymentSubscriptionItemId,+}: {+ organization: {+ id: number;+ metadata: Prisma.JsonValue;+ };+ paymentSubscriptionId: string;+ paymentSubscriptionItemId: string;+}) {+ const existingMetadata = teamMetadataSchema.parse(organization.metadata);+ const updatedOrganization = await OrganizationRepository.updateStripeSubscriptionDetails({+ id: organization.id,+ stripeSubscriptionId: paymentSubscriptionId,+ stripeSubscriptionItemId: paymentSubscriptionItemId,+ existingMetadata,+ });+ return updatedOrganization;+}++async function hasConflictingOrganization({ slug, onboardingId }: { slug: string; onboardingId: string }) {+ const organization = await OrganizationRepository.findBySlugIncludeOnboarding({ slug });+ if (!organization?.organizationOnboarding) {+ // Old organizations created without onboarding,+ return false;+ }++ // Different onboardingId means existing organization is owned by someone else+ return organization.organizationOnboarding.id !== onboardingId;+}++async function handleDomainSetup({+ organizationOnboarding,+ orgOwnerTranslation,+}: {+ organizationOnboarding: OrganizationOnboardingArg;+ orgOwnerTranslation: TFunction;+}) {+ if (!organizationOnboarding.isDomainConfigured) {+ // Important: Setup Domain first before creating the organization as Vercel/Cloudflare might not allow the domain to be created and that could cause organization booking pages to not actually work+ await setupDomain({+ slug: organizationOnboarding.slug,+ isPlatform: organizationOnboarding.isPlatform,+ orgOwnerEmail: organizationOnboarding.orgOwnerEmail,+ orgOwnerTranslation,+ });+ }++ await OrganizationOnboardingRepository.update(organizationOnboarding.id, {+ isDomainConfigured: true,+ });+}++async function handleOrganizationCreation({+ organizationOnboarding,+ owner,+ paymentSubscriptionId,+ paymentSubscriptionItemId,+}: {+ organizationOnboarding: OrganizationOnboardingArg;+ owner: OrgOwner;+ paymentSubscriptionId: string;+ paymentSubscriptionItemId: string;+}) {+ let organization;+ const orgData = {+ id: organizationOnboarding.organizationId,+ name: organizationOnboarding.name,+ // Create organization with slug=null, so that org slug doesn't conflict with existing team that is probably being migrated and thus would not be a conflict any more+ // Remember one can have a subteam with same slug as some organization, but regular team and organization can't have same slug+ slug: organizationOnboarding.slug,+ isOrganizationConfigured: true,+ // We believe that as the payment has been accepted first and we also restrict the emails to company emails, it is safe to set this to true.+ // We could easily set it to false if needed. In effect, it disables impersonations by non-admin reviewed organization's owner and also disables editing the member details+ isOrganizationAdminReviewed: true,+ autoAcceptEmail: organizationOnboarding.orgOwnerEmail.split("@")[1],+ seats: organizationOnboarding.seats,+ pricePerSeat: organizationOnboarding.pricePerSeat,+ isPlatform: false,+ billingPeriod: organizationOnboarding.billingPeriod,+ logoUrl: organizationOnboarding.logo,+ bio: organizationOnboarding.bio,+ };++ log.debug("handleOrganizationCreation", safeStringify({ orgData }));+ if (!owner) {+ const result = await createOrganizationWithNonExistentUserAsOwner({+ email: organizationOnboarding.orgOwnerEmail,+ orgData,+ });+ organization = result.organization;+ owner = result.owner;+ } else {+ const result = await createOrganizationWithExistingUserAsOwner({+ orgData,+ owner,+ });+ organization = result.organization;+ }++ if (organizationOnboarding.stripeCustomerId) {+ // Mostly needed for newly created user through the flow, existing user would have it already when checkout was created+ // We need to set it there to ensure that for the same user new customerId is not created again+ await ensureStripeCustomerIdIsUpdated({+ owner,+ stripeCustomerId: organizationOnboarding.stripeCustomerId,+ });+ }++ // Connect the organization to the onboarding+ await OrganizationOnboardingRepository.update(organizationOnboarding.id, {+ organizationId: organization.id,+ });++ const updatedOrganization = await backwardCompatibilityForSubscriptionDetails({+ organization,+ paymentSubscriptionId,+ paymentSubscriptionItemId,+ });++ return {+ organization: {+ ...organization,+ metadata: updatedOrganization.metadata,+ },+ owner,+ };+}++/**+ * This function is used by stripe webhook, so it should expect to be called multiple times till the entire flow completes without any error.+ * So, it should be idempotent.+ */+export const createOrganizationFromOnboarding = async ({+ organizationOnboarding,+ paymentSubscriptionId,+ paymentSubscriptionItemId,+}: {+ organizationOnboarding: OrganizationOnboardingArg;+ paymentSubscriptionId: string;+ paymentSubscriptionItemId: string;+}) => {+ if (+ await hasConflictingOrganization({+ slug: organizationOnboarding.slug,+ onboardingId: organizationOnboarding.id,+ })+ ) {+ throw new Error("organization_already_exists_with_this_slug");+ }++ // We know admin permissions have been validated in the above step so we can safely normalize the input+ const userFromEmail = await findUserToBeOrgOwner(organizationOnboarding.orgOwnerEmail);+ const orgOwnerTranslation = await getTranslation(userFromEmail?.locale || "en", "common");++ await handleDomainSetup({+ organizationOnboarding,+ orgOwnerTranslation,+ });++ const { organization, owner } = await handleOrganizationCreation({+ organizationOnboarding,+ owner: userFromEmail,+ paymentSubscriptionId,+ paymentSubscriptionItemId,+ });++ await inviteMembers(invitedMembersSchema.parse(organizationOnboarding.invitedMembers), organization);++ await createOrMoveTeamsToOrganization(+ teamsSchema.parse(organizationOnboarding.teams),+ owner,+ organization.id+ );++ // If the organization was created with slug=null, then set the slug now, assuming that the team having the same slug is migrated now+ // If the team wasn't owned by the orgOwner, then org creation would have failed and we wouldn't be here+ if (!organization.slug) {+ const { slug } = await OrganizationRepository.setSlug({+ id: organization.id,+ slug: organizationOnboarding.slug,+ });+ organization.slug = slug;+ }++ return { organization, owner };+};diff --git a/packages/features/ee/organizations/lib/server/orgCreationUtils.ts b/packages/features/ee/organizations/lib/server/orgCreationUtils.tsnew file mode 100644index 00000000000..33e012287e8--- /dev/null+++ b/packages/features/ee/organizations/lib/server/orgCreationUtils.ts@@ -0,0 +1,328 @@+import { lookup } from "dns";+import { type TFunction } from "i18next";++import { sendAdminOrganizationNotification } from "@calcom/emails";+import {+ RESERVED_SUBDOMAINS,+ ORG_MINIMUM_PUBLISHED_TEAMS_SELF_SERVE,+ WEBAPP_URL,+ IS_CALCOM,+} from "@calcom/lib/constants";+import { createDomain } from "@calcom/lib/domainManager/organization";+import logger from "@calcom/lib/logger";+import { safeStringify } from "@calcom/lib/safeStringify";+import { UserRepository } from "@calcom/lib/server/repository/user";+import { prisma } from "@calcom/prisma";+import { UserPermissionRole } from "@calcom/prisma/enums";++const log = logger.getSubLogger({ prefix: ["orgCreationUtils"] });++/**+ * 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 ConflictType =+ | "orgUserIsMemberOfExists"+ | "teamUserIsMemberOfExists"+ | "orgUserIsNotMemberOfExists"+ | "teamUserIsNotMemberOfExists"+ | null;++type OrgOwner = {+ id: number;+ email: string;+ username?: string | null;+ teams: {+ team: {+ isPlatform: boolean;+ slug: string | null;+ isOrganization: boolean;+ };+ }[];+ completedOnboarding?: boolean;+ emailVerified?: Date | null;+ profile?: {+ organizationId: number | null;+ } | null;+};++const getIPAddress = async (url: string): Promise<string> => {+ return new Promise((resolve, reject) => {+ lookup(url, (err, address) => {+ if (err) reject(err);+ resolve(address);+ });+ });+};++export class OrgCreationError extends Error {+ constructor(message: string) {+ super(message);+ }+}++async function assertSlugIsAvailable({+ slug,+ orgOwner,+ errorOnUserAlreadyPartOfOrg = true,+}: {+ slug: string;+ orgOwner: OrgOwner;+ errorOnUserAlreadyPartOfOrg?: boolean;+}) {+ let conflictType: ConflictType = null;++ const conflictingTeamOrOrg = await prisma.team.findFirst({+ where: {+ slug,+ parentId: null,+ },+ include: {+ members: {+ select: {+ userId: true,+ accepted: true,+ },+ },+ },+ });++ if (!conflictingTeamOrOrg) {+ return {+ conflictType,+ };+ }++ const isMemberOfConflictingTeamOrOrg = conflictingTeamOrOrg.members.some(+ (membership) => membership.userId === orgOwner.id && membership.accepted+ );+ if (conflictingTeamOrOrg.isOrganization) {+ conflictType = isMemberOfConflictingTeamOrOrg ? "orgUserIsMemberOfExists" : "orgUserIsNotMemberOfExists";+ } else {+ conflictType = isMemberOfConflictingTeamOrOrg+ ? "teamUserIsMemberOfExists"+ : "teamUserIsNotMemberOfExists";+ }++ if (conflictType === "orgUserIsNotMemberOfExists") {+ log.warn("orgUserIsNotMemberOfExists", safeStringify({ slug }));+ throw new OrgCreationError("organization_url_taken");+ } else if (conflictType === "orgUserIsMemberOfExists") {+ log.warn("you_are_part_of_this_organization_already", safeStringify({ slug }));+ if (errorOnUserAlreadyPartOfOrg) {+ throw new OrgCreationError("you_are_part_of_this_organization_already");+ }+ } else if (conflictType === "teamUserIsMemberOfExists") {+ log.debug("teamUserIsMemberOfExists", safeStringify({ slug }));+ // Allow creating the organization+ // It is needed so that later we can migrate the non-org Team(with the conflicting slug) to the newly created org+ // Publishing the organization would fail if the team with the same slug is not migrated first+ } else if (conflictType === "teamUserIsNotMemberOfExists") {+ log.error("Team with same slug already exists, owned by another user", safeStringify({ slug }));+ throw new OrgCreationError("organization_url_taken");+ }++ if (RESERVED_SUBDOMAINS.includes(slug)) {+ // Log actual reason but show regular error message to user.+ log.warn("Reserved subdomain", safeStringify({ slug }));+ throw new OrgCreationError("organization_url_taken");+ }++ return {+ conflictType,+ };+}++export async function assertCanCreateOrg({+ slug,+ isPlatform,+ orgOwner,+ restrictBasedOnMinimumPublishedTeams,+ errorOnUserAlreadyPartOfOrg = true,+}: {+ slug: string;+ isPlatform: boolean;+ orgOwner: OrgOwner;+ restrictBasedOnMinimumPublishedTeams: boolean;+ errorOnUserAlreadyPartOfOrg?: boolean;+}) {+ const verifiedUser = orgOwner.completedOnboarding && !!orgOwner.emailVerified;+ if (!verifiedUser) {+ log.warn(+ "you_need_to_complete_user_onboarding_before_creating_an_organization",+ safeStringify({ userId: orgOwner.id })+ );+ throw new OrgCreationError("you_need_to_complete_user_onboarding_before_creating_an_organization");+ }++ if (isNotACompanyEmail(orgOwner.email) && !isPlatform) {+ log.warn("use_company_email_to_create_an_organization", safeStringify({ email: orgOwner.email }));+ throw new OrgCreationError("use_company_email_to_create_an_organization");+ }++ const { conflictType: slugConflictType } = await assertSlugIsAvailable({+ slug,+ orgOwner,+ errorOnUserAlreadyPartOfOrg,+ });++ // Let slug verification be done before it as that gives better error message if the user creating the org is already a part of the org(i.e. the org exist and he is a member)+ if (orgOwner.profile?.organizationId) {+ throw new OrgCreationError("you_are_part_of_another_organization_cannot_create_organization");+ }++ const hasExistingPlatformOrOrgTeam = orgOwner?.teams.find((team) => {+ return team.team.isPlatform || team.team.isOrganization;+ });++ if (!!hasExistingPlatformOrOrgTeam?.team && isPlatform) {+ log.warn(+ "you_cannot_create_a_platform_organization_as_you_are_already_part_of_a_team",+ safeStringify({ userId: orgOwner.id })+ );+ throw new OrgCreationError("you_cannot_create_a_platform_organization_as_you_are_already_part_of_a_team");+ }++ const publishedTeams = orgOwner.teams.filter((team) => !!team.team.slug);++ if (+ restrictBasedOnMinimumPublishedTeams &&+ publishedTeams.length < ORG_MINIMUM_PUBLISHED_TEAMS_SELF_SERVE &&+ !isPlatform+ ) {+ log.warn(+ "you_need_to_have_minimum_published_teams",+ safeStringify({+ userId: orgOwner.id,+ publishedTeams: publishedTeams.length,+ minimumPublishedTeams: ORG_MINIMUM_PUBLISHED_TEAMS_SELF_SERVE,+ })+ );+ throw new OrgCreationError("you_need_to_have_minimum_published_teams");+ }++ return {+ slugConflictType,+ };+}++export const findUserToBeOrgOwner = async (email: string) => {+ const user = await prisma.user.findUnique({+ where: {+ email,+ },+ include: {+ teams: {+ select: {+ team: {+ select: {+ slug: true,+ isOrganization: true,+ isPlatform: true,+ },+ },+ },+ },+ },+ });++ if (!user) {+ return null;+ }++ return await UserRepository.enrichUserWithItsProfile({+ user,+ });+};++export const setupDomain = async ({+ slug,+ isPlatform,+ orgOwnerEmail,+ orgOwnerTranslation,+}: {+ slug: string;+ isPlatform: boolean;+ orgOwnerEmail: string;+ orgOwnerTranslation: TFunction;+}) => {+ log.debug("Starting domain setup", safeStringify({ slug, isPlatform }));+ const areDomainsConfigured = isPlatform ? true : await createDomain(slug);++ // On Cal.com, we expect the domains to be configured.+ if (IS_CALCOM && !areDomainsConfigured) {+ log.error("Failed to create domain in Vercel/Cloudflare", safeStringify({ slug }));+ throw new OrgCreationError("could_not_create_domain");+ }++ if (!areDomainsConfigured) {+ log.warn("Organization domain not configured", safeStringify({ slug }));+ // Otherwise, we proceed to send an administrative email to admins regarding+ // the need to configure DNS registry to support the newly created org+ const instanceAdmins = await prisma.user.findMany({+ where: { role: UserPermissionRole.ADMIN },+ select: { email: true },+ });+ if (instanceAdmins.length) {+ log.debug(+ "Sending admin notification for domain configuration",+ safeStringify({ slug, adminCount: instanceAdmins.length })+ );+ try {+ await sendAdminOrganizationNotification({+ instanceAdmins,+ orgSlug: slug,+ ownerEmail: orgOwnerEmail,+ webappIPAddress: await getIPAddress(+ WEBAPP_URL.replace("https://", "")?.replace("http://", "").replace(/(:.*)/, "")+ ),+ t: orgOwnerTranslation,+ });+ } catch (error) {+ // TODO: Why would this error come?+ log.error("Error sending admin notification", safeStringify({ error }));+ }+ } else {+ log.warn("Organization created: subdomain not configured and couldn't notify administrators");+ }+ } else {+ log.debug("Domain setup completed successfully", safeStringify({ slug }));+ }+};diff --git a/packages/lib/constants.ts b/packages/lib/constants.tsindex 040e84ee79b..316e472e237 100644--- a/packages/lib/constants.ts+++ b/packages/lib/constants.ts@@ -118,11 +118,15 @@ export const ENABLE_PROFILE_SWITCHER = process.env.NEXT_PUBLIC_ENABLE_PROFILE_SWexport const ALLOWED_HOSTNAMES = JSON.parse(`[${process.env.ALLOWED_HOSTNAMES || ""}]`) as string[];export const RESERVED_SUBDOMAINS = JSON.parse(`[${process.env.RESERVED_SUBDOMAINS || ""}]`) as string[];-export const ORGANIZATION_SELF_SERVE_MIN_SEATS =- process.env.NEXT_PUBLIC_ORGANIZATIONS_MIN_SELF_SERVE_SEATS || 30;-export const ORGANIZATION_SELF_SERVE_PRICE = process.env.NEXT_PUBLIC_ORGANIZATIONS_SELF_SERVE_PRICE || 3700;+export const ORGANIZATION_SELF_SERVE_MIN_SEATS = parseInt(+ process.env.NEXT_PUBLIC_ORGANIZATIONS_MIN_SELF_SERVE_SEATS || "5"+);++export const ORGANIZATION_SELF_SERVE_PRICE = parseFloat(+ process.env.NEXT_PUBLIC_ORGANIZATIONS_SELF_SERVE_PRICE_NEW || "37"+);-export const ORGANIZATION_MIN_SEATS = 30;+export const ORGANIZATION_MIN_SEATS = 5;// Needed for emails in E2Eexport const IS_MAILHOG_ENABLED = process.env.E2E_TEST_MAILHOG_ENABLED === "1";diff --git a/packages/lib/domainManager/deploymentServices/cloudflare.ts b/packages/lib/domainManager/deploymentServices/cloudflare.tsindex ccbd316d956..16257185fef 100644--- a/packages/lib/domainManager/deploymentServices/cloudflare.ts+++ b/packages/lib/domainManager/deploymentServices/cloudflare.ts@@ -5,7 +5,7 @@ import { safeStringify } from "@calcom/lib/safeStringify";import logger from "../../logger";-const log = logger.getSubLogger({ prefix: ["cloudflare"] });+const log = logger.getSubLogger({ prefix: ["cloudflare/deploymentService"] });// TODO: This and other settings should really come from DB when admin allows configuring which deployment services to use for the organizationconst IS_RECORD_PROXIED = true;diff --git a/packages/lib/domainManager/deploymentServices/vercel.ts b/packages/lib/domainManager/deploymentServices/vercel.tsindex 65c1292ee09..b7a939a946e 100644--- a/packages/lib/domainManager/deploymentServices/vercel.ts+++ b/packages/lib/domainManager/deploymentServices/vercel.ts@@ -5,6 +5,7 @@ import { safeStringify } from "@calcom/lib/safeStringify";import logger from "../../logger";+const log = logger.getSubLogger({ prefix: ["Vercel/DomainManager"] });const vercelApiForProjectUrl = `https://api.vercel.com/v9/projects/${process.env.PROJECT_ID_VERCEL}`;const vercelDomainApiResponseSchema = z.object({error: z@@ -17,7 +18,7 @@ const vercelDomainApiResponseSchema = z.object({export const createDomain = async (domain: string) => {assertVercelEnvVars(process.env);- logger.info(`Creating domain in Vercel: ${domain}`);+ log.info(`Creating domain in Vercel: ${domain}`);const response = await fetch(`${vercelApiForProjectUrl}/domains?teamId=${process.env.TEAM_ID_VERCEL}`, {body: JSON.stringify({ name: domain }),headers: {@@ -37,7 +38,7 @@ export const createDomain = async (domain: string) => {};export const deleteDomain = async (domain: string) => {- logger.info(`Deleting domain in Vercel: ${domain}`);+ log.info(`Deleting domain in Vercel: ${domain}`);assertVercelEnvVars(process.env);const response = await fetch(@@ -62,7 +63,7 @@ function handleDomainCreationError(error: { code?: string | null; domain?: strin// Domain is already owned by another team but you can request delegation to access itif (error.code === "forbidden") {const errorMessage = "Domain is already owned by another team";- logger.error(+ log.error(safeStringify({errorMessage,vercelError: error,@@ -76,7 +77,7 @@ function handleDomainCreationError(error: { code?: string | null; domain?: strinif (error.code === "domain_taken") {const errorMessage = "Domain is already being used by a different project";- logger.error(+ log.error(safeStringify({errorMessage,vercelError: error,@@ -94,7 +95,7 @@ function handleDomainCreationError(error: { code?: string | null; domain?: strin}const errorMessage = `Failed to create domain on Vercel: ${error.domain}`;- logger.error(safeStringify({ errorMessage, vercelError: error }));+ log.error(safeStringify({ errorMessage, vercelError: error }));throw new HttpError({message: errorMessage,statusCode: 400,@@ -110,7 +111,7 @@ function handleDomainDeletionError(error: { code?: string | null; domain?: strin// Domain is already owned by another team but you can request delegation to access itif (error.code === "forbidden") {const errorMessage = "Domain is owned by another team";- logger.error(+ log.error(safeStringify({errorMessage,vercelError: error,@@ -123,7 +124,7 @@ function handleDomainDeletionError(error: { code?: string | null; domain?: strin}const errorMessage = `Failed to take action for domain: ${error.domain}`;- logger.error(safeStringify({ errorMessage, vercelError: error }));+ log.error(safeStringify({ errorMessage, vercelError: error }));throw new HttpError({message: errorMessage,statusCode: 400,diff --git a/packages/lib/server/repository/organization.ts b/packages/lib/server/repository/organization.tsindex 809c91df00e..0e6bdaa5d1b 100644--- a/packages/lib/server/repository/organization.ts+++ b/packages/lib/server/repository/organization.ts@@ -1,5 +1,6 @@+import type { z } from "zod";+import { getOrgUsernameFromEmail } from "@calcom/features/auth/signup/utils/getOrgUsernameFromEmail";-import { IS_TEAM_BILLING_ENABLED } from "@calcom/lib/constants";import logger from "@calcom/lib/logger";import { safeStringify } from "@calcom/lib/safeStringify";import { prisma } from "@calcom/prisma";@@ -25,7 +26,7 @@ export class OrganizationRepository {}: {orgData: {name: string;- slug: string;+ slug: string | null;isOrganizationConfigured: boolean;isOrganizationAdminReviewed: boolean;autoAcceptEmail: string;@@ -33,6 +34,9 @@ export class OrganizationRepository {pricePerSeat: number | null;isPlatform: boolean;billingPeriod?: "MONTHLY" | "ANNUALLY";+ logoUrl: string | null;+ bio: string | null;+ requestedSlug?: string | null;};owner: {id: number;@@ -77,6 +81,8 @@ export class OrganizationRepository {billingPeriod?: "MONTHLY" | "ANNUALLY";pricePerSeat: number | null;isPlatform: boolean;+ logoUrl: string | null;+ bio: string | null;};owner: {email: string;@@ -114,7 +120,7 @@ export class OrganizationRepository {static async create(orgData: {name: string;- slug: string;+ slug: string | null;isOrganizationConfigured: boolean;isOrganizationAdminReviewed: boolean;autoAcceptEmail: string;@@ -122,12 +128,18 @@ export class OrganizationRepository {billingPeriod?: "MONTHLY" | "ANNUALLY";pricePerSeat: number | null;isPlatform: boolean;+ logoUrl: string | null;+ bio: string | null;+ requestedSlug?: string | null;}) {return await prisma.team.create({data: {name: orgData.name,isOrganization: true,- ...(!IS_TEAM_BILLING_ENABLED ? { slug: orgData.slug } : {}),+ slug: orgData.slug,+ // This is huge and causes issues, we need to have the logic to convert logo to logoUrl and then use that url ehre.+ // logoUrl: orgData.logoUrl,+ bio: orgData.bio,organizationSettings: {create: {isAdminReviewed: orgData.isOrganizationAdminReviewed,@@ -137,10 +149,16 @@ export class OrganizationRepository {},},metadata: {- ...(IS_TEAM_BILLING_ENABLED ? { requestedSlug: orgData.slug } : {}),+ isPlatform: orgData.isPlatform,++ // We still have a case where we don't have slug set directly on organization. The reason is because we want to create an org first(with same slug as another regular team) and then move the team to org.+ // Because in such cases there is a fallback existing at multiple places to use requestedSlug, we set it here still :(+ requestedSlug: orgData.requestedSlug,++ // We set these here still because some parts of code read it from metadata. This data exists in OrganizationOnboarding as well and should be used from there ideally+ // We also need to think about existing Organizations that might not have OrganizationOnboarding, before taking any decisionorgSeats: orgData.seats,orgPricePerSeat: orgData.pricePerSeat,- isPlatform: orgData.isPlatform,billingPeriod: orgData.billingPeriod,},isPlatform: orgData.isPlatform,@@ -154,7 +172,34 @@ export class OrganizationRepository {id,isOrganization: true,},- select: orgSelect,+ });+ }++ static async findBySlug({ slug }: { slug: string }) {+ // Slug is unique but could be null as well, so we can't use findUnique+ return prisma.team.findFirst({+ where: {+ slug,+ isOrganization: true,+ },+ });+ }++ static async findBySlugIncludeOnboarding({ slug }: { slug: string }) {+ return prisma.team.findFirst({+ where: { slug, isOrganization: true },+ include: {+ organizationOnboarding: {+ select: {+ id: true,+ isDomainConfigured: true,+ isPlatform: true,+ slug: true,+ teams: true,+ invitedMembers: true,+ },+ },+ },});}@@ -374,4 +419,34 @@ export class OrganizationRepository {},});}++ static async setSlug({ id, slug }: { id: number; slug: string }) {+ return await prisma.team.update({+ where: { id, isOrganization: true },+ data: { slug },+ });+ }++ static async updateStripeSubscriptionDetails({+ id,+ stripeSubscriptionId,+ stripeSubscriptionItemId,+ existingMetadata,+ }: {+ id: number;+ stripeSubscriptionId: string;+ stripeSubscriptionItemId: string;+ existingMetadata: z.infer<typeof teamMetadataSchema>;+ }) {+ return await prisma.team.update({+ where: { id, isOrganization: true },+ data: {+ metadata: {+ ...existingMetadata,+ subscriptionId: stripeSubscriptionId,+ subscriptionItemId: stripeSubscriptionItemId,+ },+ },+ });+ }}diff --git a/packages/lib/server/repository/organizationOnboarding.ts b/packages/lib/server/repository/organizationOnboarding.tsnew file mode 100644index 00000000000..9a5c7de8baa--- /dev/null+++ b/packages/lib/server/repository/organizationOnboarding.ts@@ -0,0 +1,135 @@+import logger from "@calcom/lib/logger";+import { safeStringify } from "@calcom/lib/safeStringify";+import { prisma } from "@calcom/prisma";+import type { BillingPeriod } from "@calcom/prisma/enums";++type OnboardingId = string;++export type CreateOrganizationOnboardingInput = {+ createdById: number;+ organizationId?: number | null;+ billingPeriod: BillingPeriod;+ pricePerSeat: number;+ seats: number;+ orgOwnerEmail: string;+ name: string;+ slug: string;+ logo?: string | null;+ bio?: string | null;+ stripeCustomerId?: string;+ stripeSubscriptionId?: string;+ stripeSubscriptionItemId?: string;+ invitedMembers?: { email: string; name?: string }[];+ teams?: { id: number; name: string; isBeingMigrated: boolean; slug: string | null }[];+ error?: string | null;+ isDomainConfigured?: boolean;+};++export class OrganizationOnboardingRepository {+ static async create(data: CreateOrganizationOnboardingInput) {+ logger.debug("Creating organization onboarding", safeStringify(data));++ return await prisma.organizationOnboarding.create({+ // HEKOP+ data: {+ billingPeriod: data.billingPeriod,+ pricePerSeat: data.pricePerSeat,+ seats: data.seats,+ orgOwnerEmail: data.orgOwnerEmail,+ name: data.name,+ slug: data.slug,+ logo: data.logo,+ bio: data.bio,+ stripeCustomerId: data.stripeCustomerId,+ stripeSubscriptionId: data.stripeSubscriptionId,+ invitedMembers: data.invitedMembers || [],+ teams: data.teams || [],+ createdById: data.createdById,+ },+ });+ }++ static async findByStripeCustomerId(stripeCustomerId: string) {+ logger.debug(+ "Finding organization onboarding by stripe customer id",+ safeStringify({ stripeCustomerId })+ );+ return await prisma.organizationOnboarding.findUnique({+ where: {+ stripeCustomerId,+ },+ });+ }++ static async findById(id: OnboardingId) {+ logger.debug("Finding organization onboarding by id", safeStringify({ id }));+ return await prisma.organizationOnboarding.findUnique({+ where: {+ id,+ },+ });+ }++ static async findByOrgOwnerEmail(email: string) {+ logger.debug("Finding organization onboarding by org owner email", safeStringify({ email }));+ return await prisma.organizationOnboarding.findUnique({+ where: {+ orgOwnerEmail: email,+ },+ });+ }++ // TODO: This method should be moved to OrganizationOnboardingService+ static async markAsComplete(id: OnboardingId) {+ logger.debug("Marking organization onboarding as complete", { id });+ return await prisma.organizationOnboarding.update({+ where: {+ id,+ },+ data: {+ error: null,+ isComplete: true,+ },+ });+ }++ static async update(id: OnboardingId, data: Partial<CreateOrganizationOnboardingInput>) {+ logger.debug("Updating organization onboarding", safeStringify({ id, data }));++ return await prisma.organizationOnboarding.update({+ where: {+ id,+ },+ data: {+ ...data,+ updatedAt: new Date(),+ },+ });+ }++ static async findByOrganizationId(organizationId: number) {+ logger.debug("Finding organization onboarding by organization id", safeStringify({ organizationId }));+ return await prisma.organizationOnboarding.findUnique({+ where: {+ organizationId,+ },+ });+ }++ static async findAllBySlug(slug: string) {+ logger.debug("Finding all organization onboardings by slug", safeStringify({ slug }));+ return await prisma.organizationOnboarding.findMany({+ where: {+ slug,+ },+ });+ }+ static async delete(id: OnboardingId) {+ logger.debug("Deleting organization onboarding", { id });+ return await prisma.organizationOnboarding.delete({+ where: {+ id,+ },+ });+ }+}diff --git a/packages/lib/server/repository/teamUtils.ts b/packages/lib/server/repository/teamUtils.tsindex 8fb505f8be1..b0b8471e1d6 100644--- a/packages/lib/server/repository/teamUtils.ts+++ b/packages/lib/server/repository/teamUtils.ts@@ -10,6 +10,9 @@ export const getParsedTeam = <T extends { metadata: Team["metadata"] }>(team: T)requestedSlug,metadata: {...metadata,+ /**+ * @deprecated New orgs that are being created won't have requestedSlug set as the organizations are created after payment and thus slug is always available+ */requestedSlug,},};diff --git a/packages/lib/server/repository/user.ts b/packages/lib/server/repository/user.tsindex a162bfb6825..92f149ebef8 100644--- a/packages/lib/server/repository/user.ts+++ b/packages/lib/server/repository/user.ts@@ -1,3 +1,5 @@+import type { z } from "zod";+import { whereClauseForOrgWithSlugOrRequestedSlug } from "@calcom/ee/organizations/lib/orgDomains";import logger from "@calcom/lib/logger";import { safeStringify } from "@calcom/lib/safeStringify";@@ -910,4 +912,19 @@ export class UserRepository {});return users.map(withSelectedCalendars);}++ static async updateStripeCustomerId({+ id,+ stripeCustomerId,+ existingMetadata,+ }: {+ id: number;+ stripeCustomerId: string;+ existingMetadata: z.infer<typeof userMetadata>;+ }) {+ return prisma.user.update({+ where: { id },+ data: { metadata: { ...existingMetadata, stripeCustomerId } },+ });+ }}diff --git a/packages/prisma/migrations/20250218111500_add_org_onboarding/migration.sql b/packages/prisma/migrations/20250218111500_add_org_onboarding/migration.sqlnew file mode 100644index 00000000000..539a7dd180d--- /dev/null+++ b/packages/prisma/migrations/20250218111500_add_org_onboarding/migration.sql@@ -0,0 +1,51 @@+-- CreateEnum+CREATE TYPE "BillingPeriod" AS ENUM ('MONTHLY', 'ANNUALLY');++-- CreateTable+CREATE TABLE "OrganizationOnboarding" (+ "id" TEXT NOT NULL,+ "createdById" INTEGER NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "orgOwnerEmail" TEXT NOT NULL,+ "error" TEXT,+ "updatedAt" TIMESTAMP(3) NOT NULL,+ "organizationId" INTEGER,+ "billingPeriod" "BillingPeriod" NOT NULL,+ "pricePerSeat" DOUBLE PRECISION NOT NULL,+ "seats" INTEGER NOT NULL,+ "isPlatform" BOOLEAN NOT NULL DEFAULT false,+ "name" TEXT NOT NULL,+ "slug" TEXT NOT NULL,+ "logo" TEXT,+ "bio" TEXT,+ "isDomainConfigured" BOOLEAN NOT NULL DEFAULT false,+ "stripeCustomerId" TEXT,+ "stripeSubscriptionId" TEXT,+ "stripeSubscriptionItemId" TEXT,+ "invitedMembers" JSONB NOT NULL DEFAULT '[]',+ "teams" JSONB NOT NULL DEFAULT '[]',+ "isComplete" BOOLEAN NOT NULL DEFAULT false,++ CONSTRAINT "OrganizationOnboarding_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE UNIQUE INDEX "OrganizationOnboarding_orgOwnerEmail_key" ON "OrganizationOnboarding"("orgOwnerEmail");++-- CreateIndex+CREATE UNIQUE INDEX "OrganizationOnboarding_organizationId_key" ON "OrganizationOnboarding"("organizationId");++-- CreateIndex+CREATE UNIQUE INDEX "OrganizationOnboarding_stripeCustomerId_key" ON "OrganizationOnboarding"("stripeCustomerId");++-- CreateIndex+CREATE INDEX "OrganizationOnboarding_orgOwnerEmail_idx" ON "OrganizationOnboarding"("orgOwnerEmail");++-- CreateIndex+CREATE INDEX "OrganizationOnboarding_stripeCustomerId_idx" ON "OrganizationOnboarding"("stripeCustomerId");++-- AddForeignKey+ALTER TABLE "OrganizationOnboarding" ADD CONSTRAINT "OrganizationOnboarding_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "OrganizationOnboarding" ADD CONSTRAINT "OrganizationOnboarding_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/packages/prisma/schema.prisma b/packages/prisma/schema.prismaindex 15b63436e5c..2d496b67002 100644--- a/packages/prisma/schema.prisma+++ b/packages/prisma/schema.prisma@@ -355,31 +355,32 @@ model User {bookingRedirectsTo OutOfOfficeEntry[] @relation(name: "toUser")// Used to lock the user account- locked Boolean @default(false)- platformOAuthClients PlatformOAuthClient[]- AccessToken AccessToken[]- RefreshToken RefreshToken[]- PlatformAuthorizationToken PlatformAuthorizationToken[]- profiles Profile[]- movedToProfileId Int?- movedToProfile Profile? @relation("moved_to_profile", fields: [movedToProfileId], references: [id], onDelete: SetNull)- secondaryEmails SecondaryEmail[]- isPlatformManaged Boolean @default(false)- OutOfOfficeReasons OutOfOfficeReason[]- smsLockState SMSLockState @default(UNLOCKED)- smsLockReviewedByAdmin Boolean @default(false)- NotificationsSubscriptions NotificationsSubscriptions[]- referralLinkId String?- features UserFeatures[]- reassignedBookings Booking[] @relation("reassignByUser")- createdAttributeToUsers AttributeToUser[] @relation("createdBy")- updatedAttributeToUsers AttributeToUser[] @relation("updatedBy")- createdTranslations EventTypeTranslation[] @relation("CreatedEventTypeTranslations")- updatedTranslations EventTypeTranslation[] @relation("UpdatedEventTypeTranslations")- createdWatchlists Watchlist[] @relation("CreatedWatchlists")- updatedWatchlists Watchlist[] @relation("UpdatedWatchlists")- BookingInternalNote BookingInternalNote[]- creationSource CreationSource?+ locked Boolean @default(false)+ platformOAuthClients PlatformOAuthClient[]+ AccessToken AccessToken[]+ RefreshToken RefreshToken[]+ PlatformAuthorizationToken PlatformAuthorizationToken[]+ profiles Profile[]+ movedToProfileId Int?+ movedToProfile Profile? @relation("moved_to_profile", fields: [movedToProfileId], references: [id], onDelete: SetNull)+ secondaryEmails SecondaryEmail[]+ isPlatformManaged Boolean @default(false)+ OutOfOfficeReasons OutOfOfficeReason[]+ smsLockState SMSLockState @default(UNLOCKED)+ smsLockReviewedByAdmin Boolean @default(false)+ NotificationsSubscriptions NotificationsSubscriptions[]+ referralLinkId String?+ features UserFeatures[]+ reassignedBookings Booking[] @relation("reassignByUser")+ createdAttributeToUsers AttributeToUser[] @relation("createdBy")+ updatedAttributeToUsers AttributeToUser[] @relation("updatedBy")+ createdTranslations EventTypeTranslation[] @relation("CreatedEventTypeTranslations")+ updatedTranslations EventTypeTranslation[] @relation("UpdatedEventTypeTranslations")+ createdWatchlists Watchlist[] @relation("CreatedWatchlists")+ updatedWatchlists Watchlist[] @relation("UpdatedWatchlists")+ BookingInternalNote BookingInternalNote[]+ creationSource CreationSource?+ createdOrganizationOnboardings OrganizationOnboarding[] @relation("CreatedOrganizationOnboardings")@@unique([email])@@unique([email, username])@@ -429,6 +430,8 @@ model Team {id Int @id @default(autoincrement())/// @zod.min(1)name String+ // It is unique across teams and organizations. We don't have a strong reason for organization and team slug to be conflicting, could be fixed.+ // Sub-teams could have same slug across different organizations but not within the same organization./// @zod.min(1)slug String?logoUrl String?@@ -490,8 +493,9 @@ model Team {/// @zod.custom(imports.intervalLimitsType)bookingLimits Json?- includeManagedEventsInLimits Boolean @default(false)+ includeManagedEventsInLimits Boolean @default(false)internalNotePresets InternalNotePreset[]+ organizationOnboarding OrganizationOnboarding?// note(Lauris): if a Team has parentId it is a team, if parentId is null it is an organization, but if parentId is null and managedOrganization is set,// it means that it is an organization managed by another organization.@@ -1894,6 +1898,65 @@ model Watchlist {@@index([type, value])}+enum BillingPeriod {+ MONTHLY+ ANNUALLY+}++model OrganizationOnboarding {+ // TODO: Use uuid for id+ id String @id @default(uuid())++ // User who started the onboarding. It is different from orgOwnerEmail in case Cal.com admin is doing the onboarding for someone else.+ createdBy User @relation("CreatedOrganizationOnboardings", fields: [createdById], references: [id], onDelete: Cascade)+ createdById Int+ createdAt DateTime @default(now())++ // We keep the email only here and don't need to connect it with user because on User deletion, we don't delete the entry here.+ // It is unique because an email can be the owner of only one organization at a time.+ orgOwnerEmail String @unique+ error String?++ updatedAt DateTime @updatedAt+ // TODO: updatedBy to be added when we support marking updatedBy using webhook too, as webhook also updates it++ // Set after organization payment is done and the organization is created+ organizationId Int? @unique+ organization Team? @relation(fields: [organizationId], references: [id], onDelete: Cascade)++ billingPeriod BillingPeriod+ pricePerSeat Float+ seats Int++ isPlatform Boolean @default(false)++ // Organization info+ name String+ // We don't keep it unique because we don't want self-serve flows to block a slug if it isn't paid for yet.+ slug String+ logo String?+ bio String?+ isDomainConfigured Boolean @default(false)++ // Set when payment intent is there.+ stripeCustomerId String? @unique+ // TODO: Can we make it required+ stripeSubscriptionId String?+ stripeSubscriptionItemId String?++ /// @zod.custom(imports.orgOnboardingInvitedMembersSchema)+ invitedMembers Json @default("[]")++ /// @zod.custom(imports.orgOnboardingTeamsSchema)+ teams Json @default("[]")++ // Completion status+ isComplete Boolean @default(false)++ @@index([orgOwnerEmail])+ @@index([stripeCustomerId])+}+enum IncompleteBookingActionType {SALESFORCE}diff --git a/packages/prisma/seed.ts b/packages/prisma/seed.tsindex fb6a423a73a..7d51c40a233 100644--- a/packages/prisma/seed.ts+++ b/packages/prisma/seed.ts@@ -1068,6 +1068,104 @@ async function main() {]);+ await createTeamAndAddUsers(+ {+ name: "Seeded Team (Marketing)",+ slug: "seeded-team-marketing",+ eventTypes: {+ createMany: {+ data: [+ {+ title: "Collective Seeded Team Event",+ slug: "collective-seeded-team-event",+ length: 15,+ schedulingType: "COLLECTIVE",+ },+ {+ title: "Round Robin Seeded Team Event",+ slug: "round-robin-seeded-team-event",+ length: 15,+ schedulingType: "ROUND_ROBIN",+ },+ ],+ },+ },+ createdAt: new Date(),+ },+ [+ {+ id: proUserTeam.id,+ username: proUserTeam.name || "Unknown",+ },+ {+ id: freeUserTeam.id,+ username: freeUserTeam.name || "Unknown",+ },+ {+ id: pro2UserTeam.id,+ username: pro2UserTeam.name || "Unknown",+ role: "MEMBER",+ },+ {+ id: pro3UserTeam.id,+ username: pro3UserTeam.name || "Unknown",+ },+ {+ id: pro4UserTeam.id,+ username: pro4UserTeam.name || "Unknown",+ },+ ]+ );++ await createTeamAndAddUsers(+ {+ name: "Seeded Team (Design)",+ slug: "seeded-team-design",+ eventTypes: {+ createMany: {+ data: [+ {+ title: "Collective Seeded Team Event",+ slug: "collective-seeded-team-event",+ length: 15,+ schedulingType: "COLLECTIVE",+ },+ {+ title: "Round Robin Seeded Team Event",+ slug: "round-robin-seeded-team-event",+ length: 15,+ schedulingType: "ROUND_ROBIN",+ },+ ],+ },+ },+ createdAt: new Date(),+ },+ [+ {+ id: proUserTeam.id,+ username: proUserTeam.name || "Unknown",+ },+ {+ id: freeUserTeam.id,+ username: freeUserTeam.name || "Unknown",+ },+ {+ id: pro2UserTeam.id,+ username: pro2UserTeam.name || "Unknown",+ role: "MEMBER",+ },+ {+ id: pro3UserTeam.id,+ username: pro3UserTeam.name || "Unknown",+ },+ {+ id: pro4UserTeam.id,+ username: pro4UserTeam.name || "Unknown",+ },+ ]+ );+await createOrganizationAndAddMembersAndTeams({org: {orgData: {diff --git a/packages/prisma/zod-utils.ts b/packages/prisma/zod-utils.tsindex 627ff17c2c6..87fd2e6b987 100644--- a/packages/prisma/zod-utils.ts+++ b/packages/prisma/zod-utils.ts@@ -59,6 +59,20 @@ export const bookerLayouts = z}).nullable();+export const orgOnboardingInvitedMembersSchema = z.array(+ z.object({ email: z.string().email(), name: z.string().optional() })+);++export const orgOnboardingTeamsSchema = z.array(+ z.object({+ id: z.number(),+ name: z.string(),+ isBeingMigrated: z.boolean(),+ // "slug" is null for new teams+ slug: z.string().nullable(),+ })+);+export const defaultBookerLayoutSettings = {defaultLayout: BookerLayouts.MONTH_VIEW,// if the user has no explicit layouts set (not in user profile and not in event settings), all layouts are enabled.diff --git a/packages/trpc/server/routers/viewer/organizations/_router.tsx b/packages/trpc/server/routers/viewer/organizations/_router.tsxindex 0781a51074a..78351c66ee2 100644--- a/packages/trpc/server/routers/viewer/organizations/_router.tsx+++ b/packages/trpc/server/routers/viewer/organizations/_router.tsx@@ -16,10 +16,12 @@ import { ZAdminVerifyInput } from "./adminVerify.schema";import { ZBulkUsersDelete } from "./bulkDeleteUsers.schema.";import { ZCreateInputSchema } from "./create.schema";import { ZCreateTeamsSchema } from "./createTeams.schema";+import { ZCreateWithPaymentIntentInputSchema } from "./createWithPaymentIntent.schema";import { ZDeleteTeamInputSchema } from "./deleteTeam.schema";import { ZGetMembersInput } from "./getMembers.schema";import { ZGetOtherTeamInputSchema } from "./getOtherTeam.handler";import { ZGetUserInput } from "./getUser.schema";+import { ZIntentToCreateOrgInputSchema } from "./intentToCreateOrg.schema";import { ZListMembersInputSchema } from "./listMembers.schema";import { ZListOtherTeamMembersSchema } from "./listOtherTeamMembers.handler";import { ZRemoveHostsFromEventTypes } from "./removeHostsFromEventTypes.schema";@@ -32,10 +34,34 @@ const NAMESPACE = "organizations";const namespaced = (s: string) => `${NAMESPACE}.${s}`;export const viewerOrganizationsRouter = router({+ getOrganizationOnboarding: authedProcedure.query(async (opts) => {+ const handler = await importHandler(+ namespaced("getOrganizationOnboarding"),+ () => import("./getOrganizationOnboarding.handler")+ );+ return handler(opts);+ }),+create: authedProcedure.input(ZCreateInputSchema).mutation(async (opts) => {const handler = await importHandler(namespaced("create"), () => import("./create.handler"));return handler(opts);}),+ intentToCreateOrg: authedProcedure.input(ZIntentToCreateOrgInputSchema).mutation(async (opts) => {+ const handler = await importHandler(+ namespaced("intentToCreateOrg"),+ () => import("./intentToCreateOrg.handler")+ );+ return handler(opts);+ }),+ createWithPaymentIntent: authedProcedure+ .input(ZCreateWithPaymentIntentInputSchema)+ .mutation(async (opts) => {+ const handler = await importHandler(+ namespaced("createWithPaymentIntent"),+ () => import("./createWithPaymentIntent.handler")+ );+ return handler(opts);+ }),update: authedProcedure.input(ZUpdateInputSchema).mutation(async (opts) => {const handler = await importHandler(namespaced("update"), () => import("./update.handler"));return handler(opts);diff --git a/packages/trpc/server/routers/viewer/organizations/create.handler.ts b/packages/trpc/server/routers/viewer/organizations/create.handler.tsindex dc54f1cb36b..0c8ed126365 100644--- a/packages/trpc/server/routers/viewer/organizations/create.handler.ts+++ b/packages/trpc/server/routers/viewer/organizations/create.handler.ts@@ -80,6 +80,9 @@ const getIPAddress = async (url: string): Promise<string> => {});};+/**+ * TODO: To be removed. We need to reuse the logic from orgCreationUtils like in intentToCreateOrgHandler+ */export const createHandler = async ({ input, ctx }: CreateOptions) => {const {slug,@@ -213,6 +216,9 @@ export const createHandler = async ({ input, ctx }: CreateOptions) => {pricePerSeat: pricePerSeat ?? null,isPlatform,billingPeriod,+ logoUrl: null,+ bio: null,+ paymentSubscriptionId: null,};// Create a new user and invite them as the owner of the organizationdiff --git a/packages/trpc/server/routers/viewer/organizations/createTeams.handler.ts b/packages/trpc/server/routers/viewer/organizations/createTeams.handler.tsindex f68207a636e..77ee3573af5 100644--- a/packages/trpc/server/routers/viewer/organizations/createTeams.handler.ts+++ b/packages/trpc/server/routers/viewer/organizations/createTeams.handler.ts@@ -7,20 +7,22 @@ import { safeStringify } from "@calcom/lib/safeStringify";import { UserRepository } from "@calcom/lib/server/repository/user";import slugify from "@calcom/lib/slugify";import { prisma } from "@calcom/prisma";-import { MembershipRole, RedirectType } from "@calcom/prisma/enums";import type { CreationSource } from "@calcom/prisma/enums";+import { MembershipRole, RedirectType } from "@calcom/prisma/enums";import { teamMetadataSchema } from "@calcom/prisma/zod-utils";import { TRPCError } from "@trpc/server";-import type { TrpcSessionUser } from "../../../trpc";-import inviteMemberHandler from "../teams/inviteMember/inviteMember.handler";+import { inviteMembersWithNoInviterPermissionCheck } from "../teams/inviteMember/inviteMember.handler";import type { TCreateTeamsSchema } from "./createTeams.schema";const log = logger.getSubLogger({ prefix: ["viewer/organizations/createTeams.handler"] });type CreateTeamsOptions = {ctx: {- user: NonNullable<TrpcSessionUser>;+ user: {+ id: number;+ organizationId: number | null;+ };};input: TCreateTeamsSchema;};@@ -30,16 +32,13 @@ export const createTeamsHandler = async ({ ctx, input }: CreateTeamsOptions) =>// Even when instance admin creates an org, then by the time he reaches team creation steps, he has impersonated the org owner.const organizationOwner = ctx.user;- if (!organizationOwner) {- throw new NoUserError();- }-const { orgId, moveTeams, creationSource } = input;// Remove empty team names that could be there due to the default empty team nameconst teamNames = input.teamNames.filter((name) => name.trim().length > 0);if (orgId !== organizationOwner.organizationId) {+ log.error("User is not the owner of the organization", safeStringify({ orgId, organizationOwner }));throw new NotAuthorizedError();}@@ -60,6 +59,7 @@ export const createTeamsHandler = async ({ ctx, input }: CreateTeamsOptions) =>});if (!userMembershipRole) {+ log.error("User is not a member of the organization", safeStringify({ orgId, organizationOwner }));throw new NotAuthorizedError();}@@ -106,7 +106,6 @@ export const createTeamsHandler = async ({ ctx, input }: CreateTeamsOptions) =>...organization,ownerId: organizationOwner.id,},- ctx,creationSource,});})@@ -174,7 +173,6 @@ async function moveTeam({teamId,newSlug,org,- ctx,creationSource,}: {teamId: number;@@ -185,7 +183,6 @@ async function moveTeam({ownerId: number;metadata: Prisma.JsonValue;};- ctx: CreateTeamsOptions["ctx"];creationSource: CreationSource;}) {const team = await prisma.team.findUnique({@@ -193,6 +190,7 @@ async function moveTeam({id: teamId,},select: {+ id: true,slug: true,metadata: true,members: {@@ -232,20 +230,19 @@ async function moveTeam({// Owner is already a member of the team. Inviting an existing member can throw errorconst invitableMembers = team.members.filter(isMembershipNotWithOwner).map((membership) => ({- email: membership.user.email,+ usernameOrEmail: membership.user.email,role: membership.role,}));if (invitableMembers.length) {// Invite team members to the new org. They are already members of the team.- await inviteMemberHandler({- ctx,- input: {- teamId: org.id,- language: "en",- usernameOrEmail: invitableMembers,- creationSource,- },+ await inviteMembersWithNoInviterPermissionCheck({+ orgSlug: org.slug,+ invitations: invitableMembers,+ creationSource,+ language: "en",+ inviterName: null,+ teamId: org.id,});}diff --git a/packages/trpc/server/routers/viewer/organizations/createWithPaymentIntent.handler.test.ts b/packages/trpc/server/routers/viewer/organizations/createWithPaymentIntent.handler.test.tsnew file mode 100644index 00000000000..89d2d4463f8--- /dev/null+++ b/packages/trpc/server/routers/viewer/organizations/createWithPaymentIntent.handler.test.ts@@ -0,0 +1,682 @@+import prismock from "../../../../../../tests/libs/__mocks__/prisma";++import Stripe from "stripe";+import { v4 as uuidv4 } from "uuid";+import { describe, expect, it, vi, beforeEach } from "vitest";++import { ORGANIZATION_SELF_SERVE_MIN_SEATS, ORGANIZATION_SELF_SERVE_PRICE } from "@calcom/lib/constants";+import { MembershipRole } from "@calcom/prisma/enums";+import { UserPermissionRole } from "@calcom/prisma/enums";++import { TRPCError } from "@trpc/server";++import { createHandler } from "./createWithPaymentIntent.handler";++vi.stubEnv("STRIPE_PRIVATE_KEY", "test-stripe-private-key");+vi.stubEnv("STRIPE_ORG_MONTHLY_PRICE_ID", "test-stripe-org-monthly-price-id");+vi.stubEnv("STRIPE_ORG_PRODUCT_ID", "test-stripe-org-product-id");+vi.stubEnv("NEXT_PUBLIC_ORGANIZATIONS_MIN_SELF_SERVE_SEATS", "30");+vi.stubEnv("NEXT_PUBLIC_ORGANIZATIONS_SELF_SERVE_PRICE_NEW", "37");++// eslint-disable-next-line @typescript-eslint/no-non-null-assertion+const STRIPE_ORG_PRODUCT_ID = process.env.STRIPE_ORG_PRODUCT_ID!;+// eslint-disable-next-line @typescript-eslint/no-non-null-assertion++const STRIPE_ORG_MONTHLY_PRICE_ID = process.env.STRIPE_ORG_MONTHLY_PRICE_ID!;+// eslint-disable-next-line @typescript-eslint/no-non-null-assertion++const checkoutSessionsCreate = vi.fn();+const pricesCreate = vi.fn();+const customersCreate = vi.fn();++function MockStripe() {+ return {+ checkout: {+ sessions: {+ create: checkoutSessionsCreate,+ },+ },+ prices: {+ create: pricesCreate,+ },+ customers: {+ create: customersCreate,+ },+ };+}++vi.mock("stripe", () => ({+ default: vi.fn(),+}));++const mockInput = {+ onboardingId: "test-onboarding-id",+ name: "Test Org",+ slug: "test-org",+ logo: "https://example.com/logo.png",+ bio: "Test organization bio",+};++async function createTestMembership(data: { userId: number; teamId: number; role?: MembershipRole }) {+ return prismock.membership.create({+ data: {+ userId: data.userId,+ teamId: data.teamId,+ role: data.role || MembershipRole.MEMBER,+ accepted: true,+ },+ });+}++async function createTestMemberships(data: { userIds: number[]; teamId: number }) {+ return Promise.all(+ data.userIds.map((userId) =>+ createTestMembership({+ userId,+ teamId: data.teamId,+ })+ )+ );+}++// Helper functions for creating test data+async function createTestUser(data: {+ email: string;+ name?: string;+ username?: string;+ role?: UserPermissionRole;+}) {+ return prismock.user.create({+ data: {+ email: data.email,+ name: data.name || "Test User",+ username: data.username || "testuser",+ role: data.role || UserPermissionRole.USER,+ },+ });+}++async function createNTestUsers(count: number) {+ return Promise.all(+ Array.from({ length: count }, () => createTestUser({ email: `user${Math.random()}@example.com` }))+ );+}++async function createOrganizationOnboarding(data: {+ id: string;+ name: string;+ slug: string;+ orgOwnerEmail: string;+ createdById: number;+ stripeSubscriptionId?: string | null;+ seats?: number;+ pricePerSeat?: number;+ billingPeriod?: string;+}) {+ return prismock.organizationOnboarding.create({+ data: {+ id: data.id,+ name: data.name,+ slug: data.slug,+ orgOwnerEmail: data.orgOwnerEmail,+ createdById: data.createdById,+ stripeSubscriptionId: data.stripeSubscriptionId,+ seats: parseInt(data.seats ?? ORGANIZATION_SELF_SERVE_MIN_SEATS),+ pricePerSeat: parseFloat(data.pricePerSeat ?? ORGANIZATION_SELF_SERVE_PRICE),+ billingPeriod: data.billingPeriod ?? "MONTHLY",+ },+ });+}++function expectStripePriceCreated({+ amount,+ product,+ recurring,+}: {+ amount: number;+ product: string;+ recurring: { interval: string };+}) {+ // @ts-expect-error We don't care about arguments to Stripe+ const stripe = new Stripe();+ expect(stripe.prices.create).toHaveBeenCalledWith(+ expect.objectContaining({+ // Multiply by 100 is requirement of Stripe.+ unit_amount: amount * 100,+ currency: "usd",+ product,+ recurring,+ })+ );+}++function expectStripePriceNotCreated() {+ // @ts-expect-error We don't care about arguments to Stripe+ const stripe = new Stripe();+ expect(stripe.prices.create).not.toHaveBeenCalled();+}++function expectStripeSubscriptionCreated({+ customerId,+ priceId,+ quantity,+}: {+ customerId: string;+ priceId: string;+ quantity: number;+}) {+ // @ts-expect-error We don't care about arguments to Stripe+ expect(new Stripe().checkout.sessions.create).toHaveBeenCalledWith(+ expect.objectContaining({+ customer: customerId,+ line_items: [+ expect.objectContaining({+ price: priceId,+ quantity,+ }),+ ],+ })+ );+}++let lastCreatedCustomerId = "null";+let lastCreatedPriceId = "null";+let lastCreatedSessionId = "null";+const STRIPE_CHECKOUT_URL = `https://stripe.com/checkout`;++describe("createWithPaymentIntent handler", () => {+ beforeEach(async () => {+ vi.resetAllMocks();+ // @ts-expect-error reset is a method on Prismock+ await prismock.reset();+ mockStripe();+ function mockStripe() {+ // @ts-expect-error Not all props are defined on MockStripe+ vi.mocked(Stripe).mockImplementation(MockStripe);+ checkoutSessionsCreate.mockImplementation(() => {+ const sessionId = `test-session-id-${uuidv4()}`;+ lastCreatedSessionId = sessionId;+ return {+ url: STRIPE_CHECKOUT_URL,+ id: sessionId,+ };+ });++ pricesCreate.mockImplementation(() => {+ const priceId = `test-price-id-${uuidv4()}`;+ lastCreatedPriceId = priceId;+ return {+ id: priceId,+ };+ });++ customersCreate.mockImplementation(() => {+ const customerId = `test-customer-id-${uuidv4()}`;+ lastCreatedCustomerId = customerId;+ return {+ id: customerId,+ };+ });+ }+ });++ it("should create payment intent for valid organization onboarding (regular user)", async () => {+ // Create regular user+ const user = await createTestUser({+ email: "[email protected]",+ });++ // Create organization onboarding+ await createOrganizationOnboarding({+ id: mockInput.onboardingId,+ name: mockInput.name,+ slug: mockInput.slug,+ orgOwnerEmail: user.email,+ createdById: user.id,+ });++ const result = await createHandler({+ input: mockInput,+ ctx: {+ user,+ },+ });++ expect(result).toEqual({+ checkoutUrl: STRIPE_CHECKOUT_URL,+ });+ });++ // Cal.com admin shouldn't be able to reach this step+ it.skip("should create payment intent for valid organization onboarding (admin user)", async () => {+ // Create admin user+ const adminUser = await createTestUser({+ email: "[email protected]",+ role: UserPermissionRole.ADMIN,+ });++ // Create organization onboarding for a different user+ await createOrganizationOnboarding({+ id: mockInput.onboardingId,+ name: mockInput.name,+ slug: mockInput.slug,+ orgOwnerEmail: "[email protected]",+ createdById: adminUser.id,+ });++ const result = await createHandler({+ input: mockInput,+ ctx: {+ user: adminUser,+ },+ });++ expect(result).toEqual({+ checkoutUrl: STRIPE_CHECKOUT_URL,+ });+ });++ it("should throw error when organization onboarding not found", async () => {+ const user = await createTestUser({+ email: "[email protected]",+ });++ await expect(+ createHandler({+ input: mockInput,+ ctx: {+ user,+ },+ })+ ).rejects.toThrow(new TRPCError({ code: "BAD_REQUEST", message: "organization_onboarding_not_found" }));+ });++ it("should throw error when organization already has subscription", async () => {+ const user = await createTestUser({+ email: "[email protected]",+ });++ await createOrganizationOnboarding({+ id: mockInput.onboardingId,+ name: mockInput.name,+ slug: mockInput.slug,+ orgOwnerEmail: user.email,+ createdById: user.id,+ stripeSubscriptionId: "existing-subscription-id",+ });++ await expect(+ createHandler({+ input: mockInput,+ ctx: {+ user,+ },+ })+ ).rejects.toThrow(+ new TRPCError({ code: "BAD_REQUEST", message: "organization_has_subscription_already" })+ );+ });++ it("should throw error when non-admin user tries to access another user's onboarding", async () => {+ const user = await createTestUser({+ email: "[email protected]",+ });++ await createOrganizationOnboarding({+ id: mockInput.onboardingId,+ name: mockInput.name,+ slug: mockInput.slug,+ orgOwnerEmail: "[email protected]",+ createdById: user.id,+ });++ await expect(+ createHandler({+ input: mockInput,+ ctx: {+ user,+ },+ })+ ).rejects.toThrow(new TRPCError({ code: "BAD_REQUEST", message: "organization_onboarding_not_found" }));+ });++ it("should handle input variations (without logo and bio)", async () => {+ const user = await createTestUser({+ email: "[email protected]",+ });++ await createOrganizationOnboarding({+ id: mockInput.onboardingId,+ name: mockInput.name,+ slug: mockInput.slug,+ orgOwnerEmail: user.email,+ createdById: user.id,+ });++ const result = await createHandler({+ input: {+ onboardingId: mockInput.onboardingId,+ name: mockInput.name,+ slug: mockInput.slug,+ },+ ctx: {+ user,+ },+ });++ expect(result).toEqual({+ checkoutUrl: STRIPE_CHECKOUT_URL,+ });+ });++ describe("Seats/Billing Period/Price Per Seat", () => {+ it("should handle custom seat count and price per seat - Monthly. Should create a custom price and use that", async () => {+ const user = await createTestUser({+ email: "[email protected]",+ });++ const pricePerSeat = 20;+ const seats = 10;+ await createOrganizationOnboarding({+ id: mockInput.onboardingId,+ name: mockInput.name,+ slug: mockInput.slug,+ orgOwnerEmail: user.email,+ createdById: user.id,+ seats,+ pricePerSeat,+ billingPeriod: "MONTHLY",+ });++ const customInput = {+ ...mockInput,+ };++ const result = await createHandler({+ input: customInput,+ ctx: {+ user,+ },+ });++ expectStripePriceCreated({+ amount: pricePerSeat * 1,+ product: STRIPE_ORG_PRODUCT_ID,+ recurring: {+ interval: "month",+ },+ });++ expectStripeSubscriptionCreated({+ customerId: lastCreatedCustomerId,+ priceId: lastCreatedPriceId,+ quantity: seats,+ });++ expect(result).toEqual({+ checkoutUrl: STRIPE_CHECKOUT_URL,+ });+ });++ it("should handle custom seat count and price per seat - Annually. Should create a custom price and use that", async () => {+ const user = await createTestUser({+ email: "[email protected]",+ });++ const pricePerSeat = 20;+ const seats = 10;+ await createOrganizationOnboarding({+ id: mockInput.onboardingId,+ name: mockInput.name,+ slug: mockInput.slug,+ orgOwnerEmail: user.email,+ createdById: user.id,+ seats,+ pricePerSeat,+ billingPeriod: "ANNUALLY",+ });++ const customInput = {+ ...mockInput,+ };++ const result = await createHandler({+ input: customInput,+ ctx: {+ user,+ },+ });++ expectStripePriceCreated({+ amount: pricePerSeat * 12,+ product: STRIPE_ORG_PRODUCT_ID,+ recurring: {+ interval: "year",+ },+ });++ expectStripeSubscriptionCreated({+ customerId: lastCreatedCustomerId,+ priceId: lastCreatedPriceId,+ quantity: seats,+ });++ expect(result).toEqual({+ checkoutUrl: STRIPE_CHECKOUT_URL,+ });+ });++ it("should use fixed Price ID when billingPeriod is MONTHLY and pricePerSeat and seats are default values", async () => {+ const user = await createTestUser({+ email: "[email protected]",+ });++ const pricePerSeat = ORGANIZATION_SELF_SERVE_PRICE;+ const seats = ORGANIZATION_SELF_SERVE_MIN_SEATS;+ await createOrganizationOnboarding({+ id: mockInput.onboardingId,+ name: mockInput.name,+ slug: mockInput.slug,+ orgOwnerEmail: user.email,+ createdById: user.id,+ seats,+ pricePerSeat,+ billingPeriod: "MONTHLY",+ });++ const customInput = {+ ...mockInput,+ };++ const result = await createHandler({+ input: customInput,+ ctx: {+ user,+ },+ });++ expectStripePriceNotCreated();++ expectStripeSubscriptionCreated({+ customerId: lastCreatedCustomerId,+ priceId: STRIPE_ORG_MONTHLY_PRICE_ID,+ quantity: seats,+ });++ expect(result).toEqual({+ checkoutUrl: STRIPE_CHECKOUT_URL,+ });+ });++ it("should create custom price when billingPeriod is ANNUALLY even when pricePerSeat and seats are default values", async () => {+ const user = await createTestUser({+ email: "[email protected]",+ });++ const pricePerSeat = 20;+ const seats = 10;+ await createOrganizationOnboarding({+ id: mockInput.onboardingId,+ name: mockInput.name,+ slug: mockInput.slug,+ orgOwnerEmail: user.email,+ createdById: user.id,+ seats,+ pricePerSeat,+ billingPeriod: "ANNUALLY",+ });++ const customInput = {+ ...mockInput,+ };++ const result = await createHandler({+ input: customInput,+ ctx: {+ user,+ },+ });++ expectStripePriceCreated({+ amount: pricePerSeat * 12,+ product: STRIPE_ORG_PRODUCT_ID,+ recurring: {+ interval: "year",+ },+ });++ expectStripeSubscriptionCreated({+ customerId: lastCreatedCustomerId,+ priceId: lastCreatedPriceId,+ quantity: seats,+ });++ expect(result).toEqual({+ checkoutUrl: STRIPE_CHECKOUT_URL,+ });+ });++ it("should increase numberOfSeats to max of seats in onboarding and number of invited members", async () => {+ const user = await createTestUser({+ email: "[email protected]",+ });++ const pricePerSeat = 20;+ const seats = 5;+ const totalMembersToMigrateThroughTeamsMigration = 7;+ await createOrganizationOnboarding({+ id: mockInput.onboardingId,+ name: mockInput.name,+ slug: mockInput.slug,+ orgOwnerEmail: user.email,+ createdById: user.id,+ seats,+ pricePerSeat,+ billingPeriod: "ANNUALLY",+ });++ const testUsers = await createNTestUsers(totalMembersToMigrateThroughTeamsMigration);++ await createTestMemberships({+ userIds: testUsers.map((user) => user.id),+ teamId: 1,+ });++ await createTestMembership({+ userId: user.id,+ teamId: 1,+ role: MembershipRole.ADMIN,+ });++ const customInput = {+ ...mockInput,+ invitedMembers: [+ { email: "[email protected]" },+ { email: "[email protected]" },+ { email: "[email protected]" },+ // Two emails reused from members being invited through teams migration+ { email: testUsers[0].email },+ { email: testUsers[1].email },+ ],+ teams: [+ { id: 1, name: "Existing Team 1", slug: "team-1", isBeingMigrated: true },+ { id: -1, name: "New Team 1", slug: null, isBeingMigrated: false },+ ],+ };+ const result = await createHandler({+ input: customInput,+ ctx: {+ user,+ },+ });++ expectStripePriceCreated({+ amount: pricePerSeat * 12,+ product: STRIPE_ORG_PRODUCT_ID,+ recurring: {+ interval: "year",+ },+ });++ expectStripeSubscriptionCreated({+ customerId: lastCreatedCustomerId,+ priceId: lastCreatedPriceId,+ // +1 because owner also takes a seat+ // +3 because three members are net new invited, rest two are already counted via teams migration+ quantity: totalMembersToMigrateThroughTeamsMigration + 3 + 1,+ });++ expect(result).toEqual({+ checkoutUrl: STRIPE_CHECKOUT_URL,+ });+ });++ it("should handle decimal price per seat", async () => {+ const user = await createTestUser({+ email: "[email protected]",+ });++ const pricePerSeat = 9.5;+ const seats = 10;+ await createOrganizationOnboarding({+ id: mockInput.onboardingId,+ name: mockInput.name,+ slug: mockInput.slug,+ orgOwnerEmail: user.email,+ createdById: user.id,+ seats,+ pricePerSeat,+ billingPeriod: "ANNUALLY",+ });++ const customInput = {+ ...mockInput,+ };++ const result = await createHandler({+ input: customInput,+ ctx: {+ user,+ },+ });++ expectStripePriceCreated({+ amount: pricePerSeat * 12,+ product: STRIPE_ORG_PRODUCT_ID,+ recurring: {+ interval: "year",+ },+ });++ expectStripeSubscriptionCreated({+ customerId: lastCreatedCustomerId,+ priceId: lastCreatedPriceId,+ quantity: seats,+ });++ expect(result).toEqual({+ checkoutUrl: STRIPE_CHECKOUT_URL,+ });+ });+ });+});diff --git a/packages/trpc/server/routers/viewer/organizations/createWithPaymentIntent.handler.ts b/packages/trpc/server/routers/viewer/organizations/createWithPaymentIntent.handler.tsnew file mode 100644index 00000000000..1ae3f288ceb--- /dev/null+++ b/packages/trpc/server/routers/viewer/organizations/createWithPaymentIntent.handler.ts@@ -0,0 +1,69 @@+import { OrganizationPaymentService } from "@calcom/features/ee/organizations/lib/OrganizationPaymentService";+import logger from "@calcom/lib/logger";+import { safeStringify } from "@calcom/lib/safeStringify";+import { OrganizationOnboardingRepository } from "@calcom/lib/server/repository/organizationOnboarding";++import { TRPCError } from "@trpc/server";++import type { TrpcSessionUser } from "../../../trpc";+import type { TCreateWithPaymentIntentInputSchema } from "./createWithPaymentIntent.schema";++type CreateOptions = {+ ctx: {+ user: NonNullable<TrpcSessionUser>;+ };+ input: TCreateWithPaymentIntentInputSchema;+};+const log = logger.getSubLogger({ prefix: ["viewer", "organizations", "createWithPaymentIntent"] });+export const createHandler = async ({ input, ctx }: CreateOptions) => {+ const paymentService = new OrganizationPaymentService(ctx.user);+ 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+ const organizationOnboarding = await OrganizationOnboardingRepository.findById(input.onboardingId);++ if (!organizationOnboarding) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "organization_onboarding_not_found",+ });+ }++ if (organizationOnboarding.stripeSubscriptionId) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "organization_has_subscription_already",+ });+ }++ if (!isAdmin && organizationOnboarding.orgOwnerEmail !== ctx.user.email) {+ log.warn(+ "Organization onboarding there but not have access",+ safeStringify({+ orgOwnerEmail: organizationOnboarding?.orgOwnerEmail,+ userEmail: ctx.user.email,+ })+ );++ // Intentionally throw vague error to avoid leaking information+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "organization_onboarding_not_found",+ });+ }++ const paymentIntent = await paymentService.createPaymentIntent(+ {+ ...input,+ logo: input.logo ?? null,+ bio: input.bio ?? null,+ },+ organizationOnboarding+ );++ return {+ checkoutUrl: paymentIntent.checkoutUrl,+ };+};++export default createHandler;diff --git a/packages/trpc/server/routers/viewer/organizations/createWithPaymentIntent.schema.ts b/packages/trpc/server/routers/viewer/organizations/createWithPaymentIntent.schema.tsnew file mode 100644index 00000000000..039d9d912f4--- /dev/null+++ b/packages/trpc/server/routers/viewer/organizations/createWithPaymentIntent.schema.ts@@ -0,0 +1,20 @@+import { z } from "zod";++import { orgOnboardingInvitedMembersSchema, orgOnboardingTeamsSchema } from "@calcom/prisma/zod-utils";++export enum BillingPeriod {+ MONTHLY = "MONTHLY",+ ANNUALLY = "ANNUALLY",+}++// Base user schema - fields that any user can set+export const ZCreateWithPaymentIntentInputSchema = z.object({+ language: z.string().optional(),+ logo: z.string().nullish(),+ bio: z.string().nullish(),+ onboardingId: z.string(),+ invitedMembers: orgOnboardingInvitedMembersSchema.optional(),+ teams: orgOnboardingTeamsSchema.optional(),+});++export type TCreateWithPaymentIntentInputSchema = z.infer<typeof ZCreateWithPaymentIntentInputSchema>;diff --git a/packages/trpc/server/routers/viewer/organizations/getOrganizationOnboarding.handler.ts b/packages/trpc/server/routers/viewer/organizations/getOrganizationOnboarding.handler.tsnew file mode 100644index 00000000000..810bacf05c7--- /dev/null+++ b/packages/trpc/server/routers/viewer/organizations/getOrganizationOnboarding.handler.ts@@ -0,0 +1,21 @@+import { OrganizationOnboardingRepository } from "@calcom/lib/server/repository/organizationOnboarding";++import type { TrpcSessionUser } from "../../../trpc";++type OrganizationOnboarding = {+ ctx: {+ user: NonNullable<TrpcSessionUser>;+ };+};++export async function getOrganizationOnboardingHandler({ ctx }: OrganizationOnboarding) {+ const { user: loggedInUser } = ctx;++ const organizationOnboarding = await OrganizationOnboardingRepository.findByOrgOwnerEmail(+ loggedInUser.email+ );++ return organizationOnboarding;+}++export default getOrganizationOnboardingHandler;diff --git a/packages/trpc/server/routers/viewer/organizations/intentToCreateOrg.handler.test.ts b/packages/trpc/server/routers/viewer/organizations/intentToCreateOrg.handler.test.tsnew file mode 100644index 00000000000..3d29a9bb6c5--- /dev/null+++ b/packages/trpc/server/routers/viewer/organizations/intentToCreateOrg.handler.test.ts@@ -0,0 +1,215 @@+import prismock from "../../../../../../tests/libs/__mocks__/prisma";++import { describe, expect, it, vi, beforeEach } from "vitest";++import { UserPermissionRole } from "@calcom/prisma/enums";++import { TRPCError } from "@trpc/server";++import { intentToCreateOrgHandler } from "./intentToCreateOrg.handler";++const mockInput = {+ name: "Test Org",+ slug: "test-org",+ orgOwnerEmail: "[email protected]",+ billingPeriod: "MONTHLY",+ seats: 5,+ pricePerSeat: 20,+ isPlatform: false,+};++// Helper functions for creating test data+async function createTestUser(data: {+ email: string;+ name?: string;+ username?: string;+ role?: UserPermissionRole;+ completedOnboarding?: boolean;+ emailVerified?: Date | null;+}) {+ return prismock.user.create({+ data: {+ email: data.email,+ name: data.name || "Test User",+ username: data.username || "testuser",+ role: data.role || UserPermissionRole.USER,+ completedOnboarding: data.completedOnboarding ?? false,+ emailVerified: data.emailVerified ?? null,+ },+ });+}++describe("intentToCreateOrgHandler", () => {+ beforeEach(async () => {+ vi.resetAllMocks();+ // @ts-expect-error reset is a method on Prismock+ await prismock.reset();+ });++ it("should allow admin user to create org for another user", async () => {+ // Create admin user+ const adminUser = await createTestUser({+ email: "[email protected]",+ role: UserPermissionRole.ADMIN,+ });++ // Create target org owner with completed onboarding and verified email+ await createTestUser({+ email: mockInput.orgOwnerEmail,+ completedOnboarding: true,+ emailVerified: new Date(),+ });++ const result = await intentToCreateOrgHandler({+ input: mockInput,+ ctx: {+ user: adminUser,+ },+ });++ // Verify the result shape+ expect(result).toEqual({+ userId: expect.any(Number),+ orgOwnerEmail: mockInput.orgOwnerEmail,+ name: mockInput.name,+ slug: mockInput.slug,+ seats: mockInput.seats,+ pricePerSeat: mockInput.pricePerSeat,+ billingPeriod: mockInput.billingPeriod,+ isPlatform: mockInput.isPlatform,+ organizationOnboardingId: expect.any(String),+ });++ // Verify organization onboarding was created+ const organizationOnboarding = await prismock.organizationOnboarding.findFirst({+ where: {+ slug: mockInput.slug,+ },+ });++ expect(organizationOnboarding).toBeDefined();+ expect(organizationOnboarding?.name).toBe(mockInput.name);+ expect(organizationOnboarding?.slug).toBe(mockInput.slug);+ expect(organizationOnboarding?.orgOwnerEmail).toBe(mockInput.orgOwnerEmail);+ });++ it("should allow user to create org for themselves", async () => {+ // Create user+ const user = await createTestUser({+ email: mockInput.orgOwnerEmail,+ completedOnboarding: true,+ emailVerified: new Date(),+ });++ const result = await intentToCreateOrgHandler({+ input: {+ ...mockInput,+ // Use default payment settings+ seats: undefined,+ pricePerSeat: undefined,+ },+ ctx: {+ user,+ },+ });++ expect(result.userId).toBe(user.id);+ expect(result.orgOwnerEmail).toBe(user.email);+ });++ it("should throw unauthorized error when no user is logged in", async () => {+ await expect(+ intentToCreateOrgHandler({+ input: mockInput,+ ctx: {+ user: null as any,+ },+ })+ ).rejects.toThrow(new TRPCError({ code: "UNAUTHORIZED", message: "You are not authorized." }));+ });++ it("should throw forbidden error when non-admin tries to create org for another user", async () => {+ // Create non-admin user+ const nonAdminUser = await createTestUser({+ email: "[email protected]",+ role: UserPermissionRole.USER,+ });++ await expect(+ intentToCreateOrgHandler({+ input: mockInput,+ ctx: {+ user: nonAdminUser,+ },+ })+ ).rejects.toThrow(+ new TRPCError({+ code: "FORBIDDEN",+ message: "You can only create organization where you are the owner",+ })+ );+ });++ it("should throw error when target user is not found", async () => {+ // Create admin user+ const adminUser = await createTestUser({+ email: "[email protected]",+ role: UserPermissionRole.ADMIN,+ });++ await expect(+ intentToCreateOrgHandler({+ input: mockInput,+ ctx: {+ user: adminUser,+ },+ })+ ).rejects.toThrow(+ new TRPCError({+ code: "BAD_REQUEST",+ message: `No user found with email ${mockInput.orgOwnerEmail}`,+ })+ );+ });++ it("should throw error when organization onboarding already exists", async () => {+ // Create admin user+ const adminUser = await createTestUser({+ email: "[email protected]",+ role: UserPermissionRole.ADMIN,+ });++ // Create target org owner+ await createTestUser({+ email: mockInput.orgOwnerEmail,+ completedOnboarding: true,+ emailVerified: new Date(),+ });++ // Create existing organization onboarding+ await prismock.organizationOnboarding.create({+ data: {+ name: mockInput.name,+ slug: mockInput.slug,+ orgOwnerEmail: mockInput.orgOwnerEmail,+ billingPeriod: mockInput.billingPeriod,+ seats: mockInput.seats,+ pricePerSeat: mockInput.pricePerSeat,+ createdById: adminUser.id,+ },+ });++ await expect(+ intentToCreateOrgHandler({+ input: mockInput,+ ctx: {+ user: adminUser,+ },+ })+ ).rejects.toThrow("organization_onboarding_already_exists");+ });++ // This endpoint doesn't handle platform organizations as that is completely different flow at the moment+ // eslint-disable-next-line playwright/no-skipped-test+ describe.skip("platform organization tests");+});diff --git a/packages/trpc/server/routers/viewer/organizations/intentToCreateOrg.handler.ts b/packages/trpc/server/routers/viewer/organizations/intentToCreateOrg.handler.tsnew file mode 100644index 00000000000..1fd0201d020--- /dev/null+++ b/packages/trpc/server/routers/viewer/organizations/intentToCreateOrg.handler.ts@@ -0,0 +1,92 @@+import { OrganizationPaymentService } from "@calcom/features/ee/organizations/lib/OrganizationPaymentService";+import {+ assertCanCreateOrg,+ findUserToBeOrgOwner,+} from "@calcom/features/ee/organizations/lib/server/orgCreationUtils";+import logger from "@calcom/lib/logger";+import { safeStringify } from "@calcom/lib/safeStringify";+import { OrganizationOnboardingRepository } from "@calcom/lib/server/repository/organizationOnboarding";+import { UserPermissionRole } from "@calcom/prisma/enums";++import { TRPCError } from "@trpc/server";++import type { TrpcSessionUser } from "../../../trpc";+import type { TIntentToCreateOrgInputSchema } from "./intentToCreateOrg.schema";++const log = logger.getSubLogger({ prefix: ["intentToCreateOrgHandler"] });++type CreateOptions = {+ ctx: {+ user: NonNullable<TrpcSessionUser>;+ };+ input: TIntentToCreateOrgInputSchema;+};++export const intentToCreateOrgHandler = async ({ input, ctx }: CreateOptions) => {+ const { slug, name, orgOwnerEmail, seats, pricePerSeat, billingPeriod, isPlatform } = input;+ log.debug(+ "Starting organization creation intent",+ safeStringify({ slug, name, orgOwnerEmail, isPlatform })+ );++ const loggedInUser = ctx.user;+ if (!loggedInUser) throw new TRPCError({ code: "UNAUTHORIZED", message: "You are not authorized." });++ const IS_USER_ADMIN = loggedInUser.role === UserPermissionRole.ADMIN;+ log.debug("User authorization check", safeStringify({ userId: loggedInUser.id, isAdmin: IS_USER_ADMIN }));++ if (!IS_USER_ADMIN && loggedInUser.email !== orgOwnerEmail && !isPlatform) {+ log.warn(+ "Unauthorized organization creation attempt",+ safeStringify({ loggedInUserEmail: loggedInUser.email, orgOwnerEmail })+ );+ throw new TRPCError({+ code: "FORBIDDEN",+ message: "You can only create organization where you are the owner",+ });+ }++ const orgOwner = await findUserToBeOrgOwner(orgOwnerEmail);+ if (!orgOwner) {+ // The flow exists to create the user through the stripe webhook invoice.paid but there could be a possible security issue with the approach. So, we avoid it currently.+ // Issue: As the onboarding link(which has onboardingId) could be used by unwanted person to pay and then invite some unwanted members to the organization.+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: `No user found with email ${orgOwnerEmail}`,+ });+ }+ log.debug("Found organization owner", safeStringify({ orgOwnerId: orgOwner.id, email: orgOwner.email }));++ let organizationOnboarding = await OrganizationOnboardingRepository.findByOrgOwnerEmail(orgOwner.email);+ if (organizationOnboarding) {+ throw new Error("organization_onboarding_already_exists");+ }++ await assertCanCreateOrg({+ slug,+ isPlatform,+ orgOwner,+ restrictBasedOnMinimumPublishedTeams: !IS_USER_ADMIN,+ });++ const paymentService = new OrganizationPaymentService(ctx.user);+ organizationOnboarding = await paymentService.createOrganizationOnboarding({+ ...input,+ createdByUserId: loggedInUser.id,+ });++ 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,+ };+};++export default intentToCreateOrgHandler;diff --git a/packages/trpc/server/routers/viewer/organizations/intentToCreateOrg.schema.ts b/packages/trpc/server/routers/viewer/organizations/intentToCreateOrg.schema.tsnew file mode 100644index 00000000000..3c4a9fdd24d--- /dev/null+++ b/packages/trpc/server/routers/viewer/organizations/intentToCreateOrg.schema.ts@@ -0,0 +1,24 @@+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",+}++export const ZIntentToCreateOrgInputSchema = z.object({+ name: z.string(),+ slug: z.string().transform((val) => slugify(val.trim())),+ orgOwnerEmail: emailSchema,+ language: z.string().optional(),+ seats: z.number().nullish(),+ pricePerSeat: z.number().nullish(),+ isPlatform: z.boolean().default(false),+ billingPeriod: z.nativeEnum(BillingPeriod).default(BillingPeriod.MONTHLY),+ creationSource: z.nativeEnum(CreationSource),+});++export type TIntentToCreateOrgInputSchema = z.infer<typeof ZIntentToCreateOrgInputSchema>;diff --git a/turbo.json b/turbo.jsonindex 3ad6b7700ae..6e1f478c3f7 100644--- a/turbo.json+++ b/turbo.json@@ -45,6 +45,7 @@"STRIPE_TEAM_MONTHLY_PRICE_ID","STRIPE_TEAM_PRODUCT_ID","STRIPE_ORG_MONTHLY_PRICE_ID",+ "STRIPE_ORG_PRODUCT_ID","NEXT_PUBLIC_API_V2_URL","NEXT_PUBLIC_VAPID_PUBLIC_KEY","BUILD_STANDALONE",@@ -352,7 +353,7 @@"NEXT_PUBLIC_VERCEL_BRANCH_URL","NEXT_PUBLIC_GTM_ID","NEXT_PUBLIC_ORGANIZATIONS_MIN_SELF_SERVE_SEATS",- "NEXT_PUBLIC_ORGANIZATIONS_SELF_SERVE_PRICE",+ "NEXT_PUBLIC_ORGANIZATIONS_SELF_SERVE_PRICE_NEW","NEXT_PUBLIC_WEBSITE_PRIVACY_POLICY_URL","NEXT_PUBLIC_WEBSITE_TERMS_URL","NEXT_RUNTIME",