2023-04-25 22:39:47 +00:00
|
|
|
import type { Prisma } from "@prisma/client";
|
2023-08-04 00:26:40 +00:00
|
|
|
import type { GetServerSidePropsContext, NextApiResponse } from "next";
|
2023-04-25 22:39:47 +00:00
|
|
|
|
|
|
|
import stripe from "@calcom/app-store/stripepayment/lib/server";
|
|
|
|
import { getPremiumPlanProductId } from "@calcom/app-store/stripepayment/lib/utils";
|
2023-08-04 00:26:40 +00:00
|
|
|
import { passwordResetRequest } from "@calcom/features/auth/lib/passwordResetRequest";
|
2023-04-25 22:39:47 +00:00
|
|
|
import hasKeyInMetadata from "@calcom/lib/hasKeyInMetadata";
|
2023-08-16 00:27:48 +00:00
|
|
|
import logger from "@calcom/lib/logger";
|
2023-06-08 12:32:17 +00:00
|
|
|
import { getTranslation } from "@calcom/lib/server";
|
2023-04-25 22:39:47 +00:00
|
|
|
import { checkUsername } from "@calcom/lib/server/checkUsername";
|
|
|
|
import { resizeBase64Image } from "@calcom/lib/server/resizeBase64Image";
|
|
|
|
import slugify from "@calcom/lib/slugify";
|
|
|
|
import { updateWebUser as syncServicesUpdateWebUser } from "@calcom/lib/sync/SyncServiceManager";
|
2023-06-08 12:32:17 +00:00
|
|
|
import { validateBookerLayouts } from "@calcom/lib/validateBookerLayouts";
|
2023-04-25 22:39:47 +00:00
|
|
|
import { prisma } from "@calcom/prisma";
|
2023-08-04 00:26:40 +00:00
|
|
|
import { IdentityProvider } from "@calcom/prisma/enums";
|
2023-09-06 23:40:50 +00:00
|
|
|
import { userMetadata as userMetadataSchema } from "@calcom/prisma/zod-utils";
|
2023-04-25 22:39:47 +00:00
|
|
|
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
|
|
|
|
|
|
|
|
import { TRPCError } from "@trpc/server";
|
|
|
|
|
2023-09-26 19:41:16 +00:00
|
|
|
import { getDefaultScheduleId } from "../viewer/availability/util";
|
2023-08-16 00:27:48 +00:00
|
|
|
import { updateUserMetadataAllowedKeys, type TUpdateProfileInputSchema } from "./updateProfile.schema";
|
2023-04-25 22:39:47 +00:00
|
|
|
|
|
|
|
type UpdateProfileOptions = {
|
|
|
|
ctx: {
|
|
|
|
user: NonNullable<TrpcSessionUser>;
|
|
|
|
res?: NextApiResponse | GetServerSidePropsContext["res"];
|
|
|
|
};
|
|
|
|
input: TUpdateProfileInputSchema;
|
|
|
|
};
|
|
|
|
|
|
|
|
export const updateProfileHandler = async ({ ctx, input }: UpdateProfileOptions) => {
|
|
|
|
const { user } = ctx;
|
2023-09-06 23:40:50 +00:00
|
|
|
const userMetadata = handleUserMetadata({ ctx, input });
|
2023-04-25 22:39:47 +00:00
|
|
|
const data: Prisma.UserUpdateInput = {
|
|
|
|
...input,
|
2023-09-06 23:40:50 +00:00
|
|
|
metadata: userMetadata,
|
2023-04-25 22:39:47 +00:00
|
|
|
};
|
2023-06-06 15:31:43 +00:00
|
|
|
|
2023-08-04 00:26:40 +00:00
|
|
|
// some actions can invalidate a user session.
|
|
|
|
let signOutUser = false;
|
|
|
|
let passwordReset = false;
|
2023-04-25 22:39:47 +00:00
|
|
|
let isPremiumUsername = false;
|
2023-06-08 12:32:17 +00:00
|
|
|
|
|
|
|
const layoutError = validateBookerLayouts(input?.metadata?.defaultBookerLayouts || null);
|
|
|
|
if (layoutError) {
|
|
|
|
const t = await getTranslation("en", "common");
|
|
|
|
throw new TRPCError({ code: "BAD_REQUEST", message: t(layoutError) });
|
|
|
|
}
|
|
|
|
|
feat: Organizations (#8993)
* Initial commit
* Adding feature flag
* feat: Orgs Schema Changing `scopedMembers` to `orgUsers` (#9209)
* Change scopedMembers to orgMembers
* Change to orgUsers
* Letting duplicate slugs for teams to support orgs
* Covering null on unique clauses
* Supporting having the orgId in the session cookie
* feat: organization event type filter (#9253)
Signed-off-by: Udit Takkar <udit.07814802719@cse.mait.ac.in>
* Missing changes to support orgs schema changes
* 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 <55134778+sean-brydon@users.noreply.github.com>
* 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 <55134778+sean-brydon@users.noreply.github.com>
* Vercel subdomain creation in PROD only
* Making sure we let localhost still work
* Feedback
* Type check fixes
* feat: Organization branding in side menu (#9279)
* 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
* Org branding provider used in shell sidebar
* Using meta component for head/descr
* Missing i18n strings
* Feedback
* Making an org avatar (temp)
* Using org avatar (temp)
* Not showing org logo if not set
* User onboarding with org branding (slug)
* Check for subteams slug clashes with usernames
* Fixing create teams onsuccess
* feedback
* Feedback
* Org public profile
* Public profiles for team event types
* Added setup profile alert
* Using org avatar on subteams avatar
* Making sure we show the set up profile on org only
* Profile username availability rely on org hook
* Update apps/web/pages/team/[slug].tsx
Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
* Update apps/web/pages/team/[slug].tsx
Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
---------
Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
* feat: Organization support for event types page (#9449)
* 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
* Org branding provider used in shell sidebar
* Using meta component for head/descr
* Missing i18n strings
* Feedback
* Making an org avatar (temp)
* Using org avatar (temp)
* Not showing org logo if not set
* User onboarding with org branding (slug)
* Check for subteams slug clashes with usernames
* Fixing create teams onsuccess
* feedback
* Feedback
* Org public profile
* Public profiles for team event types
* Added setup profile alert
* Using org avatar on subteams avatar
* Processing orgs and children as profile options
* Reverting change not belonging to this PR
* Making sure we show the set up profile on org only
* Removing console.log
* Comparing memberships to choose the highest one
---------
Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
* Type errors
* Refactor and type fixes
* Update orgDomains.ts
* Feedback
* Reverting
* NIT
* fix issue getting org slug from domain
* Improving orgDomains util
* Host comes with port
* Update useRouterQuery.ts
* Feedback
* Feedback
* Feedback
* Feedback: SSR for user event-types to have org context
* chore: Cache node_modules (#9492)
* Adding check for cache hit
* Adding a separate install step first
* Put the restore cache steps back
* Revert the uses type for restoring cache
* Added step to restore nm cache
* Removed the cache-hit check
* Comments and naming
* Removed extra install command
* Updated the name of the linting step to be more clear
* Removes the need for useEffect here
* Feedback
* Feedback
* Cookie domain needs a dot
* Type fix
* Update apps/web/public/static/locales/en/common.json
Co-authored-by: Omar López <zomars@me.com>
* Update packages/emails/src/templates/OrganizationAccountVerifyEmail.tsx
* Feedback
---------
Signed-off-by: Udit Takkar <udit.07814802719@cse.mait.ac.in>
Co-authored-by: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
Co-authored-by: zomars <zomars@me.com>
Co-authored-by: Efraín Rochín <roae.85@gmail.com>
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
2023-06-14 21:40:20 +00:00
|
|
|
if (input.username && !user.organizationId) {
|
2023-04-25 22:39:47 +00:00
|
|
|
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 });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (input.avatar) {
|
|
|
|
data.avatar = await resizeBase64Image(input.avatar);
|
|
|
|
}
|
2023-09-29 12:41:41 +00:00
|
|
|
if (input.avatar === null) {
|
|
|
|
data.avatar = null;
|
|
|
|
}
|
2023-08-16 00:27:48 +00:00
|
|
|
|
2023-04-25 22:39:47 +00:00
|
|
|
if (isPremiumUsername) {
|
2023-09-06 23:40:50 +00:00
|
|
|
const stripeCustomerId = userMetadata?.stripeCustomerId;
|
|
|
|
const isPremium = userMetadata?.isPremium;
|
2023-04-25 22:39:47 +00:00
|
|
|
if (!isPremium || !stripeCustomerId) {
|
|
|
|
throw new TRPCError({ code: "BAD_REQUEST", message: "User is not premium" });
|
|
|
|
}
|
|
|
|
|
|
|
|
const stripeSubscriptions = await stripe.subscriptions.list({ customer: stripeCustomerId });
|
|
|
|
|
|
|
|
if (!stripeSubscriptions || !stripeSubscriptions.data.length) {
|
|
|
|
throw new TRPCError({
|
|
|
|
code: "INTERNAL_SERVER_ERROR",
|
|
|
|
message: "No stripeSubscription found",
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// Iterate over subscriptions and look for premium product id and status active
|
|
|
|
// @TODO: iterate if stripeSubscriptions.hasMore is true
|
|
|
|
const isPremiumUsernameSubscriptionActive = stripeSubscriptions.data.some(
|
|
|
|
(subscription) =>
|
|
|
|
subscription.items.data[0].price.product === getPremiumPlanProductId() &&
|
|
|
|
subscription.status === "active"
|
|
|
|
);
|
|
|
|
|
|
|
|
if (!isPremiumUsernameSubscriptionActive) {
|
|
|
|
throw new TRPCError({
|
|
|
|
code: "BAD_REQUEST",
|
|
|
|
message: "You need to pay for premium username",
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2023-08-04 00:26:40 +00:00
|
|
|
const hasEmailBeenChanged = data.email && user.email !== data.email;
|
2023-07-27 08:41:33 +00:00
|
|
|
|
|
|
|
if (hasEmailBeenChanged) {
|
|
|
|
data.emailVerified = null;
|
|
|
|
}
|
2023-04-25 22:39:47 +00:00
|
|
|
|
2023-08-04 00:26:40 +00:00
|
|
|
// check if we are changing email and identity provider is not CAL
|
|
|
|
const hasEmailChangedOnNonCalProvider =
|
|
|
|
hasEmailBeenChanged && user.identityProvider !== IdentityProvider.CAL;
|
|
|
|
const hasEmailChangedOnCalProvider = hasEmailBeenChanged && user.identityProvider === IdentityProvider.CAL;
|
|
|
|
|
|
|
|
if (hasEmailChangedOnNonCalProvider) {
|
|
|
|
// Only validate if we're changing email
|
|
|
|
data.identityProvider = IdentityProvider.CAL;
|
|
|
|
data.identityProviderId = null;
|
|
|
|
} else if (hasEmailChangedOnCalProvider) {
|
|
|
|
// when the email changes, the user needs to sign in again.
|
|
|
|
signOutUser = true;
|
|
|
|
}
|
|
|
|
|
2023-04-25 22:39:47 +00:00
|
|
|
const updatedUser = await prisma.user.update({
|
|
|
|
where: {
|
|
|
|
id: user.id,
|
|
|
|
},
|
|
|
|
data,
|
|
|
|
select: {
|
|
|
|
id: true,
|
|
|
|
username: true,
|
|
|
|
email: true,
|
2023-08-04 00:26:40 +00:00
|
|
|
identityProvider: true,
|
|
|
|
identityProviderId: true,
|
2023-04-25 22:39:47 +00:00
|
|
|
metadata: true,
|
|
|
|
name: true,
|
|
|
|
createdDate: true,
|
2023-08-04 00:26:40 +00:00
|
|
|
locale: true,
|
2023-09-26 19:41:16 +00:00
|
|
|
schedules: {
|
|
|
|
select: {
|
|
|
|
id: true,
|
|
|
|
},
|
|
|
|
},
|
2023-04-25 22:39:47 +00:00
|
|
|
},
|
|
|
|
});
|
|
|
|
|
2023-09-26 19:41:16 +00:00
|
|
|
if (user.timeZone !== data.timeZone && updatedUser.schedules.length > 0) {
|
|
|
|
// on timezone change update timezone of default schedule
|
|
|
|
const defaultScheduleId = await getDefaultScheduleId(user.id, prisma);
|
|
|
|
|
|
|
|
if (!user.defaultScheduleId) {
|
|
|
|
// set default schedule if not already set
|
|
|
|
await prisma.user.update({
|
|
|
|
where: {
|
|
|
|
id: user.id,
|
|
|
|
},
|
|
|
|
data: {
|
|
|
|
defaultScheduleId,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
await prisma.schedule.updateMany({
|
|
|
|
where: {
|
|
|
|
id: defaultScheduleId,
|
|
|
|
},
|
|
|
|
data: {
|
|
|
|
timeZone: data.timeZone,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-08-04 00:26:40 +00:00
|
|
|
if (hasEmailChangedOnNonCalProvider) {
|
|
|
|
// Because the email has changed, we are now attempting to use the CAL provider-
|
|
|
|
// which has no password yet. We have to send the reset password email.
|
|
|
|
await passwordResetRequest(updatedUser);
|
|
|
|
signOutUser = true;
|
|
|
|
passwordReset = true;
|
|
|
|
}
|
|
|
|
|
2023-04-25 22:39:47 +00:00
|
|
|
// Sync Services
|
|
|
|
await syncServicesUpdateWebUser(updatedUser);
|
|
|
|
|
|
|
|
// Notify stripe about the change
|
|
|
|
if (updatedUser && updatedUser.metadata && hasKeyInMetadata(updatedUser, "stripeCustomerId")) {
|
|
|
|
const stripeCustomerId = `${updatedUser.metadata.stripeCustomerId}`;
|
|
|
|
await stripe.customers.update(stripeCustomerId, {
|
|
|
|
metadata: {
|
|
|
|
username: updatedUser.username,
|
|
|
|
email: updatedUser.email,
|
|
|
|
userId: updatedUser.id,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
// Revalidate booking pages
|
2023-06-16 16:08:58 +00:00
|
|
|
// Disabled because the booking pages are currently not using getStaticProps
|
|
|
|
/*const res = ctx.res as NextApiResponse;
|
2023-04-25 22:39:47 +00:00
|
|
|
if (typeof res?.revalidate !== "undefined") {
|
|
|
|
const eventTypes = await prisma.eventType.findMany({
|
|
|
|
where: {
|
|
|
|
userId: user.id,
|
|
|
|
team: null,
|
|
|
|
},
|
|
|
|
select: {
|
|
|
|
id: true,
|
|
|
|
slug: true,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
// waiting for this isn't needed
|
2023-06-16 16:08:58 +00:00
|
|
|
Promise.all(
|
|
|
|
eventTypes.map((eventType) => res?.revalidate(`/new-booker/${ctx.user.username}/${eventType.slug}`))
|
|
|
|
)
|
2023-04-25 22:39:47 +00:00
|
|
|
.then(() => console.info("Booking pages revalidated"))
|
|
|
|
.catch((e) => console.error(e));
|
2023-06-16 16:08:58 +00:00
|
|
|
}*/
|
2023-08-04 00:26:40 +00:00
|
|
|
return { ...input, signOutUser, passwordReset };
|
2023-04-25 22:39:47 +00:00
|
|
|
};
|
2023-08-16 00:27:48 +00:00
|
|
|
|
|
|
|
const cleanMetadataAllowedUpdateKeys = (metadata: TUpdateProfileInputSchema["metadata"]) => {
|
|
|
|
if (!metadata) {
|
2023-09-06 23:40:50 +00:00
|
|
|
return {};
|
2023-08-16 00:27:48 +00:00
|
|
|
}
|
|
|
|
const cleanedMetadata = updateUserMetadataAllowedKeys.safeParse(metadata);
|
|
|
|
if (!cleanedMetadata.success) {
|
|
|
|
logger.error("Error cleaning metadata", cleanedMetadata.error);
|
2023-09-06 23:40:50 +00:00
|
|
|
return {};
|
2023-08-16 00:27:48 +00:00
|
|
|
}
|
|
|
|
|
2023-09-06 23:40:50 +00:00
|
|
|
return cleanedMetadata.data;
|
|
|
|
};
|
|
|
|
|
|
|
|
const handleUserMetadata = ({ ctx, input }: UpdateProfileOptions) => {
|
|
|
|
const { user } = ctx;
|
|
|
|
const cleanMetadata = cleanMetadataAllowedUpdateKeys(input.metadata);
|
|
|
|
const userMetadata = userMetadataSchema.parse(user.metadata);
|
|
|
|
// Required so we don't override and delete saved values
|
|
|
|
return { ...userMetadata, ...cleanMetadata };
|
2023-08-16 00:27:48 +00:00
|
|
|
};
|