Signup Flow improvements (#4012)

* Get login working

* Update website

* Fixes

* Save

* svae

* Save

* Change translation key

* Various fixes after testing

* Update website

* Add TS Tests

* Upate website

* Fix tests

* Fix linting and other issues

* Fix linting and other issues

* Fix bugs found during recording of demos

* Revert default coookie change

* Self review fixe

* Link fixes

* Removed inline styles, cleanup

* Various fixes

* Added new envs to e2e

Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Co-authored-by: zomars <[email protected]>
This commit is contained in:
authored and GitHub committed 2022-09-07 18:38:37 -06:00
1 parent d36d925788
commit 4856ed9977
47 files changed
+547 -245

No files matched your search

@@ -2,5 +2,7 @@ export { default as add } from "./add";
export { default as callback } from "./callback";
export { default as portal } from "./portal";
export { default as subscription } from "./subscription";
export { default as paymentCallback } from "./paymentCallback";
// TODO: Figure out how to handle webhook endpoints from App Store
// export { default as webhook } from "./webhook";
@@ -0,0 +1,51 @@
import { NextApiRequest, NextApiResponse } from "next";
import z from "zod";
import { getCustomerAndCheckoutSession } from "@calcom/app-store/stripepayment/lib/getCustomerAndCheckoutSession";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
import { prisma } from "@calcom/prisma";
const querySchema = z.object({
callbackUrl: z.string().transform((url) => {
if (url.search(/^https?:\/\//) === -1) {
url = `${WEBAPP_URL}${url}`;
}
return new URL(url);
}),
checkoutSessionId: z.string(),
});
// It handles premium user payment success/failure. Can be modified to handle other PRO upgrade payment as well.
async function getHandler(req: NextApiRequest, res: NextApiResponse) {
const { callbackUrl, checkoutSessionId } = querySchema.parse(req.query);
const { stripeCustomer, checkoutSession } = await getCustomerAndCheckoutSession(checkoutSessionId);
if (!stripeCustomer) return { message: "Stripe customer not found or deleted" };
if (checkoutSession.payment_status === "paid") {
console.log("Found payment ");
try {
await prisma.user.update({
data: {
username: stripeCustomer.metadata.username,
},
where: {
email: stripeCustomer.metadata.email,
},
});
} catch (error) {
console.error(error);
return {
message:
"We have received your payment. Your premium username could still not be reserved. Please contact [email protected] and mention your premium username",
};
}
}
callbackUrl.searchParams.set("paymentStatus", checkoutSession.payment_status);
return res.redirect(callbackUrl.toString()).end();
}
export default defaultHandler({
GET: Promise.resolve({ default: defaultResponder(getHandler) }),
});
@@ -2,45 +2,32 @@ import { UserPlan } from "@prisma/client";
import type { NextApiRequest, NextApiResponse } from "next";
import Stripe from "stripe";
import {
getPremiumPlanMode,
getPremiumPlanPrice,
getPremiumPlanProductId,
} from "@calcom/app-store/stripepayment/lib/utils";
import { checkPremiumUsername } from "@calcom/features/ee/common/lib/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 "../lib/constants";
import { PRO_PLAN_PRICE, PRO_PLAN_PRODUCT_ID } from "../lib/constants";
import { getStripeCustomerIdFromUserId } from "../lib/customer";
import stripe from "../lib/server";
enum UsernameChangeStatusEnum {
export 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;
let { intentUsername = null } = req.query;
const { action, callbackUrl } = req.query;
if (!userId || !intentUsername) {
res.status(404).end();
return;
@@ -66,18 +53,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
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 return_url = `${process.env.NEXT_PUBLIC_WEBAPP_URL}/api/integrations/stripepayment/paymentCallback?checkoutSessionId={CHECKOUT_SESSION_ID}&callbackUrl=${callbackUrl}`;
const createSessionParams: Stripe.BillingPortal.SessionCreateParams = {
customer: customerId,
return_url,
@@ -87,11 +63,21 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
if (!checkPremiumResult.available) {
return res.status(404).json({ message: "Intent username not available" });
}
const stripeCustomer = await stripe.customers.retrieve(customerId);
if (!stripeCustomer || stripeCustomer.deleted) {
return res.status(400).json({ message: "Stripe customer not found or deleted" });
}
await stripe.customers.update(customerId, {
metadata: {
...stripeCustomer.metadata,
username: intentUsername,
},
});
if (userData && (userData.plan === UserPlan.FREE || userData.plan === UserPlan.TRIAL)) {
const subscriptionPrice = checkPremiumResult.premium ? PREMIUM_PLAN_PRICE : PRO_PLAN_PRICE;
const subscriptionPrice = checkPremiumResult.premium ? getPremiumPlanPrice() : PRO_PLAN_PRICE;
const checkoutSession = await stripe.checkout.sessions.create({
mode: "subscription",
mode: getPremiumPlanMode(),
payment_method_types: ["card"],
customer: customerId,
line_items: [
@@ -104,24 +90,30 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
cancel_url: return_url,
allow_promotion_codes: true,
});
// Save the intentUsername in the metadata
await prisma.user.update({
where: { id: userId },
data: {
metadata: {
...(userData.metadata as Prisma.JsonObject),
checkoutSessionId: checkoutSession.id,
intentUsername,
},
},
});
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 });
customProductsSession.push({ prices: [getPremiumPlanPrice()], product: getPremiumPlanProductId() });
} else {
customProductsSession.push({ prices: [PRO_PLAN_PRICE], product: PRO_PLAN_PRODUCT_ID });
}
@@ -148,6 +140,15 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
},
},
});
await prisma.user.update({
where: { id: userId },
data: {
metadata: {
...(userData.metadata as Prisma.JsonObject),
intentUsername,
},
},
});
if (configuration) {
createSessionParams.configuration = configuration.id;
}
@@ -1,5 +1,7 @@
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 IS_PREMIUM_NEW_PLAN = process.env.NEXT_PUBLIC_IS_PREMIUM_NEW_PLAN === "1" ? true : false;
export const PREMIUM_NEW_PLAN_PRICE = process.env.NEXT_PUBLIC_STRIPE_PREMIUM_NEW_PLAN_PRICE || "";
export const PRO_PLAN_PRICE = process.env.NEXT_PUBLIC_STRIPE_PRO_PLAN_PRICE || "";
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 || "";
@@ -0,0 +1,24 @@
import stripe from "@calcom/app-store/stripepayment/lib/server";
export async function getCustomerAndCheckoutSession(checkoutSessionId: string) {
const checkoutSession = await stripe.checkout.sessions.retrieve(checkoutSessionId);
const customerOrCustomerId = checkoutSession.customer;
let customerId = null;
if (!customerOrCustomerId) {
return { checkoutSession, customer: null };
}
if (typeof customerOrCustomerId === "string") {
customerId = customerOrCustomerId;
} else if (customerOrCustomerId.deleted) {
return { checkoutSession, customer: null };
} else {
customerId = customerOrCustomerId.id;
}
const stripeCustomer = await stripe.customers.retrieve(customerId);
if (stripeCustomer.deleted) {
return { checkoutSession, customer: null };
}
return { stripeCustomer, checkoutSession };
}
@@ -33,7 +33,6 @@ export const stripeDataSchema = stripeOAuthTokenSchema.extend({
export type StripeData = z.infer<typeof stripeDataSchema>;
const stripePrivateKey = process.env.STRIPE_PRIVATE_KEY!;
const stripe = new Stripe(stripePrivateKey, {
apiVersion: "2020-08-27",
});
+13 -3
View File
@@ -4,15 +4,25 @@ import {
PREMIUM_PLAN_PRICE,
PREMIUM_PLAN_PRODUCT_ID,
PRO_PLAN_PRICE,
PREMIUM_NEW_PLAN_PRICE,
IS_PREMIUM_NEW_PLAN,
PRO_PLAN_PRODUCT_ID,
} from "./constants";
export function getPerSeatProPlanPrice(): string {
return PRO_PLAN_PRICE;
export function getPremiumPlanMode() {
return IS_PREMIUM_NEW_PLAN ? "payment" : "subscription";
}
export function getPremiumPlanPriceValue() {
return IS_PREMIUM_NEW_PLAN ? "$499" : "$29/mo";
}
export function getPremiumPlanPrice(): string {
return PREMIUM_PLAN_PRICE;
return IS_PREMIUM_NEW_PLAN ? PREMIUM_NEW_PLAN_PRICE : PREMIUM_PLAN_PRICE;
}
export function getPerSeatProPlanPrice(): string {
return PRO_PLAN_PRICE;
}
export function getProPlanPrice(): string {
@@ -39,7 +39,6 @@ export default class CloseComService extends SyncServiceCore implements ISyncSer
// Get Custom Contact fields ids
const customFieldsIds = await getCustomFieldsIds("contact", calComCustomContactFields, this.service);
this.log.debug("sync:closecom:user:customFieldsIds", { customFieldsIds });
debugger;
// Get shared fields ids
const sharedFieldsIds = await getCustomFieldsIds("shared", calComSharedFields, this.service);
this.log.debug("sync:closecom:user:sharedFieldsIds", { sharedFieldsIds });
+1
View File
@@ -128,6 +128,7 @@ export const userMetadata = z
vitalSettings: vitalSettingsUpdateSchema.optional(),
isPremium: z.boolean().optional(),
intentUsername: z.string().optional(),
checkoutSessionId: z.string().nullable().optional(),
})
.nullable();
+130
View File
@@ -7,6 +7,7 @@ import { z } from "zod";
import app_RoutingForms from "@calcom/app-store/ee/routing_forms/trpc-router";
import ethRouter from "@calcom/app-store/rainbow/trpc/router";
import { deleteStripeCustomer } from "@calcom/app-store/stripepayment/lib/customer";
import { getCustomerAndCheckoutSession } from "@calcom/app-store/stripepayment/lib/getCustomerAndCheckoutSession";
import stripe, { closePayments } from "@calcom/app-store/stripepayment/lib/server";
import getApps, { getLocationOptions } from "@calcom/app-store/utils";
import { cancelScheduledJobs } from "@calcom/app-store/zapier/lib/nodeScheduler";
@@ -37,6 +38,7 @@ import {
updateWebUser as syncServicesUpdateWebUser,
} from "@calcom/lib/sync/SyncServiceManager";
import prisma, { baseEventTypeSelect, bookingMinimalSelect } from "@calcom/prisma";
import { userMetadata } from "@calcom/prisma/zod-utils";
import { resizeBase64Image } from "@calcom/web/server/lib/resizeBase64Image";
import { TRPCError } from "@trpc/server";
@@ -79,6 +81,71 @@ const publicViewerRouter = createRouter()
return await samlTenantProduct(prisma, email);
},
})
.query("stripeCheckoutSession", {
input: z.object({
stripeCustomerId: z.string().optional(),
checkoutSessionId: z.string().optional(),
}),
async resolve({ input }) {
const { checkoutSessionId, stripeCustomerId } = input;
// TODO: Move the following data checks to superRefine
if (!checkoutSessionId && !stripeCustomerId) {
throw new Error("Missing checkoutSessionId or stripeCustomerId");
}
if (checkoutSessionId && stripeCustomerId) {
throw new Error("Both checkoutSessionId and stripeCustomerId provided");
}
let customerId: string;
let isPremiumUsername = false;
let hasPaymentFailed = false;
if (checkoutSessionId) {
try {
const session = await stripe.checkout.sessions.retrieve(checkoutSessionId);
if (typeof session.customer !== "string") {
return {
valid: false,
};
}
customerId = session.customer;
isPremiumUsername = true;
hasPaymentFailed = session.payment_status !== "paid";
} catch (e) {
return {
valid: false,
};
}
} else {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
customerId = stripeCustomerId!;
}
try {
const customer = await stripe.customers.retrieve(customerId);
if (customer.deleted) {
return {
valid: false,
};
}
return {
valid: true,
hasPaymentFailed,
isPremiumUsername,
customer: {
username: customer.metadata.username,
email: customer.metadata.email,
stripeCustomerId: customerId,
},
};
} catch (e) {
return {
valid: false,
};
}
},
})
.merge("slots.", slotsRouter);
// routes only available to authenticated users
@@ -687,6 +754,43 @@ const loggedInViewerRouter = createProtectedRouter()
return app;
},
})
.query("stripeCustomer", {
async resolve({ ctx }) {
const {
user: { id: userId },
prisma,
} = ctx;
const user = await prisma.user.findUnique({
where: {
id: userId,
},
select: {
metadata: true,
},
});
if (!user) {
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "User not found" });
}
const metadata = userMetadata.parse(user.metadata);
const checkoutSessionId = metadata?.checkoutSessionId;
//TODO: Rename checkoutSessionId to premiumUsernameCheckoutSessionId
if (!checkoutSessionId) return { isPremium: false };
const { stripeCustomer, checkoutSession } = await getCustomerAndCheckoutSession(checkoutSessionId);
if (!stripeCustomer) {
throw new TRPCError({ code: "NOT_FOUND", message: "Stripe User not found" });
}
return {
isPremium: true,
paidForPremium: checkoutSession.payment_status === "paid",
username: stripeCustomer.metadata.username,
};
},
})
.mutation("updateProfile", {
input: z.object({
username: z.string().optional(),
@@ -711,12 +815,14 @@ const loggedInViewerRouter = createProtectedRouter()
const data: Prisma.UserUpdateInput = {
...input,
};
let isPremiumUsername = false;
if (input.username) {
const username = slugify(input.username);
// Only validate if we're changing usernames
if (username !== user.username) {
data.username = username;
const response = await checkUsername(username);
isPremiumUsername = response.premium;
if (!response.available) {
throw new TRPCError({ code: "BAD_REQUEST", message: response.message });
}
@@ -725,6 +831,30 @@ const loggedInViewerRouter = createProtectedRouter()
if (input.avatar) {
data.avatar = await resizeBase64Image(input.avatar);
}
const userToUpdate = await prisma.user.findUnique({
where: {
id: user.id,
},
});
if (!userToUpdate) {
throw new TRPCError({ code: "NOT_FOUND", message: "User not found" });
}
const metadata = userMetadata.parse(userToUpdate.metadata);
// Checking the status of payment directly from stripe allows to avoid the situation where the user has got the refund or maybe something else happened asyncly at stripe but our DB thinks it's still paid for
// TODO: Test the case where one time payment is refunded.
const premiumUsernameCheckoutSessionId = metadata?.checkoutSessionId;
if (premiumUsernameCheckoutSessionId) {
const checkoutSession = await stripe.checkout.sessions.retrieve(premiumUsernameCheckoutSessionId);
const canUserHavePremiumUsername = checkoutSession.payment_status == "paid";
if (isPremiumUsername && !canUserHavePremiumUsername) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "You need to pay for premium username",
});
}
}
const updatedUser = await prisma.user.update({
where: {
+1 -1
View File
@@ -7,7 +7,7 @@ export { CollectionIcon } from "@heroicons/react/outline";
export { ShieldCheckIcon } from "@heroicons/react/outline";
export { BadgeCheckIcon } from "@heroicons/react/outline";
export { ClipboardCopyIcon } from "@heroicons/react/outline";
export { StarIcon as StarIconSolid } from "@heroicons/react/solid";
// TODO:
// right now: Icon.Sun comes from react-feather
// CollectionIcon comes from "@heroicons/react/outline";
+1 -1
View File
@@ -33,7 +33,7 @@ const SkeletonText: React.FC<SkeletonBaseProps> = ({ width = "", height = "", cl
className = width ? `${className} w-${width}` : className;
className = height ? `${className} h-${height}` : className;
return (
<div
<span
className={classNames(
`dark:white-300 animate-pulse rounded-md bg-gray-300 empty:before:inline-block empty:before:content-[''] w-${width} h-${height}`,
className