feat: org invite billing (#9291)

* Initial commit

* Adding feature flag

* Desktop first banner, mobile pending

* Removing dead code and img

* AppInstallButtonBase

* WIP

* Adds Email verification template+translations for organizations (#9202)

* feat: Orgs Schema Changing `scopedMembers` to `orgUsers` (#9209)

* Change scopedMembers to orgMembers

* Change to orgUsers

* First step done

* Merge branch 'feat/organizations-onboarding' of github.com:calcom/cal.com into feat/organizations-onboarding

* Session logic to show org label

* Step 2 done, avatar not working

* List orgs and list teams specific if orgs exist

* Conditionally show org - fix settings layout - add labels for all pages

* Profile Page + update

* Org specific team creation

* appearance page

* Ensure members cant of org cant update settings in UI

* Fix update handler imports

* hide billing on sub teams

* Update profile slug page

* Letting duplicate slugs for teams to support orgs

* Add slug coliisions for org

* Covering null on unique clauses

* Covering null on unique clauses

* Extract to utils

* Update settings to use subdomain path in team url , team + org

* Supporting having the orgId in the session cookie

* Onboarding admins step

* Last step to create teams

* Update handler comments

* Upgrade ORG banner - disabled team banner for child teams

* Handle publishing ORGS

* Fix licenese issue

* Update packages/trpc/server/routers/viewer/teams/create.handler.ts

* Split into function calls to make this file more explisit

* Update parents stripe sub not teamID

* Moving change password handler, improving verifying code flow

* Clearing error before submitting

* Reverting email testing api changes

* Reverting having the banner for now

* Consistent exported components

* Remove unneeded files from banner

* Removing uneeded code

* Fixing avatar selector

* Using meta component for head/descr

* Missing i18n strings

* Create org membership also - billing portal page

* A11ly

* Hide create team if no valid permisisons

* Get Org members router

* Handle updating subscription if orgId

* Fix double upgrade banner

* Update constants

* Feedback

* Copy change

* Making an org avatar (temp)

* Add slug colission detection for user and team name

* Fix Import

* Remove update password func

* Fix module import over relative

* feat: organization event type filter (#9253)

Signed-off-by: Udit Takkar <[email protected]>

* Missing changes to support orgs schema changes

* Fix import again

* Throw no team found before auth error

* Check if invited found user is already in differnt org

* Move to for of loop to throw errors in usenamelist

* Remove app install button sa its in 9337

* Remove i18n key not being used

* feat: Onboarding process to create an organization (#9184)

* Desktop first banner, mobile pending

* Removing dead code and img

* WIP

* Adds Email verification template+translations for organizations (#9202)

* First step done

* Merge branch 'feat/organizations-onboarding' of github.com:calcom/cal.com into feat/organizations-onboarding

* Step 2 done, avatar not working

* Covering null on unique clauses

* Onboarding admins step

* Last step to create teams

* Moving change password handler, improving verifying code flow

* Clearing error before submitting

* Reverting email testing api changes

* Reverting having the banner for now

* Consistent exported components

* Remove unneeded files from banner

* Removing uneeded code

* Fixing avatar selector

* Using meta component for head/descr

* Missing i18n strings

* Feedback

* Making an org avatar (temp)

* Check for subteams slug clashes with usernames

* Fixing create teams onsuccess

* feedback

* Making sure we check requestedSlug now

---------

Co-authored-by: sean-brydon <[email protected]>

* feat: [CAL-1816] Organization subdomain support (#9345)

* Desktop first banner, mobile pending

* Removing dead code and img

* WIP

* Adds Email verification template+translations for organizations (#9202)

* First step done

* Merge branch 'feat/organizations-onboarding' of github.com:calcom/cal.com into feat/organizations-onboarding

* Step 2 done, avatar not working

* Covering null on unique clauses

* Onboarding admins step

* Last step to create teams

* Moving change password handler, improving verifying code flow

* Clearing error before submitting

* Reverting email testing api changes

* Reverting having the banner for now

* Consistent exported components

* Remove unneeded files from banner

* Removing uneeded code

* Fixing avatar selector

* Using meta component for head/descr

* Missing i18n strings

* Feedback

* Making an org avatar (temp)

* Check for subteams slug clashes with usernames

* Fixing create teams onsuccess

* Covering users and subteams, excluding non-org users

* Unpublished teams shows correctly

* Create subdomain in Vercel

* feedback

* Renaming Vercel env vars

* Vercel domain check before creation

* Supporting cal-staging.com

* Change to have vercel detect it

* vercel domain check data message error

* Remove check domain

* Making sure we check requestedSlug now

* Feedback and unneeded code

* Reverting unneeded changes

* Unneeded changes

---------

Co-authored-by: sean-brydon <[email protected]>

* Vercel subdomain creation in PROD only

* Fix router

* feat: organization settings general and members page (#9266)

* feat: organization settings general page

Signed-off-by: Udit Takkar <[email protected]>

* feat: add members page

Signed-off-by: Udit Takkar <[email protected]>

* chore: remove

Signed-off-by: Udit Takkar <[email protected]>

* fix: use invalidate

Signed-off-by: Udit Takkar <[email protected]>

* fix: delete mutation

Signed-off-by: Udit Takkar <[email protected]>

* fix: remove organization id

Signed-off-by: Udit Takkar <[email protected]>

* chore

Signed-off-by: Udit Takkar <[email protected]>

* fix: use zod schema

Signed-off-by: Udit Takkar <[email protected]>

---------

Signed-off-by: Udit Takkar <[email protected]>

* Type fixes

* Use org Stripe product when upgrading

* Removed unused code

* Reverting changes

* Update UsernameTextfield.tsx

* More reverts

* Update next-auth-options.ts

* Update common.json

* Type fixes

* Include invite token for orgs

* Update org schema

* Make token settings optional as it isnt used in orgs yet

* Reverts

* remove yarn.lock from commit

* Fix types

* feat: orgs unverified (#9415)

Co-authored-by: Joe Au-Yeung <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Keith Williams <[email protected]>

* Fix wrong banner being displayed

* Type fix

* Fix type issues

* Update packages/trpc/server/routers/viewer/teams/inviteMember.handler.ts

Co-authored-by: alannnc <[email protected]>

* fix missing input on trpc query

* Fix for parentId value for createProvisionalMembership

---------

Signed-off-by: Udit Takkar <[email protected]>
Co-authored-by: Leo Giovanetti <[email protected]>
Co-authored-by: Joe Au-Yeung <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: zomars <[email protected]>
Co-authored-by: Joe Au-Yeung <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Keith Williams <[email protected]>
Co-authored-by: alannnc <[email protected]>
This commit is contained in:
33 files changed
+1154 -186

No files matched your search

@@ -129,7 +129,7 @@ export default function ApiKeyDialogForm({
}
}}
className="space-y-4">
<div className="mt-1 mb-4">
<div className="mb-4 mt-1">
<h2 className="font-semi-bold font-cal text-emphasis text-xl tracking-wide">
{defaultValues ? t("edit_api_key") : t("create_api_key")}
</h2>
@@ -8,7 +8,7 @@ export function OrgUpgradeBanner() {
const { t } = useLocale();
const router = useRouter();
const { data } = trpc.viewer.organizations.checkIfOrgNeedsUpgrade.useQuery();
const publishTeamMutation = trpc.viewer.organizations.publish.useMutation({
const publishOrgMutation = trpc.viewer.organizations.publish.useMutation({
onSuccess(data) {
router.push(data.url);
},
@@ -29,7 +29,7 @@ export function OrgUpgradeBanner() {
<button
className="border-b border-b-black"
onClick={() => {
publishTeamMutation.mutate();
publishOrgMutation.mutate();
}}>
{t("upgrade_banner_action")}
</button>
@@ -0,0 +1,102 @@
import NoSSR from "@calcom/core/components/NoSSR";
import LicenseRequired from "@calcom/ee/common/components/LicenseRequired";
import { extractDomainFromWebsiteUrl } from "@calcom/ee/organizations/lib/utils";
import { trpc } from "@calcom/trpc/react";
import { Meta } from "@calcom/ui";
import { DropdownActions, showToast, Table } from "@calcom/ui";
import { Check, X } from "@calcom/ui/components/icon";
import { getLayout } from "../../../../../settings/layouts/SettingsLayout";
const { Body, Cell, ColumnTitle, Header, Row } = Table;
function UnverifiedOrgTable() {
const utils = trpc.useContext();
const [data] = trpc.viewer.organizations.adminGetUnverified.useSuspenseQuery();
const mutation = trpc.viewer.organizations.adminVerify.useMutation({
onSuccess: async () => {
showToast("Org has been processed", "success");
await utils.viewer.organizations.adminGetUnverified.invalidate();
},
onError: (err) => {
console.error(err.message);
showToast("There has been an error processing this org.", "error");
},
});
return (
<div>
<Table>
<Header>
<ColumnTitle widthClassNames="w-auto">Organization</ColumnTitle>
<ColumnTitle widthClassNames="w-auto">Owner</ColumnTitle>
<ColumnTitle widthClassNames="w-auto">
<span className="sr-only">Edit</span>
</ColumnTitle>
</Header>
<Body>
{data.map((org) => (
<Row key={org.id}>
<Cell widthClassNames="w-auto">
<div className="text-subtle font-medium">
<span className="text-default">{org.name}</span>
<br />
<span className="text-muted">
{org.slug}.{extractDomainFromWebsiteUrl}
</span>
</div>
</Cell>
<Cell widthClassNames="w-auto">
<span className="break-all">{org.members[0].user.email}</span>
</Cell>
<Cell widthClassNames="w-auto">
<div className="flex w-full justify-end">
<DropdownActions
actions={[
{
id: "accept",
label: "Accept",
onClick: () => {
mutation.mutate({
orgId: org.id,
status: "ACCEPT",
});
},
icon: Check,
},
{
id: "reject",
label: "Reject",
icon: X,
},
]}
/>
</div>
</Cell>
</Row>
))}
</Body>
</Table>
</div>
);
}
const UnverifiedOrgList = () => {
return (
<LicenseRequired>
<Meta
title="Organizations"
description="A list of all organizations that need verification based on their email domain. Accepting an organization will allow all users with that email domain to sign up WITHOUT email verifciation."
/>
<NoSSR>
<UnverifiedOrgTable />
</NoSSR>
</LicenseRequired>
);
};
UnverifiedOrgList.getLayout = getLayout;
export default UnverifiedOrgList;
@@ -91,7 +91,7 @@ const CreateConnectionDialog = ({
<h2 className="font-semi-bold font-cal text-emphasis text-xl tracking-wide">
{t("sso_oidc_configuration_title")}
</h2>
<p className="text-subtle mt-1 mb-4 text-sm">{t("sso_oidc_configuration_description")}</p>
<p className="text-subtle mb-4 mt-1 text-sm">{t("sso_oidc_configuration_description")}</p>
<div className="space-y-5">
<Controller
control={form.control}
@@ -1,4 +1,4 @@
import { PaperclipIcon, UserIcon, Users } from "lucide-react";
import { BuildingIcon, PaperclipIcon, UserIcon, Users } from "lucide-react";
import { Trans } from "next-i18next";
import { useMemo, useState } from "react";
import type { FormEvent } from "react";
@@ -8,6 +8,7 @@ import { classNames } from "@calcom/lib";
import { IS_TEAM_BILLING_ENABLED, WEBAPP_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { MembershipRole } from "@calcom/prisma/enums";
import type { RouterOutputs } from "@calcom/trpc";
import { trpc } from "@calcom/trpc";
import {
Button,
@@ -31,6 +32,7 @@ import { GoogleWorkspaceInviteButton } from "./GoogleWorkspaceInviteButton";
type MemberInvitationModalProps = {
isOpen: boolean;
onExit: () => void;
orgMembers?: RouterOutputs["viewer"]["organizations"]["getMembers"];
onSubmit: (values: NewMemberForm, resetFields: () => void) => void;
onSettingsOpen?: () => void;
teamId: number;
@@ -86,6 +88,25 @@ export default function MemberInvitationModal(props: MemberInvitationModalProps)
];
}, [t]);
const toggleGroupOptions = useMemo(() => {
const array = [
{
value: "INDIVIDUAL",
label: t("invite_team_individual_segment"),
iconLeft: <UserIcon />,
},
{ value: "BULK", label: t("invite_team_bulk_segment"), iconLeft: <Users /> },
];
if (props.orgMembers) {
array.unshift({
value: "ORGANIZATION",
label: t("organization"),
iconLeft: <BuildingIcon />,
});
}
return array;
}, [t, props.orgMembers]);
const newMemberFormMethods = useForm<NewMemberForm>();
const validateUniqueInvite = (value: string) => {
@@ -149,23 +170,12 @@ export default function MemberInvitationModal(props: MemberInvitationModalProps)
isFullWidth={true}
onValueChange={(val) => setModalInputMode(val as ModalMode)}
defaultValue="INDIVIDUAL"
options={[
{
value: "INDIVIDUAL",
label: <span className="line-clamp-1">{t("invite_team_individual_segment")}</span>,
iconLeft: <UserIcon />,
},
{
value: "BULK",
label: <span className="line-clamp-1">{t("invite_team_bulk_segment")}</span>,
iconLeft: <Users />,
},
]}
options={toggleGroupOptions}
/>
</div>
<Form form={newMemberFormMethods} handleSubmit={(values) => props.onSubmit(values, resetFields)}>
<div className="mb-12 mt-6 space-y-6">
<div className="mb-10 mt-6 space-y-6">
{/* Indivdual Invite */}
{modalImportMode === "INDIVIDUAL" && (
<Controller
@@ -299,39 +309,39 @@ export default function MemberInvitationModal(props: MemberInvitationModalProps)
)}
</div>
<DialogFooter showDivider>
<div className="flex w-full flex-col items-end gap-2 md:flex-row md:items-center md:justify-between">
<div>
<Button
type="button"
color="minimal"
variant="icon"
onClick={() =>
props.token
? copyInviteLinkToClipboard(props.token)
: createInviteMutation.mutate({ teamId: props.teamId })
}
className={classNames("gap-2", props.token && "opacity-50")}
data-testid="copy-invite-link-button">
<Link className="text-default h-4 w-4" aria-hidden="true" />
{t("copy_invite_link")}
</Button>
</div>
<div className="flex gap-2">
<Button
type="button"
color="minimal"
onClick={() => {
props.onExit();
resetFields();
}}>
{t("cancel")}
</Button>
<Button type="submit" color="primary" data-testid="invite-new-member-button">
{t("send_invite")}
</Button>
</div>
<div className="relative right-40">
<Button
type="button"
color="minimal"
variant="icon"
onClick={() =>
props.token
? copyInviteLinkToClipboard(props.token)
: createInviteMutation.mutate({ teamId: props.teamId })
}
className={classNames("gap-2", props.token && "opacity-50")}
data-testid="copy-invite-link-button">
<Link className="text-default h-4 w-4" aria-hidden="true" />
{t("copy_invite_link")}
</Button>
</div>
<Button
type="button"
color="minimal"
onClick={() => {
props.onExit();
resetFields();
}}>
{t("cancel")}
</Button>
<Button
type="submit"
color="primary"
className="me-2 ms-2"
data-testid="invite-new-member-button">
{t("send_invite")}
</Button>
</DialogFooter>
</Form>
</DialogContent>
+26 -5
View File
@@ -28,10 +28,17 @@ export const checkIfTeamPaymentRequired = async ({ teamId = -1 }) => {
return { url: `${WEBAPP_URL}/api/teams/${teamId}/upgrade?session_id=${metadata.paymentId}` };
};
export const purchaseTeamSubscription = async (input: { teamId: number; seats: number; userId: number }) => {
const { teamId, seats, userId } = input;
export const purchaseTeamSubscription = async (input: {
teamId: number;
seats: number;
userId: number;
isOrg?: boolean;
}) => {
const { teamId, seats, userId, isOrg } = 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 customer = await getStripeCustomerIdFromUserId(userId);
const session = await stripe.checkout.sessions.create({
customer,
@@ -42,8 +49,8 @@ export const purchaseTeamSubscription = async (input: { teamId: number; seats: n
line_items: [
{
/** We only need to set the base price and we can upsell it directly on Stripe's checkout */
price: process.env.STRIPE_TEAM_MONTHLY_PRICE_ID,
quantity: seats,
price: isOrg ? process.env.STRIPE_ORG_MONTHLY_PRICE_ID : process.env.STRIPE_TEAM_MONTHLY_PRICE_ID,
quantity: quantity,
},
],
customer_update: {
@@ -95,8 +102,22 @@ export const updateQuantitySubscriptionFromStripe = async (teamId: number) => {
if (!url) return;
const team = await getTeamWithPaymentMetadata(teamId);
const { subscriptionId, subscriptionItemId } = team.metadata;
const membershipCount = team.members.length;
const subscription = await stripe.subscriptions.retrieve(subscriptionId);
const subscriptionQuantity = subscription.items.data.find(
(sub) => sub.id === subscriptionItemId
)?.quantity;
if (!subscriptionQuantity) throw new Error("Subscription not found");
if (membershipCount < subscriptionQuantity) {
console.info(`Team ${teamId} has less members than seats, skipping updating subscription.`);
return;
}
const newQuantity = membershipCount - subscriptionQuantity;
await stripe.subscriptions.update(subscriptionId, {
items: [{ quantity: team.members.length, id: subscriptionItemId }],
items: [{ quantity: membershipCount + newQuantity, id: subscriptionItemId }],
});
console.info(
`Updated subscription ${subscriptionId} for team ${teamId} to ${team.members.length} seats.`
@@ -74,7 +74,7 @@ export default function EmptyScreen(props: { isFilteredView: boolean }) {
</div>
<div className="max-w-[420px] text-center">
<h2 className="text-semibold font-cal mt-6 text-xl dark:text-gray-300">{t("workflows")}</h2>
<p className="text-default line-clamp-2 mt-3 text-sm font-normal leading-6 dark:text-gray-300">
<p className="text-default mt-3 line-clamp-2 text-sm font-normal leading-6 dark:text-gray-300">
{t("no_workflows_description")}
</p>
<div className="mt-8 ">
@@ -46,7 +46,7 @@ export const CheckedTeamSelect = ({
key={option.value}
className={`flex px-3 py-2 ${index === value.length - 1 ? "" : "border-subtle border-b"}`}>
<Avatar size="sm" imageSrc={option.avatar} alt={option.label} />
<p className="text-emphasis ms-3 my-auto text-sm">{option.label}</p>
<p className="text-emphasis my-auto ms-3 text-sm">{option.label}</p>
<X
onClick={() => props.onChange(value.filter((item) => item.value !== option.value))}
className="my-auto ml-auto h-4 w-4"
@@ -119,6 +119,7 @@ const tabs: VerticalTabItemProps[] = [
{ name: "impersonation", href: "/settings/admin/impersonation" },
{ name: "apps", href: "/settings/admin/apps/calendar" },
{ name: "users", href: "/settings/admin/users" },
{ name: "organizations", href: "/settings/admin/organizations" },
],
},
];
@@ -193,6 +194,7 @@ const SettingsSidebarContainer = ({
useState<{ teamId: number | undefined; teamMenuOpen: boolean }[]>();
const { data: teams } = trpc.viewer.teams.list.useQuery();
const { data: currentOrg } = trpc.viewer.organizations.listCurrent.useQuery();
useEffect(() => {
if (teams) {
@@ -385,14 +387,15 @@ const SettingsSidebarContainer = ({
</Collapsible>
);
})}
<VerticalTabItem
name={t("add_a_team")}
href={`${WEBAPP_URL}/settings/teams/new`}
textClassNames="px-3 items-center mt-2 text-emphasis font-medium text-sm"
icon={Plus}
iconClassName="me-3"
disableChevron
/>
{(!currentOrg || (currentOrg && currentOrg?.user?.role !== "MEMBER")) && (
<VerticalTabItem
name={t("add_a_team")}
href={`${WEBAPP_URL}/settings/teams/new`}
textClassNames="px-3 items-center mt-2 text-emphasis font-medium text-sm"
icon={Plus}
disableChevron
/>
)}
</div>
</React.Fragment>
);