* 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]>
131 lines
4.7 KiB
TypeScript
131 lines
4.7 KiB
TypeScript
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 prisma from "@calcom/prisma";
|
|
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
|
|
|
|
const teamPaymentMetadataSchema = z.object({
|
|
paymentId: z.string(),
|
|
subscriptionId: z.string(),
|
|
subscriptionItemId: z.string(),
|
|
});
|
|
|
|
/** Used to prevent double charges for the same team */
|
|
export const checkIfTeamPaymentRequired = async ({ teamId = -1 }) => {
|
|
const team = await prisma.team.findUniqueOrThrow({
|
|
where: { id: teamId },
|
|
select: { metadata: true },
|
|
});
|
|
const metadata = teamMetadataSchema.parse(team.metadata);
|
|
/** If there's no paymentId, we need to pay this team */
|
|
if (!metadata?.paymentId) return { url: null };
|
|
const checkoutSession = await stripe.checkout.sessions.retrieve(metadata.paymentId);
|
|
/** If there's a pending session but it isn't paid, we need to pay this team */
|
|
if (checkoutSession.payment_status !== "paid") return { url: null };
|
|
/** If the session is already paid we return the upgrade URL so team is updated. */
|
|
return { url: `${WEBAPP_URL}/api/teams/${teamId}/upgrade?session_id=${metadata.paymentId}` };
|
|
};
|
|
|
|
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,
|
|
mode: "subscription",
|
|
allow_promotion_codes: true,
|
|
success_url: `${WEBAPP_URL}/api/teams/${teamId}/upgrade?session_id={CHECKOUT_SESSION_ID}`,
|
|
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,
|
|
quantity: quantity,
|
|
},
|
|
],
|
|
customer_update: {
|
|
address: "auto",
|
|
},
|
|
automatic_tax: {
|
|
enabled: true,
|
|
},
|
|
metadata: {
|
|
teamId,
|
|
},
|
|
subscription_data: {
|
|
metadata: {
|
|
teamId,
|
|
},
|
|
},
|
|
});
|
|
return { url: session.url };
|
|
};
|
|
|
|
const getTeamWithPaymentMetadata = async (teamId: number) => {
|
|
const team = await prisma.team.findUniqueOrThrow({
|
|
where: { id: teamId },
|
|
select: { metadata: true, members: true },
|
|
});
|
|
const metadata = teamPaymentMetadataSchema.parse(team.metadata);
|
|
return { ...team, metadata };
|
|
};
|
|
|
|
export const cancelTeamSubscriptionFromStripe = async (teamId: number) => {
|
|
try {
|
|
const team = await getTeamWithPaymentMetadata(teamId);
|
|
const { subscriptionId } = team.metadata;
|
|
return await stripe.subscriptions.cancel(subscriptionId);
|
|
} catch (error) {
|
|
let message = "Unknown error on cancelTeamSubscriptionFromStripe";
|
|
if (error instanceof Error) message = error.message;
|
|
console.error(message);
|
|
}
|
|
};
|
|
|
|
export const updateQuantitySubscriptionFromStripe = async (teamId: number) => {
|
|
try {
|
|
const { url } = await checkIfTeamPaymentRequired({ teamId });
|
|
/**
|
|
* 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.
|
|
**/
|
|
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: membershipCount + newQuantity, id: subscriptionItemId }],
|
|
});
|
|
console.info(
|
|
`Updated subscription ${subscriptionId} for team ${teamId} to ${team.members.length} seats.`
|
|
);
|
|
} catch (error) {
|
|
let message = "Unknown error on updateQuantitySubscriptionFromStripe";
|
|
if (error instanceof Error) message = error.message;
|
|
console.error(message);
|
|
}
|
|
};
|