feat: new org onboarding wizard (#13139)

* added layouts for moving teams step

* added admin section for org creation step

* extended org creation to also move existing teams

* wip

* wip

* wip

* further changes

* Add checkout for org in onboarding

* Fix ts errors

* Self review feedback

* Self review addressed

* Fix unit tests

* Fix ts error

* Seans feedback addressed

* feat: fix correct accounts pending

* fix: unit tests for new invite member permissions

* tests: org admin onboarding tests for existing user

* tests: Inital user self serve flow

* chore: update teamAndUserFixture to create X amount of teams

* chore: add testId to card actionButton

* test: add test-Id to continue or checkout button

* tests: add tests for migrating existing teams

* feat: match new designs

* fix: isAdminCheck

* chore: fix pricing copy

* fix: flacky tests

* Fix tests?

* More test fixes

* Check all checkboxes

* Fix type error

* Fix failing test and typescript issues

* Fix unpaid org allowing auto-add users

* Add self-serve flag

* Skip tests

---------

Co-authored-by: Alex van Andel <[email protected]>
Co-authored-by: Hariom <[email protected]>
Co-authored-by: sean-brydon <[email protected]>
Co-authored-by: Joe Au-Yeung <[email protected]>
Co-authored-by: Joe Au-Yeung <[email protected]>
Co-authored-by: Omar López <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-04-03 18:53:02 +05:30
1 parent c3b1de498d
commit b3f4cfab32
49 files changed
+1813 -755

No files matched your search

@@ -33,7 +33,6 @@ export async function getServerSession(options: {
res?: NextApiResponse | GetServerSidePropsContext["res"];
authOptions?: AuthOptions;
}) {
log.debug("Getting server session");
const { req, authOptions: { secret } = {} } = options;
const token = await getToken({
@@ -41,6 +40,8 @@ export async function getServerSession(options: {
secret,
});
log.debug("Getting server session", safeStringify({ token }));
if (!token || !token.email || !token.sub) {
log.debug("Couldnt get token");
return null;
@@ -49,6 +50,7 @@ export async function getServerSession(options: {
const cachedSession = CACHE.get(JSON.stringify(token));
if (cachedSession) {
log.debug("Returning cached session", safeStringify(cachedSession));
return cachedSession;
}
@@ -161,17 +161,27 @@ const handleGroupEvents = async (event: DirectorySyncEvent, organizationId: numb
const translation = await getTranslation(user.locale || "en", "common");
return sendExistingUserTeamInviteEmails({
currentUserTeamName: group.team.name,
existingUsersWithMembersips: [user],
existingUsersWithMembersips: [
{
...user,
profile: null,
},
],
language: translation,
isOrg: false,
teamId: group.teamId,
isAutoJoin: true,
currentUserParentTeamName: org.name,
orgSlug: null,
});
}),
...newOrgMembers.map((user) => {
return createAProfileForAnExistingUser({
user,
user: {
id: user.id,
email: user.email,
currentUsername: user.username,
},
organizationId,
});
}),
@@ -49,12 +49,18 @@ const handleUserEvents = async (event: DirectorySyncEvent, organizationId: numbe
await sendExistingUserTeamInviteEmails({
currentUserName: user.username,
currentUserTeamName: org.name,
existingUsersWithMembersips: [addedUser],
existingUsersWithMembersips: [
{
...addedUser,
profile: null,
},
],
language: translation,
isOrg: true,
teamId: org.id,
isAutoJoin: true,
currentUserParentTeamName: org?.parent?.name,
orgSlug: org.slug,
});
} else {
// If data.active is false then remove the user from the org
@@ -17,7 +17,11 @@ const inviteExistingUserToOrg = async ({
translation: TFunction;
}) => {
await createAProfileForAnExistingUser({
user,
user: {
id: user.id,
email: user.email,
currentUsername: user.username,
},
organizationId: org.id,
});
@@ -1,13 +1,16 @@
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useFieldArray, useForm } from "react-hook-form";
import { useFieldArray, useForm, Controller } from "react-hook-form";
import { z } from "zod";
import { classNames } from "@calcom/lib";
import { IS_TEAM_BILLING_ENABLED_CLIENT } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
import { UserPermissionRole } from "@calcom/prisma/enums";
import { trpc } from "@calcom/trpc/react";
import { Button, showToast, TextField } from "@calcom/ui";
import { Button, showToast, TextField, CheckboxField, Form } from "@calcom/ui";
import { ArrowRight, Plus, X } from "@calcom/ui/components/icon";
const querySchema = z.object({
@@ -15,24 +18,60 @@ const querySchema = z.object({
});
const schema = z.object({
teams: z
.array(
z.object({
name: z.string().min(2, "org_team_name_min_2_chars").trim(),
})
)
.min(1, "At least one team is required"),
teams: z.array(
z.object({
name: z.string().trim(),
})
),
moveTeams: z.array(
z.object({
id: z.number(),
shouldMove: z.boolean(),
newSlug: z.string().optional(),
})
),
});
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 orgWithRequestedSlug = {
...org,
requestedSlug: org.metadata.requestedSlug ?? null,
};
const regularTeams = teams.filter((team) => !team.parentId);
return <AddNewTeamsFormChild org={orgWithRequestedSlug} teams={regularTeams} />;
};
const AddNewTeamsFormChild = ({
teams,
org,
}: {
org: { id: number; slug: string | null; requestedSlug: string | null };
teams: { id: number; name: string; slug: string | null }[];
}) => {
const { t } = useLocale();
const router = useRouter();
const routerQuery = useRouterQuery();
const { id: orgId } = querySchema.parse(routerQuery);
const [counter, setCounter] = useState(1);
const { register, control, handleSubmit, formState, trigger, setValue, getValues } = useForm({
defaultValues: { teams: [{ name: "" }] }, // Set initial values
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 }),
})),
}, // Set initial values
resolver: async (data) => {
try {
const validatedData = await schema.parseAsync(data);
@@ -50,11 +89,27 @@ export const AddNewTeamsForm = () => {
}
},
});
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);
@@ -73,11 +128,18 @@ export const AddNewTeamsForm = () => {
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(() => {
router.push(`/event-types`);
}, 3000);
setTimeout(() => handleSuccessRedirect, 3000);
} else {
router.push(`/event-types`);
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) => {
@@ -85,29 +147,58 @@ export const AddNewTeamsForm = () => {
},
});
const handleInputChange = (index: number, event: any) => {
const { name, value } = event.target;
setValue(`teams.${index}.name`, value);
trigger(`teams.${index}.name`);
};
const handleFormSubmit = () => {
if (formState.isValid) {
const fields = getValues("teams");
createTeamsMutation.mutate({ orgId, teamNames: fields.map((field) => field.name) });
}
const fields = getValues("teams");
const moveTeams = getValues("moveTeams");
createTeamsMutation.mutate({ orgId: org.id, moveTeams, teamNames: fields.map((field) => field.name) });
};
const moveTeams = watch("moveTeams");
return (
<>
<form onSubmit={handleSubmit(handleFormSubmit)}>
<Form form={form} handleSubmit={handleFormSubmit}>
{moveTeams.length ? (
<>
<label className="text-emphasis mb-2 block text-sm font-medium leading-none">
Move existing teams
</label>
<ul className="mb-8 space-y-4">
{moveTeams.map((team, index) => {
return (
<li key={team.id}>
<Controller
name={`moveTeams.${index}.shouldMove`}
render={({ field: { value, onChange } }) => (
<CheckboxField
defaultValue={value}
checked={value}
onChange={onChange}
description={teams.find((t) => t.id === team.id)?.name ?? ""}
/>
)}
/>
{moveTeams[index].shouldMove ? (
<TextField
placeholder="New Slug"
defaultValue={teams.find((t) => t.id === team.id)?.slug ?? ""}
{...register(`moveTeams.${index}.newSlug`)}
className="mt-2"
label=""
/>
) : null}
</li>
);
})}
</ul>
</>
) : null}
<label className="text-emphasis mb-2 block text-sm font-medium leading-none">Add New Teams</label>
{fields.map((field, index) => (
<div className={classNames("relative", index > 0 ? "mb-2" : "")} key={field.id}>
<TextField
key={field.id}
{...register(`teams.${index}.name`)}
label=""
onChange={(e) => handleInputChange(index, e)}
addOnClassname="bg-transparent p-0 border-l-0"
className={index > 0 ? "mb-2" : ""}
placeholder={t(`org_team_names_example_${index + 1}`)}
@@ -143,11 +234,21 @@ export const AddNewTeamsForm = () => {
EndIcon={ArrowRight}
color="primary"
className="mt-6 w-full justify-center"
disabled={!formState.isValid || createTeamsMutation.isPending || createTeamsMutation.isSuccess}
data-testId="continue_or_checkout"
disabled={createTeamsMutation.isPending || createTeamsMutation.isSuccess}
onClick={handleFormSubmit}>
{t("continue")}
{allowWizardCompletionWithoutUpgrading ? t("continue") : t("checkout")}
</Button>
</form>
</Form>
</>
);
};
const getSuggestedSlug = ({ teamSlug, orgSlug }: { teamSlug: string | null; orgSlug: string | null }) => {
// If there is no orgSlug, we can't suggest a slug
if (!teamSlug || !orgSlug) {
return teamSlug;
}
return teamSlug.replace(`${orgSlug}-`, "").replace(`-${orgSlug}`, "");
};
@@ -1,16 +1,20 @@
import { useSession } from "next-auth/react";
import { signIn } from "next-auth/react";
import type { SessionContextValue } from "next-auth/react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { useVerifyCode } from "@calcom/features/bookings/Booker/components/hooks/useVerifyCode";
import { VerifyCodeDialog } from "@calcom/features/bookings/components/VerifyCodeDialog";
import { subdomainSuffix } from "@calcom/features/ee/organizations/lib/orgDomains";
import classNames from "@calcom/lib/classNames";
import { 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 { trpc } from "@calcom/trpc/react";
import { Button, Form, TextField, Alert } from "@calcom/ui";
import type { Ensure } from "@calcom/types/utils";
import { Button, Form, TextField, Alert, RadioGroup as RadioArea } from "@calcom/ui";
import { ArrowRight } from "@calcom/ui/components/icon";
function extractDomainFromEmail(email: string) {
@@ -22,47 +26,55 @@ function extractDomainFromEmail(email: string) {
return out.split(".")[0];
}
export const CreateANewOrganizationForm = ({ slug }: { slug?: string }) => {
const { t, i18n } = useLocale();
export const CreateANewOrganizationForm = () => {
const session = useSession();
if (!session.data) {
return null;
}
return <CreateANewOrganizationFormChild session={session} />;
};
const CreateANewOrganizationFormChild = ({ session }: { session: Ensure<SessionContextValue, "data"> }) => {
const { t } = useLocale();
const router = useRouter();
const telemetry = useTelemetry();
const [serverErrorMessage, setServerErrorMessage] = useState<string | null>(null);
const [showVerifyCode, setShowVerifyCode] = useState(false);
const isAdmin = session.data.user.role === UserPermissionRole.ADMIN;
const isImpersonated = session.data.user.impersonatedBy;
const defaultOrgOwnerEmail = session.data.user.email ?? "";
const newOrganizationFormMethods = useForm<{
name: string;
seats: number;
pricePerSeat: number;
slug: string;
adminEmail: string;
adminUsername: string;
orgOwnerEmail: string;
}>({
defaultValues: {
slug: `${slug ?? ""}`,
slug: !isAdmin ? deriveSlugFromEmail(defaultOrgOwnerEmail) : undefined,
orgOwnerEmail: !isAdmin ? defaultOrgOwnerEmail : undefined,
name: !isAdmin ? deriveOrgNameFromEmail(defaultOrgOwnerEmail) : undefined,
},
});
const watchAdminEmail = newOrganizationFormMethods.watch("adminEmail");
const createOrganizationMutation = trpc.viewer.organizations.create.useMutation({
onSuccess: async (data) => {
if (data.checked) {
setShowVerifyCode(true);
} else if (data.user) {
telemetry.event(telemetryEventTypes.org_created);
await signIn("credentials", {
redirect: false,
callbackUrl: "/",
email: data.user.email,
password: data.user.password,
telemetry.event(telemetryEventTypes.org_created);
// This is necessary so that server token has the updated upId
await session.update({
upId: data.upId,
});
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`,
});
router.push(`/settings/organizations/${data.user.organizationId}/set-password`);
}
router.push(`/settings/organizations/${data.organizationId}/about`);
},
onError: (err) => {
if (err.message === "admin_email_taken") {
newOrganizationFormMethods.setError("adminEmail", {
type: "custom",
message: t("email_already_used"),
});
} else if (err.message === "organization_url_taken") {
if (err.message === "organization_url_taken") {
newOrganizationFormMethods.setError("slug", { type: "custom", message: t("url_taken") });
} else if (err.message === "domain_taken_team" || err.message === "domain_taken_project") {
newOrganizationFormMethods.setError("slug", {
@@ -75,22 +87,11 @@ export const CreateANewOrganizationForm = ({ slug }: { slug?: string }) => {
},
});
const verifyCode = useVerifyCode({
onSuccess: (isVerified) => {
if (isVerified) {
createOrganizationMutation.mutate({
...newOrganizationFormMethods.getValues(),
language: i18n.language,
check: false,
});
}
},
});
return (
<>
<Form
form={newOrganizationFormMethods}
className="space-y-5"
id="createOrg"
handleSubmit={(v) => {
if (!createOrganizationMutation.isPending) {
@@ -98,17 +99,15 @@ export const CreateANewOrganizationForm = ({ slug }: { slug?: string }) => {
createOrganizationMutation.mutate(v);
}
}}>
<div className="mb-5">
<div>
{serverErrorMessage && (
<div className="mb-4">
<Alert severity="error" message={serverErrorMessage} />
</div>
)}
<Controller
name="adminEmail"
name="orgOwnerEmail"
control={newOrganizationFormMethods.control}
defaultValue=""
rules={{
required: t("must_enter_organization_admin_email"),
}}
@@ -117,23 +116,18 @@ export const CreateANewOrganizationForm = ({ slug }: { slug?: string }) => {
<TextField
containerClassName="w-full"
placeholder="[email protected]"
name="adminEmail"
name="orgOwnerEmail"
disabled={!isAdmin && !isImpersonated}
label={t("admin_email")}
defaultValue={value}
onChange={(e) => {
const domain = extractDomainFromEmail(e?.target.value);
newOrganizationFormMethods.setValue("adminEmail", e?.target.value.trim());
newOrganizationFormMethods.setValue(
"adminUsername",
e?.target.value.split("@")[0].trim()
);
const email = e?.target.value;
const slug = deriveSlugFromEmail(email);
newOrganizationFormMethods.setValue("orgOwnerEmail", email.trim());
if (newOrganizationFormMethods.getValues("slug") === "") {
newOrganizationFormMethods.setValue("slug", domain);
newOrganizationFormMethods.setValue("slug", slug);
}
newOrganizationFormMethods.setValue(
"name",
domain.charAt(0).toUpperCase() + domain.slice(1)
);
newOrganizationFormMethods.setValue("name", deriveOrgNameFromEmail(email));
}}
autoComplete="off"
/>
@@ -141,7 +135,7 @@ export const CreateANewOrganizationForm = ({ slug }: { slug?: string }) => {
)}
/>
</div>
<div className="mb-5">
<div>
<Controller
name="name"
control={newOrganizationFormMethods.control}
@@ -170,7 +164,7 @@ export const CreateANewOrganizationForm = ({ slug }: { slug?: string }) => {
/>
</div>
<div className="mb-5">
<div>
<Controller
name="slug"
control={newOrganizationFormMethods.control}
@@ -196,7 +190,82 @@ export const CreateANewOrganizationForm = ({ slug }: { slug?: string }) => {
/>
</div>
<input hidden {...newOrganizationFormMethods.register("adminUsername")} />
{(isAdmin || isImpersonated) && (
<>
<section className="grid grid-cols-2 gap-2">
<div className="w-full">
<Controller
name="seats"
control={newOrganizationFormMethods.control}
render={({ field: { value, onChange } }) => (
<div className="flex">
<TextField
containerClassName="w-full"
placeholder="30"
name="seats"
type="number"
label="Seats (optional)"
min={MINIMUM_NUMBER_OF_ORG_SEATS}
defaultValue={value || MINIMUM_NUMBER_OF_ORG_SEATS}
onChange={(e) => {
onChange(+e.target.value);
}}
autoComplete="off"
/>
</div>
)}
/>
</div>
<div className="w-full">
<Controller
name="pricePerSeat"
control={newOrganizationFormMethods.control}
render={({ field: { value, onChange } }) => (
<div className="flex">
<TextField
containerClassName="w-full"
placeholder="30"
name="pricePerSeat"
type="number"
addOnSuffix="$"
label="Price per seat (optional)"
defaultValue={value}
onChange={(e) => {
onChange(+e.target.value);
}}
autoComplete="off"
/>
</div>
)}
/>
</div>
</section>
</>
)}
{/* This radio group does nothing - its just for visuall purposes */}
{!isAdmin && (
<>
<div className="bg-subtle space-y-5 rounded-lg p-5">
<h3 className="font-cal text-default text-lg font-semibold leading-4">
Upgrade to Organizations
</h3>
<RadioArea.Group className={classNames("mt-1 flex flex-col gap-4")} value="ORGANIZATION">
<RadioArea.Item
className={classNames("bg-default w-full text-sm opacity-70")}
value="TEAMS"
disabled>
<strong className="mb-1 block">{t("teams")}</strong>
<p>{t("your_current_plan")}</p>
</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>
</RadioArea.Item>
</RadioArea.Group>
</div>
</>
)}
<div className="flex space-x-2 rtl:space-x-reverse">
<Button
@@ -212,17 +281,18 @@ export const CreateANewOrganizationForm = ({ slug }: { slug?: string }) => {
</Button>
</div>
</Form>
<VerifyCodeDialog
isOpenDialog={showVerifyCode}
setIsOpenDialog={setShowVerifyCode}
email={watchAdminEmail}
verifyCodeWithSessionNotRequired={verifyCode.verifyCodeWithSessionNotRequired}
verifyCodeWithSessionRequired={verifyCode.verifyCodeWithSessionRequired}
error={verifyCode.error}
resetErrors={verifyCode.resetErrors}
isPending={verifyCode.isPending}
setIsPending={verifyCode.setIsPending}
/>
</>
);
};
function deriveSlugFromEmail(email: string) {
const domain = extractDomainFromEmail(email);
return domain;
}
function deriveOrgNameFromEmail(email: string) {
const domain = extractDomainFromEmail(email);
return domain.charAt(0).toUpperCase() + domain.slice(1);
}
@@ -31,6 +31,7 @@ export function OrgUpgradeBanner({ data }: OrgUpgradeBannerProps) {
variant="warning"
actions={
<button
data-testid="upgrade_org_banner_button"
className="border-b border-b-black"
onClick={() => {
publishOrgMutation.mutate();
@@ -1,111 +0,0 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { z } from "zod";
import { isPasswordValid } from "@calcom/features/auth/lib/isPasswordValid";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
import { trpc } from "@calcom/trpc/react";
import { Alert, Button, Form, PasswordField } from "@calcom/ui";
import { ArrowRight } from "@calcom/ui/components/icon";
const querySchema = z.object({
id: z.string(),
});
const formSchema = z.object({
password: z.string().superRefine((data, ctx) => {
const isStrict = true;
const result = isPasswordValid(data, true, isStrict);
Object.keys(result).map((key: string) => {
if (!result[key as keyof typeof result]) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: [key],
message: key,
});
}
});
}),
});
export const SetPasswordForm = () => {
const { t } = useLocale();
const router = useRouter();
const routerQuery = useRouterQuery();
const { id: orgId } = querySchema.parse(routerQuery);
const [serverErrorMessage, setServerErrorMessage] = useState<string | null>(null);
const setPasswordFormMethods = useForm<{
password: string;
}>({
resolver: zodResolver(formSchema),
});
const setPasswordMutation = trpc.viewer.organizations.setPassword.useMutation({
onSuccess: (data) => {
if (data.update) {
router.push(`/settings/organizations/${orgId}/about`);
}
},
onError: (err) => {
setServerErrorMessage(err.message);
},
});
return (
<>
<Form
form={setPasswordFormMethods}
handleSubmit={(v) => {
if (!setPasswordMutation.isPending) {
setServerErrorMessage(null);
setPasswordMutation.mutate({ newPassword: v.password });
}
}}>
<div>
{serverErrorMessage && (
<div className="mb-4">
<Alert severity="error" message={serverErrorMessage} />
</div>
)}
</div>
<div className="mb-5">
<Controller
name="password"
control={setPasswordFormMethods.control}
render={({ field: { onBlur, onChange, value } }) => (
<PasswordField
value={value || ""}
onBlur={onBlur}
onChange={async (e) => {
onChange(e.target.value);
setPasswordFormMethods.setValue("password", e.target.value);
await setPasswordFormMethods.trigger("password");
}}
hintErrors={["caplow", "admin_min", "num"]}
name="password"
autoComplete="off"
/>
)}
/>
</div>
<div className="flex">
<Button
disabled={setPasswordFormMethods.formState.isSubmitting || setPasswordMutation.isPending}
color="primary"
EndIcon={ArrowRight}
type="submit"
className="w-full justify-center">
{t("continue")}
</Button>
</div>
</Form>
</>
);
};
@@ -1,4 +1,3 @@
export { CreateANewOrganizationForm } from "./CreateANewOrganizationForm";
export { AboutOrganizationForm } from "./AboutOrganizationForm";
export { SetPasswordForm } from "./SetPasswordForm";
export { AddNewTeamsForm } from "./AddNewTeamsForm";
@@ -16,7 +16,8 @@ export const getServerSideProps = async ({ req, res }: GetServerSidePropsContext
// Check if logged in user has an organization assigned
const session = await getServerSession({ req, res });
if (!session?.user.org?.id) {
if (!session?.user.profile.organizationId) {
return {
notFound: true,
};
@@ -26,7 +27,7 @@ export const getServerSideProps = async ({ req, res }: GetServerSidePropsContext
const membership = await prisma.membership.findFirst({
where: {
userId: session?.user.id,
teamId: session?.user.org.id,
teamId: session?.user.profile.organizationId,
},
select: {
role: true,
@@ -1,16 +1,20 @@
import { useState } from "react";
import { ORG_SELF_SERVE_ENABLED } from "@calcom/lib/constants";
import { trackFormbricksAction } from "@calcom/lib/formbricks-client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import { Card, showToast } from "@calcom/ui";
import { UserPlus, Users, Edit } from "@calcom/ui/components/icon";
import { UserPlus, Building, LineChart, Paintbrush, Users, Edit } from "@calcom/ui/components/icon";
import TeamListItem from "./TeamListItem";
interface Props {
teams: RouterOutputs["viewer"]["teams"]["list"];
/**
* True for teams that are pending invite acceptance
*/
pending?: boolean;
}
@@ -18,6 +22,7 @@ export default function TeamList(props: Props) {
const utils = trpc.useUtils();
const { t } = useLocale();
const { data: user } = trpc.viewer.me.useQuery();
const [hideDropdown, setHideDropdown] = useState(false);
@@ -44,8 +49,62 @@ export default function TeamList(props: Props) {
deleteTeamMutation.mutate({ teamId });
}
if (!user) return null;
const isUserAlreadyInAnOrganization = user.profile.organization;
return (
<ul className="bg-default divide-subtle border-subtle mb-2 divide-y overflow-hidden rounded-md border">
{ORG_SELF_SERVE_ENABLED &&
!props.pending &&
!isUserAlreadyInAnOrganization &&
props.teams.length > 2 &&
props.teams.map(
(team, i) =>
team.role !== "MEMBER" &&
i === 0 && (
<div className="bg-subtle p-4">
<div className="grid-col-1 grid gap-2 md:grid-cols-3">
<Card
icon={<Building className="h-5 w-5 text-red-700" />}
variant="basic"
title={t("You have a lot of teams")}
description={t(
"Consider consolidating your teams in an organisation, unify billing, admin tools and analytics."
)}
actionButton={{
href: `/settings/organizations/new`,
child: t("set_up_your_organization"),
"data-testId": "setup_your_org_action_button",
}}
/>
<Card
icon={<Paintbrush className="h-5 w-5 text-orange-700" />}
variant="basic"
title={t("Get a clean subdomain")}
description={t(
"Right now, team member URLs are all over the place. Get a beautiful link and turn every email address into a scheduling link: [email protected] → acme.cal.com/anna"
)}
actionButton={{
href: "https://www.youtube.com/watch?v=G0Jd2dp7064",
child: t("learn_more"),
}}
/>
<Card
icon={<LineChart className="h-5 w-5 text-green-700" />}
variant="basic"
title={t("Admin tools and analytics")}
description={t(
"As an organization owner, you are in charge of every team account. You can make changes with admin-only tools and see organization wide analytics in one place."
)}
actionButton={{
href: "https://i.cal.com/sales/enterprise",
child: t("learn_more"),
}}
/>
</div>
</div>
)
)}
{props.teams.map((team) => (
<TeamListItem
key={team?.id as number}
+59 -8
View File
@@ -2,11 +2,15 @@ import { z } from "zod";
import { getStripeCustomerIdFromUserId } from "@calcom/app-store/stripepayment/lib/customer";
import stripe from "@calcom/app-store/stripepayment/lib/server";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { IS_PRODUCTION } from "@calcom/lib/constants";
import { MINIMUM_NUMBER_OF_ORG_SEATS, WEBAPP_URL } from "@calcom/lib/constants";
import { ORGANIZATION_MIN_SEATS } from "@calcom/lib/constants";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import prisma from "@calcom/prisma";
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
const log = logger.getSubLogger({ prefix: ["teams/lib/payments"] });
const teamPaymentMetadataSchema = z.object({
paymentId: z.string(),
subscriptionId: z.string(),
@@ -59,8 +63,9 @@ export const generateTeamCheckoutSession = async ({
customer_update: {
address: "auto",
},
// Disabled when testing locally as usually developer doesn't setup Tax in Stripe Test mode
automatic_tax: {
enabled: true,
enabled: IS_PRODUCTION,
},
metadata: {
teamName,
@@ -74,18 +79,21 @@ export const generateTeamCheckoutSession = async ({
/**
* Used to generate a checkout session when creating a new org (parent team) or backwards compatibility for old teams
*/
export const purchaseTeamSubscription = async (input: {
export const purchaseTeamOrOrgSubscription = async (input: {
teamId: number;
seats: number;
userId: number;
isOrg?: boolean;
pricePerSeat: number | null;
}) => {
const { teamId, seats, userId, isOrg } = input;
const { teamId, seats, userId, isOrg, pricePerSeat } = input;
const { url } = await checkIfTeamPaymentRequired({ teamId });
if (url) return { url };
// For orgs, enforce minimum of 30 seats
const quantity = isOrg ? (seats < 30 ? 30 : seats) : seats;
const quantity = isOrg ? Math.max(seats, MINIMUM_NUMBER_OF_ORG_SEATS) : seats;
const customer = await getStripeCustomerIdFromUserId(userId);
const session = await stripe.checkout.sessions.create({
customer,
mode: "subscription",
@@ -94,16 +102,16 @@ export const purchaseTeamSubscription = async (input: {
cancel_url: `${WEBAPP_URL}/settings/my-account/profile`,
line_items: [
{
/** We only need to set the base price and we can upsell it directly on Stripe's checkout */
price: isOrg ? process.env.STRIPE_ORG_MONTHLY_PRICE_ID : process.env.STRIPE_TEAM_MONTHLY_PRICE_ID,
price: await getPriceId(),
quantity: quantity,
},
],
customer_update: {
address: "auto",
},
// Disabled when testing locally as usually developer doesn't setup Tax in Stripe Test mode
automatic_tax: {
enabled: true,
enabled: IS_PRODUCTION,
},
metadata: {
teamId,
@@ -115,6 +123,49 @@ export const purchaseTeamSubscription = async (input: {
},
});
return { url: session.url };
/**
* Determines the priceId depending on if a custom price is required or not.
* If the organization has a custom price per seat, it will create a new price in stripe and return its ID.
*/
async function getPriceId() {
const fixedPriceId = isOrg
? process.env.STRIPE_ORG_MONTHLY_PRICE_ID
: process.env.STRIPE_TEAM_MONTHLY_PRICE_ID;
if (!fixedPriceId) {
throw new Error(
"You need to have STRIPE_ORG_MONTHLY_PRICE_ID and STRIPE_TEAM_MONTHLY_PRICE_ID env variables set"
);
}
log.debug("Getting price ID", safeStringify({ fixedPriceId, isOrg, teamId, pricePerSeat }));
if (!pricePerSeat) {
return fixedPriceId;
}
const priceObj = await stripe.prices.retrieve(fixedPriceId);
if (!priceObj) throw new Error(`No price found for ID ${fixedPriceId}`);
try {
const customPriceObj = await stripe.prices.create({
nickname: `Custom price for ${isOrg ? "Organization" : "Team"} ID: ${teamId}`,
unit_amount: pricePerSeat * 100, // Stripe expects the amount in cents
// Use the same currency as in the fixed price to avoid hardcoding it.
currency: priceObj.currency,
recurring: { interval: "month" }, // Define your subscription interval
product: typeof priceObj.product === "string" ? priceObj.product : priceObj.product.id,
});
return customPriceObj.id;
} catch (e) {
log.error(
`Error creating custom price for ${isOrg ? "Organization" : "Team"} ID: ${teamId}`,
safeStringify(e)
);
throw new Error("Error in creation of custom price");
}
}
};
const getTeamWithPaymentMetadata = async (teamId: number) => {