chore: Upgrade prisma to 6.7.0 (#21264)

* chore: Upgrade prisma to 6.7.0

* Build fixes

* type fixes

Signed-off-by: Omar López <[email protected]>

* Update schema.prisma

* Patching

* Revert "Update schema.prisma"

This reverts commit 47d8618bf89ef4d007b30084df766f17281e21a1.

* Revert "Patching"

This reverts commit a1d2e3040e71690a44d4324db95d73b4d68c6adb.

* Revert schema changes

Signed-off-by: Omar López <[email protected]>

* WIP

Signed-off-by: Omar López <[email protected]>

* Update getPublicEvent.ts

* Update imports

Signed-off-by: Omar López <[email protected]>

* Update gitignore

Signed-off-by: Omar López <[email protected]>

* update remaining imports

Signed-off-by: Omar López <[email protected]>

* Delete .cursor/config.json

* Discard changes to packages/features/eventtypes/lib/getPublicEvent.ts

* Update _get.ts

* Update user.ts

* Update .gitignore

* update

* Update WorkflowStepContainer.tsx

* Update next-auth-custom-adapter.ts

* Update getPublicEvent.ts

* Update workflow.ts

* Update next-auth-custom-adapter.ts

* Update next-auth-options.ts

* Update bookingScenario.ts

* fix missing imports

* upgrades prismock

Signed-off-by: Omar López <[email protected]>

* patches prismock

Signed-off-by: Omar López <[email protected]>

* Update reschedule.test.ts

* Update prisma.ts

* patch prismock

Signed-off-by: Omar López <[email protected]>

* fix enums imports

Signed-off-by: Omar López <[email protected]>

* Revert "Update prisma.ts"

This reverts commit 64edcf8db54171ff4456c209d563b5d431d99619.

* Revert "patch prismock"

This reverts commit e95819113dc9d88e7130947aa120cd42710977c8.

* fix patch

* Fix test that overrun the boundary, it shouldn't test too much

* Move prisma import to changeSMSLockState

* Bring back broken test without illegal imports

* Merge with main and fix filter hosts by same round robin host

* Fixed buildDryRunBooking fn tests

* Fix and move ooo create or update handler test

* Fix packages/features/eventtypes/lib/isCurrentlyAvailable.test.ts

* Fix packages/trpc/server/routers/viewer/organizations/listMembers.handler.test.ts

* Mock @calcom/prisma

* Fix: verify-email.test.ts

* fix: Moved WebhookService test and fixed default import mock

* Fix: Added missing prisma mock, handleNewBooking uses that of course

* We're not testing createContext here

* fix: Prisma mock fix for listMembers.test.ts

* More fixes to broken testcases

* Forgot to remove borked test

* Prevent the need to mock a lot of dependencies by moving out buildBaseWhereCondition to its own file

* Temporarily skip getCalendarEvents, needs a rewrite

* Fix: turns out you can access protected in testcases

* fix further mocks

* Added packages/features/insights/server/buildBaseWhereCondition.ts, types

* Always great to have a mock and then not use it

* And one less again.

* fix: confirm.handler.test, didn't mock prisma

* fix: Address minor nit by @eunjae & fix ImpersonationProvider test

* Updated isPrismaAvailableCheck that doesn't crash on import

* fix: Get Prisma directly from the client, it usually involves the Validator and does not need 'local' inclusion

* Add zod-prisma-types without the generator enabled (commented out)

* Uncomment and see what happens

* Change method of import as imports did not work in Input Schemas

* Remove custom 'zod' booking model, it does not belong with Prisma

* Fix all other global Model imports

* Rewrite most schema includes AND remove barrel file

* Add bookingCreateBodySchema to features/bookings

* Flurry of type fixes for compatibility with new zod gen

* Refactor out the custom prisma type createEventTypeInput

* Work around nullable eventTypeLocations

* HandlePayment type fix

* More fixes, final fix remaining is CompleteEventType

* Should fix a bunch more booking related type errors

* Missed one

* Some props missing from BookingCreateBodySchema

* Fix location type in handleChildrenEventTypes

* Little bit hacky imo but it works

* Final type error \o/

* Forgot to include Prisma

* Do not include zod-utils in booker/types

* Oops, was already including Booker/types

* Fix membership type, also disallow updating createdAt/updatedAt, make part of patch/post

* Fix api v1 type errors

* Fix EventTypeDescription typings

* Remove getParserWithGeneric, use userBodySchema with UserSchema

* use centralized timeZoneSchema

* Implement feedback by @zomars

* Couple of WIP pushes

* Fix tests

* Type fixes in `handleChildrenEventTypes` test

* Try and parse metadata before use

* Change zod-prisma-types configuration for optimal performance

* Fix prisma validator error in `prisma/selects/credential`

* Disable seperate relations model, hits a bug

* Import absolute - this makes rollup work in @platform/libraries

* Attempt at removing resolutions override

* Refactor using `Prisma.validator` to `satisfies`

* Build atoms using @calcom/prisma/client

* Build atoms using @calcom/prisma/client

* fixes

* Update eventTypeSelect.ts

* Adjust `eventTypeMetaDataSchemaWithUntypedApps` from `unknown` to `record(any)`

* `EventTypeDescription` rely on `descriptionAsSafeHTML` instead of `description`

* Add `seatsPerTimeSlot` to event type public select

* Fix typing in `users-public-view` getServerSide props

* Add missing `schedulingType` to prop

* chore: bump platform libraries

* Function return type is illegal, not sure how this passed eslint (#21567)

* Merged with main

* Update updateTokenObject.ts

* Update handleResponse.ts

* Update index.ts

* Update handleChildrenEventTypes.ts

* Update booking-idempotency-key.ts

* Update WebhookService.test.ts

* Update events.test.ts

* Update queued-response.test.ts

* Update events.test.ts

* Update getRoutedUrl.test.ts

* fix: type checks

Signed-off-by: Omar López <[email protected]>

* fixes

Signed-off-by: Omar López <[email protected]>

* chore: bump platform libraries

* Update yarn.lock

* more fixes

Signed-off-by: Omar López <[email protected]>

* fixes

Signed-off-by: Omar López <[email protected]>

* biuld fixes

* chore: bump platform libraries

* Update conferencing.repository.ts

* Update conferencing.repository.ts

* Update getCalendarsEvents.test.ts

* Update vite.config.js

* chore: bump platform libraries

* Update users.ts

* Discard changes to docs/api-reference/v2/openapi.json

* Update vite.config.ts

* updated platform libraries

* Update get.handler.test.ts

* Update get.handler.test.ts

* Update schema.prisma

* Discard changes to docs/api-reference/v2/openapi.json

* Update next-auth-custom-adapter.ts

* Update team.ts

* Flurry of type fixes

* Fix majority of insight related type errors

* Type fixes for unlink of account

* Make user nullable again

* Fixed a bunch of unit tests and one type error

* Attempted mock fix

* Attempted fix for Attribute type

* Ensure default import becomes prisma, but not direct usage

* Import default as prisma in prisma.module

* Add attributeOption to attribute type

* Fix calcom/prisma mock

* Refactor Prisma client imports to @calcom/prisma/client

Updated all imports from '@prisma/client' to '@calcom/prisma/client' across tests and repository files for consistency and to use the correct Prisma client package. This change improves maintainability and ensures the correct client is referenced throughout the codebase.

* Undo removal of max-warnings=0 to get main to merge

* Remove unit tests for e2e fixtures, provide new prisma mock

* Mock @calcom/prisma in event manager

* Mock @calcom/prisma in event manager

* Add correct format even with --no-verify

* Mock prisma in CalendarManager

* Add mock for permission-check.service

* Better injection in PrismaApiKeyRepository imports

* More mock fixes :)

* Fix listMembers.handler.test

* Fix User import

* Appropriately adjust all types to be imported as types, there were a lot of types imported as normal deps

* Why was this a thing?

* Strictly speaking; Not using prismock anymore

* Ditched patch file for prismock

* Fix output.service.ts platform type imports, need concrete for plainToClass

* Better typing and tests for unlinkConnectedAccount.handler

* Small type fix

* Disable calendar cache tests as they are dependent on prismock

* chore: bump platform lib

* getRoutedUrl test remove of unused import

* Extract select to external const on getEventTypesFromDB

* Direct select of userSelect from selects/user

* fix type error from merging 23653

* Fixed integration tests by removing hardcoded values that were possible due to mocking, but as its now directly hitting the db no longer

* fix: vite config atoms prisma client type location

* revert: example app prisma client

* revert: example app prisma client

* bump platform libs

* fix: use class instead of type for DI of PlatformBookingsService

* update platform libs

* remove unused variable

* chore: generate prisma client for api v2

* fix: api v2 e2e

* fix: atoms e2e

* fix: atoms e2e

* fix: atoms e2e

* fix: api v2 e2e

* fix: tsconfig apiv2 enums

* publish libraries

* Simplify check for existence teamId

---------

Signed-off-by: Omar López <[email protected]>
Co-authored-by: Alex van Andel <[email protected]>
Co-authored-by: Joe Au-Yeung <[email protected]>
Co-authored-by: supalarry <[email protected]>
Co-authored-by: cal.com <[email protected]>
Co-authored-by: Morgan <[email protected]>
Co-authored-by: Benny Joo <[email protected]>
This commit is contained in:
authored and GitHub committed 2025-09-11 15:27:50 +01:00
1 parent a55d56f260
commit c28eb90928
623 files changed
+4363 -12559

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
import type { Prisma } from "@prisma/client";
import type { TFunction } from "i18next";
import type { TimeFormat } from "@calcom/lib/timeFormat";
import type { Prisma } from "@calcom/prisma/client";
import type { SchedulingType } from "@calcom/prisma/enums";
import type { CalendarEvent, Person, CalEventResponses, AppsStatus } from "@calcom/types/Calendar";
import type { VideoCallData } from "@calcom/types/VideoApiAdapter";
@@ -1,12 +1,12 @@
"use client";
import { useAutoAnimate } from "@formkit/auto-animate/react";
import type { AppCategories } from "@prisma/client";
import type { UIEvent } from "react";
import { useEffect, useRef, useState } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { UserAdminTeams } from "@calcom/lib/server/repository/user";
import type { AppCategories } from "@calcom/prisma/client";
import type { AppFrontendPayload as App } from "@calcom/types/App";
import type { CredentialFrontendPayload as Credential } from "@calcom/types/Credential";
import classNames from "@calcom/ui/classNames";
@@ -1,6 +1,6 @@
"use client";
import type { User } from "@prisma/client";
import type { User } from "@calcom/prisma/client";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
@@ -1,7 +0,0 @@
import { IdentityProvider } from "@calcom/prisma/enums";
export const identityProviderNameMap: { [key in IdentityProvider]: string } = {
[IdentityProvider.CAL]: "Cal",
[IdentityProvider.GOOGLE]: "Google",
[IdentityProvider.SAML]: "SAML",
};
@@ -1,87 +1,137 @@
import type { Account, IdentityProvider, User, VerificationToken } from "@prisma/client";
import { Prisma } from "@prisma/client";
import type { Awaitable } from "next-auth";
import type { Adapter, AdapterUser, AdapterAccount } from "next-auth/adapters";
import type { PrismaClient } from "@calcom/prisma";
import { Prisma } from "@calcom/prisma/client";
import type { Account, IdentityProvider, User } from "@calcom/prisma/client";
import { identityProviderNameMap } from "./identityProviderNameMap";
type CalComAdapter = {
createUser: (data: Prisma.UserCreateInput) => Awaitable<User>;
getUser: (id: string | number) => Awaitable<User | null>;
getUserByEmail: (email: User["email"]) => Awaitable<User | null>;
getUserByAccount: (provider_providerAccountId: {
providerAccountId: Account["providerAccountId"];
provider: User["identityProvider"];
}) => Awaitable<User | null>;
updateUser: (data: Prisma.UserUncheckedCreateInput) => Awaitable<User>;
deleteUser: (id: User["id"]) => Awaitable<User>;
createVerificationToken: (data: VerificationToken) => Awaitable<Omit<VerificationToken, "id">>;
useVerificationToken: (
identifier_token: Prisma.VerificationTokenIdentifierTokenCompoundUniqueInput
) => Awaitable<Omit<VerificationToken, "id"> | null>;
linkAccount: (data: Prisma.AccountCreateInput) => Awaitable<Account>;
unlinkAccount: (
provider_providerAccountId: Prisma.AccountProviderProviderAccountIdCompoundUniqueInput
) => Awaitable<Account>;
const parseIntSafe = (id: string | number): number => {
if (typeof id === "number") return id;
const parsed = parseInt(id, 10);
if (isNaN(parsed)) throw new Error(`Invalid ID format: ${id}`);
return parsed;
};
/** @return { import("next-auth/adapters").Adapter } */
export default function CalComAdapter(prismaClient: PrismaClient): CalComAdapter {
// Simple utility functions for transformations
const toAdapterUser = (user: User): AdapterUser => ({
id: user.id.toString(),
name: user.name,
email: user.email,
emailVerified: user.emailVerified,
image: user.avatarUrl,
});
const toAdapterAccount = (account: Account): AdapterAccount => ({
userId: account.userId.toString(),
type: account.type as AdapterAccount["type"],
provider: account.provider,
providerAccountId: account.providerAccountId,
refresh_token: account.refresh_token ?? undefined,
access_token: account.access_token ?? undefined,
expires_at: account.expires_at ?? undefined,
token_type: account.token_type ?? undefined,
scope: account.scope ?? undefined,
id_token: account.id_token ?? undefined,
session_state: account.session_state ?? undefined,
});
const createUserData = (data: Omit<AdapterUser, "id">): Prisma.UserCreateInput => ({
name: data.name || null,
email: data.email,
emailVerified: data.emailVerified || null,
avatarUrl: data.image || null,
});
const createAccountData = (account: AdapterAccount): Prisma.AccountCreateInput => ({
provider: account.provider,
providerAccountId: account.providerAccountId,
type: account.type,
user: { connect: { id: parseIntSafe(account.userId) } },
access_token: account.access_token,
refresh_token: account.refresh_token,
expires_at: account.expires_at,
token_type: account.token_type,
scope: account.scope,
id_token: account.id_token,
session_state: account.session_state,
});
const getAccountWhere = (provider: string, providerAccountId: string) => ({
provider_providerAccountId: { provider, providerAccountId },
});
export default function CalComAdapter(prismaClient: PrismaClient): Adapter {
return {
createUser: (data: Prisma.UserCreateInput) => prismaClient.user.create({ data }),
getUser: (id: string | number) =>
prismaClient.user.findUnique({ where: { id: typeof id === "string" ? parseInt(id) : id } }),
getUserByEmail: (email: User["email"]) => prismaClient.user.findUnique({ where: { email } }),
async getUserByAccount(provider_providerAccountId: {
providerAccountId: Account["providerAccountId"];
provider: User["identityProvider"];
}) {
let _account;
createUser: async (data) => {
const user = await prismaClient.user.create({ data: createUserData(data) });
return toAdapterUser(user);
},
getUser: async (id) => {
const user = await prismaClient.user.findUnique({ where: { id: parseIntSafe(id) } });
return user ? toAdapterUser(user) : null;
},
getUserByEmail: async (email) => {
const user = await prismaClient.user.findUnique({ where: { email } });
return user ? toAdapterUser(user) : null;
},
async getUserByAccount(providerAccountId) {
const account = await prismaClient.account.findUnique({
where: {
provider_providerAccountId,
},
where: getAccountWhere(providerAccountId.provider, providerAccountId.providerAccountId),
select: { user: true },
});
if (account) {
return (_account = account === null || account === void 0 ? void 0 : account.user) !== null &&
_account !== void 0
? _account
: null;
if (account?.user) {
return toAdapterUser(account.user);
}
// NOTE: this code it's our fallback to users without Account but credentials in User Table
// We should remove this code after all googles tokens have expired
const provider = provider_providerAccountId?.provider.toUpperCase() as IdentityProvider;
if (["GOOGLE", "SAML"].indexOf(provider) < 0) {
return null;
}
const obtainProvider = identityProviderNameMap[provider].toUpperCase() as IdentityProvider;
// Fallback for legacy users without Account entries
const provider = providerAccountId.provider.toUpperCase();
const isGoogleOrSaml = (p: string): p is Extract<IdentityProvider, "GOOGLE" | "SAML"> =>
["GOOGLE", "SAML"].includes(p);
if (!isGoogleOrSaml(provider)) return null;
const user = await prismaClient.user.findFirst({
where: {
identityProviderId: provider_providerAccountId?.providerAccountId,
identityProvider: obtainProvider,
identityProviderId: providerAccountId.providerAccountId,
identityProvider: provider,
},
});
return user || null;
return user ? toAdapterUser(user) : null;
},
updateUser: ({ id, ...data }: Prisma.UserUncheckedCreateInput) =>
prismaClient.user.update({ where: { id }, data }),
deleteUser: (id: User["id"]) => prismaClient.user.delete({ where: { id } }),
async createVerificationToken(data: VerificationToken) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { id: _, ...verificationToken } = await prismaClient.verificationToken.create({
data,
updateUser: async (userData) => {
const { id, ...data } = userData;
const user = await prismaClient.user.update({
where: { id: parseIntSafe(id) },
data: {
name: data.name,
email: data.email,
emailVerified: data.emailVerified,
avatarUrl: data.image,
},
});
return toAdapterUser(user);
},
deleteUser: async (userId) => {
const user = await prismaClient.user.delete({ where: { id: parseIntSafe(userId) } });
return toAdapterUser(user);
},
createVerificationToken: async (data) => {
const token = await prismaClient.verificationToken.create({ data });
const { id, ...verificationToken } = token;
return verificationToken;
},
async useVerificationToken(identifier_token: Prisma.VerificationTokenIdentifierTokenCompoundUniqueInput) {
useVerificationToken: async (identifier_token) => {
try {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { id: _, ...verificationToken } = await prismaClient.verificationToken.delete({
where: { identifier_token },
});
const token = await prismaClient.verificationToken.delete({ where: { identifier_token } });
const { id, ...verificationToken } = token;
return verificationToken;
} catch (error) {
// If token already used/deleted, just return null
@@ -92,8 +142,28 @@ export default function CalComAdapter(prismaClient: PrismaClient): CalComAdapter
throw error;
}
},
linkAccount: (data: Prisma.AccountCreateInput) => prismaClient.account.create({ data }),
unlinkAccount: (provider_providerAccountId: Prisma.AccountProviderProviderAccountIdCompoundUniqueInput) =>
prismaClient.account.delete({ where: { provider_providerAccountId } }),
};
linkAccount: async (account) => {
const createdAccount = await prismaClient.account.create({ data: createAccountData(account) });
return toAdapterAccount(createdAccount);
},
unlinkAccount: async (providerAccountId) => {
const deletedAccount = await prismaClient.account.delete({
where: getAccountWhere(providerAccountId.provider, providerAccountId.providerAccountId),
});
return toAdapterAccount(deletedAccount);
},
createSession: async (session) => session,
getSessionAndUser: async () => null,
updateSession: async (session) => ({
sessionToken: session.sessionToken || "",
userId: session.userId || "",
expires: session.expires || new Date(),
}),
deleteSession: async () => {
// No-op implementation for minimal session support
},
} satisfies Adapter;
}
+73 -25
View File
@@ -1,8 +1,7 @@
import { calendar_v3 } from "@googleapis/calendar";
import type { Membership, Team, UserPermissionRole } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import { OAuth2Client } from "googleapis-common";
import type { AuthOptions, Session, User } from "next-auth";
import type { AuthOptions, Account, Session, User } from "next-auth";
import type { JWT } from "next-auth/jwt";
import { encode } from "next-auth/jwt";
import type { Provider } from "next-auth/providers";
@@ -39,6 +38,7 @@ import { ProfileRepository } from "@calcom/lib/server/repository/profile";
import { UserRepository } from "@calcom/lib/server/repository/user";
import slugify from "@calcom/lib/slugify";
import prisma from "@calcom/prisma";
import type { Membership, Team, UserPermissionRole } from "@calcom/prisma/client";
import { CreationSource } from "@calcom/prisma/enums";
import { IdentityProvider, MembershipRole } from "@calcom/prisma/enums";
import { teamMetadataSchema, userMetadata } from "@calcom/prisma/zod-utils";
@@ -50,6 +50,40 @@ import { isPasswordValid } from "./isPasswordValid";
import CalComAdapter from "./next-auth-custom-adapter";
import { verifyPassword } from "./verifyPassword";
type UserWithProfiles = NonNullable<
Awaited<ReturnType<UserRepository["findByEmailAndIncludeProfilesAndPassword"]>>
>;
// This adapts our internal user model to what NextAuth expects
// NextAuth core requires id to be a string, so we handle that here
const AdapterUserPresenter = {
fromCalUser: (
user: UserWithProfiles,
role: UserPermissionRole | "INACTIVE_ADMIN",
hasActiveTeams: boolean
) => ({
...user,
role: role as UserPermissionRole,
belongsToActiveTeam: hasActiveTeams,
profile: user.allProfiles[0],
}),
};
// Account presenter to handle linkAccount calls
const AdapterAccountPresenter = {
fromCalAccount: (account: Account, userId: number, providerEmail: string) => {
return {
...account,
userId: String(userId), // Convert userId to string for Next Auth
providerEmail,
// Ensure these required fields are present
provider: account.provider,
providerAccountId: account.providerAccountId,
type: account.type,
};
},
};
const log = logger.getSubLogger({ prefix: ["next-auth-options"] });
const GOOGLE_API_CREDENTIALS = process.env.GOOGLE_API_CREDENTIALS || "{}";
const { client_id: GOOGLE_CLIENT_ID, client_secret: GOOGLE_CLIENT_SECRET } =
@@ -110,7 +144,7 @@ const providers: Provider[] = [
totpCode: { label: "Two-factor Code", type: "input", placeholder: "Code from authenticator app" },
backupCode: { label: "Backup Code", type: "input", placeholder: "Two-factor backup code" },
},
async authorize(credentials) {
async authorize(credentials): Promise<User | null> {
log.debug("CredentialsProvider:credentials:authorize", safeStringify({ credentials }));
if (!credentials) {
console.error(`For some reason credentials are missing`);
@@ -232,17 +266,8 @@ const providers: Provider[] = [
return "INACTIVE_ADMIN";
};
return {
id: user.id,
username: user.username,
email: user.email,
name: user.name,
role: validateRole(user.role),
belongsToActiveTeam: hasActiveTeams,
locale: user.locale,
profile: user.allProfiles[0],
createdDate: user.createdDate,
};
// Create a NextAuth compatible user object using our presenter
return AdapterUserPresenter.fromCalUser(user, validateRole(user.role), hasActiveTeams);
},
}),
ImpersonationProvider,
@@ -505,7 +530,12 @@ export const getOptions = ({
movedToProfileId: true,
teams: {
include: {
team: true,
team: {
select: {
id: true,
metadata: true,
},
},
},
},
},
@@ -739,7 +769,7 @@ export const getOptions = ({
};
return calendsoSession;
},
async signIn(params) {
async signIn(params): Promise<boolean | string> {
const {
/**
* Available when Credentials provider is used - Has the value returned by authorize callback
@@ -789,6 +819,11 @@ export const getOptions = ({
let existingUser = await prisma.user.findFirst({
include: {
password: {
select: {
hash: true,
},
},
accounts: {
where: {
provider: account.provider,
@@ -805,6 +840,11 @@ export const getOptions = ({
if (!existingUser) {
existingUser = await prisma.user.findFirst({
include: {
password: {
select: {
hash: true,
},
},
accounts: {
where: {
provider: account.provider,
@@ -835,11 +875,11 @@ export const getOptions = ({
try {
// If old user without Account entry we link their google account
if (existingUser.accounts.length === 0) {
const linkAccountWithUserData = {
...account,
userId: existingUser.id,
providerEmail: user.email,
};
const linkAccountWithUserData = AdapterAccountPresenter.fromCalAccount(
account,
existingUser.id,
user.email
);
await calcomAdapter.linkAccount(linkAccountWithUserData);
}
} catch (error) {
@@ -885,7 +925,11 @@ export const getOptions = ({
},
},
include: {
password: true,
password: {
select: {
hash: true,
},
},
},
});
@@ -1003,7 +1047,11 @@ export const getOptions = ({
creationSource: CreationSource.WEBAPP,
},
});
const linkAccountNewUserData = { ...account, userId: newUser.id, providerEmail: user.email };
const linkAccountNewUserData = AdapterAccountPresenter.fromCalAccount(
account,
newUser.id,
user.email
);
await calcomAdapter.linkAccount(linkAccountNewUserData);
if (account.twoFactorEnabled) {
@@ -1042,7 +1090,7 @@ export const getOptions = ({
createdDate: string;
};
// check if the user was created in the last 10 minutes
// this is a workaround – in the future once we move to use the Account model in the DB
// this is a workaround – in the future once we move to use the Account model in the DB
// we should use NextAuth's isNewUser flag instead: https://next-auth.js.org/configuration/events#signin
const isNewUser = new Date(user.createdDate) > new Date(Date.now() - 10 * 60 * 1000);
if ((isENVDev || IS_CALCOM) && isNewUser) {
@@ -1050,7 +1098,7 @@ export const getOptions = ({
const clickId = getDubId();
// check if there's a clickId (dub_id) cookie set by @dub/analytics
if (clickId) {
// here we use waitUntil – meaning this code will run async to not block the main thread
// here we use waitUntil – meaning this code will run async to not block the main thread
waitUntil(
// if so, send a lead event to Dub
// @see https://d.to/conversions/next-auth
@@ -1,8 +1,7 @@
import type { User } from "@prisma/client";
import dayjs from "@calcom/dayjs";
import { getTranslation } from "@calcom/lib/server/i18n";
import prisma from "@calcom/prisma";
import type { User } from "@calcom/prisma/client";
export const PASSWORD_RESET_EXPIRY_HOURS = 6;
@@ -1,9 +1,9 @@
import type { Prisma } from "@prisma/client";
import fetch from "node-fetch";
import { uploadAvatar } from "@calcom/lib/server/avatar";
import { resizeBase64Image } from "@calcom/lib/server/resizeBase64Image";
import prisma from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
interface IPrefillAvatar {
email: string;
+2 -2
View File
@@ -10,7 +10,6 @@ import type { UseVerifyEmailReturnType } from "@calcom/features/bookings/Booker/
import type { useScheduleForEventReturnType } from "@calcom/features/bookings/Booker/utils/event";
import type { BookerEventQuery } from "@calcom/features/bookings/types";
import type { IntlSupportedTimeZones } from "@calcom/lib/timeZones";
import type { BookerLayouts } from "@calcom/prisma/zod-utils";
import type { GetBookingType } from "../lib/get-booking";
@@ -151,9 +150,10 @@ export type WrappedBookerPropsForWeb = WrappedBookerPropsMain & {
};
export type WrappedBookerProps = WrappedBookerPropsForPlatform | WrappedBookerPropsForWeb;
export type VIEW_TYPE = "MONTH_VIEW" | "WEEK_VIEW" | "COLUMN_VIEW";
export type BookerState = "loading" | "selecting_date" | "selecting_time" | "booking";
export type BookerLayout = BookerLayouts | "mobile";
export type BookerLayout = "month_view" | "week_view" | "column_view" | "mobile";
export type BookerAreas = "calendar" | "timeslots" | "main" | "meta" | "header";
export type CustomClassNames = {
@@ -0,0 +1,104 @@
// `responses` is merged with it during handleNewBooking call because `responses` schema is dynamic and depends on eventType
import z from "zod";
import { routingFormResponseInDbSchema } from "@calcom/app-store/routing-forms/zod";
import { timeZoneSchema } from "@calcom/lib/dayjs/timeZone.schema";
import { CreationSource } from "@calcom/prisma/enums";
export const bookingCreateBodySchema = z.object({
end: z.string().optional(),
eventTypeId: z.number(),
eventTypeSlug: z.string().optional(),
rescheduleUid: z.string().optional(),
recurringEventId: z.string().optional(),
rescheduledBy: z.string().email({ message: "Invalid email" }).optional(),
start: z.string(),
timeZone: timeZoneSchema,
user: z.union([z.string(), z.array(z.string())]).optional(),
language: z.string(),
bookingUid: z.string().optional(),
metadata: z.record(z.string()),
hasHashedBookingLink: z.boolean().optional(),
hashedLink: z.string().nullish(),
seatReferenceUid: z.string().optional(),
orgSlug: z.string().optional(),
teamMemberEmail: z.string().nullish(),
crmOwnerRecordType: z.string().nullish(),
crmRecordId: z.string().nullish(),
routedTeamMemberIds: z.array(z.number()).nullish(),
routingFormResponseId: z.number().optional(),
skipContactOwner: z.boolean().optional(),
crmAppSlug: z.string().nullish().optional(),
cfToken: z.string().nullish().optional(),
/**
* Holds the corrected responses of the Form for a booking, provided during rerouting
*/
reroutingFormResponses: routingFormResponseInDbSchema.optional(),
/**
* Used to identify if the booking is a dry run.
*/
_isDryRun: z.boolean().optional(),
/** Whether to override the cache */
_shouldServeCache: z.boolean().optional(),
tracking: z
.object({
utm_source: z.string().optional(),
utm_medium: z.string().optional(),
utm_campaign: z.string().optional(),
utm_term: z.string().optional(),
utm_content: z.string().optional(),
})
.optional(),
dub_id: z.string().nullish(),
creationSource: z.nativeEnum(CreationSource).optional(),
});
export type BookingCreateBody = z.input<typeof bookingCreateBodySchema>;
export const extendedBookingCreateBody = bookingCreateBodySchema.merge(
z.object({
noEmail: z.boolean().optional(),
recurringCount: z.number().optional(),
allRecurringDates: z
.array(
z.object({
start: z.string(),
end: z.string(),
})
)
.optional(),
currentRecurringIndex: z.number().optional(),
appsStatus: z
.array(
z.object({
appName: z.string(),
success: z.number(),
failures: z.number(),
type: z.string(),
errors: z.string().array(),
warnings: z.string().array().optional(),
})
)
.optional(),
luckyUsers: z.array(z.number()).optional(),
customInputs: z.undefined().optional(),
})
);
// It has only the legacy props that are part of `responses` now. The API can still hit old props
export const bookingCreateSchemaLegacyPropsForApi = z.object({
email: z.string(),
name: z.string(),
guests: z.array(z.string()).optional(),
notes: z.string().optional(),
location: z.string(),
smsReminderNumber: z.string().optional().nullable(),
rescheduleReason: z.string().optional(),
customInputs: z.array(z.object({ label: z.string(), value: z.union([z.string(), z.boolean()]) })),
});
// This is the schema that is used for the API. It has all the legacy props that are part of `responses` now.
export const bookingCreateBodySchemaForApi = extendedBookingCreateBody.merge(
bookingCreateSchemaLegacyPropsForApi.partial()
);
@@ -1,10 +1,10 @@
import type { Prisma } from "@prisma/client";
import type { z } from "zod";
import { bookingResponsesDbSchema } from "@calcom/features/bookings/lib/getBookingResponsesSchema";
import slugify from "@calcom/lib/slugify";
import type { PrismaClient } from "@calcom/prisma";
import prisma from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
type BookingSelect = {
description: true;
@@ -101,7 +101,7 @@ async function getBooking(prisma: PrismaClient, uid: string, isSeatedEvent?: boo
return booking;
}
export type GetBookingType = Prisma.PromiseReturnType<typeof getBooking>;
export type GetBookingType = Awaited<ReturnType<typeof getBooking>>;
export const getBookingWithResponses = <
T extends Prisma.BookingGetPayload<{
@@ -1,7 +1,6 @@
import { z } from "zod";
import { extendedBookingCreateBody } from "@calcom/prisma/zod/custom/booking";
import { extendedBookingCreateBody } from "./bookingCreateBodySchema";
import type { getBookingFieldsWithSystemFields } from "./getBookingFields";
import getBookingResponsesSchema from "./getBookingResponsesSchema";
@@ -3,8 +3,7 @@ import { z } from "zod";
import {
bookingCreateBodySchemaForApi,
bookingCreateSchemaLegacyPropsForApi,
} from "@calcom/prisma/zod/custom/booking";
} from "./bookingCreateBodySchema";
import type { getBookingFieldsWithSystemFields } from "./getBookingFields";
import getBookingResponsesSchema from "./getBookingResponsesSchema";
@@ -1,4 +1,3 @@
import type { EventTypeCustomInput, EventType } from "@prisma/client";
import type { z } from "zod";
import {
@@ -10,6 +9,7 @@ import { fieldsThatSupportLabelAsSafeHtml } from "@calcom/features/form-builder/
import { getFieldIdentifier } from "@calcom/features/form-builder/utils/getFieldIdentifier";
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
import slugify from "@calcom/lib/slugify";
import type { EventTypeCustomInput, EventType } from "@calcom/prisma/client";
import { EventTypeCustomInputType } from "@calcom/prisma/enums";
import {
BookingFieldTypeEnum,
@@ -1,4 +1,3 @@
import type { EventType, Prisma } from "@prisma/client";
import type z from "zod";
import { SystemField } from "@calcom/features/bookings/lib/SystemField";
@@ -7,6 +6,7 @@ import { contructEmailFromPhoneNumber } from "@calcom/lib/contructEmailFromPhone
import { getBookingWithResponses } from "@calcom/lib/getBooking";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import type { EventType, Prisma } from "@calcom/prisma/client";
import { eventTypeBookingFields } from "@calcom/prisma/zod-utils";
import type { CalendarEvent } from "@calcom/types/Calendar";
@@ -1,4 +1,3 @@
import type { Prisma } from "@prisma/client";
import type { TFunction } from "i18next";
import { createEvent } from "ics";
import { RRule } from "rrule";
@@ -6,6 +5,7 @@ import type { z } from "zod";
import type { Dayjs } from "@calcom/dayjs";
import dayjs from "@calcom/dayjs";
import type { Prisma } from "@calcom/prisma/client";
import type { nameObjectSchema } from "@calcom/features/eventtypes/lib/eventNaming";
import { getEventName } from "@calcom/features/eventtypes/lib/eventNaming";
import { bookingMetadataSchema } from "@calcom/prisma/zod-utils";
@@ -1,5 +1,3 @@
import type { Prisma } from "@prisma/client";
import { sendAttendeeRequestEmailAndSMS, sendOrganizerRequestEmail } from "@calcom/emails";
import { getWebhookPayloadForBooking } from "@calcom/features/bookings/lib/getWebhookPayloadForBooking";
import type { Workflow } from "@calcom/features/ee/workflows/lib/types";
@@ -9,6 +7,7 @@ import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { WorkflowService } from "@calcom/lib/server/service/workflows";
import type { Prisma } from "@calcom/prisma/client";
import { WebhookTriggerEvents, WorkflowTriggerEvents } from "@calcom/prisma/enums";
import type { EventTypeMetadata } from "@calcom/prisma/zod-utils";
import { getAllWorkflowsFromEventType } from "@calcom/trpc/server/routers/viewer/workflows/util";
@@ -1,4 +1,3 @@
import type { Prisma, WorkflowReminder } from "@prisma/client";
import type { z } from "zod";
import { DailyLocationType } from "@calcom/app-store/constants";
@@ -30,6 +29,7 @@ import { getTranslation } from "@calcom/lib/server/i18n";
import { WorkflowRepository } from "@calcom/lib/server/repository/workflow";
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
import prisma from "@calcom/prisma";
import type { Prisma, WorkflowReminder } from "@calcom/prisma/client";
import type { WebhookTriggerEvents } from "@calcom/prisma/enums";
import { BookingStatus } from "@calcom/prisma/enums";
import {
@@ -1,5 +1,3 @@
import type { Prisma } from "@prisma/client";
import { scheduleMandatoryReminder } from "@calcom/ee/workflows/lib/reminders/scheduleMandatoryReminder";
import { sendScheduledEmailsAndSMS } from "@calcom/emails";
import {
@@ -21,6 +19,7 @@ import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { WorkflowService } from "@calcom/lib/server/service/workflows";
import type { PrismaClient } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import type { SchedulingType } from "@calcom/prisma/enums";
import { BookingStatus, WebhookTriggerEvents, WorkflowTriggerEvents } from "@calcom/prisma/enums";
import type { PlatformClientParams } from "@calcom/prisma/zod-utils";
@@ -1,4 +1,3 @@
import type { DestinationCalendar, User } from "@prisma/client";
// eslint-disable-next-line no-restricted-imports
import short, { uuid } from "short-uuid";
import { v5 as uuidv5 } from "uuid";
@@ -67,15 +66,15 @@ import { HashedLinkService } from "@calcom/lib/server/service/hashedLinkService"
import { WorkflowService } from "@calcom/lib/server/service/workflows";
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
import type { PrismaClient } from "@calcom/prisma";
import prisma from "@calcom/prisma";
import type { AssignmentReasonEnum } from "@calcom/prisma/enums";
import { prisma } from "@calcom/prisma";
import type { DestinationCalendar, Prisma, User, AssignmentReasonEnum } from "@calcom/prisma/client";
import {
BookingStatus,
SchedulingType,
WebhookTriggerEvents,
WorkflowTriggerEvents,
CreationSource,
} from "@calcom/prisma/enums";
import { CreationSource } from "@calcom/prisma/enums";
import {
eventTypeAppMetadataOptionalSchema,
eventTypeMetaDataSchemaWithTypedApps,
@@ -99,8 +98,8 @@ import getBookingDataSchema from "./getBookingDataSchema";
import { addVideoCallDataToEvent } from "./handleNewBooking/addVideoCallDataToEvent";
import { checkActiveBookingsLimitForBooker } from "./handleNewBooking/checkActiveBookingsLimitForBooker";
import { checkIfBookerEmailIsBlocked } from "./handleNewBooking/checkIfBookerEmailIsBlocked";
import { createBooking } from "./handleNewBooking/createBooking";
import type { Booking } from "./handleNewBooking/createBooking";
import { createBooking } from "./handleNewBooking/createBooking";
import { ensureAvailableUsers } from "./handleNewBooking/ensureAvailableUsers";
import { getBookingData } from "./handleNewBooking/getBookingData";
import { getCustomInputsResponses } from "./handleNewBooking/getCustomInputsResponses";
@@ -113,8 +112,8 @@ import { getVideoCallDetails } from "./handleNewBooking/getVideoCallDetails";
import { handleAppsStatus } from "./handleNewBooking/handleAppsStatus";
import { loadAndValidateUsers } from "./handleNewBooking/loadAndValidateUsers";
import { createLoggerWithEventDetails } from "./handleNewBooking/logger";
import { getOriginalRescheduledBooking } from "./handleNewBooking/originalRescheduledBookingUtils";
import type { BookingType } from "./handleNewBooking/originalRescheduledBookingUtils";
import { getOriginalRescheduledBooking } from "./handleNewBooking/originalRescheduledBookingUtils";
import { scheduleNoShowTriggers } from "./handleNewBooking/scheduleNoShowTriggers";
import type { IEventTypePaymentCredentialType, Invitee, IsFixedAwareUser } from "./handleNewBooking/types";
import { validateBookingTimeIsNotOutOfBounds } from "./handleNewBooking/validateBookingTimeIsNotOutOfBounds";
@@ -2070,7 +2069,15 @@ async function handler(
if (!booking.user) booking.user = organizerUser;
const payment = await handlePayment({
evt,
selectedEventType: eventType,
selectedEventType: {
...eventType,
metadata: eventType.metadata
? {
...eventType.metadata,
apps: eventType.metadata?.apps as Prisma.JsonValue,
}
: {},
},
paymentAppCredentials: eventTypePaymentAppCredential as IEventTypePaymentCredentialType,
booking,
bookerName: fullName,
@@ -1,4 +1,3 @@
import { Prisma } from "@prisma/client";
import type short from "short-uuid";
import type { z } from "zod";
@@ -7,6 +6,7 @@ import dayjs from "@calcom/dayjs";
import { isPrismaObjOrUndefined } from "@calcom/lib/isPrismaObj";
import { withReporting } from "@calcom/lib/sentryWrapper";
import prisma from "@calcom/prisma";
import { Prisma } from "@calcom/prisma/client";
import { BookingStatus } from "@calcom/prisma/enums";
import type { CreationSource } from "@calcom/prisma/enums";
import type { CalendarEvent } from "@calcom/types/Calendar";
@@ -344,4 +344,4 @@ function buildNewBookingData(params: CreateBookingParams) {
}
}
export type Booking = Prisma.PromiseReturnType<typeof createBooking>;
export type Booking = Awaited<ReturnType<typeof createBooking>>;
@@ -1,12 +1,12 @@
import type { EventTypeCustomInput } from "@prisma/client";
import type z from "zod";
import dayjs from "@calcom/dayjs";
import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventResponses";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { withReporting } from "@calcom/lib/sentryWrapper";
import { bookingCreateSchemaLegacyPropsForApi } from "@calcom/prisma/zod/custom/booking";
import type { EventTypeCustomInput } from "@calcom/prisma/client";
import { bookingCreateSchemaLegacyPropsForApi } from "../bookingCreateBodySchema";
import type { TgetBookingDataSchema } from "../getBookingDataSchema";
import type { getEventTypeResponse } from "./getEventTypesFromDB";
import { handleCustomInputs } from "./handleCustomInputs";
@@ -1,9 +1,9 @@
import type z from "zod";
import { slugify } from "@calcom/lib/slugify";
import type { bookingCreateSchemaLegacyPropsForApi } from "@calcom/prisma/zod/custom/booking";
import type { CalendarEvent } from "@calcom/types/Calendar";
import type { bookingCreateSchemaLegacyPropsForApi } from "../bookingCreateBodySchema";
import type { getEventTypeResponse } from "./getEventTypesFromDB";
type CustomInputs = z.infer<typeof bookingCreateSchemaLegacyPropsForApi>["customInputs"];
@@ -5,222 +5,219 @@ import type { DefaultEvent } from "@calcom/lib/defaultEvents";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { parseRecurringEvent } from "@calcom/lib/isRecurringEvent";
import { withSelectedCalendars } from "@calcom/lib/server/repository/user";
import prisma, { userSelect } from "@calcom/prisma";
import { prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import { userSelect } from "@calcom/prisma/selects/user";
import {
EventTypeMetaDataSchema,
customInputSchema,
rrSegmentQueryValueSchema,
} from "@calcom/prisma/zod-utils";
const getEventTypesFromDBSelect = {
id: true,
customInputs: true,
disableGuests: true,
restrictionScheduleId: true,
useBookerTimezone: true,
disableRescheduling: true,
disableCancelling: true,
users: {
select: {
credentials: {
select: credentialForCalendarServiceSelect,
},
...userSelect,
},
},
slug: true,
profile: {
select: {
organizationId: true,
},
},
teamId: true,
team: {
select: {
id: true,
name: true,
parentId: true,
bookingLimits: true,
includeManagedEventsInLimits: true,
rrResetInterval: true,
rrTimestampBasis: true,
},
},
bookingFields: true,
title: true,
length: true,
eventName: true,
schedulingType: true,
description: true,
periodType: true,
periodStartDate: true,
periodEndDate: true,
periodDays: true,
periodCountCalendarDays: true,
lockTimeZoneToggleOnBookingPage: true,
lockedTimeZone: true,
requiresConfirmation: true,
requiresConfirmationForFreeEmail: true,
requiresBookerEmailVerification: true,
maxLeadThreshold: true,
includeNoShowInRRCalculation: true,
minimumBookingNotice: true,
maxActiveBookingsPerBooker: true,
maxActiveBookingPerBookerOfferReschedule: true,
userId: true,
price: true,
currency: true,
metadata: true,
destinationCalendar: true,
hideCalendarNotes: true,
hideCalendarEventDetails: true,
hideOrganizerEmail: true,
seatsPerTimeSlot: true,
recurringEvent: true,
seatsShowAttendees: true,
seatsShowAvailabilityCount: true,
bookingLimits: true,
durationLimits: true,
rescheduleWithSameRoundRobinHost: true,
assignAllTeamMembers: true,
isRRWeightsEnabled: true,
beforeEventBuffer: true,
customReplyToEmail: true,
afterEventBuffer: true,
parentId: true,
parent: {
select: {
teamId: true,
team: {
select: {
id: true,
bookingLimits: true,
includeManagedEventsInLimits: true,
},
},
},
},
useEventTypeDestinationCalendarEmail: true,
owner: {
select: {
hideBranding: true,
},
},
workflows: {
select: {
workflow: {
select: workflowSelect,
},
},
},
locations: true,
timeZone: true,
schedule: {
select: {
id: true,
availability: true,
timeZone: true,
},
},
hosts: {
select: {
isFixed: true,
priority: true,
weight: true,
createdAt: true,
groupId: true,
user: {
select: {
credentials: {
select: credentialForCalendarServiceSelect,
},
...userSelect,
},
},
schedule: {
select: {
availability: {
select: {
date: true,
startTime: true,
endTime: true,
days: true,
},
},
timeZone: true,
id: true,
},
},
},
},
availability: {
select: {
date: true,
startTime: true,
endTime: true,
days: true,
},
},
secondaryEmailId: true,
secondaryEmail: {
select: {
id: true,
email: true,
},
},
assignRRMembersUsingSegment: true,
rrSegmentQueryValue: true,
useEventLevelSelectedCalendars: true,
hostGroups: {
select: {
id: true,
name: true,
},
},
} satisfies Prisma.EventTypeSelect;
export const getEventTypesFromDB = async (eventTypeId: number) => {
try {
const eventType = await prisma.eventType.findUniqueOrThrow({
where: {
id: eventTypeId,
},
select: {
id: true,
customInputs: true,
disableGuests: true,
restrictionScheduleId: true,
useBookerTimezone: true,
disableRescheduling: true,
disableCancelling: true,
users: {
select: {
credentials: {
select: credentialForCalendarServiceSelect,
},
...userSelect.select,
},
},
slug: true,
profile: {
select: {
organizationId: true,
},
},
teamId: true,
team: {
select: {
id: true,
name: true,
parentId: true,
bookingLimits: true,
includeManagedEventsInLimits: true,
rrResetInterval: true,
rrTimestampBasis: true,
},
},
bookingFields: true,
title: true,
length: true,
eventName: true,
schedulingType: true,
description: true,
periodType: true,
periodStartDate: true,
periodEndDate: true,
periodDays: true,
periodCountCalendarDays: true,
lockTimeZoneToggleOnBookingPage: true,
lockedTimeZone: true,
requiresConfirmation: true,
requiresConfirmationForFreeEmail: true,
requiresBookerEmailVerification: true,
maxLeadThreshold: true,
includeNoShowInRRCalculation: true,
minimumBookingNotice: true,
maxActiveBookingsPerBooker: true,
maxActiveBookingPerBookerOfferReschedule: true,
userId: true,
price: true,
currency: true,
metadata: true,
destinationCalendar: true,
hideCalendarNotes: true,
hideCalendarEventDetails: true,
hideOrganizerEmail: true,
seatsPerTimeSlot: true,
recurringEvent: true,
seatsShowAttendees: true,
seatsShowAvailabilityCount: true,
bookingLimits: true,
durationLimits: true,
rescheduleWithSameRoundRobinHost: true,
assignAllTeamMembers: true,
isRRWeightsEnabled: true,
beforeEventBuffer: true,
customReplyToEmail: true,
afterEventBuffer: true,
parentId: true,
parent: {
select: {
teamId: true,
team: {
select: {
id: true,
bookingLimits: true,
includeManagedEventsInLimits: true,
},
},
},
},
useEventTypeDestinationCalendarEmail: true,
owner: {
select: {
hideBranding: true,
},
},
workflows: {
select: {
workflow: {
select: workflowSelect,
},
},
},
locations: true,
timeZone: true,
schedule: {
select: {
id: true,
availability: true,
timeZone: true,
},
},
hosts: {
select: {
isFixed: true,
priority: true,
weight: true,
createdAt: true,
groupId: true,
user: {
select: {
credentials: {
select: credentialForCalendarServiceSelect,
},
...userSelect.select,
},
},
schedule: {
select: {
availability: {
select: {
date: true,
startTime: true,
endTime: true,
days: true,
},
},
timeZone: true,
id: true,
},
},
},
},
availability: {
select: {
date: true,
startTime: true,
endTime: true,
days: true,
},
},
secondaryEmailId: true,
secondaryEmail: {
select: {
id: true,
email: true,
},
},
assignRRMembersUsingSegment: true,
rrSegmentQueryValue: true,
useEventLevelSelectedCalendars: true,
hostGroups: {
select: {
id: true,
name: true,
},
},
},
});
const eventType = await prisma.eventType.findUniqueOrThrow({
where: {
id: eventTypeId,
},
select: getEventTypesFromDBSelect,
});
if (!eventType) {
throw new Error(ErrorCode.EventTypeNotFound);
}
const { profile, hosts, users, ...restEventType } = eventType;
const isOrgTeamEvent = !!eventType?.team && !!profile?.organizationId;
const hostsWithSelectedCalendars = hosts.map((host) => ({
...host,
user: withSelectedCalendars(host.user),
}));
const usersWithSelectedCalendars = users.map((user) => withSelectedCalendars(user));
return {
...restEventType,
hosts: hostsWithSelectedCalendars,
users: usersWithSelectedCalendars,
metadata: EventTypeMetaDataSchema.parse(eventType?.metadata || {}),
recurringEvent: parseRecurringEvent(eventType?.recurringEvent),
customInputs: customInputSchema.array().parse(eventType?.customInputs || []),
locations: (eventType?.locations ?? []) as LocationObject[],
bookingFields: getBookingFieldsWithSystemFields({ ...restEventType, isOrgTeamEvent }),
rrSegmentQueryValue: rrSegmentQueryValueSchema.parse(eventType.rrSegmentQueryValue) ?? null,
isDynamic: false,
hostGroups: eventType.hostGroups || [],
};
} catch (error) {
if (error instanceof Error && error.message.includes("Record to update not found")) {
throw new Error(ErrorCode.EventTypeNotFound);
}
throw error;
if (!eventType) {
throw new Error(ErrorCode.EventTypeNotFound);
}
const { profile, hosts, users, ...restEventType } = eventType;
const isOrgTeamEvent = !!eventType?.team && !!profile?.organizationId;
const hostsWithSelectedCalendars = hosts.map((host) => ({
...host,
user: withSelectedCalendars(host.user),
}));
const usersWithSelectedCalendars = users.map((user) => withSelectedCalendars(user));
return {
...restEventType,
hosts: hostsWithSelectedCalendars,
users: usersWithSelectedCalendars,
metadata: EventTypeMetaDataSchema.parse(eventType?.metadata || {}),
recurringEvent: parseRecurringEvent(eventType?.recurringEvent),
customInputs: customInputSchema.array().parse(eventType?.customInputs || []),
locations: (eventType?.locations ?? []) as LocationObject[],
bookingFields: getBookingFieldsWithSystemFields({ ...restEventType, isOrgTeamEvent }),
rrSegmentQueryValue: rrSegmentQueryValueSchema.parse(eventType.rrSegmentQueryValue) ?? null,
isDynamic: false,
hostGroups: eventType.hostGroups || [],
};
};
export type getEventTypeResponse = Awaited<ReturnType<typeof getEventTypesFromDB>>;
@@ -1,7 +1,8 @@
import type { EventTypeCustomInput } from "@prisma/client";
import { isValidPhoneNumber } from "libphonenumber-js";
import z from "zod";
import type { EventTypeCustomInput } from "@calcom/prisma/client";
type CustomInput = {
value: string | boolean;
label: string;
@@ -1,4 +1,3 @@
import type { Prisma } from "@prisma/client";
import type { Logger } from "tslog";
import { checkIfUsersAreBlocked } from "@calcom/features/watchlist/operations/check-if-users-are-blocked.controller";
@@ -13,6 +12,7 @@ import type { RoutingFormResponse } from "@calcom/lib/server/getLuckyUser";
import { withSelectedCalendars } from "@calcom/lib/server/repository/user";
import { userSelect } from "@calcom/prisma";
import prisma from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { SchedulingType } from "@calcom/prisma/enums";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
@@ -117,7 +117,7 @@ const _loadAndValidateUsers = async ({
credentials: {
select: credentialForCalendarServiceSelect,
}, // Don't leak to client
...userSelect.select,
...userSelect,
},
});
if (!eventTypeUser) {
@@ -1,5 +1,3 @@
import { Prisma } from "@prisma/client";
import { getOrgDomainConfig } from "@calcom/features/ee/organizations/lib/orgDomains";
import {
getRoutedUsersWithContactOwnerAndFixedUsers,
@@ -11,6 +9,7 @@ import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { withSelectedCalendars, UserRepository } from "@calcom/lib/server/repository/user";
import prisma, { userSelect } from "@calcom/prisma";
import { Prisma } from "@calcom/prisma/client";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { NewBookingEventType } from "./getEventTypesFromDB";
@@ -125,7 +124,7 @@ export const findUsersByUsername = async ({
await prisma.user.findMany({
where,
select: {
...userSelect.select,
...userSelect,
credentials: {
select: credentialForCalendarServiceSelect,
},
@@ -1,11 +1,11 @@
import type { Prisma } from "@prisma/client";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { HttpError } from "@calcom/lib/http-error";
import { BookingRepository } from "@calcom/lib/server/repository/booking";
import { prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { BookingStatus } from "@calcom/prisma/enums";
import prisma from "@calcom/prisma";
// TODO: Inject.
export async function getOriginalRescheduledBooking(uid: string, seatsEventType?: boolean) {
const bookingRepo = new BookingRepository(prisma);
const originalBooking = await bookingRepo.findOriginalRescheduledBooking(uid, seatsEventType);
@@ -1,4 +1,3 @@
import type { Booking, User, Webhook } from "@prisma/client";
import { afterAll, beforeAll, describe, expect, test, vi } from "vitest";
import { DailyLocationType } from "@calcom/app-store/constants";
@@ -6,6 +5,7 @@ import { getMeetingSessionsFromRoomName } from "@calcom/features/tasker/tasks/tr
import { triggerHostNoShow } from "@calcom/features/tasker/tasks/triggerNoShow/triggerHostNoShow";
import { sendGenericWebhookPayload } from "@calcom/features/webhooks/lib/sendPayload";
import { prisma } from "@calcom/prisma";
import type { Booking, User, Webhook } from "@calcom/prisma/client";
import { TimeUnit, WebhookTriggerEvents } from "@calcom/prisma/enums";
import { scheduleNoShowTriggers } from "./scheduleNoShowTriggers";
@@ -1,9 +1,13 @@
import { describe, it, expect } from "vitest";
import { describe, it, expect, vi } from "vitest";
import { BookingStatus, CreationSource } from "@calcom/prisma/enums";
import { buildDryRunBooking } from "../../handleNewBooking";
vi.mock("@calcom/prisma", () => ({
default: {}, // empty object as default export
}));
describe("buildDryRunBooking", () => {
const baseOrganizerUser = {
id: 1,
@@ -9,6 +9,12 @@ vi.mock("@calcom/lib/server/i18n", () => ({
getTranslation: vi.fn().mockResolvedValue("translated"),
}));
vi.mock("@calcom/prisma", () => {
return {
default: vi.fn(),
};
});
const withTeamSpy = vi.fn().mockReturnThis();
const withDestinationCalendarSpy = vi.fn().mockReturnThis();
@@ -2741,6 +2741,17 @@ describe("handleNewBooking", () => {
})
);
// Ensure the App_RoutingForms_FormResponse exists for the test
await prismaMock.app_RoutingForms_FormResponse.create({
data: {
id: 12323,
formId: "test-form", // Assuming a simple string ID for the form
responses: {},
fields: [], // Assuming fields might be an array
// Add any other minimally required fields if the test fails due to their absence
},
});
mockSuccessfulVideoMeetingCreation({
metadataLookupKey: "dailyvideo",
});
@@ -1,15 +1,15 @@
import type { App } from "@prisma/client";
import type { Prisma } from "@prisma/client";
import type { TFunction } from "i18next";
import type { EventTypeAppsList } from "@calcom/app-store/utils";
import type { PaymentAppData } from "@calcom/lib/getPaymentAppData";
import type { GetUserAvailabilityResult } from "@calcom/lib/getUserAvailability";
import type { userSelect } from "@calcom/prisma";
import type { App } from "@calcom/prisma/client";
import type { Prisma } from "@calcom/prisma/client";
import type { SelectedCalendar } from "@calcom/prisma/client";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
type User = Omit<Prisma.UserGetPayload<typeof userSelect>, "selectedCalendars">;
type User = Omit<Prisma.UserGetPayload<{ select: typeof userSelect }>, "selectedCalendars">;
export type Invitee = {
email: string;
@@ -1,18 +1,13 @@
import type { AppCategories, Prisma } from "@prisma/client";
import { PaymentServiceMap } from "@calcom/app-store/payment.services.generated";
import type { EventTypeAppsList } from "@calcom/app-store/utils";
import type { CompleteEventType } from "@calcom/prisma/zod";
import { eventTypeAppMetadataOptionalSchema } from "@calcom/prisma/zod-utils";
import type { AppCategories, Prisma, EventType } from "@calcom/prisma/client";
import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/prisma/zod-utils";
import type { CalendarEvent } from "@calcom/types/Calendar";
import type { IAbstractPaymentService } from "@calcom/types/PaymentService";
const isPaymentService = (x: unknown): x is { PaymentService: any } =>
!!x && typeof x === "object" && "PaymentService" in x && typeof x.PaymentService === "function";
const isKeyOf = <T extends object>(obj: T, key: unknown): key is keyof T =>
typeof key === "string" && key in obj;
const handlePayment = async ({
evt,
selectedEventType,
@@ -24,7 +19,7 @@ const handlePayment = async ({
isDryRun = false,
}: {
evt: CalendarEvent;
selectedEventType: Pick<CompleteEventType, "metadata" | "title">;
selectedEventType: Pick<EventType, "metadata" | "title">;
paymentAppCredentials: {
key: Prisma.JsonValue;
appId: EventTypeAppsList;
@@ -62,7 +57,8 @@ const handlePayment = async ({
const PaymentService = paymentAppModule.PaymentService;
const paymentInstance = new PaymentService(paymentAppCredentials) as IAbstractPaymentService;
const apps = eventTypeAppMetadataOptionalSchema.parse(selectedEventType?.metadata?.apps);
const apps = eventTypeMetaDataSchemaWithTypedApps.parse(selectedEventType?.metadata)?.apps;
const paymentOption = apps?.[paymentAppCredentials.appId].paymentOption || "ON_BOOKING";
let paymentData;
@@ -13,6 +13,7 @@ import EventManager from "@calcom/lib/EventManager";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { HttpError } from "@calcom/lib/http-error";
import prisma from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { BookingStatus } from "@calcom/prisma/enums";
import { eventTypeAppMetadataOptionalSchema } from "@calcom/prisma/zod-utils";
@@ -192,7 +193,15 @@ const createNewSeat = async (
const payment = await handlePayment({
evt,
selectedEventType: eventType,
selectedEventType: {
...eventType,
metadata: eventType.metadata
? {
...eventType.metadata,
apps: eventType.metadata?.apps as Prisma.JsonValue,
}
: {},
},
paymentAppCredentials: eventTypePaymentAppCredential as IEventTypePaymentCredentialType,
booking: seatedBooking,
bookerName: fullName,
@@ -1,11 +1,10 @@
import type { Attendee } from "@prisma/client";
// eslint-disable-next-line no-restricted-imports
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
import { getAllDelegationCredentialsForUserIncludeServiceAccountKey } from "@calcom/lib/delegationCredential/server";
import { getDelegationCredentialOrFindRegularCredential } from "@calcom/lib/delegationCredential/server";
import { deleteMeeting } from "@calcom/lib/videoClient";
import prisma from "@calcom/prisma";
import type { Attendee } from "@calcom/prisma/client";
import { BookingStatus } from "@calcom/prisma/enums";
import type { CalendarEvent } from "@calcom/types/Calendar";
+1 -1
View File
@@ -1,7 +1,7 @@
import type { Prisma } from "@prisma/client";
import type z from "zod";
import type { Workflow } from "@calcom/features/ee/workflows/lib/types";
import type { Prisma } from "@calcom/prisma/client";
import type { AppsStatus, CalendarEvent } from "@calcom/types/Calendar";
import type { Booking } from "../handleNewBooking/createBooking";
+2 -2
View File
@@ -1,11 +1,11 @@
import type { SchedulingType } from "@prisma/client";
import type { ErrorOption, FieldPath } from "react-hook-form";
import type { BookingCreateBody } from "@calcom/prisma/zod/custom/booking";
import type { SchedulingType } from "@calcom/prisma/client";
import type { RouterOutputs } from "@calcom/trpc/react";
import type { AppsStatus } from "@calcom/types/Calendar";
import type { DatePickerProps } from "../calendars/DatePicker";
import type { BookingCreateBody } from "./lib/bookingCreateBodySchema";
export type PublicEvent = NonNullable<RouterOutputs["viewer"]["public"]["event"]>;
@@ -1,3 +1,5 @@
import { prisma } from "@calcom/prisma/__mocks__/prisma";
import { describe, it, expect, beforeEach, vi } from "vitest";
import type {
@@ -17,6 +19,10 @@ import { RetellAIPhoneServiceProvider } from "./RetellAIPhoneServiceProvider";
import type { RetellAIService } from "./RetellAIService";
import type { RetellAIRepository } from "./types";
vi.mock("@calcom/prisma", () => ({
prisma,
}));
function createMockRetellAIService(overrides: Partial<RetellAIService> = {}): RetellAIService {
const defaultMocks = {
setupAIConfiguration: vi.fn(),
@@ -27,7 +27,8 @@ export class AgentService {
) {}
private async createApiKey({ userId, teamId }: { userId: number; teamId?: number }) {
return await PrismaApiKeyRepository.createApiKey({
const apiKeyRepository = await PrismaApiKeyRepository.withGlobalPrisma();
return await apiKeyRepository.createApiKey({
userId,
teamId,
expiresAt: null,
@@ -501,7 +502,7 @@ export class AgentService {
id,
userId,
teamId,
name,
name: _name,
generalPrompt,
beginMessage,
generalTools,
@@ -1,5 +1,4 @@
import type { CalendarCache, Prisma } from "@prisma/client";
import type { CalendarCache, Prisma } from "@calcom/prisma/client";
import type { SelectedCalendarEventTypeIds } from "@calcom/types/Calendar";
export type FreeBusyArgs = { timeMin: string; timeMax: string; items: { id: string }[] };
@@ -1,190 +0,0 @@
import prismock from "../../../tests/libs/__mocks__/prisma";
import { describe, expect, it, beforeEach, vi } from "vitest";
import type { Calendar } from "@calcom/types/Calendar";
import { CalendarCacheRepository } from "./calendar-cache.repository";
vi.mock("./lib/datesForCache", () => ({
getTimeMin: vi.fn().mockImplementation((timeMin) => timeMin),
getTimeMax: vi.fn().mockImplementation((timeMax) => timeMax),
}));
describe("CalendarCacheRepository", () => {
let mockCalendar: Calendar;
beforeEach(() => {
// Clear the database before each test
prismock.calendarCache.deleteMany();
// Setup mock calendar
mockCalendar = {
watchCalendar: vi.fn(),
unwatchCalendar: vi.fn(),
} as unknown as Calendar;
});
// It needs to consider parseKeyForCache being called
// eslint-disable-next-line playwright/no-skipped-test
describe("getCachedAvailability", () => {
it("should return cached availability data", async () => {
const repository = new CalendarCacheRepository();
const args = {
timeMin: "2023-01-01T00:00:00Z",
timeMax: "2023-01-02T00:00:00Z",
items: [{ id: "calendar-1" }],
};
const testData = {
credentialId: 1,
userId: 1,
key: JSON.stringify({
timeMin: args.timeMin,
timeMax: args.timeMax,
items: args.items,
}),
value: { busy: [] },
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
};
await prismock.calendarCache.create({ data: testData });
const result = await repository.getCachedAvailability({
credentialId: 1,
userId: 1,
args,
});
expect(result).toEqual(
expect.objectContaining({
key: testData.key,
value: testData.value,
})
);
});
it("should return cached availability data even if credentialId is -1", async () => {
const repository = new CalendarCacheRepository();
const args = {
timeMin: "2023-01-01T00:00:00Z",
timeMax: "2023-01-02T00:00:00Z",
items: [{ id: "calendar-1" }],
};
const testData = {
credentialId: -1,
userId: 1,
key: JSON.stringify({
timeMin: args.timeMin,
timeMax: args.timeMax,
items: args.items,
}),
value: { busy: [] },
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
};
await prismock.calendarCache.create({ data: testData });
const resultWithWrongUserId = await repository.getCachedAvailability({
credentialId: -1,
userId: 2,
args,
});
expect(resultWithWrongUserId).toBeNull();
const resultWithCorrectUserId = await repository.getCachedAvailability({
credentialId: -1,
userId: 1,
args,
});
expect(resultWithCorrectUserId).toEqual(
expect.objectContaining({
key: testData.key,
value: testData.value,
})
);
});
});
describe("upsertCachedAvailability(mocks min and max time fns)", () => {
it("should create new cache entry when none exists", async () => {
const repository = new CalendarCacheRepository();
const args = {
timeMin: "2023-01-01T00:00:00Z",
timeMax: "2023-01-02T00:00:00Z",
items: [{ id: "calendar-1" }],
};
const value = { busy: [] };
await repository.upsertCachedAvailability({
credentialId: 1,
userId: 1,
args,
value,
});
const result = await prismock.calendarCache.findFirst({
where: {
credentialId: 1,
},
});
expect(result).toEqual(
expect.objectContaining({
credentialId: 1,
value,
})
);
});
it("should update existing cache entry", async () => {
const repository = new CalendarCacheRepository();
const args = {
timeMin: "2023-01-01T00:00:00Z",
timeMax: "2023-01-02T00:00:00Z",
items: [{ id: "calendar-1" }],
};
const key = JSON.stringify({
timeMin: args.timeMin,
timeMax: args.timeMax,
items: args.items,
});
// Create initial cache entry
const initialData = {
credentialId: 1,
key,
value: { busy: [] },
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
};
await prismock.calendarCache.create({ data: initialData });
// Update with new value
const newValue = { busy: [{ start: "2023-01-01T10:00:00Z", end: "2023-01-01T11:00:00Z" }] };
await repository.upsertCachedAvailability({
credentialId: 1,
userId: 1,
args,
value: newValue,
});
const result = await prismock.calendarCache.findFirst({
where: {
credentialId: 1,
key,
},
});
expect(result).toEqual(
expect.objectContaining({
credentialId: 1,
key,
value: newValue,
})
);
});
});
});
@@ -1,10 +1,9 @@
import type { Prisma } from "@prisma/client";
import { uniqueBy } from "@calcom/lib/array";
import { isInMemoryDelegationCredential } from "@calcom/lib/delegationCredential/clientAndServer";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import prisma from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import type { Calendar, SelectedCalendarEventTypeIds } from "@calcom/types/Calendar";
import type { ICalendarCacheRepository } from "./calendar-cache.repository.interface";
@@ -1,4 +1,3 @@
import type { Prisma } from "@prisma/client";
import z from "zod";
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
@@ -13,6 +12,7 @@ import { DailyLocationType } from "@calcom/lib/location";
import { deletePayment } from "@calcom/lib/payment/deletePayment";
import { getTranslation } from "@calcom/lib/server/i18n";
import { bookingMinimalSelect, prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { AppCategories, BookingStatus } from "@calcom/prisma/enums";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { EventTypeAppMetadataSchema, EventTypeMetadata } from "@calcom/prisma/zod-utils";
@@ -1,6 +1,7 @@
import { Prisma } from "@prisma/client";
import { describe, expect, it } from "vitest";
import { Prisma } from "@calcom/prisma/client";
import { makeSqlCondition } from "../server";
import { ColumnFilterType } from "../types";
import type {
+1 -1
View File
@@ -1,4 +1,4 @@
import { Prisma } from "@prisma/client";
import { Prisma } from "@calcom/prisma/client";
import type { FilterValue, SortingState } from "./types";
import {
@@ -6,14 +6,13 @@ import * as EmailManager from "@calcom/emails/email-manager";
import { CreditsRepository } from "@calcom/lib/server/repository/credits";
import { MembershipRepository } from "@calcom/lib/server/repository/membership";
import { TeamRepository } from "@calcom/lib/server/repository/team";
import prisma from "@calcom/prisma";
import { CreditType } from "@calcom/prisma/enums";
import { CreditService as OriginalCreditService } from "./credit-service";
import { CreditService } from "./credit-service";
import { StripeBillingService } from "./stripe-billling-service";
import { InternalTeamBilling } from "./teams/internal-team-billing";
const MOCK_TX = prisma;
const MOCK_TX = {};
vi.mock("@calcom/prisma", () => {
return {
@@ -63,38 +62,24 @@ vi.mock("../workflows/lib/reminders/reminderScheduler", () => ({
cancelScheduledMessagesAndScheduleEmails: vi.fn(),
}));
// Create a testable version of CreditService that exposes protected methods
class CreditService extends OriginalCreditService {
public async _getTeamWithAvailableCredits(
params: Parameters<OriginalCreditService["_getTeamWithAvailableCredits"]>[0]
) {
return super._getTeamWithAvailableCredits(params);
}
const creditService = new CreditService();
public async _getUserOrTeamToCharge(
params: Parameters<OriginalCreditService["_getUserOrTeamToCharge"]>[0]
) {
return super._getUserOrTeamToCharge(params);
}
vi.spyOn(creditService, "_getAllCreditsForTeam").mockResolvedValue({
totalRemainingMonthlyCredits: 5,
additionalCredits: 0,
});
public async _createExpenseLog(props: Parameters<OriginalCreditService["_createExpenseLog"]>[0]) {
return super._createExpenseLog(props);
}
vi.spyOn(creditService, "_getTeamWithAvailableCredits").mockResolvedValue({
availableCredits: 3,
});
public async _handleLowCreditBalance(
params: Parameters<OriginalCreditService["_handleLowCreditBalance"]>[0]
) {
return super._handleLowCreditBalance(params);
}
vi.spyOn(creditService, "_getAllCredits").mockResolvedValue({
additionalCredits: 1,
});
public async _getAllCreditsForTeam(params: Parameters<OriginalCreditService["_getAllCreditsForTeam"]>[0]) {
return super._getAllCreditsForTeam(params);
}
public async _getAllCredits(params: Parameters<OriginalCreditService["_getAllCredits"]>[0]) {
return super._getAllCredits(params);
}
}
CreditsRepository.findCreditBalance.mockResolvedValueOnce({
limitReachedAt: null,
});
describe("CreditService", () => {
let creditService: CreditService;
+16 -2
View File
@@ -15,7 +15,8 @@ import { CreditsRepository } from "@calcom/lib/server/repository/credits";
import { MembershipRepository } from "@calcom/lib/server/repository/membership";
import { TeamRepository } from "@calcom/lib/server/repository/team";
import prisma, { type PrismaTransaction } from "@calcom/prisma";
import { CreditType, CreditUsageType } from "@calcom/prisma/enums";
import type { CreditUsageType } from "@calcom/prisma/enums";
import { CreditType } from "@calcom/prisma/enums";
const log = logger.getSubLogger({ prefix: ["[CreditService]"] });
@@ -336,7 +337,20 @@ export class CreditService {
tx: PrismaTransaction;
externalRef?: string;
}) {
const { credits, creditType, bookingUid, smsSid, teamId, userId, smsSegments, callDuration, creditFor, phoneNumber, email, tx } = props;
const {
credits,
creditType,
bookingUid,
smsSid,
teamId,
userId,
smsSegments,
callDuration,
creditFor,
phoneNumber,
email,
tx,
} = props;
let creditBalance: { id: string; additionalCredits: number } | null | undefined =
await CreditsRepository.findCreditBalance({ teamId, userId }, tx);
@@ -1,4 +1,4 @@
import type { Team } from "@prisma/client";
import type { Team } from "@calcom/prisma/client";
export interface OrganizationBillingRepository {
findById(organizationId: number): Promise<Pick<Team, "id" | "slug" | "name" | "billingPeriod"> | null>;
@@ -1,4 +1,4 @@
import type { Team } from "@prisma/client";
import type { Team } from "@calcom/prisma/client";
import type { OrganizationBillingRepository } from "./organization-billing.repository";
@@ -1,4 +1,3 @@
import type { Prisma } from "@prisma/client";
import type { z } from "zod";
import { getRequestedSlugError } from "@calcom/app-store/stripepayment/lib/team-billing";
@@ -9,7 +8,8 @@ import logger from "@calcom/lib/logger";
import { Redirect } from "@calcom/lib/redirect";
import { safeStringify } from "@calcom/lib/safeStringify";
import { OrganizationOnboardingRepository } from "@calcom/lib/server/repository/organizationOnboarding";
import prisma from "@calcom/prisma";
import { prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { teamMetadataStrictSchema } from "@calcom/prisma/zod-utils";
import billing from "..";
@@ -1,4 +1,4 @@
import type { Prisma } from "@prisma/client";
import type { Prisma } from "@calcom/prisma/client";
export const teamBillingSelect = {
id: true,
@@ -1,4 +1,4 @@
import type { Team } from "@prisma/client";
import type { Team } from "@calcom/prisma/client";
export type TeamBillingInput = Pick<Team, "id" | "parentId" | "metadata" | "isOrganization">;
export const TeamBillingPublishResponseStatus = {
@@ -1,5 +1,5 @@
import type { Session } from "next-auth";
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { UserPermissionRole } from "@calcom/prisma/enums";
import { MembershipRole } from "@calcom/prisma/enums";
@@ -23,6 +23,12 @@ const session: Session = {
},
};
vi.mock("@calcom/prisma", () => {
return {
default: vi.fn(),
};
});
describe("parseTeamId", () => {
it("should return undefined if no teamId is provided", () => {
expect(parseTeamId(undefined)).toBeUndefined();
@@ -1,4 +1,3 @@
import type { User } from "@prisma/client";
import type { Session } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { z } from "zod";
@@ -8,6 +7,7 @@ import { getSession } from "@calcom/features/auth/lib/getSession";
import { getSpecificPermissions } from "@calcom/features/pbac/lib/resource-permissions";
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
import prisma from "@calcom/prisma";
import type { User } from "@calcom/prisma/client";
import type { Prisma } from "@calcom/prisma/client";
import type { Membership } from "@calcom/prisma/client";
import { MembershipRole } from "@calcom/prisma/enums";
@@ -3,12 +3,11 @@ import { default as get } from "lodash/get";
import type { Dispatch, SetStateAction } from "react";
import { useState } from "react";
import type { UseFormReturn } from "react-hook-form";
import type z from "zod";
import type { FormValues } from "@calcom/features/eventtypes/lib/types";
import type { Prisma } from "@calcom/prisma/client";
import type { Prisma, EventType } from "@calcom/prisma/client";
import { SchedulingType } from "@calcom/prisma/enums";
import type { _EventTypeModel } from "@calcom/prisma/zod/eventtype";
import { eventTypeMetaDataSchemaWithoutApps } from "@calcom/prisma/zod-utils";
import classNames from "@calcom/ui/classNames";
import { Badge } from "@calcom/ui/components/badge";
import { Switch } from "@calcom/ui/components/form";
@@ -95,21 +94,23 @@ const useLockedFieldsManager = ({
translate,
formMethods,
}: {
eventType: Pick<z.infer<typeof _EventTypeModel>, "schedulingType" | "userId" | "metadata" | "id">;
eventType: Pick<EventType, "schedulingType" | "userId" | "metadata" | "id">;
translate: TFunction;
formMethods: UseFormReturn<FormValues>;
}) => {
const { setValue, getValues } = formMethods;
const [fieldStates, setFieldStates] = useState<Record<string, boolean>>({});
const metadata = eventTypeMetaDataSchemaWithoutApps.parse(eventType.metadata);
const unlockedFields =
(eventType.metadata?.managedEventConfig?.unlockedFields !== undefined &&
eventType.metadata?.managedEventConfig?.unlockedFields) ||
(metadata?.managedEventConfig?.unlockedFields !== undefined &&
metadata?.managedEventConfig?.unlockedFields) ||
{};
const isManagedEventType = eventType.schedulingType === SchedulingType.MANAGED;
const isChildrenManagedEventType =
eventType.metadata?.managedEventConfig !== undefined &&
eventType.schedulingType !== SchedulingType.MANAGED;
metadata?.managedEventConfig !== undefined && eventType.schedulingType !== SchedulingType.MANAGED;
const setUnlockedFields = (fieldName: string, val: boolean | undefined) => {
const path = "metadata.managedEventConfig.unlockedFields";
@@ -175,7 +176,7 @@ const useLockedFieldsManager = ({
return {
disabled:
!isManagedEventType &&
eventType.metadata?.managedEventConfig !== undefined &&
metadata?.managedEventConfig !== undefined &&
unlockedFields[fieldName as keyof Omit<Prisma.EventTypeSelect, "id">] === undefined,
LockedIcon: useShouldLockIndicator(fieldName, options),
isLocked,
@@ -203,7 +204,7 @@ const useLockedFieldsManager = ({
return {
disabled:
!isManagedEventType &&
eventType.metadata?.managedEventConfig !== undefined &&
metadata?.managedEventConfig !== undefined &&
unlockedFields[fieldName as keyof Omit<Prisma.EventTypeSelect, "id">] === undefined,
LockedIcon: useShouldLockIndicator(fieldName, options),
isLocked: fieldStates[fieldName],
@@ -1,14 +1,14 @@
import type { Prisma } from "@prisma/client";
// eslint-disable-next-line no-restricted-imports
import type { DeepMockProxy } from "vitest-mock-extended";
import { sendSlugReplacementEmail } from "@calcom/emails/email-manager";
import { getTranslation } from "@calcom/lib/server/i18n";
import type { PrismaClient } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { SchedulingType } from "@calcom/prisma/enums";
import { _EventTypeModel } from "@calcom/prisma/zod";
import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/prisma/zod-utils";
import { allManagedEventTypeProps, unlockedManagedEventTypeProps } from "@calcom/prisma/zod-utils";
import { EventTypeSchema } from "@calcom/prisma/zod/modelSchema/EventTypeSchema";
interface handleChildrenEventTypesProps {
eventTypeId: number;
@@ -114,8 +114,8 @@ export default async function handleChildrenEventTypes({
};
// bookingFields is expected to be filled by the _EventTypeModel but is null at create event
const _ManagedEventTypeModel = _EventTypeModel.extend({
bookingFields: _EventTypeModel.shape.bookingFields.nullish(),
const _ManagedEventTypeModel = EventTypeSchema.extend({
bookingFields: EventTypeSchema.shape.bookingFields.nullish(),
});
const allManagedEventTypePropsZod = _ManagedEventTypeModel.pick(allManagedEventTypeProps);
@@ -158,12 +158,25 @@ export default async function handleChildrenEventTypes({
// Create event types for new users added
await prisma.$transaction(
newUserIds.map((userId) => {
// Exclude profileId and instantMeetingScheduleId from managed values to avoid duplication
const {
profileId: _,
instantMeetingScheduleId: __,
...managedValuesWithoutExplicit
} = managedEventTypeValues;
return prisma.eventType.create({
data: {
instantMeetingScheduleId: eventType.instantMeetingScheduleId ?? undefined,
profileId: profileId ?? null,
...managedEventTypeValues,
...unlockedEventTypeValues,
...managedValuesWithoutExplicit,
...{
...unlockedEventTypeValues,
// pre-genned as allowed null
locations: Array.isArray(unlockedEventTypeValues.locations)
? unlockedEventTypeValues.locations
: undefined,
},
bookingLimits:
(managedEventTypeValues.bookingLimits as unknown as Prisma.InputJsonObject) ?? undefined,
recurringEvent:
@@ -1,10 +1,10 @@
import type { Prisma } from "@prisma/client";
import type { IncomingMessage } from "http";
import { IS_PRODUCTION, WEBSITE_URL, SINGLE_ORG_SLUG } from "@calcom/lib/constants";
import { ALLOWED_HOSTNAMES, RESERVED_SUBDOMAINS, WEBAPP_URL } from "@calcom/lib/constants";
import logger from "@calcom/lib/logger";
import slugify from "@calcom/lib/slugify";
import type { Prisma } from "@calcom/prisma/client";
const log = logger.getSubLogger({
prefix: ["orgDomains.ts"],
@@ -1,16 +1,16 @@
"use client";
import type { Team } from "@prisma/client";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import type { z } from "zod";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { Team } from "@calcom/prisma/client";
import type { orgSettingsSchema } from "@calcom/prisma/zod-utils";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { Form } from "@calcom/ui/components/form";
import { TextField } from "@calcom/ui/components/form";
import { Button } from "@calcom/ui/components/button";
import { showToast } from "@calcom/ui/components/toast";
type FormValues = {
@@ -1,7 +1,6 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import type { Prisma } from "@prisma/client";
import { useSession } from "next-auth/react";
import Link from "next/link";
import { useRouter } from "next/navigation";
@@ -20,6 +19,7 @@ import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
import objectKeys from "@calcom/lib/objectKeys";
import slugify from "@calcom/lib/slugify";
import turndown from "@calcom/lib/turndownService";
import type { Prisma } from "@calcom/prisma/client";
import { trpc } from "@calcom/trpc/react";
import { Avatar } from "@calcom/ui/components/avatar";
import { Button, LinkIconButton } from "@calcom/ui/components/button";
@@ -1,7 +1,6 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import type { Prisma } from "@prisma/client";
import { useRouter } from "next/navigation";
import { useEffect, useLayoutEffect, useState } from "react";
import { Controller, useForm } from "react-hook-form";
@@ -16,6 +15,7 @@ import { useLocale } from "@calcom/lib/hooks/useLocale";
import { md } from "@calcom/lib/markdownIt";
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
import turndown from "@calcom/lib/turndownService";
import type { Prisma } from "@calcom/prisma/client";
import { trpc } from "@calcom/trpc/react";
import { Avatar } from "@calcom/ui/components/avatar";
import { Button } from "@calcom/ui/components/button";
+1 -1
View File
@@ -1,4 +1,3 @@
import type { Prisma } from "@prisma/client";
import { buffer } from "micro";
import type { NextApiRequest, NextApiResponse } from "next";
import type Stripe from "stripe";
@@ -19,6 +18,7 @@ import logger from "@calcom/lib/logger";
import { getBooking } from "@calcom/lib/payment/getBooking";
import { safeStringify } from "@calcom/lib/safeStringify";
import { prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { BookingStatus } from "@calcom/prisma/enums";
import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/prisma/zod-utils";
@@ -1,6 +1,5 @@
"use client";
import type { EventType, Payment } from "@prisma/client";
import { Elements, PaymentElement, useElements, useStripe } from "@stripe/react-stripe-js";
import type { StripeElementLocale, StripeElements, StripePaymentElementOptions } from "@stripe/stripe-js";
import { useRouter } from "next/navigation";
@@ -12,6 +11,7 @@ import { useBookingSuccessRedirect } from "@calcom/lib/bookingSuccessRedirect";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { EventType, Payment } from "@calcom/prisma/client";
import type { PaymentOption } from "@calcom/prisma/enums";
import { Button } from "@calcom/ui/components/button";
import { CheckboxField } from "@calcom/ui/components/form";
@@ -1,6 +1,3 @@
import type { DestinationCalendar } from "@prisma/client";
import type { Prisma } from "@prisma/client";
import { metadata as GoogleMeetMetadata } from "@calcom/app-store/googlevideo/_metadata";
import { MeetLocationType } from "@calcom/app-store/locations";
import { getAllCredentialsIncludeServiceAccountKey } from "@calcom/features/bookings/lib/getAllCredentialsForUsersOnEvent/getAllCredentials";
@@ -13,6 +10,8 @@ import logger from "@calcom/lib/logger";
import { getTranslation } from "@calcom/lib/server/i18n";
import { BookingReferenceRepository } from "@calcom/lib/server/repository/bookingReference";
import { prisma } from "@calcom/prisma";
import type { DestinationCalendar } from "@calcom/prisma/client";
import type { Prisma } from "@calcom/prisma/client";
import type { CalendarEvent, AdditionalInformation } from "@calcom/types/Calendar";
type InitParams = {
@@ -1,7 +1,7 @@
"use client";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState, type FC } from "react";
import { useEffect, type FC } from "react";
import { IntercomProvider } from "react-use-intercom";
import { useBootIntercom } from "@calcom/ee/support/lib/intercom/useIntercom";
@@ -1,7 +1,6 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import type { Prisma } from "@prisma/client";
import { useSession } from "next-auth/react";
import Link from "next/link";
import { useRouter } from "next/navigation";
@@ -23,6 +22,7 @@ import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
import objectKeys from "@calcom/lib/objectKeys";
import slugify from "@calcom/lib/slugify";
import turndown from "@calcom/lib/turndownService";
import type { Prisma } from "@calcom/prisma/client";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import { Avatar } from "@calcom/ui/components/avatar";
@@ -2,7 +2,6 @@
import { usePathname, useRouter } from "next/navigation";
import { getParserWithGeneric } from "@calcom/prisma/zod-utils";
import { trpc } from "@calcom/trpc/react";
import { showToast } from "@calcom/ui/components/toast";
@@ -34,8 +33,7 @@ const UsersAddView = () => {
<UserForm
submitLabel="Add user"
onSubmit={async (values) => {
const parser = getParserWithGeneric(userBodySchema);
const parsedValues = parser(values);
const parsedValues = userBodySchema.parse(values);
mutation.mutate(parsedValues);
}}
/>
@@ -1,13 +1,18 @@
import { z } from "zod";
import { UserSchema } from "@calcom/prisma/zod/modelSchema/UserSchema";
import { optionToValueSchema } from "@calcom/prisma/zod-utils";
export const userBodySchema = z
.object({
locale: optionToValueSchema(z.string()),
role: optionToValueSchema(z.enum(["USER", "ADMIN"])),
weekStart: optionToValueSchema(z.string()),
timeFormat: optionToValueSchema(z.number()),
identityProvider: optionToValueSchema(z.enum(["CAL", "GOOGLE", "SAML"])),
})
.passthrough();
export const userBodySchema = UserSchema.pick({
username: true,
name: true,
email: true,
role: true,
identityProvider: true,
bio: true,
avatarUrl: true,
timeZone: true,
weekStart: true,
theme: true,
defaultScheduleId: true,
locale: true,
timeFormat: true,
allowDynamicBooking: true,
});
@@ -1,9 +1,8 @@
import { z } from "zod";
import { getOrgFullOrigin } from "@calcom/ee/organizations/lib/orgDomains";
import { CreationSource } from "@calcom/prisma/enums";
import { RedirectType } from "@calcom/prisma/enums";
import { _UserModel as User } from "@calcom/prisma/zod";
import { RedirectType, CreationSource } from "@calcom/prisma/enums";
import { UserSchema } from "@calcom/prisma/zod/modelSchema/UserSchema";
import { authedAdminProcedure } from "@calcom/trpc/server/procedures/authedProcedure";
import { router } from "@calcom/trpc/server/trpc";
@@ -15,7 +14,7 @@ export type UserAdminRouterOutputs = inferRouterOutputs<UserAdminRouter>;
const userIdSchema = z.object({ userId: z.coerce.number() });
const userBodySchema = User.pick({
const userBodySchema = UserSchema.pick({
name: true,
email: true,
username: true,
@@ -1,5 +1,4 @@
import { useAutoAnimate } from "@formkit/auto-animate/react";
import type { Membership, Workflow } from "@prisma/client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
@@ -7,6 +6,7 @@ import { useState } from "react";
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { WorkflowPermissions } from "@calcom/lib/server/repository/workflow-permissions";
import type { Membership, Workflow } from "@calcom/prisma/client";
import { trpc } from "@calcom/trpc/react";
import classNames from "@calcom/ui/classNames";
import { ArrowButton } from "@calcom/ui/components/arrow-button";
@@ -1,4 +1,3 @@
import type { WorkflowStep } from "@prisma/client";
import { type TFunction } from "i18next";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import type { Dispatch, SetStateAction } from "react";
@@ -10,13 +9,14 @@ import "react-phone-number-input/style.css";
import type { RetellAgentWithDetails } from "@calcom/features/calAIPhone/providers/retellAI";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import PhoneInput from "@calcom/features/components/phone-input";
import { SENDER_ID, SENDER_NAME } from "@calcom/lib/constants";
import { SENDER_ID } from "@calcom/lib/constants";
import { formatPhoneNumber } from "@calcom/lib/formatPhoneNumber";
import { useHasActiveTeamPlan } from "@calcom/lib/hooks/useHasPaidPlan";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import useMediaQuery from "@calcom/lib/hooks/useMediaQuery";
import { HttpError } from "@calcom/lib/http-error";
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
import type { WorkflowStep } from "@calcom/prisma/client";
import {
MembershipRole,
PhoneNumberSubscriptionStatus,
@@ -45,7 +45,6 @@ import { EmailField } from "@calcom/ui/components/form";
import { TextArea } from "@calcom/ui/components/form";
import { Label } from "@calcom/ui/components/form";
import { TextField } from "@calcom/ui/components/form";
import { Input } from "@calcom/ui/components/form";
import { Select } from "@calcom/ui/components/form";
import { MultiSelectCheckbox } from "@calcom/ui/components/form";
import type { MultiSelectCheckboxesOptionType as Option } from "@calcom/ui/components/form";
@@ -251,7 +250,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
const senderNeeded =
step?.action === WorkflowActions.SMS_NUMBER || step?.action === WorkflowActions.SMS_ATTENDEE;
const [isSenderIsNeeded, setIsSenderIsNeeded] = useState(senderNeeded);
const [, setIsSenderIsNeeded] = useState(senderNeeded);
const [isEmailAddressNeeded, setIsEmailAddressNeeded] = useState(
step?.action === WorkflowActions.EMAIL_ADDRESS ? true : false
@@ -1,7 +1,7 @@
import type { WorkflowTriggerEvents } from "@prisma/client";
import type { TFunction } from "i18next";
import type { TimeFormat } from "@calcom/lib/timeFormat";
import type { WorkflowTriggerEvents } from "@calcom/prisma/client";
import { WorkflowActions, WorkflowTemplates } from "@calcom/prisma/enums";
import {
@@ -1,6 +1,7 @@
import dayjs from "@calcom/dayjs";
import prisma from "@calcom/prisma";
import type { EventType, User, WorkflowReminder, WorkflowStep, Prisma } from "@calcom/prisma/client";
import type { EventType, User, WorkflowReminder, WorkflowStep } from "@calcom/prisma/client";
import type { Prisma } from "@calcom/prisma/client";
import { WorkflowMethods } from "@calcom/prisma/enums";
type PartialWorkflowStep =
@@ -74,7 +75,8 @@ async function getWorkflowReminders<T extends Prisma.WorkflowReminderSelect>(
}
filteredWorkflowReminders.push(
...(newFilteredWorkflowReminders as Array<Prisma.WorkflowReminderGetPayload<{ select: T }>>)
// FIXME: This is a workaround to avoid type errors
...(newFilteredWorkflowReminders as unknown as Array<Prisma.WorkflowReminderGetPayload<{ select: T }>>)
);
pageNumber++;
}
@@ -13,11 +13,11 @@ import {
} from "@calcom/web/test/utils/bookingScenario/expects";
import { setupAndTeardown } from "@calcom/web/test/utils/bookingScenario/setupAndTeardown";
import type { Prisma } from "@prisma/client";
import { v4 as uuidv4 } from "uuid";
import { describe, expect, beforeAll, vi, beforeEach } from "vitest";
import dayjs from "@calcom/dayjs";
import type { Prisma } from "@calcom/prisma/client";
import {
BookingStatus,
WorkflowMethods,
@@ -32,7 +32,6 @@ import {
} from "@calcom/trpc/server/routers/viewer/workflows/util";
import { test } from "@calcom/web/test/fixtures/fixtures";
import { FeaturesRepository } from "../../../../flags/features.repository";
import { deleteWorkfowRemindersOfRemovedMember } from "../../../teams/lib/deleteWorkflowRemindersOfRemovedMember";
import { scheduleEmailReminder } from "../reminders/emailReminderManager";
import * as emailProvider from "../reminders/providers/emailProvider";
@@ -1,7 +1,6 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import type { WorkflowStep } from "@prisma/client";
import { useSession } from "next-auth/react";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
@@ -12,6 +11,7 @@ import { useLocale } from "@calcom/lib/hooks/useLocale";
import { HttpError } from "@calcom/lib/http-error";
import type { WorkflowRepository } from "@calcom/lib/server/repository/workflow";
import type { WorkflowPermissions } from "@calcom/lib/server/repository/workflow-permissions";
import type { WorkflowStep } from "@calcom/prisma/client";
import type { TimeUnit, WorkflowTriggerEvents } from "@calcom/prisma/enums";
import { WorkflowActions } from "@calcom/prisma/enums";
import type { RouterOutputs } from "@calcom/trpc/react";
@@ -1,4 +1,3 @@
import type { EventType } from "@prisma/client";
import { isValidPhoneNumber } from "libphonenumber-js";
import { useRouter } from "next/navigation";
import { z } from "zod";
@@ -10,6 +9,7 @@ import { TeamEventTypeForm } from "@calcom/features/ee/teams/components/TeamEven
import { useCreateEventType } from "@calcom/lib/hooks/useCreateEventType";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { useTypedQuery } from "@calcom/lib/hooks/useTypedQuery";
import type { EventType } from "@calcom/prisma/client";
import type { MembershipRole } from "@calcom/prisma/enums";
import { SchedulingType } from "@calcom/prisma/enums";
import { trpc } from "@calcom/trpc/react";
@@ -5,6 +5,7 @@ import { useForm } from "react-hook-form";
import { z } from "zod";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { EventTypeDuplicateInput } from "@calcom/features/eventtypes/lib/types";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useDebounce } from "@calcom/lib/hooks/useDebounce";
import { useLocale } from "@calcom/lib/hooks/useLocale";
@@ -13,7 +14,6 @@ import { HttpError } from "@calcom/lib/http-error";
import { md } from "@calcom/lib/markdownIt";
import slugify from "@calcom/lib/slugify";
import turndown from "@calcom/lib/turndownService";
import { EventTypeDuplicateInput } from "@calcom/prisma/zod/custom/eventtype";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { DialogContent, DialogFooter, DialogClose } from "@calcom/ui/components/dialog";
@@ -1,6 +1,4 @@
import type { Prisma } from "@prisma/client";
import { useMemo } from "react";
import type { z } from "zod";
import { Price } from "@calcom/features/bookings/components/event-meta/Price";
import { PriceIcon } from "@calcom/features/bookings/components/event-meta/PriceIcon";
@@ -9,16 +7,18 @@ import { useLocale } from "@calcom/lib/hooks/useLocale";
import { parseRecurringEvent } from "@calcom/lib/isRecurringEvent";
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
import type { baseEventTypeSelect } from "@calcom/prisma";
import type { Prisma, EventType } from "@calcom/prisma/client";
import { SchedulingType } from "@calcom/prisma/enums";
import type { EventTypeModel } from "@calcom/prisma/zod";
import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/prisma/zod-utils";
import classNames from "@calcom/ui/classNames";
import { Badge } from "@calcom/ui/components/badge";
export type EventTypeDescriptionProps = {
eventType: Pick<
z.infer<typeof EventTypeModel>,
Exclude<keyof typeof baseEventTypeSelect, "recurringEvent"> | "metadata" | "seatsPerTimeSlot"
EventType,
| Exclude<keyof typeof baseEventTypeSelect, "recurringEvent" | "description">
| "metadata"
| "seatsPerTimeSlot"
> & {
descriptionAsSafeHTML?: string | null;
recurringEvent: Prisma.JsonValue;
@@ -41,15 +41,17 @@ export const EventTypeDescription = ({
[eventType.recurringEvent]
);
const metadata = eventTypeMetaDataSchemaWithTypedApps.parse(eventType.metadata);
const paymentAppData = getPaymentAppData({
...eventType,
metadata: eventTypeMetaDataSchemaWithTypedApps.parse(eventType.metadata),
metadata,
});
return (
<>
<div className={classNames("text-subtle", className)}>
{eventType.description && (
{eventType.descriptionAsSafeHTML && (
<div
className={classNames(
"text-subtle line-clamp-3 break-words py-1 text-sm sm:max-w-[650px] [&_a]:text-blue-500 [&_a]:underline [&_a]:hover:text-blue-600",
@@ -62,8 +64,8 @@ export const EventTypeDescription = ({
/>
)}
<ul className="mt-2 flex flex-wrap gap-x-2 gap-y-1">
{eventType.metadata?.multipleDuration ? (
eventType.metadata.multipleDuration.map((dur, idx) => (
{metadata?.multipleDuration ? (
metadata.multipleDuration.map((dur, idx) => (
<li key={idx}>
<Badge variant="gray" startIcon="clock">
{dur}m
@@ -112,7 +114,7 @@ export const EventTypeDescription = ({
{eventType.requiresConfirmation && (
<li className="hidden xl:block" data-testid="requires-confirmation-badge">
<Badge variant="gray" startIcon="clipboard">
{eventType.metadata?.requiresConfirmationThreshold
{metadata?.requiresConfirmationThreshold
? t("may_require_confirmation")
: t("requires_confirmation")}
</Badge>
@@ -1,4 +1,3 @@
import type { Webhook } from "@prisma/client";
import { useSession } from "next-auth/react";
import { useState } from "react";
import { useFormContext, Controller } from "react-hook-form";
@@ -14,6 +13,7 @@ import type { WebhookFormSubmitData } from "@calcom/features/webhooks/components
import WebhookListItem from "@calcom/features/webhooks/components/WebhookListItem";
import { subscriberUrlReserved } from "@calcom/features/webhooks/lib/subscriberUrlReserved";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { Webhook } from "@calcom/prisma/client";
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
import { trpc } from "@calcom/trpc/react";
import classNames from "@calcom/ui/classNames";
@@ -1,4 +1,3 @@
import type { Webhook } from "@prisma/client";
import Link from "next/link";
import { useState } from "react";
import { useFormContext } from "react-hook-form";
@@ -13,6 +12,7 @@ import { subscriberUrlReserved } from "@calcom/features/webhooks/lib/subscriberU
import ServerTrans from "@calcom/lib/components/ServerTrans";
import { APP_NAME } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { Webhook } from "@calcom/prisma/client";
import { trpc } from "@calcom/trpc/react";
import { Alert } from "@calcom/ui/components/alert";
import { Button } from "@calcom/ui/components/button";
@@ -1,6 +1,3 @@
import type { User as UserType } from "@prisma/client";
import type { Prisma } from "@prisma/client";
import type { LocationObject } from "@calcom/app-store/locations";
import { privacyFilteredLocations } from "@calcom/app-store/locations";
import { getAppFromSlug } from "@calcom/app-store/utils";
@@ -16,6 +13,8 @@ import { isRecurringEvent, parseRecurringEvent } from "@calcom/lib/isRecurringEv
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
import { UserRepository } from "@calcom/lib/server/repository/user";
import type { PrismaClient } from "@calcom/prisma";
import type { User as UserType } from "@calcom/prisma/client";
import type { Prisma } from "@calcom/prisma/client";
import type { Team } from "@calcom/prisma/client";
import type { BookerLayoutSettings } from "@calcom/prisma/zod-utils";
import {
@@ -574,301 +573,9 @@ export const getPublicEvent = async (
};
};
// A cleaner version of `getPublicEvent` that uses various helper functions like `processEventDataShared` and `getEventTypeHosts`
// There is still a lot of room for improvement, but it's a good starting point.
// For example, currently we have logic for all user / team / org / platform logic in this function.
// We should break this down into more dedicated functions.
const getPublicEventRefactored = async (
username: string,
eventSlug: string,
isTeamEvent: boolean | undefined,
org: string | null,
prisma: PrismaClient,
fromRedirectOfNonOrgLink: boolean,
currentUserId?: number,
fetchAllUsers = false
) => {
const usernameList = getUsernameList(username);
const orgQuery = org ? getSlugOrRequestedSlug(org) : null;
// In case of dynamic group event, we fetch user's data and use the default event.
if (usernameList.length > 1) {
const usersInOrgContext = await new UserRepository(prisma).findUsersByUsername({
usernameList,
orgSlug: org,
});
const users = usersInOrgContext;
const eventData = getPublicEventSelect(true);
const defaultEvent = getDefaultEvent(eventSlug);
let locations = defaultEvent.locations ? (defaultEvent.locations as LocationObject[]) : [];
// Get the preferred location type from the first user
const firstUsersMetadata = userMetadataSchema.parse(users[0].metadata || {});
const preferedLocationType = firstUsersMetadata?.defaultConferencingApp;
if (preferedLocationType?.appSlug) {
const foundApp = getAppFromSlug(preferedLocationType.appSlug);
const appType = foundApp?.appData?.location?.type;
if (appType) {
// Replace the location with the preferred location type
// This will still be default to daily if the app is not found
locations = [{ type: appType, link: preferedLocationType.appLink }] as LocationObject[];
}
}
const defaultEventBookerLayouts = {
enabledLayouts: [...bookerLayoutOptions],
defaultLayout: BookerLayouts.MONTH_VIEW,
} as BookerLayoutSettings;
const disableBookingTitle = !defaultEvent.isDynamic;
const unPublishedOrgUser = users.find((user) => user.profile?.organization?.slug === null);
let orgDetails: Pick<Team, "logoUrl" | "name"> | undefined;
if (org) {
orgDetails = await prisma.team.findFirstOrThrow({
where: {
slug: org,
},
select: {
logoUrl: true,
name: true,
},
});
}
return {
...defaultEvent,
bookingFields: getBookingFieldsWithSystemFields({ ...defaultEvent, disableBookingTitle }),
// Clears meta data since we don't want to send this in the public api.
subsetOfUsers: users.map((user) => ({
...user,
metadata: undefined,
bookerUrl: getBookerBaseUrlSync(user.profile?.organization?.slug ?? null),
})),
users: fetchAllUsers
? users.map((user) => ({
...user,
metadata: undefined,
bookerUrl: getBookerBaseUrlSync(user.profile?.organization?.slug ?? null),
}))
: undefined,
locations: privacyFilteredLocations(locations),
profile: {
weekStart: users[0].weekStart,
brandColor: users[0].brandColor,
darkBrandColor: users[0].darkBrandColor,
theme: null,
bookerLayouts: bookerLayoutsSchema.parse(
firstUsersMetadata?.defaultBookerLayouts || defaultEventBookerLayouts
),
...(orgDetails
? {
image: getPlaceholderAvatar(orgDetails?.logoUrl, orgDetails?.name),
name: orgDetails?.name,
username: org,
}
: {}),
},
entity: {
considerUnpublished: !fromRedirectOfNonOrgLink && unPublishedOrgUser !== undefined,
fromRedirectOfNonOrgLink,
orgSlug: org,
name: unPublishedOrgUser?.profile?.organization?.name ?? null,
teamSlug: null,
logoUrl: null,
hideProfileLink: false,
},
isInstantEvent: false,
instantMeetingParameters: [],
showInstantEventConnectNowModal: false,
autoTranslateDescriptionEnabled: false,
fieldTranslations: [],
};
}
const usersOrTeamQuery = isTeamEvent
? {
team: {
...getSlugOrRequestedSlug(username),
parent: orgQuery,
},
}
: {
users: {
some: {
...(orgQuery
? {
profiles: {
some: {
organization: orgQuery,
username: username,
},
},
}
: {
username,
profiles: { none: {} },
}),
},
},
team: null,
};
// In case it's not a group event, it's either a single user or a team, and we query that data.
let event = await prisma.eventType.findFirst({
where: {
slug: eventSlug,
...usersOrTeamQuery,
},
select: getPublicEventSelect(fetchAllUsers),
});
// If no event was found, check for platform org user event
if (!event && !orgQuery) {
event = await prisma.eventType.findFirst({
where: {
slug: eventSlug,
users: {
some: {
username,
isPlatformManaged: false,
profiles: {
some: {
organization: {
isPlatform: true,
},
},
},
},
},
},
select: getPublicEventSelect(fetchAllUsers),
});
}
if (!event) return null;
const eventMetaData = eventTypeMetaDataSchemaWithTypedApps.parse(event.metadata || {});
const teamMetadata = teamMetadataSchema.parse(event.team?.metadata || {});
const { subsetOfHosts, hosts } = await getEventTypeHosts({
hosts: event.hosts,
fetchAllUsers,
prisma,
});
const eventWithUserProfiles = {
...event,
owner: event.owner
? await new UserRepository(prisma).enrichUserWithItsProfile({
user: event.owner,
})
: null,
subsetOfHosts,
hosts,
};
let users =
(await getUsersFromEvent(eventWithUserProfiles, prisma)) ||
(await getOwnerFromUsersArray(prisma, event.id));
if (users === null) {
throw new Error(`EventType ${event.id} has no owner or users.`);
}
//In case the event schedule is not defined ,use the event owner's default schedule
if (!eventWithUserProfiles.schedule && eventWithUserProfiles.owner?.defaultScheduleId) {
const eventOwnerDefaultSchedule = await prisma.schedule.findUnique({
where: {
id: eventWithUserProfiles.owner?.defaultScheduleId,
},
select: {
id: true,
timeZone: true,
},
});
eventWithUserProfiles.schedule = eventOwnerDefaultSchedule;
}
let orgDetails: Pick<Team, "logoUrl" | "name"> | undefined | null;
if (org) {
orgDetails = await prisma.team.findFirst({
where: {
slug: org,
parentId: null,
},
select: {
logoUrl: true,
name: true,
},
});
}
const isTeamAdminOrOwner = await prisma.membership.findFirst({
where: {
userId: currentUserId ?? -1,
teamId: event.teamId ?? -1,
accepted: true,
role: { in: ["ADMIN", "OWNER"] },
},
});
const isOrgAdminOrOwner = await prisma.membership.findFirst({
where: {
userId: currentUserId ?? -1,
teamId: event.team?.parentId ?? -1,
accepted: true,
role: { in: ["ADMIN", "OWNER"] },
},
});
if (event.team?.isPrivate && !isTeamAdminOrOwner && !isOrgAdminOrOwner) {
users = [];
}
const eventDataShared = await processEventDataShared({
eventData: event,
metadata: eventMetaData,
prisma,
});
return {
...eventDataShared,
// getPublicEvent-specific overrides
owner: eventWithUserProfiles.owner,
subsetOfHosts,
hosts,
// Sets user data on profile object for easier access
profile: getProfileFromEvent(eventWithUserProfiles),
subsetOfUsers: users,
users: fetchAllUsers ? users : undefined,
entity: {
fromRedirectOfNonOrgLink,
considerUnpublished:
!fromRedirectOfNonOrgLink &&
(eventWithUserProfiles.team?.slug === null ||
eventWithUserProfiles.owner?.profile?.organization?.slug === null ||
eventWithUserProfiles.team?.parent?.slug === null),
orgSlug: org,
teamSlug: (eventWithUserProfiles.team?.slug || teamMetadata?.requestedSlug) ?? null,
name:
(eventWithUserProfiles.owner?.profile?.organization?.name ||
eventWithUserProfiles.team?.parent?.name ||
eventWithUserProfiles.team?.name) ??
null,
hideProfileLink: eventWithUserProfiles.team?.hideTeamProfileLink ?? false,
...(orgDetails
? {
logoUrl: getPlaceholderAvatar(orgDetails?.logoUrl, orgDetails?.name),
name: orgDetails?.name,
}
: {}),
},
};
};
const eventData = {
select: getPublicEventSelect(true),
} satisfies Prisma.EventTypeArgs;
type Event = Prisma.EventTypeGetPayload<typeof eventData>;
type Event = Prisma.EventTypeGetPayload<{ select: typeof eventData }>;
type GetProfileFromEventInput = Omit<Event, "hosts"> & {
hosts?: Event["hosts"];
@@ -1,9 +1,18 @@
import { PrismaClient } from "@prisma/client";
import { describe, it, expect, vi, beforeAll } from "vitest";
import { isCurrentlyAvailable } from "./getPublicEvent";
const prisma = new PrismaClient();
const prismaMock = {
schedule: {
findUniqueOrThrow: vi.fn(),
},
};
vi.mock("@calcom/prisma", () => {
return {
PrismaClient: vi.fn(() => prismaMock),
};
});
beforeAll(() => {
vi.setSystemTime(new Date("2024-09-01T10:00:00Z"));
@@ -19,12 +28,12 @@ describe("isCurrentlyAvailable", () => {
},
];
vi.spyOn(prisma.schedule, "findUniqueOrThrow").mockResolvedValue({
vi.spyOn(prismaMock.schedule, "findUniqueOrThrow").mockResolvedValue({
availability: mockAvailability,
});
const result = await isCurrentlyAvailable({
prisma,
prisma: prismaMock,
instantMeetingScheduleId: 1,
availabilityTimezone: "Europe/London",
length: 30,
@@ -42,12 +51,12 @@ describe("isCurrentlyAvailable", () => {
},
];
vi.spyOn(prisma.schedule, "findUniqueOrThrow").mockResolvedValue({
vi.spyOn(prismaMock.schedule, "findUniqueOrThrow").mockResolvedValue({
availability: mockAvailability,
});
const result = await isCurrentlyAvailable({
prisma,
prisma: prismaMock,
instantMeetingScheduleId: 1,
availabilityTimezone: "Europe/London",
length: 30,
@@ -65,12 +74,12 @@ describe("isCurrentlyAvailable", () => {
},
];
vi.spyOn(prisma.schedule, "findUniqueOrThrow").mockResolvedValue({
vi.spyOn(prismaMock.schedule, "findUniqueOrThrow").mockResolvedValue({
availability: mockAvailability,
});
const result = await isCurrentlyAvailable({
prisma,
prisma: prismaMock,
instantMeetingScheduleId: 1,
availabilityTimezone: "Europe/London",
length: 30,
@@ -88,12 +97,12 @@ describe("isCurrentlyAvailable", () => {
},
];
vi.spyOn(prisma.schedule, "findUniqueOrThrow").mockResolvedValue({
vi.spyOn(prismaMock.schedule, "findUniqueOrThrow").mockResolvedValue({
availability: mockAvailability,
});
const result = await isCurrentlyAvailable({
prisma,
prisma: prismaMock,
instantMeetingScheduleId: 1,
availabilityTimezone: "Europe/London",
length: 60,
@@ -118,12 +127,12 @@ describe("isCurrentlyAvailable", () => {
},
];
vi.spyOn(prisma.schedule, "findUniqueOrThrow").mockResolvedValue({
vi.spyOn(prismaMock.schedule, "findUniqueOrThrow").mockResolvedValue({
availability: mockAvailability,
});
const result = await isCurrentlyAvailable({
prisma,
prisma: prismaMock,
instantMeetingScheduleId: 1,
availabilityTimezone: "Europe/London",
length: 30,
+60 -6
View File
@@ -1,15 +1,20 @@
import type { z } from "zod";
import { z } from "zod";
import type { ChildrenEventType } from "@calcom/features/eventtypes/components/ChildrenEventTypeSelect";
import type { IntervalLimit } from "@calcom/lib/intervalLimits/intervalLimitSchema";
import type { EventLocationType } from "@calcom/lib/location";
import type { AttributesQueryValue } from "@calcom/lib/raqb/types";
import type { EventTypeTranslation } from "@calcom/prisma/client";
import type { PeriodType, SchedulingType } from "@calcom/prisma/enums";
import type { BookerLayoutSettings, eventTypeMetaDataSchemaWithTypedApps } from "@calcom/prisma/zod-utils";
import type { customInputSchema } from "@calcom/prisma/zod-utils";
import type { eventTypeBookingFields } from "@calcom/prisma/zod-utils";
import type { eventTypeColor } from "@calcom/prisma/zod-utils";
import type { PeriodType } from "@calcom/prisma/enums";
import { SchedulingType } from "@calcom/prisma/enums";
import type {
BookerLayoutSettings,
customInputSchema,
eventTypeMetaDataSchemaWithTypedApps,
eventTypeBookingFields,
eventTypeColor,
} from "@calcom/prisma/zod-utils";
import { eventTypeSlug, eventTypeLocations, EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import type { RouterOutputs, RouterInputs } from "@calcom/trpc/react";
import type { RecurringEvent } from "@calcom/types/Calendar";
@@ -228,6 +233,55 @@ export type SelectClassNames = {
container?: string;
};
export const EventTypeDuplicateInput = z
.object({
id: z.number(),
slug: z.string(),
title: z.string().min(1),
description: z.string(),
length: z.number(),
teamId: z.number().nullish(),
})
.strict();
const calVideoSettingsSchema = z
.object({
disableRecordingForGuests: z.boolean().nullish(),
disableRecordingForOrganizer: z.boolean().nullish(),
enableAutomaticTranscription: z.boolean().nullish(),
enableAutomaticRecordingForOrganizer: z.boolean().nullish(),
disableTranscriptionForGuests: z.boolean().nullish(),
disableTranscriptionForOrganizer: z.boolean().nullish(),
redirectUrlOnExit: z.string().url().nullish(),
})
.optional()
.nullable();
export const createEventTypeInput = z
.object({
title: z.string().min(1),
slug: eventTypeSlug,
description: z.string().nullish(),
length: z.number().int(),
hidden: z.boolean(),
teamId: z.number().int().nullish(),
schedulingType: z.nativeEnum(SchedulingType).nullish(),
locations: eventTypeLocations,
metadata: EventTypeMetaDataSchema.optional(),
disableGuests: z.boolean().optional(),
slotInterval: z.number().min(0).nullish(),
minimumBookingNotice: z.number().int().min(0).optional(),
beforeEventBuffer: z.number().int().min(0).optional(),
afterEventBuffer: z.number().int().min(0).optional(),
scheduleId: z.number().int().optional(),
calVideoSettings: calVideoSettingsSchema,
})
.partial({ hidden: true, locations: true })
.refine((data) => (data.teamId ? data.teamId && data.schedulingType : true), {
path: ["schedulingType"],
message: "You must select a scheduling type for team events",
});
export type FormValidationResult = {
isValid: boolean;
errors: Record<string, unknown>;
@@ -1,7 +1,5 @@
import { describe, expect, beforeAll, afterAll, beforeEach, it } from "vitest";
import prisma from "@calcom/prisma";
import type { AppFlags } from "./config";
import { FeaturesRepository } from "./features.repository";
@@ -1,8 +1,7 @@
import { Prisma } from "@prisma/client";
import { captureException } from "@sentry/nextjs";
import type { PrismaClient } from "@calcom/prisma";
import { Prisma } from "@calcom/prisma/client";
import type { AppFlags, TeamFeatures } from "./config";
import type { IFeaturesRepository } from "./features.repository.interface";
+1 -1
View File
@@ -1,7 +1,7 @@
import { PROMPT_TEMPLATES, LegacyRetellAIService } from "@calcom/features/calAIPhone";
import { validatePhoneNumber } from "@calcom/features/calAIPhone/retellAIService";
import { templateTypeEnum } from "@calcom/features/calAIPhone";
import type { TCreatePhoneCallSchema } from "@calcom/features/calAIPhone";
import { validatePhoneNumber } from "@calcom/features/calAIPhone/retellAIService";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import logger from "@calcom/lib/logger";
import prisma from "@calcom/prisma";
@@ -1,8 +1,8 @@
import { Prisma } from "@prisma/client";
import { describe, expect, beforeEach, afterEach, it } from "vitest";
import type { Field as FormField } from "@calcom/app-store/routing-forms/types/types";
import prisma from "@calcom/prisma";
import { Prisma } from "@calcom/prisma/client";
import { BookingStatus, SchedulingType } from "@calcom/prisma/enums";
describe("RoutingFormResponseDenormalized", () => {
@@ -1,7 +1,7 @@
import { Prisma } from "@prisma/client";
import { describe, expect, beforeEach, afterEach, it } from "vitest";
import prisma from "@calcom/prisma";
import { Prisma } from "@calcom/prisma/client";
import { BookingStatus } from "@calcom/prisma/enums";
describe("RoutingFormResponseField", () => {
@@ -1,3 +1,5 @@
import "../../../../../tests/libs/__mocks__/prisma";
import { describe, expect, it } from "vitest";
import dayjs from "@calcom/dayjs";
@@ -2,7 +2,7 @@ import { describe, expect, it, vi, beforeEach } from "vitest";
import type { readonlyPrisma } from "@calcom/prisma";
import { buildBaseWhereCondition } from "../trpc-router";
import { buildBaseWhereCondition } from "./buildBaseWhereCondition";
const mockTeamFindMany = vi.fn();
const mockMembershipFindMany = vi.fn();
@@ -0,0 +1,144 @@
import type { readonlyPrisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
type BuildBaseWhereConditionCtxType = {
userIsOwnerAdminOfParentTeam: boolean;
userOrganizationId: number | null;
insightsDb: typeof readonlyPrisma;
};
interface BuildBaseWhereConditionType {
teamId?: number | null;
eventTypeId?: number;
memberUserId?: number;
userId?: number;
isAll?: boolean;
ctx: BuildBaseWhereConditionCtxType;
}
export const buildBaseWhereCondition = async ({
teamId,
eventTypeId,
memberUserId,
userId,
isAll,
ctx,
}: BuildBaseWhereConditionType): Promise<{
whereCondition: Prisma.BookingTimeStatusDenormalizedWhereInput;
}> => {
const conditions: Prisma.BookingTimeStatusDenormalizedWhereInput[] = [];
// EventType Filter
if (eventTypeId) {
conditions.push({
OR: [{ eventTypeId }, { eventParentId: eventTypeId }],
});
}
// User/Member filter
if (memberUserId) {
conditions.push({ userId: memberUserId });
}
if (userId) {
conditions.push({
teamId: null,
userId: userId,
});
}
// organization-wide queries condition
if (isAll && ctx.userIsOwnerAdminOfParentTeam && ctx.userOrganizationId) {
const teamsFromOrg = await ctx.insightsDb.team.findMany({
where: {
parentId: ctx.userOrganizationId,
},
select: {
id: true,
},
});
const teamIds = [ctx.userOrganizationId, ...teamsFromOrg.map((t) => t.id)];
const usersFromOrg =
teamsFromOrg.length > 0
? await ctx.insightsDb.membership.findMany({
where: {
team: {
id: {
in: teamIds,
},
},
accepted: true,
},
select: {
userId: true,
},
})
: [];
conditions.push({
OR: [
{
teamId: {
in: teamIds,
},
isTeamBooking: true,
},
...(usersFromOrg.length > 0
? [
{
userId: {
in: usersFromOrg.map((u) => u.userId),
},
isTeamBooking: false,
},
]
: []),
],
});
}
// Team-specific queries condition
if (!isAll && teamId) {
const usersFromTeam = await ctx.insightsDb.membership.findMany({
where: {
teamId: teamId,
accepted: true,
},
select: {
userId: true,
},
});
const userIdsFromTeam = usersFromTeam.map((u) => u.userId);
conditions.push({
OR: [
{
teamId,
isTeamBooking: true,
},
{
userId: {
in: userIdsFromTeam,
},
isTeamBooking: false,
},
],
});
}
let whereCondition: Prisma.BookingTimeStatusDenormalizedWhereInput = {};
if (conditions.length === 1) {
whereCondition = conditions[0];
} else if (conditions.length > 1) {
whereCondition = { AND: conditions };
}
return {
whereCondition:
Object.keys(whereCondition).length === 0
? { id: -1 } // Ensure no data is returned for invalid parameters
: whereCondition,
};
};
@@ -1,4 +1,3 @@
import type { Prisma } from "@prisma/client";
// eslint-disable-next-line no-restricted-imports
import mapKeys from "lodash/mapKeys";
// eslint-disable-next-line no-restricted-imports
@@ -12,6 +11,7 @@ import { zodFields as routingFormFieldsSchema } from "@calcom/app-store/routing-
import { WEBAPP_URL } from "@calcom/lib/constants";
import type { InsightsRoutingBaseService } from "@calcom/lib/server/service/InsightsRoutingBaseService";
import { readonlyPrisma as prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
type RoutingFormInsightsTeamFilter = {
userId?: number | null;
@@ -1,4 +1,3 @@
import type { Prisma } from "@prisma/client";
import { z } from "zod";
import dayjs from "@calcom/dayjs";
@@ -13,6 +12,7 @@ import {
import { getInsightsBookingService } from "@calcom/lib/di/containers/InsightsBooking";
import { getInsightsRoutingService } from "@calcom/lib/di/containers/InsightsRouting";
import type { PrismaClient } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import authedProcedure from "@calcom/trpc/server/procedures/authedProcedure";
import { router } from "@calcom/trpc/server/trpc";
@@ -1,4 +1,3 @@
import { Prisma } from "@prisma/client";
import { randomBytes } from "crypto";
import type { NextApiRequest } from "next";
import short from "short-uuid";
@@ -25,6 +24,7 @@ import logger from "@calcom/lib/logger";
import { getTranslation } from "@calcom/lib/server/i18n";
import { createInstantMeetingWithCalVideo } from "@calcom/lib/videoClient";
import prisma from "@calcom/prisma";
import { Prisma } from "@calcom/prisma/client";
import { BookingStatus, WebhookTriggerEvents } from "@calcom/prisma/enums";
import { subscriptionSchema } from "./schema";
@@ -1,3 +1,5 @@
import { prisma } from "@calcom/prisma/__mocks__/prisma";
import { vi, type Mock, describe, it, expect, beforeEach } from "vitest";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
@@ -16,6 +18,10 @@ vi.mock("../../domain/mappers/PermissionMapper", () => ({
},
}));
vi.mock("@calcom/prisma", () => ({
prisma,
}));
describe("getResourcePermissions", () => {
let mockFeaturesRepository: {
checkIfTeamHasFeature: Mock;
@@ -35,7 +41,9 @@ describe("getResourcePermissions", () => {
getResourcePermissions: vi.fn(),
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(FeaturesRepository).mockImplementation(() => mockFeaturesRepository as any);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(PermissionCheckService).mockImplementation(() => mockPermissionCheckService as any);
});
@@ -160,6 +168,7 @@ describe("getResourcePermissions", () => {
[CrudAction.Update]: true,
[CrudAction.Delete]: false,
[CrudAction.Create]: false,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any);
const result = await getResourcePermissions({
@@ -191,6 +200,7 @@ describe("getResourcePermissions", () => {
vi.mocked(PermissionMapper.toActionMap).mockReturnValue({
[CrudAction.Read]: null,
[CrudAction.Update]: undefined,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any);
const result = await getResourcePermissions({
@@ -221,6 +231,7 @@ describe("getResourcePermissions", () => {
[CrudAction.Create]: true,
[CrudAction.Update]: true,
[CrudAction.Delete]: true,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any);
const result = await getResourcePermissions({
@@ -3,8 +3,8 @@ import { prisma } from "@calcom/prisma";
import type { MembershipRole } from "@calcom/prisma/enums";
import { PermissionMapper } from "../domain/mappers/PermissionMapper";
import type { Resource } from "../domain/types/permission-registry";
import { CrudAction, CustomAction } from "../domain/types/permission-registry";
import type { Resource, CustomAction } from "../domain/types/permission-registry";
import { CrudAction } from "../domain/types/permission-registry";
import { PermissionCheckService } from "../services/permission-check.service";
interface RoleMapping {
@@ -1,3 +1,5 @@
import { prisma } from "@calcom/prisma/__mocks__/prisma";
import { vi, type Mock, describe, it, expect, beforeEach } from "vitest";
import type { FeaturesRepository } from "@calcom/features/flags/features.repository";
@@ -15,6 +17,10 @@ vi.mock("@calcom/features/flags/features.repository");
vi.mock("@calcom/lib/server/repository/membership");
vi.mock("../permission.service");
vi.mock("@calcom/prisma", () => ({
prisma,
}));
type MockRepository = {
[K in keyof IPermissionRepository]: Mock;
};
@@ -1,6 +1,7 @@
import type { RolePermission } from "@prisma/client";
import { describe, it, expect } from "vitest";
import type { RolePermission } from "@calcom/prisma/client";
import type { PermissionString } from "../../domain/types/permission-registry";
import { PermissionDiffService } from "../permission-diff.service";
@@ -1,4 +1,4 @@
import type { PlatformOAuthClient } from "@prisma/client";
import type { PlatformOAuthClient } from "@calcom/prisma/client";
export function getPlatformParams(platformOAuthClient: PlatformOAuthClient) {
return {
@@ -1,4 +1,4 @@
import type { PlatformOAuthClient } from "@prisma/client";
import type { PlatformOAuthClient } from "@calcom/prisma/client";
export interface IPlatformOAuthClientRepository {
getByUserId(userId: number): Promise<PlatformOAuthClient | null>;
Loaded 100 of 623 files, more files were not shown because too many files have changed in this diff. Show more