Stripe to monorepo (#2063)

* downgrade func

* fix security hole lol

* fix query conditions

* - set to trial not free
- auto create stripe customer if missing
- fix production check

* Extracts downgrade logic to script, fixes ts-node conflicts with prisma

* Adds trialEndsAt field to users

* Updates trial/downgrade logic

* Typo

* Legibility fixes

* Update team-billing.ts

* Legibility improvements

* Updates illegal logic

* WIP

* WIP migrating stripe to package

* Update website

* Import fixes

* Import fixes

* Fixes to downgrade script

* Check for premium usernames before downgrading

* Fixed formatting

* Delete deploy-env.sh

* Locks dayjs to 1.10.6

* Type fixes

* Seems like we're stuck with dayjs 1.10.4

* Script fixes

* Adds first name to dump

* Loop fix

Co-authored-by: Jamie <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2022-03-09 15:56:05 -07:00
1 parent adbae64619
commit 5625cf226b
40 files changed
+454 -405

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
The Cal.com Enterprise Edition (EE) license (the “EE License”)
Copyright (c) 2020-present Cal.com, Inc
With regard to the Cal.com Software:
This software and associated documentation files (the "Software") may only be
used in production, if you (and any entity that you represent) have agreed to,
and are in compliance with, the Cal.com Subscription Terms available
at https://cal.com/terms (the “EE Terms”), or other agreements governing
the use of the Software, as mutually agreed by you and Cal.com, Inc ("Cal.com"),
and otherwise have a valid Cal.com Enterprise Edition subscription ("EE Subscription")
for the correct number of hosts as defined in the EE Terms ("Hosts"). Subject to the foregoing sentence,
you are free to modify this Software and publish patches to the Software. You agree
that Cal.com and/or its licensors (as applicable) retain all right, title and interest in
and to all such modifications and/or patches, and all such modifications and/or
patches may only be used, copied, modified, displayed, distributed, or otherwise
exploited with a valid EE Subscription for the correct number of hosts.
Notwithstanding the foregoing, you may copy and modify the Software for development
and testing purposes, without requiring a subscription. You agree that Cal.com and/or
its licensors (as applicable) retain all right, title and interest in and to all such
modifications. You are not granted any other rights beyond what is expressly stated herein.
Subject to the foregoing, it is forbidden to copy, merge, publish, distribute, sublicense,
and/or sell the Software.
This EE License applies only to the part of this Software that is not distributed under
the AGPLv3 license. Any part of this Software distributed under the MIT license or which
is served client-side as an image, font, cascading stylesheet (CSS), file which produces
or is compiled, arranged, augmented, or combined into client-side JavaScript, in whole or
in part, is copyrighted under the AGPLv3 license. The full text of this EE License shall
be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
For all third party components incorporated into the Cal.com Software, those
components are licensed under the original license provided by the owner of the
applicable component.
+38
View File
@@ -0,0 +1,38 @@
<!-- PROJECT LOGO -->
<div align="center">
<a href="https://cal.com/enterprise">
<img src="https://user-images.githubusercontent.com/8019099/133430653-24422d2a-3c8d-4052-9ad6-0580597151ee.png" alt="Logo">
</a>
<a href="https://cal.com/enterprise">Get Started with Enterprise</a>
</div>
# Enterprise Edition
Welcome to the Enterprise Edition ("/ee") of Cal.com.
The [/ee](https://github.com/calcom/cal.com/tree/main/apps/web/ee) subfolder is the place for all the **Pro** features from our [hosted](https://cal.com/pricing) plan and [enterprise-grade](https://cal.com/enterprise) features such as SSO, SAML, ADFS, OIDC, SCIM, SIEM, HRIS and much more.
> _❗ WARNING: This repository is copyrighted (unlike our [main repo](https://github.com/calcom/cal.com)). You are not allowed to use this code to host your own version of app.cal.com without obtaining a proper [license](https://cal.com/enterprise) first❗_
## Setting up Stripe
1. Create a stripe account or use an existing one. For testing, you should use all stripe dashboard functions with the Test-Mode toggle in the top right activated.
2. Open [Stripe ApiKeys](https://dashboard.stripe.com/apikeys) save the token starting with `pk_...` to `NEXT_PUBLIC_STRIPE_PUBLIC_KEY` and `sk_...` to `STRIPE_PRIVATE_KEY` in the .env file.
3. Open [Stripe Connect Settings](https://dashboard.stripe.com/settings/connect) and activate OAuth for Standard Accounts
4. Add `<CALENDSO URL>/api/integrations/stripepayment/callback` as redirect URL.
5. Copy your client*id (`ca*...`) to `STRIPE_CLIENT_ID` in the .env file.
6. Open [Stripe Webhooks](https://dashboard.stripe.com/webhooks) and add `<CALENDSO URL>/api/integrations/stripepayment/webhook` as webhook for connected applications.
7. Select all `payment_intent` events for the webhook.
8. Copy the webhook secret (`whsec_...`) to `STRIPE_WEBHOOK_SECRET` in the .env file.
## Setting up SAML login
1. Set SAML_DATABASE_URL to a postgres database. Please use a different database than the main Cal instance since the migrations are separate for this database. For example `postgresql://postgres:@localhost:5450/cal-saml`
2. Set SAML_ADMINS to a comma separated list of admin emails from where the SAML metadata can be uploaded and configured.
3. Create a SAML application with your Identity Provider (IdP) using the instructions here - [SAML Setup](../docs/saml-setup.md)
4. Remember to configure access to the IdP SAML app for all your users (who need access to Cal).
5. You will need the XML metadata from your IdP later, so keep it accessible.
6. Log in to one of the admin accounts configured in SAML_ADMINS and then navigate to Settings -> Security.
7. You should see a SAML configuration section, copy and paste the XML metadata from step 5 and click on Save.
8. Your provisioned users can now log into Cal using SAML.
@@ -0,0 +1,22 @@
import slugify from "@calcom/lib/slugify";
export async function checkPremiumUsername(_username: string): Promise<{
available: boolean;
premium: boolean;
message?: string;
suggestion?: string;
}> {
const username = slugify(_username);
const response = await fetch("https://cal.com/api/username", {
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ username }),
method: "POST",
mode: "cors",
});
const json = await response.json();
return json;
}
+16
View File
@@ -0,0 +1,16 @@
{
"name": "@calcom/ee",
"description": "Cal.com Enterprise Edition features",
"version": "0.0.0",
"private": true,
"license": "AGPLv3",
"scripts": {
"clean": "rm -rf .turbo && rm -rf node_modules"
},
"dependencies": {
"@calcom/lib": "*"
},
"devDependencies": {
"@calcom/tsconfig": "*"
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "@calcom/tsconfig/base.json",
"compilerOptions": {
"baseUrl": "."
},
"include": ["."],
"exclude": ["dist", "build", "node_modules"]
}
+6
View File
@@ -0,0 +1,6 @@
export const BASE_URL = process.env.BASE_URL || `https://${process.env.VERCEL_URL}`;
export const WEBSITE_URL = process.env.NEXT_PUBLIC_APP_URL || "https://cal.com";
export const IS_PRODUCTION = process.env.NODE_ENV === "production";
export const TRIAL_LIMIT_DAYS = 14;
export const HOSTED_CAL_FEATURES = process.env.HOSTED_CAL_FEATURES || BASE_URL === "https://app.cal.com";
export const NEXT_PUBLIC_BASE_URL = process.env.NEXT_PUBLIC_BASE_URL || `https://${process.env.VERCEL_URL}`;
+33
View File
@@ -0,0 +1,33 @@
export class HttpError<TCode extends number = number> extends Error {
public readonly cause?: Error;
public readonly statusCode: TCode;
public readonly message: string;
public readonly url: string | undefined;
public readonly method: string | undefined;
constructor(opts: { url?: string; method?: string; message?: string; statusCode: TCode; cause?: Error }) {
super(opts.message ?? `HTTP Error ${opts.statusCode} `);
Object.setPrototypeOf(this, HttpError.prototype);
this.name = HttpError.prototype.constructor.name;
this.cause = opts.cause;
this.statusCode = opts.statusCode;
this.url = opts.url;
this.method = opts.method;
this.message = opts.message ?? `HTTP Error ${opts.statusCode}`;
if (opts.cause instanceof Error && opts.cause.stack) {
this.stack = opts.cause.stack;
}
}
public static fromRequest(request: Request, response: Response) {
return new HttpError({
message: response.statusText,
url: response.url,
method: request.method,
statusCode: response.status,
});
}
}
+1 -1
View File
@@ -6,7 +6,7 @@
"license": "MIT",
"dependencies": {
"bcryptjs": "^2.4.3",
"dayjs": "^1.10.6",
"dayjs": "^1.10.4",
"dayjs-business-time": "^1.0.4"
},
"devDependencies": {
+1 -1
View File
@@ -7,7 +7,7 @@ declare global {
export const prisma =
globalThis.prisma ||
new PrismaClient({
log: ["query", "error", "warn"],
// log: ["query", "error", "warn"],
});
if (process.env.NODE_ENV !== "production") {
+42
View File
@@ -0,0 +1,42 @@
The Cal.com Enterprise Edition (EE) license (the “EE License”)
Copyright (c) 2020-present Cal.com, Inc
With regard to the Cal.com Software:
This software and associated documentation files (the "Software") may only be
used in production, if you (and any entity that you represent) have agreed to,
and are in compliance with, the Cal.com Subscription Terms available
at https://cal.com/terms (the “EE Terms”), or other agreements governing
the use of the Software, as mutually agreed by you and Cal.com, Inc ("Cal.com"),
and otherwise have a valid Cal.com Enterprise Edition subscription ("EE Subscription")
for the correct number of hosts as defined in the EE Terms ("Hosts"). Subject to the foregoing sentence,
you are free to modify this Software and publish patches to the Software. You agree
that Cal.com and/or its licensors (as applicable) retain all right, title and interest in
and to all such modifications and/or patches, and all such modifications and/or
patches may only be used, copied, modified, displayed, distributed, or otherwise
exploited with a valid EE Subscription for the correct number of hosts.
Notwithstanding the foregoing, you may copy and modify the Software for development
and testing purposes, without requiring a subscription. You agree that Cal.com and/or
its licensors (as applicable) retain all right, title and interest in and to all such
modifications. You are not granted any other rights beyond what is expressly stated herein.
Subject to the foregoing, it is forbidden to copy, merge, publish, distribute, sublicense,
and/or sell the Software.
This EE License applies only to the part of this Software that is not distributed under
the AGPLv3 license. Any part of this Software distributed under the MIT license or which
is served client-side as an image, font, cascading stylesheet (CSS), file which produces
or is compiled, arranged, augmented, or combined into client-side JavaScript, in whole or
in part, is copyrighted under the AGPLv3 license. The full text of this EE License shall
be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
For all third party components incorporated into the Cal.com Software, those
components are licensed under the original license provided by the owner of the
applicable component.
+38
View File
@@ -0,0 +1,38 @@
<!-- PROJECT LOGO -->
<div align="center">
<a href="https://cal.com/enterprise">
<img src="https://user-images.githubusercontent.com/8019099/133430653-24422d2a-3c8d-4052-9ad6-0580597151ee.png" alt="Logo">
</a>
<a href="https://cal.com/enterprise">Get Started with Enterprise</a>
</div>
# Enterprise Edition
Welcome to the Enterprise Edition ("/ee") of Cal.com.
The [/ee](https://github.com/calcom/cal.com/tree/main/apps/web/ee) subfolder is the place for all the **Pro** features from our [hosted](https://cal.com/pricing) plan and [enterprise-grade](https://cal.com/enterprise) features such as SSO, SAML, ADFS, OIDC, SCIM, SIEM, HRIS and much more.
> _❗ WARNING: This repository is copyrighted (unlike our [main repo](https://github.com/calcom/cal.com)). You are not allowed to use this code to host your own version of app.cal.com without obtaining a proper [license](https://cal.com/enterprise) first❗_
## Setting up Stripe
1. Create a stripe account or use an existing one. For testing, you should use all stripe dashboard functions with the Test-Mode toggle in the top right activated.
2. Open [Stripe ApiKeys](https://dashboard.stripe.com/apikeys) save the token starting with `pk_...` to `NEXT_PUBLIC_STRIPE_PUBLIC_KEY` and `sk_...` to `STRIPE_PRIVATE_KEY` in the .env file.
3. Open [Stripe Connect Settings](https://dashboard.stripe.com/settings/connect) and activate OAuth for Standard Accounts
4. Add `<CALENDSO URL>/api/integrations/stripepayment/callback` as redirect URL.
5. Copy your client*id (`ca*...`) to `STRIPE_CLIENT_ID` in the .env file.
6. Open [Stripe Webhooks](https://dashboard.stripe.com/webhooks) and add `<CALENDSO URL>/api/integrations/stripepayment/webhook` as webhook for connected applications.
7. Select all `payment_intent` events for the webhook.
8. Copy the webhook secret (`whsec_...`) to `STRIPE_WEBHOOK_SECRET` in the .env file.
## Setting up SAML login
1. Set SAML_DATABASE_URL to a postgres database. Please use a different database than the main Cal instance since the migrations are separate for this database. For example `postgresql://postgres:@localhost:5450/cal-saml`
2. Set SAML_ADMINS to a comma separated list of admin emails from where the SAML metadata can be uploaded and configured.
3. Create a SAML application with your Identity Provider (IdP) using the instructions here - [SAML Setup](../docs/saml-setup.md)
4. Remember to configure access to the IdP SAML app for all your users (who need access to Cal).
5. You will need the XML metadata from your IdP later, so keep it accessible.
6. Log in to one of the admin accounts configured in SAML_ADMINS and then navigate to Settings -> Security.
7. You should see a SAML configuration section, copy and paste the XML metadata from step 5 and click on Save.
8. Your provisioned users can now log into Cal using SAML.
+37
View File
@@ -0,0 +1,37 @@
import { Stripe } from "@stripe/stripe-js";
import { loadStripe } from "@stripe/stripe-js/pure";
import { stringify } from "querystring";
export type Maybe<T> = T | undefined | null;
const stripePublicKey = process.env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY!;
let stripePromise: Promise<Stripe | null>;
/**
* This is a singleton to ensure we only instantiate Stripe once.
*/
const getStripe = (userPublicKey?: string) => {
if (!stripePromise) {
stripePromise = loadStripe(
userPublicKey || stripePublicKey /* , {
locale: "es-419" TODO: Handle multiple locales,
} */
);
}
return stripePromise;
};
export function createPaymentLink(opts: {
paymentUid: string;
name?: Maybe<string>;
date?: Maybe<string>;
absolute?: boolean;
}): string {
const { paymentUid, name, date, absolute = true } = opts;
let link = "";
if (absolute) link = process.env.NEXT_PUBLIC_APP_URL!;
const query = stringify({ date, name });
return link + `/payment/${paymentUid}?${query}`;
}
export default getStripe;
+4
View File
@@ -0,0 +1,4 @@
export const FREE_PLAN_PRICE = process.env.NEXT_PUBLIC_STRIPE_FREE_PLAN_PRICE || "";
export const PREMIUM_PLAN_PRICE = process.env.NEXT_PUBLIC_STRIPE_PREMIUM_PLAN_PRICE || "";
export const PRO_PLAN_PRICE = process.env.NEXT_PUBLIC_STRIPE_PRO_PLAN_PRICE || "";
export const PRO_PLAN_PRODUCT = process.env.NEXT_PUBLIC_STRIPE_PRO_PLAN_PRODUCT || "";
+83
View File
@@ -0,0 +1,83 @@
import { Prisma } from "@prisma/client";
import { HttpError as HttpCode } from "@calcom/lib/http-error";
import prisma from "@calcom/prisma";
import stripe from "@calcom/stripe/server";
export async function getStripeCustomerIdFromUserId(userId: number) {
// Get user
const user = await prisma.user.findUnique({
where: {
id: userId,
},
select: {
email: true,
name: true,
metadata: true,
},
});
if (!user?.email) throw new HttpCode({ statusCode: 404, message: "User email not found" });
const customerId = await getStripeCustomerId(user);
return customerId;
}
const userType = Prisma.validator<Prisma.UserArgs>()({
select: {
email: true,
metadata: true,
},
});
type UserType = Prisma.UserGetPayload<typeof userType>;
/** This will retrieve the customer ID from Stripe or create it if it doesn't exists yet. */
export async function getStripeCustomerId(user: UserType): Promise<string> {
let customerId: string | null = null;
if (user?.metadata && typeof user.metadata === "object" && "stripeCustomerId" in user.metadata) {
customerId = (user?.metadata as Prisma.JsonObject).stripeCustomerId as string;
} else {
/* We fallback to finding the customer by email (which is not optimal) */
const customersResponse = await stripe.customers.list({
email: user.email,
limit: 1,
});
if (customersResponse.data[0]?.id) {
customerId = customersResponse.data[0].id;
} else {
/* Creating customer on Stripe and saving it on prisma */
const customer = await stripe.customers.create({ email: user.email });
customerId = customer.id;
}
await prisma.user.update({
where: {
email: user.email,
},
data: {
metadata: {
...(user.metadata as Prisma.JsonObject),
stripeCustomerId: customerId,
},
},
});
}
return customerId;
}
export async function deleteStripeCustomer(user: UserType): Promise<string | null> {
const customerId = await getStripeCustomerId(user);
if (!customerId) {
console.warn("No stripe customer found for user:" + user.email);
return null;
}
//delete stripe customer
const deletedCustomer = await stripe.customers.del(customerId);
return deletedCustomer.id;
}
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env ts-node
// To run this script: `yarn downgrade 2>&1 | tee result.log`
import { Prisma, UserPlan } from "@prisma/client";
import dayjs from "dayjs";
import { TRIAL_LIMIT_DAYS } from "@calcom/lib/constants";
import prisma from "@calcom/prisma";
import stripe from "@calcom/stripe/server";
// import { isPremiumUserName } from "../../apps/website/lib/username";
import { getStripeCustomerIdFromUserId } from "./customer";
import { getPremiumPlanPrice, getProPlanPrice, getProPlanProduct } from "./utils";
export async function downgradeIllegalProUsers() {
const illegalProUsers = await prisma.user.findMany({
where: {
plan: UserPlan.PRO,
},
select: {
id: true,
name: true,
email: true,
username: true,
plan: true,
metadata: true,
},
});
const usersDowngraded: Partial<typeof illegalProUsers[number]>[] = [];
const downgrade = async (user: typeof illegalProUsers[number]) => {
await prisma.user.update({
where: { id: user.id },
data: {
plan: UserPlan.TRIAL,
trialEndsAt: dayjs().add(TRIAL_LIMIT_DAYS, "day").toDate(),
},
});
console.log(`Downgraded: ${user.email}`);
usersDowngraded.push({
id: user.id,
username: user.username,
name: user.name,
email: user.email,
plan: user.plan,
metadata: user.metadata,
});
};
for (const suspectUser of illegalProUsers) {
console.log(`Checking: ${suspectUser.email}`);
const metadata = (suspectUser.metadata as Prisma.JsonObject) ?? {};
// if their pro is already sponsored by a team, do not downgrade
if (metadata.proPaidForByTeamId !== undefined) continue;
const stripeCustomerId = await getStripeCustomerIdFromUserId(suspectUser.id);
const customer = await stripe.customers.retrieve(stripeCustomerId, {
expand: ["subscriptions.data.plan"],
});
if (!customer || customer.deleted) {
await downgrade(suspectUser);
continue;
}
const subscription = customer.subscriptions?.data[0];
if (!subscription) {
await downgrade(suspectUser);
continue;
}
const hasProPlan = !!subscription.items.data.find(
(item) =>
item.plan.product === getProPlanProduct() ||
[getProPlanPrice(), getPremiumPlanPrice()].includes(item.plan.id)
);
// if they're pro, do not downgrade
if (hasProPlan) continue;
// If they already have a premium username, do not downgrade
// if (suspectUser.username && isPremiumUserName(suspectUser.username)) continue;
await downgrade(suspectUser);
}
return {
usersDowngraded,
usersDowngradedAmount: usersDowngraded.length,
};
}
downgradeIllegalProUsers()
.then(({ usersDowngraded, usersDowngradedAmount }) => {
console.log(`Downgraded ${usersDowngradedAmount} illegal pro users`);
console.table(usersDowngraded);
})
.catch((e) => {
console.error(e);
process.exit(1);
});
+1
View File
@@ -0,0 +1 @@
export * from "./constants";
+29
View File
@@ -0,0 +1,29 @@
{
"name": "@calcom/stripe",
"version": "0.0.0",
"private": true,
"license": "AGPLv3",
"scripts": {
"clean": "rm -rf .turbo && rm -rf node_modules",
"downgrade": "ts-node ./downgrade.ts"
},
"devDependencies": {
"ts-node": "^10.6.0"
},
"dependencies": {
"@calcom/ee": "*",
"@calcom/lib": "*",
"@stripe/react-stripe-js": "^1.4.1",
"@stripe/stripe-js": "^1.16.0",
"dayjs": "^1.10.4",
"stripe": "^8.191.0"
},
"main": "index.ts",
"types": "index.d.ts",
"files": [
"client.ts",
"constants.ts",
"server.ts",
"utils.ts"
]
}
+18
View File
@@ -0,0 +1,18 @@
import Stripe from "stripe";
export type PaymentData = Stripe.Response<Stripe.PaymentIntent> & {
stripe_publishable_key: string;
stripeAccount: string;
};
export type StripeData = Stripe.OAuthToken & {
default_currency: string;
};
const stripePrivateKey = process.env.STRIPE_PRIVATE_KEY!;
const stripe = new Stripe(stripePrivateKey, {
apiVersion: "2020-08-27",
});
export default stripe;
+264
View File
@@ -0,0 +1,264 @@
import { MembershipRole, Prisma, UserPlan } from "@prisma/client";
import Stripe from "stripe";
import { HOSTED_CAL_FEATURES } from "@calcom/lib/constants";
import { HttpError } from "@calcom/lib/http-error";
import prisma from "@calcom/prisma";
import stripe from "@calcom/stripe/server";
import { getStripeCustomerIdFromUserId } from "./customer";
import { getPerSeatProPlanPrice, getPremiumPlanPrice, getProPlanPrice } from "./utils";
// get team owner's Pro Plan subscription from Cal userId
export async function getProPlanSubscription(userId: number) {
const stripeCustomerId = await getStripeCustomerIdFromUserId(userId);
if (!stripeCustomerId) return null;
const customer = await stripe.customers.retrieve(stripeCustomerId, {
expand: ["subscriptions.data.plan"],
});
if (customer.deleted) throw new HttpError({ statusCode: 404, message: "Stripe customer not found" });
// get the first subscription item which is the Pro Plan TODO: change to find()
return customer.subscriptions?.data[0];
}
async function getMembersMissingSeats(teamId: number) {
const members = await prisma.membership.findMany({
where: { teamId },
select: { role: true, accepted: true, user: { select: { id: true, plan: true, metadata: true } } },
});
// any member that is not Pro is missing a seat excluding the owner
const membersMissingSeats = members.filter(
(m) => m.role !== MembershipRole.OWNER || m.user.plan !== UserPlan.PRO
);
// as owner's billing is handled by a different Price, we count this separately
const ownerIsMissingSeat = !!members.find(
(m) => m.role === MembershipRole.OWNER && m.user.plan === UserPlan.FREE
);
return {
members,
membersMissingSeats,
ownerIsMissingSeat,
};
}
// a helper for the upgrade dialog
export async function getTeamSeatStats(teamId: number) {
const { membersMissingSeats, members, ownerIsMissingSeat } = await getMembersMissingSeats(teamId);
return {
totalMembers: members.length,
// members we need not pay for
freeSeats: members.length - membersMissingSeats.length,
// members we need to pay for (if not hosted cal, team billing is disabled)
missingSeats: HOSTED_CAL_FEATURES ? membersMissingSeats.length : 0,
// members who have been hidden from view
hiddenMembers: members.filter((m) => m.user.plan === UserPlan.FREE).length,
ownerIsMissingSeat: HOSTED_CAL_FEATURES ? ownerIsMissingSeat : false,
};
}
async function updatePerSeatQuantity(subscription: Stripe.Subscription, quantity: number) {
const perSeatProPlan = subscription.items.data.find((item) => item.plan.id === getPerSeatProPlanPrice());
// if their subscription does not contain Per Seat Pro, add it—otherwise, update the existing one
return await stripe.subscriptions.update(subscription.id, {
items: [
perSeatProPlan ? { id: perSeatProPlan.id, quantity } : { plan: getPerSeatProPlanPrice(), quantity },
],
});
}
// called by the team owner when they are ready to upgrade their team to Per Seat Pro
// if user has no subscription, this will be called again after successful stripe checkout callback, with subscription now present
export async function upgradeTeam(userId: number, teamId: number) {
const ownerUser = await prisma.membership.findFirst({
where: { userId, teamId },
select: { role: true, user: true },
});
if (ownerUser?.role !== MembershipRole.OWNER)
throw new HttpError({ statusCode: 400, message: "User is not an owner" });
const subscription = await getProPlanSubscription(userId);
const { membersMissingSeats, ownerIsMissingSeat } = await getMembersMissingSeats(teamId);
if (!subscription) {
let customerId = await getStripeCustomerIdFromUserId(userId);
if (!customerId) {
// create stripe customer if it doesn't already exist
const res = await stripe.customers.create({
email: ownerUser.user.email,
});
customerId = res.id;
}
// create a checkout session with the quantity of missing seats
const session = await createCheckoutSession(
customerId,
membersMissingSeats.length,
teamId,
ownerIsMissingSeat
);
// return checkout session url for redirect
return { url: session.url };
}
// if the owner has a subscription but does not have an individual Pro account
if (ownerIsMissingSeat) {
const ownerHasProPlan = !!subscription.items.data.find(
(item) => item.plan.id === getProPlanPrice() || item.plan.id === getPremiumPlanPrice()
);
if (!ownerHasProPlan)
await stripe.subscriptions.update(subscription.id, {
items: [
{
price: getProPlanPrice(),
quantity: 1,
},
],
});
await prisma.user.update({
where: { id: userId },
data: { plan: UserPlan.PRO },
});
}
// update the subscription with Stripe
await updatePerSeatQuantity(subscription, membersMissingSeats.length);
// loop through all members and update their account to Pro
for (const member of membersMissingSeats) {
await prisma.user.update({
where: { id: member.user.id },
data: {
plan: UserPlan.PRO,
// declare which team is sponsoring their Pro membership
metadata: { proPaidForByTeamId: teamId, ...((member.user.metadata as Prisma.JsonObject) ?? {}) },
},
});
}
return { success: true };
}
// shared logic for add/removing members, called on member invite and member removal/leave
async function addOrRemoveSeat(remove: boolean, userId: number, teamId: number, memberUserId?: number) {
console.log(remove ? "removing member" : "adding member", { userId, teamId, memberUserId });
const subscription = await getProPlanSubscription(userId);
if (!subscription) return;
// get the per seat plan from the subscription
const perSeatProPlanPrice = subscription?.items.data.find(
(item) => item.plan.id === getPerSeatProPlanPrice()
);
// find the member's local user account
const memberUser = await prisma.user.findUnique({
where: { id: memberUserId },
select: { id: true, plan: true, metadata: true },
});
// in the rare event there is no account, return
if (!memberUser) return;
// check if this user is paying for their own Pro account, if so return.
const memberSubscription = await getProPlanSubscription(memberUser.id);
const proPlanPrice = memberSubscription?.items.data.find((item) => item.plan.id === getProPlanPrice());
if (proPlanPrice) return;
// takes care of either adding per seat pricing, or updating the existing one's quantity
await updatePerSeatQuantity(
subscription,
remove ? (perSeatProPlanPrice?.quantity ?? 1) - 1 : (perSeatProPlanPrice?.quantity ?? 0) + 1
);
// add or remove proPaidForByTeamId from metadata
const metadata: Record<string, unknown> = {
proPaidForByTeamId: teamId,
...((memberUser.metadata as Prisma.JsonObject) ?? {}),
};
// entirely remove property if removing member from team and proPaidForByTeamId is this team
if (remove && metadata.proPaidForByTeamId === teamId) delete metadata.proPaidForByTeamId;
await prisma.user.update({
where: { id: memberUserId },
data: { plan: remove ? UserPlan.FREE : UserPlan.PRO, metadata: metadata as Prisma.JsonObject },
});
}
// aliased helpers for more verbose usage
export async function addSeat(userId: number, teamId: number, memberUserId?: number) {
return await addOrRemoveSeat(false, userId, teamId, memberUserId);
}
export async function removeSeat(userId: number, teamId: number, memberUserId?: number) {
return await addOrRemoveSeat(true, userId, teamId, memberUserId);
}
// if a team has failed to pay for the pro plan, downgrade all team members to free
export async function downgradeTeamMembers(teamId: number) {
const members = await prisma.membership.findMany({
where: { teamId, user: { plan: UserPlan.PRO } },
select: { role: true, accepted: true, user: { select: { id: true, plan: true, metadata: true } } },
});
for (const member of members) {
// skip if user had their own Pro subscription
const subscription = await getProPlanSubscription(member.user.id);
if (subscription?.items.data.length) continue;
// skip if Pro is paid for by another team
const metadata = (member.user.metadata as Prisma.JsonObject) ?? {};
if (metadata.proPaidForByTeamId !== teamId) continue;
// downgrade only if their pro plan was paid for by this team
delete metadata.proPaidForByTeamId;
await prisma.user.update({
where: { id: member.user.id },
data: { plan: UserPlan.FREE, metadata },
});
}
}
async function createCheckoutSession(
customerId: string,
quantity: number,
teamId: number,
includeBaseProPlan?: boolean
) {
// if the user is missing the base plan, we should include it agnostic of the seat quantity
const line_items: Stripe.Checkout.SessionCreateParams["line_items"] =
quantity === 0
? []
: [
{
price: getPerSeatProPlanPrice(),
quantity: quantity ?? 1,
},
];
if (includeBaseProPlan) line_items.push({ price: getProPlanPrice(), quantity: 1 });
const params: Stripe.Checkout.SessionCreateParams = {
mode: "subscription",
payment_method_types: ["card"],
customer: customerId,
line_items,
success_url: `${process.env.NEXT_PUBLIC_APP_URL}/api/teams/${teamId}/upgrade?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}/`,
allow_promotion_codes: true,
};
return await stripe.checkout.sessions.create(params);
}
// verifies that the subscription's quantity is correct for the number of members the team has
// this is a function is a dev util, but could be utilized as a sync technique in the future
export async function ensureSubscriptionQuantityCorrectness(userId: number, teamId: number) {
const subscription = await getProPlanSubscription(userId);
const stripeQuantity =
subscription?.items.data.find((item) => item.plan.id === getPerSeatProPlanPrice())?.quantity ?? 0;
const { membersMissingSeats } = await getMembersMissingSeats(teamId);
// correct the quantity if missing seats is out of sync with subscription quantity
if (subscription && membersMissingSeats.length !== stripeQuantity) {
await updatePerSeatQuantity(subscription, membersMissingSeats.length);
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "@calcom/tsconfig/base.json",
"compilerOptions": {
"baseUrl": "."
},
"include": ["."],
"exclude": ["dist", "build", "node_modules"]
}
+21
View File
@@ -0,0 +1,21 @@
import { FREE_PLAN_PRICE, PREMIUM_PLAN_PRICE, PRO_PLAN_PRICE, PRO_PLAN_PRODUCT } from "./constants";
export function getPerSeatProPlanPrice(): string {
return PRO_PLAN_PRICE;
}
export function getPremiumPlanPrice(): string {
return PREMIUM_PLAN_PRICE;
}
export function getProPlanPrice(): string {
return PRO_PLAN_PRICE;
}
export function getProPlanProduct(): string {
return PRO_PLAN_PRODUCT;
}
export function getFreePlanPrice(): string {
return FREE_PLAN_PRICE;
}