feature/settings-username-update (#2306)
* WIP feature/settings-username-update * WIP username change * WIP downgrade stripe * stripe downgrade and prorate preview * new UI for username premium component * Fix server side props * Remove migration, changed field to metadata user * WIP for update subscriptions * WIP intent username table * WIP saving and updating username via hooks * WIP saving working username sub update * WIP, update html to work with tests * Added stripe test for username update go to stripe * WIP username change test * Working test for username change * Fix timeout for flaky test * Review changes, remove logs * Move input username as a self contained component * Self review changes * Removing unnecesary arrow function * Removed intentUsername table and now using user metadata * Update website * Update turbo.json * Update e2e.yml * Update yarn.lock * Fixes for self host username update * Revert yarn lock from main branch * E2E fixes * Centralizes username check * Improvements * WIP separate logic between premium and save username button * WIP refactor username premium update * Saving WIP * WIP redo of username check * WIP obtain action normal, update or downgrade * Update username change components * Fix test for change-username self host or cal server * Fix user type for premiumTextfield * Using now a global unique const to know if is selfhosted, css fixes * Remove unused import * Using dynamic import for username textfield, prevent submit on enter Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: zomars <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
30 files changed
+1405
-336
No files matched your search
@@ -1,5 +1,6 @@
|
||||
export { default as add } from "./add";
|
||||
export { default as callback } from "./callback";
|
||||
export { default as portal } from "./portal";
|
||||
export { default as subscription } from "./subscription";
|
||||
// TODO: Figure out how to handle webhook endpoints from App Store
|
||||
// export { default as webhook } from "./webhook";
|
||||
@@ -0,0 +1,158 @@
|
||||
import { UserPlan } from "@prisma/client";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import Stripe from "stripe";
|
||||
|
||||
import { checkPremiumUsername } from "@calcom/ee/lib/core/checkPremiumUsername";
|
||||
import hasKeyInMetadata from "@calcom/lib/hasKeyInMetadata";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { Prisma } from "@calcom/prisma/client";
|
||||
import {
|
||||
PREMIUM_PLAN_PRICE,
|
||||
PREMIUM_PLAN_PRODUCT_ID,
|
||||
PRO_PLAN_PRICE,
|
||||
PRO_PLAN_PRODUCT_ID,
|
||||
} from "@calcom/stripe/constants";
|
||||
import { getStripeCustomerIdFromUserId } from "@calcom/stripe/customer";
|
||||
import stripe from "@calcom/stripe/server";
|
||||
|
||||
enum UsernameChangeStatusEnum {
|
||||
NORMAL = "NORMAL",
|
||||
UPGRADE = "UPGRADE",
|
||||
DOWNGRADE = "DOWNGRADE",
|
||||
}
|
||||
|
||||
const obtainNewConditionAction = ({
|
||||
userCurrentPlan,
|
||||
isNewUsernamePremium,
|
||||
}: {
|
||||
userCurrentPlan: UserPlan;
|
||||
isNewUsernamePremium: boolean;
|
||||
}) => {
|
||||
if (userCurrentPlan === UserPlan.PRO) {
|
||||
if (isNewUsernamePremium) return UsernameChangeStatusEnum.UPGRADE;
|
||||
return UsernameChangeStatusEnum.DOWNGRADE;
|
||||
}
|
||||
return UsernameChangeStatusEnum.NORMAL;
|
||||
};
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "GET") {
|
||||
const userId = req.session?.user.id;
|
||||
let { intentUsername = null } = req.query;
|
||||
|
||||
if (!userId || !intentUsername) {
|
||||
res.status(404).end();
|
||||
return;
|
||||
}
|
||||
if (intentUsername && typeof intentUsername === "object") {
|
||||
intentUsername = intentUsername[0];
|
||||
}
|
||||
const customerId = await getStripeCustomerIdFromUserId(userId);
|
||||
|
||||
if (!customerId) {
|
||||
res.status(404).json({ message: "Missing customer id" });
|
||||
return;
|
||||
}
|
||||
|
||||
const userData = await prisma.user.findFirst({
|
||||
where: { id: userId },
|
||||
select: { id: true, plan: true, metadata: true },
|
||||
});
|
||||
if (!userData) {
|
||||
res.status(404).json({ message: "Missing user data" });
|
||||
return;
|
||||
}
|
||||
|
||||
const isCurrentlyPremium = hasKeyInMetadata(userData, "isPremium") && !!userData.metadata.isPremium;
|
||||
|
||||
// Save the intentUsername in the metadata
|
||||
await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
metadata: {
|
||||
...(userData.metadata as Prisma.JsonObject),
|
||||
intentUsername,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const return_url = `${process.env.NEXT_PUBLIC_WEBAPP_URL}/settings/profile`;
|
||||
const createSessionParams: Stripe.BillingPortal.SessionCreateParams = {
|
||||
customer: customerId,
|
||||
return_url,
|
||||
};
|
||||
|
||||
const checkPremiumResult = await checkPremiumUsername(intentUsername);
|
||||
if (!checkPremiumResult.available) {
|
||||
return res.status(404).json({ message: "Intent username not available" });
|
||||
}
|
||||
|
||||
if (userData && (userData.plan === UserPlan.FREE || userData.plan === UserPlan.TRIAL)) {
|
||||
const subscriptionPrice = checkPremiumResult.premium ? PREMIUM_PLAN_PRICE : PRO_PLAN_PRICE;
|
||||
const checkoutSession = await stripe.checkout.sessions.create({
|
||||
mode: "subscription",
|
||||
payment_method_types: ["card"],
|
||||
customer: customerId,
|
||||
line_items: [
|
||||
{
|
||||
price: subscriptionPrice,
|
||||
quantity: 1,
|
||||
},
|
||||
],
|
||||
success_url: return_url,
|
||||
cancel_url: return_url,
|
||||
allow_promotion_codes: true,
|
||||
});
|
||||
if (checkoutSession && checkoutSession.url) {
|
||||
return res.redirect(checkoutSession.url).end();
|
||||
}
|
||||
return res.status(404).json({ message: "Couldn't redirect to stripe checkout session" });
|
||||
}
|
||||
|
||||
const action = obtainNewConditionAction({
|
||||
userCurrentPlan: userData?.plan ?? UserPlan.FREE,
|
||||
isNewUsernamePremium: checkPremiumResult.premium,
|
||||
});
|
||||
|
||||
if (action && userData) {
|
||||
let actionText = "";
|
||||
const customProductsSession = [];
|
||||
if (action === UsernameChangeStatusEnum.UPGRADE) {
|
||||
actionText = "Upgrade your plan account";
|
||||
if (checkPremiumResult.premium) {
|
||||
customProductsSession.push({ prices: [PREMIUM_PLAN_PRICE], product: PREMIUM_PLAN_PRODUCT_ID });
|
||||
} else {
|
||||
customProductsSession.push({ prices: [PRO_PLAN_PRICE], product: PRO_PLAN_PRODUCT_ID });
|
||||
}
|
||||
} else if (action === UsernameChangeStatusEnum.DOWNGRADE) {
|
||||
actionText = "Downgrade your plan account";
|
||||
if (isCurrentlyPremium) {
|
||||
customProductsSession.push({ prices: [PRO_PLAN_PRICE], product: PRO_PLAN_PRODUCT_ID });
|
||||
}
|
||||
}
|
||||
|
||||
const configuration = await stripe.billingPortal.configurations.create({
|
||||
business_profile: {
|
||||
headline: actionText,
|
||||
},
|
||||
features: {
|
||||
payment_method_update: {
|
||||
enabled: true,
|
||||
},
|
||||
subscription_update: {
|
||||
enabled: true,
|
||||
proration_behavior: "always_invoice",
|
||||
default_allowed_updates: ["price"],
|
||||
products: customProductsSession,
|
||||
},
|
||||
},
|
||||
});
|
||||
if (configuration) {
|
||||
createSessionParams.configuration = configuration.id;
|
||||
}
|
||||
}
|
||||
const stripeSession = await stripe.billingPortal.sessions.create(createSessionParams);
|
||||
|
||||
res.redirect(stripeSession.url).end();
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { JSONObject } from "superjson/dist/types";
|
||||
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "GET" && req.session && req.session.user.id) {
|
||||
const userId = req.session.user.id;
|
||||
try {
|
||||
const user = await prisma?.user.findFirst({
|
||||
const user = await prisma.user.findFirst({
|
||||
select: {
|
||||
metadata: true,
|
||||
},
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
import { WEBSITE_URL } from "@calcom/lib/constants";
|
||||
|
||||
export type ResponseUsernameApi = {
|
||||
interface ResponseUsernameApi {
|
||||
available: boolean;
|
||||
premium: boolean;
|
||||
message?: string;
|
||||
suggestion?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export async function checkPremiumUsername(_username: string): Promise<ResponseUsernameApi> {
|
||||
const username = slugify(_username);
|
||||
|
||||
@@ -12,6 +12,9 @@ export const CONSOLE_URL =
|
||||
new URL(WEBAPP_URL).hostname.endsWith(".cal.dev") || process.env.NODE_ENV !== "production"
|
||||
? `https://console.cal.dev`
|
||||
: `https://console.cal.com`;
|
||||
export const IS_SELF_HOSTED = !(
|
||||
new URL(WEBAPP_URL).hostname.endsWith(".cal.dev") || !!new URL(WEBAPP_URL).hostname.endsWith(".cal.com")
|
||||
);
|
||||
export const EMBED_LIB_URL = process.env.NEXT_PUBLIC_EMBED_LIB_URL || `${WEBAPP_URL}/embed/embed.js`;
|
||||
export const IS_PRODUCTION = process.env.NODE_ENV === "production";
|
||||
export const TRIAL_LIMIT_DAYS = 14;
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
type ResponseUsernameApi = {
|
||||
available: boolean;
|
||||
premium: boolean;
|
||||
message?: string;
|
||||
suggestion?: string;
|
||||
};
|
||||
|
||||
export async function fetchUsername(username: string) {
|
||||
const response = await fetch("/api/username", {
|
||||
credentials: "include",
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
username: username.trim(),
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
const data = (await response.json()) as ResponseUsernameApi;
|
||||
return { response, data };
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import isPrismaObj from "./isPrismaObj";
|
||||
|
||||
const hasKeyInMetadata = <T extends string>(
|
||||
x: { metadata: unknown } | null,
|
||||
key: T
|
||||
): x is { metadata: { [key in T]: string | boolean | number } } =>
|
||||
isPrismaObj(x?.metadata) && !!x?.metadata && key in x.metadata;
|
||||
|
||||
export default hasKeyInMetadata;
|
||||
@@ -106,5 +106,7 @@ export const userMetadata = z
|
||||
proPaidForByTeamId: z.number().optional(),
|
||||
stripeCustomerId: z.string().optional(),
|
||||
vitalSettings: vitalSettingsUpdateSchema.optional(),
|
||||
isPremium: z.boolean().optional(),
|
||||
intentUsername: z.string().optional(),
|
||||
})
|
||||
.nullable();
|
||||
@@ -1,4 +1,6 @@
|
||||
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 || "";
|
||||
export const FREE_PLAN_PRODUCT_ID = process.env.STRIPE_FREE_PLAN_PRODUCT_ID || "";
|
||||
export const PRO_PLAN_PRODUCT_ID = process.env.STRIPE_PRO_PLAN_PRODUCT_ID || "";
|
||||
export const PREMIUM_PLAN_PRODUCT_ID = process.env.STRIPE_PREMIUM_PLAN_PRODUCT_ID || "";
|
||||
@@ -0,0 +1,73 @@
|
||||
import { UserPlan } from "@prisma/client";
|
||||
import Stripe from "stripe";
|
||||
|
||||
import stripe from "@calcom/stripe/server";
|
||||
|
||||
import {
|
||||
getFreePlanPrice,
|
||||
getPremiumPlanPrice,
|
||||
getProPlanPrice,
|
||||
getFreePlanProductId,
|
||||
getPremiumPlanProductId,
|
||||
getProPlanProductId,
|
||||
} from "./utils";
|
||||
|
||||
interface IRetrieveSubscriptionIdResponse {
|
||||
message?: string;
|
||||
subscriptionId?: string;
|
||||
}
|
||||
|
||||
export async function retrieveSubscriptionIdFromStripeCustomerId(
|
||||
stripeCustomerId: string
|
||||
): Promise<IRetrieveSubscriptionIdResponse> {
|
||||
const customer = await stripe.customers.retrieve(stripeCustomerId, {
|
||||
expand: ["subscriptions.data.plan"],
|
||||
});
|
||||
if (!customer || customer.deleted) {
|
||||
return {
|
||||
message: "Not found",
|
||||
};
|
||||
}
|
||||
|
||||
const subscription = customer.subscriptions?.data[0];
|
||||
if (!subscription) {
|
||||
return {
|
||||
message: "Not found",
|
||||
};
|
||||
}
|
||||
return {
|
||||
subscriptionId: subscription.id,
|
||||
};
|
||||
}
|
||||
|
||||
// @NOTE: Remove when user subscription plan id is saved on db and not on stripe only
|
||||
export function obtainUserPlanDetails(subscription: Stripe.Subscription) {
|
||||
const proPlanProductId = getProPlanProductId();
|
||||
const premiumPlanProductId = getPremiumPlanProductId();
|
||||
const freePlanProductId = getFreePlanProductId();
|
||||
let priceId = "";
|
||||
const hasProPlan = !!subscription.items.data.find((item) => item.plan.product === proPlanProductId);
|
||||
const hasPremiumPlan = !!subscription.items.data.find((item) => item.plan.product === premiumPlanProductId);
|
||||
const hasFreePlan = !!subscription.items.data.find((item) => item.plan.product === freePlanProductId);
|
||||
let userPlan: UserPlan;
|
||||
if (hasPremiumPlan) {
|
||||
priceId = getPremiumPlanPrice();
|
||||
userPlan = UserPlan.PRO;
|
||||
} else if (hasProPlan) {
|
||||
priceId = getProPlanPrice();
|
||||
userPlan = UserPlan.PRO;
|
||||
} else if (hasFreePlan) {
|
||||
priceId = getFreePlanPrice();
|
||||
userPlan = UserPlan.FREE;
|
||||
} else {
|
||||
userPlan = UserPlan.TRIAL;
|
||||
}
|
||||
|
||||
return {
|
||||
userPlan,
|
||||
priceId,
|
||||
isProPlan: hasProPlan,
|
||||
isPremiumPlan: hasPremiumPlan,
|
||||
isFreePlan: hasFreePlan,
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,11 @@
|
||||
import { FREE_PLAN_PRICE, PREMIUM_PLAN_PRICE, PRO_PLAN_PRICE, PRO_PLAN_PRODUCT } from "./constants";
|
||||
import {
|
||||
FREE_PLAN_PRICE,
|
||||
FREE_PLAN_PRODUCT_ID,
|
||||
PREMIUM_PLAN_PRICE,
|
||||
PREMIUM_PLAN_PRODUCT_ID,
|
||||
PRO_PLAN_PRICE,
|
||||
PRO_PLAN_PRODUCT_ID,
|
||||
} from "./constants";
|
||||
|
||||
export function getPerSeatProPlanPrice(): string {
|
||||
return PRO_PLAN_PRICE;
|
||||
@@ -12,10 +19,18 @@ export function getProPlanPrice(): string {
|
||||
return PRO_PLAN_PRICE;
|
||||
}
|
||||
|
||||
export function getProPlanProduct(): string {
|
||||
return PRO_PLAN_PRODUCT;
|
||||
}
|
||||
|
||||
export function getFreePlanPrice(): string {
|
||||
return FREE_PLAN_PRICE;
|
||||
}
|
||||
|
||||
export function getProPlanProductId(): string {
|
||||
return PRO_PLAN_PRODUCT_ID;
|
||||
}
|
||||
|
||||
export function getPremiumPlanProductId(): string {
|
||||
return PREMIUM_PLAN_PRODUCT_ID;
|
||||
}
|
||||
|
||||
export function getFreePlanProductId(): string {
|
||||
return FREE_PLAN_PRODUCT_ID;
|
||||
}
|
||||
Reference in new issue
Block a user