refactor: remove @calcom/web imports from @calcom/features and add @calcom/testing package (#26480)

* fix: remove @calcom/web imports from packages/features to eliminate circular dependency

- Migrate UserTableUser and MemberPermissions types to packages/features/users/types/user-table.ts
- Migrate useGeo hook to packages/features/geo/GeoContext.tsx
- Migrate buildLegacyRequest to packages/lib/buildLegacyCtx.ts
- Migrate Calendar component to packages/features/calendars/weeklyview/components/
- Move test utilities (bookingScenario, fixtures) to packages/features/test/
- Update all imports in packages/features to use new locations
- Add re-exports in apps/web for backward compatibility

Co-Authored-By: [email protected] <[email protected]>

* fix: delete original implementation files and fix type issues

- Delete original calendar component files in apps/web (keep only re-export stubs)
- Migrate OutOfOfficeInSlots to packages/features/bookings/components
- Convert apps/web OutOfOfficeInSlots to re-export stub
- Fix className vs class issue in Calendar.tsx
- Fix @calcom/trpc import violation in user-table.ts by using structural type

Co-Authored-By: [email protected] <[email protected]>

* fix: add missing isGroup and contains fields to UserTableUser attributes type

Co-Authored-By: [email protected] <[email protected]>

* fix: update customRole type to match actual Prisma Role model

Co-Authored-By: [email protected] <[email protected]>

* fix build

* fix

* fix

* cleanup weeklyview

* fix

* refactor to mv MemberPermissions to types package

* add types dependency to features

* fix

* fix

* fix

* fix

* fix

* fix

* rename

* rename

* migrate

* migrate

* migrate

* fix

* fix

* fix

* refactor: move test utilities from packages/features/test to tests/libs

- Move bookingScenario utilities to tests/libs/bookingScenario
- Move fixtures to tests/libs/fixtures
- Update all imports in packages/features test files to use new location
- Update all imports in apps/web test files to use new location
- Eliminates duplication of test utilities between packages/features and apps/web

Co-Authored-By: [email protected] <[email protected]>

* fix: correct relative import paths for tests/libs in test files

Co-Authored-By: [email protected] <[email protected]>

* refactor: replace test utility implementations with re-exports to tests/libs

Co-Authored-By: [email protected] <[email protected]>

* fix: fix test import paths and move signup handler tests to apps/web

Co-Authored-By: [email protected] <[email protected]>

* fix: move buildLegacyCtx to packages/lib and restore handlers to packages/features

- Move buildLegacyCtx from apps/web/lib to packages/lib to break circular dependency
- Update apps/web/lib/buildLegacyCtx.ts to re-export from @calcom/lib
- Restore signup handlers and tests to packages/features/auth/signup/handlers
- Update handler imports to use @calcom/lib/buildLegacyCtx instead of @calcom/web/lib/buildLegacyCtx

Co-Authored-By: [email protected] <[email protected]>

* fix: update recurring-event.test.ts imports to use tests/libs path

Co-Authored-By: [email protected] <[email protected]>

* refactor: delete test re-export files and update imports to use tests/libs directly

Co-Authored-By: [email protected] <[email protected]>

* fix: update remaining test imports to use tests/libs directly

Co-Authored-By: [email protected] <[email protected]>

* fix: update handleRecurringEventBooking calls to match function signature (1 arg)

Co-Authored-By: [email protected] <[email protected]>

* remove

* migrate tests

* migrate tests

* refactor: update test mock imports by removing  and using async  for mock creators.

* fix type errors

* fix: add type assertion for MockUser in p2002.test-suite.ts

Co-Authored-By: [email protected] <[email protected]>

* fix: restore locale import in compareReminderBodyToTemplate.test.ts using relative path

Co-Authored-By: [email protected] <[email protected]>

* feat: create @calcom/testing package and migrate tests from /tests directory

- Created new @calcom/testing package in /packages/testing
- Moved all files from /tests to /packages/testing
- Updated all imports across the codebase to use @calcom/testing alias
- Removed /tests directory at root level

This allows other packages like @calcom/features and @calcom/web to import
testing utilities using the @calcom/testing alias instead of relative paths.

Co-Authored-By: [email protected] <[email protected]>

* fix

* fix

* fix: add missing useBookings export to @calcom/atoms package

Co-Authored-By: [email protected] <[email protected]>

* fix: add missing useCalendarsBusyTimes and useConnectedCalendars exports to @calcom/atoms

Co-Authored-By: [email protected] <[email protected]>

* chore: add @calcom/testing as explicit devDependency to packages that use it

Co-Authored-By: [email protected] <[email protected]>

* refactor: move setupVitest.ts into @calcom/testing package

Co-Authored-By: [email protected] <[email protected]>

* fix

* chore: add biome rules to restrict @calcom/testing imports

Co-Authored-By: [email protected] <[email protected]>

* fix

* rename libs to lib

* rename libs to lib

* add rule

* add rule

* refactor: remove @calcom/features imports from @calcom/testing

- Move mockPaymentSuccessWebhookFromStripe to fresh-booking.test.ts
- Replace ProfileRepository.generateProfileUid() with uuidv4()
- Clone Tracking type into @calcom/testing/src/lib/types.ts
- Update imports in expects.ts and getMockRequestDataForBooking.ts
- Move source files into src/ folder
- Move CalendarManager mock to @calcom/features

Co-Authored-By: [email protected] <[email protected]>

* fix: add explicit exports for nested paths in @calcom/testing

Co-Authored-By: [email protected] <[email protected]>

* improve

* improve

* fix

* fix

* fix type checks

* fix type checks

* fix type checks

* fix tests

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
Benny JooandDevin AI authored and GitHub committed 2026-01-08 16:59:11 +09:00
1 parent 04e447058c
commit f5d345b133
209 files changed
+593 -522

No files matched your search

@@ -3,7 +3,7 @@
import { useState } from "react";
import dayjs from "@calcom/dayjs";
import { Calendar } from "@calcom/features/calendars/weeklyview";
import { Calendar } from "@calcom/web/modules/calendars/weeklyview/components/Calendar";
import type { CalendarEvent } from "@calcom/features/calendars/weeklyview/types/events";
import type { CalendarComponentProps, Hours } from "@calcom/features/calendars/weeklyview/types/state";
@@ -1,4 +1,4 @@
import prismaMock from "../../../../../../../../tests/libs/__mocks__/prismaMock";
import prismaMock from "@calcom/testing/lib/__mocks__/prismaMock";
import jwt from "jsonwebtoken";
// Import mocked dependencies after mocks are set up
@@ -0,0 +1,104 @@
import type { Mock } from "vitest";
import { vi } from "vitest";
import type { MockResponse } from "@calcom/features/auth/signup/handlers/__tests__/mocks/next.mocks";
import {
prismaMock,
resetPrismaMock,
} from "@calcom/features/auth/signup/handlers/__tests__/mocks/prisma.mocks";
import {
createMockTeam,
createMockFoundToken,
} from "@calcom/features/auth/signup/handlers/__tests__/mocks/signup.factories";
import type { SignupBody } from "@calcom/features/auth/signup/handlers/__tests__/mocks/signup.factories";
const mockFindTokenByToken: Mock = vi.fn();
const mockValidateAndGetCorrectedUsernameForTeam: Mock = vi.fn();
type UsernameStatus = {
statusCode: 200 | 402 | 418;
requestedUserName: string;
json: { available: boolean; premium: boolean };
};
type InnerHandler = (body: Record<string, string>, status: UsernameStatus) => Promise<MockResponse>;
var mockCapturedHandler: InnerHandler | null;
vi.mock("next/server", async () => {
const { createNextServerMock } = await import("@calcom/features/auth/signup/handlers/__tests__/mocks/next.mocks");
return createNextServerMock();
});
vi.mock("next/headers", async () => {
const { createNextHeadersMock } = await import("@calcom/features/auth/signup/handlers/__tests__/mocks/next.mocks");
return createNextHeadersMock();
});
vi.mock("@calcom/prisma", async () => {
const { createPrismaMock } = await import("@calcom/features/auth/signup/handlers/__tests__/mocks/prisma.mocks");
return createPrismaMock();
});
vi.mock("@calcom/prisma/client", async () => {
const { createPrismaMock } = await import("@calcom/features/auth/signup/handlers/__tests__/mocks/prisma.mocks");
return createPrismaMock();
});
vi.mock("@calcom/lib/logger", () => ({
default: { getSubLogger: () => ({ warn: vi.fn(), error: vi.fn(), debug: vi.fn(), info: vi.fn() }) },
}));
vi.mock("@calcom/lib/auth/hashPassword", () => ({ hashPassword: vi.fn().mockResolvedValue("hashed") }));
vi.mock("@calcom/lib/constants", () => ({ WEBAPP_URL: "http://localhost:3000" }));
vi.mock("@calcom/lib/tracking", () => ({ getTrackingFromCookies: vi.fn().mockReturnValue({}) }));
vi.mock("@calcom/app-store/stripepayment/lib/utils", () => ({ getPremiumMonthlyPlanPriceId: vi.fn() }));
vi.mock("@calcom/features/auth/lib/getLocaleFromRequest", () => ({ getLocaleFromRequest: vi.fn().mockResolvedValue("en") }));
vi.mock("@calcom/features/auth/lib/verifyEmail", () => ({ sendEmailVerification: vi.fn() }));
vi.mock("@calcom/features/auth/signup/utils/createOrUpdateMemberships", () => ({ createOrUpdateMemberships: vi.fn() }));
vi.mock("@calcom/features/auth/signup/utils/prefillAvatar", () => ({ prefillAvatar: vi.fn() }));
vi.mock("@calcom/features/auth/signup/utils/validateUsername", () => ({
validateAndGetCorrectedUsernameAndEmail: vi.fn().mockResolvedValue({ isValid: true, username: "testuser" }),
}));
vi.mock("@calcom/features/ee/billing/di/containers/Billing", () => ({
getBillingProviderService: vi.fn().mockReturnValue({
createCustomer: vi.fn().mockResolvedValue({ stripeCustomerId: "cus_123" }),
}),
}));
vi.mock("@calcom/features/watchlist/lib/telemetry", () => ({ sentrySpan: {} }));
vi.mock("@calcom/features/watchlist/operations/check-if-email-in-watchlist.controller", () => ({
checkIfEmailIsBlockedInWatchlistController: vi.fn().mockResolvedValue(false),
}));
vi.mock("@calcom/web/lib/buildLegacyCtx", () => ({ buildLegacyRequest: vi.fn() }));
vi.mock("@calcom/features/auth/signup/utils/organization", () => ({ joinAnyChildTeamOnOrgInvite: vi.fn() }));
vi.mock("@calcom/features/auth/signup/utils/token", () => ({
findTokenByToken: (...args: unknown[]) => mockFindTokenByToken(...args),
throwIfTokenExpired: vi.fn(),
validateAndGetCorrectedUsernameForTeam: (...args: unknown[]) => mockValidateAndGetCorrectedUsernameForTeam(...args),
}));
// Capture inner handler from usernameHandler wrapper
vi.mock("@calcom/lib/server/username", () => ({
usernameHandler: (handler: InnerHandler) => {
mockCapturedHandler = handler;
return handler;
},
}));
// Import after mocks
import "./calcomSignupHandler";
import { runP2002TestSuite } from "@calcom/features/auth/signup/handlers/__tests__/p2002.test-suite";
function callHandler(body: SignupBody): Promise<MockResponse> {
if (!mockCapturedHandler) throw new Error("Handler not captured");
return mockCapturedHandler(body as unknown as Record<string, string>, {
statusCode: 200,
requestedUserName: body.username || "testuser",
json: { available: true, premium: false },
});
}
runP2002TestSuite("calcomHandler", callHandler, () => {
vi.clearAllMocks();
resetPrismaMock();
mockFindTokenByToken.mockResolvedValue(createMockFoundToken());
mockValidateAndGetCorrectedUsernameForTeam.mockResolvedValue("testuser");
prismaMock.team.findUnique.mockResolvedValue(createMockTeam() as never);
prismaMock.verificationToken.delete.mockResolvedValue({} as never);
});
@@ -0,0 +1,311 @@
import { cookies, headers } from "next/headers";
import { NextResponse } from "next/server";
import { getPremiumMonthlyPlanPriceId } from "@calcom/app-store/stripepayment/lib/utils";
import { getLocaleFromRequest } from "@calcom/features/auth/lib/getLocaleFromRequest";
import { sendEmailVerification } from "@calcom/features/auth/lib/verifyEmail";
import { createOrUpdateMemberships } from "@calcom/features/auth/signup/utils/createOrUpdateMemberships";
import { prefillAvatar } from "@calcom/features/auth/signup/utils/prefillAvatar";
import { validateAndGetCorrectedUsernameAndEmail } from "@calcom/features/auth/signup/utils/validateUsername";
import { getBillingProviderService } from "@calcom/features/ee/billing/di/containers/Billing";
import { sentrySpan } from "@calcom/features/watchlist/lib/telemetry";
import { checkIfEmailIsBlockedInWatchlistController } from "@calcom/features/watchlist/operations/check-if-email-in-watchlist.controller";
import { hashPassword } from "@calcom/lib/auth/hashPassword";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { isPrismaError } from "@calcom/lib/server/getServerErrorFromUnknown";
import type { CustomNextApiHandler } from "@calcom/lib/server/username";
import { usernameHandler } from "@calcom/lib/server/username";
import { getTrackingFromCookies } from "@calcom/lib/tracking";
import prisma from "@calcom/prisma";
import { CreationSource } from "@calcom/prisma/enums";
import { IdentityProvider } from "@calcom/prisma/enums";
import { signupSchema } from "@calcom/prisma/zod-utils";
import { buildLegacyRequest } from "@calcom/web/lib/buildLegacyCtx";
import { joinAnyChildTeamOnOrgInvite } from "@calcom/features/auth/signup/utils/organization";
import { SIGNUP_ERROR_CODES } from "@calcom/features/auth/signup/constants";
import {
findTokenByToken,
throwIfTokenExpired,
validateAndGetCorrectedUsernameForTeam,
} from "@calcom/features/auth/signup/utils/token";
const log = logger.getSubLogger({ prefix: ["signupCalcomHandler"] });
const handler: CustomNextApiHandler = async (body, usernameStatus) => {
const {
email: _email,
password,
token,
} = signupSchema
.pick({
email: true,
password: true,
token: true,
})
.parse(body);
const billingService = getBillingProviderService();
const shouldLockByDefault = await checkIfEmailIsBlockedInWatchlistController({
email: _email,
organizationId: null,
span: sentrySpan,
});
log.debug("handler", { email: _email });
let username: string | null = usernameStatus.requestedUserName;
let checkoutSessionId: string | null = null;
// Check for premium username
if (usernameStatus.statusCode === 418) {
return NextResponse.json(usernameStatus.json, { status: 418 });
}
// Validate the user
if (!username) {
throw new HttpError({
statusCode: 422,
message: "Invalid username",
});
}
const email = _email.toLowerCase();
let foundToken: { id: number; teamId: number | null; expires: Date } | null = null;
if (token) {
foundToken = await findTokenByToken({ token });
throwIfTokenExpired(foundToken?.expires);
username = await validateAndGetCorrectedUsernameForTeam({
username,
email,
teamId: foundToken?.teamId ?? null,
isSignup: true,
});
if (foundToken?.teamId) {
const existingUser = await prisma.user.findUnique({
where: { email },
select: { invitedTo: true },
});
if (existingUser && existingUser.invitedTo !== foundToken.teamId) {
return NextResponse.json({ message: SIGNUP_ERROR_CODES.USER_ALREADY_EXISTS }, { status: 409 });
}
}
} else {
const usernameAndEmailValidation = await validateAndGetCorrectedUsernameAndEmail({
username,
email,
isSignup: true,
});
if (!usernameAndEmailValidation.isValid) {
throw new HttpError({
statusCode: 409,
message: "Username or email is already taken",
});
}
if (!usernameAndEmailValidation.username) {
throw new HttpError({
statusCode: 422,
message: "Invalid username",
});
}
username = usernameAndEmailValidation.username;
}
// Create the customer in Stripe with ad tracking metadata
const cookieStore = await cookies();
const cookiesObj = Object.fromEntries(cookieStore.getAll().map((c) => [c.name, c.value]));
const tracking = getTrackingFromCookies(cookiesObj);
const customer = await billingService.createCustomer({
email,
metadata: {
email /* Stripe customer email can be changed, so we add this to keep track of which email was used to signup */,
username,
...(tracking.googleAds?.gclid && {
gclid: tracking.googleAds.gclid,
campaignId: tracking.googleAds.campaignId,
}),
...(tracking.linkedInAds?.liFatId && {
liFatId: tracking.linkedInAds.liFatId,
linkedInCampaignId: tracking.linkedInAds.campaignId,
}),
},
});
const returnUrl = `${WEBAPP_URL}/api/integrations/stripepayment/paymentCallback?checkoutSessionId={CHECKOUT_SESSION_ID}&callbackUrl=/auth/verify?sessionId={CHECKOUT_SESSION_ID}`;
// Pro username, must be purchased
if (usernameStatus.statusCode === 402) {
const checkoutSession = await billingService.createSubscriptionCheckout({
mode: "subscription",
customerId: customer.stripeCustomerId,
successUrl: returnUrl,
cancelUrl: returnUrl,
priceId: getPremiumMonthlyPlanPriceId(),
quantity: 1,
allowPromotionCodes: true,
});
/** We create a username-less user until he pays */
checkoutSessionId = checkoutSession.sessionId;
username = null;
}
// Hash the password
const hashedPassword = await hashPassword(password);
if (foundToken && foundToken?.teamId) {
const team = await prisma.team.findUnique({
where: {
id: foundToken.teamId,
},
include: {
parent: {
select: {
id: true,
slug: true,
organizationSettings: true,
},
},
organizationSettings: true,
},
});
if (team) {
const organizationId = team.isOrganization ? team.id : team.parent?.id ?? null;
if (username) {
const existingUserByUsername = await prisma.user.findFirst({
where: {
username,
organizationId,
NOT: { email },
},
select: { id: true },
});
if (existingUserByUsername) {
return NextResponse.json({ message: SIGNUP_ERROR_CODES.USER_ALREADY_EXISTS }, { status: 409 });
}
}
let user: { id: number };
try {
user = await prisma.user.upsert({
where: { email },
update: {
username,
emailVerified: new Date(Date.now()),
identityProvider: IdentityProvider.CAL,
password: {
upsert: {
create: { hash: hashedPassword },
update: { hash: hashedPassword },
},
},
organizationId,
},
create: {
username,
email,
emailVerified: new Date(Date.now()),
identityProvider: IdentityProvider.CAL,
password: { create: { hash: hashedPassword } },
organizationId,
},
select: { id: true },
});
} catch (error) {
if (isPrismaError(error) && error.code === "P2002") {
const target = String(error.meta?.target ?? "");
if (target.includes("email") || target.includes("username")) {
return NextResponse.json({ message: SIGNUP_ERROR_CODES.USER_ALREADY_EXISTS }, { status: 409 });
}
}
throw error;
}
await createOrUpdateMemberships({
user,
team,
});
// Accept any child team invites for orgs.
if (team.parent) {
await joinAnyChildTeamOnOrgInvite({
userId: user.id,
org: team.parent,
});
}
}
// Cleanup token after use
await prisma.verificationToken.delete({
where: {
id: foundToken.id,
},
});
} else {
// Create the user
try {
await prisma.user.create({
data: {
username,
email,
locked: shouldLockByDefault,
password: { create: { hash: hashedPassword } },
metadata: {
stripeCustomerId: customer.stripeCustomerId,
checkoutSessionId,
},
creationSource: CreationSource.WEBAPP,
},
});
} catch (error) {
// Fallback for race conditions where user was created between our check and create
if (isPrismaError(error) && error.code === "P2002") {
const target = String(error.meta?.target ?? "");
if (target.includes("email") || target.includes("username")) {
return NextResponse.json(
{ message: SIGNUP_ERROR_CODES.USER_ALREADY_EXISTS },
{ status: 409 }
);
}
}
throw error;
}
if (process.env.AVATARAPI_USERNAME && process.env.AVATARAPI_PASSWORD) {
await prefillAvatar({ email });
}
// Only send verification email for non-premium usernames
// Premium usernames will get a magic link after payment in paymentCallback
if (!checkoutSessionId) {
sendEmailVerification({
email,
language: await getLocaleFromRequest(buildLegacyRequest(await headers(), await cookies())),
username: username || "",
});
}
}
if (checkoutSessionId) {
console.log("Created user but missing payment", checkoutSessionId);
return NextResponse.json(
{ message: "Created user but missing payment", checkoutSessionId },
{ status: 402 }
);
}
return NextResponse.json(
{ message: "Created user", stripeCustomerId: customer.stripeCustomerId },
{ status: 201 }
);
};
export default usernameHandler(handler);
@@ -0,0 +1,64 @@
import type { Mock } from "vitest";
import { vi } from "vitest";
import {
prismaMock,
resetPrismaMock,
} from "@calcom/features/auth/signup/handlers/__tests__/mocks/prisma.mocks";
import {
createMockTeam,
createMockFoundToken,
} from "@calcom/features/auth/signup/handlers/__tests__/mocks/signup.factories";
import type { SignupBody } from "@calcom/features/auth/signup/handlers/__tests__/mocks/signup.factories";
const mockFindTokenByToken: Mock = vi.fn();
const mockValidateAndGetCorrectedUsernameForTeam: Mock = vi.fn();
vi.mock("next/server", async () => {
const { createNextServerMock } = await import("@calcom/features/auth/signup/handlers/__tests__/mocks/next.mocks");
return createNextServerMock();
});
vi.mock("@calcom/prisma", async () => {
const { createPrismaMock } = await import("@calcom/features/auth/signup/handlers/__tests__/mocks/prisma.mocks");
return createPrismaMock();
});
vi.mock("@calcom/prisma/client", async () => {
const { createPrismaMock } = await import("@calcom/features/auth/signup/handlers/__tests__/mocks/prisma.mocks");
return createPrismaMock();
});
vi.mock("@calcom/lib/logger", () => ({
default: { getSubLogger: () => ({ warn: vi.fn(), error: vi.fn(), debug: vi.fn(), info: vi.fn() }) },
}));
vi.mock("@calcom/lib/auth/hashPassword", () => ({ hashPassword: vi.fn().mockResolvedValue("hashed") }));
vi.mock("@calcom/lib/slugify", () => ({ default: vi.fn((s: string) => s.toLowerCase()) }));
vi.mock("@calcom/lib/constants", () => ({ IS_PREMIUM_USERNAME_ENABLED: false }));
vi.mock("@calcom/lib/server/username", () => ({ isUsernameReservedDueToMigration: vi.fn().mockResolvedValue(false) }));
vi.mock("@calcom/features/auth/lib/verifyEmail", () => ({ sendEmailVerification: vi.fn() }));
vi.mock("@calcom/features/auth/signup/utils/createOrUpdateMemberships", () => ({ createOrUpdateMemberships: vi.fn() }));
vi.mock("@calcom/features/auth/signup/utils/validateUsername", () => ({
validateAndGetCorrectedUsernameAndEmail: vi.fn().mockResolvedValue({ isValid: true, username: "testuser" }),
}));
vi.mock("@calcom/features/auth/signup/utils/organization", () => ({ joinAnyChildTeamOnOrgInvite: vi.fn() }));
vi.mock("@calcom/features/auth/signup/utils/prefillAvatar", () => ({ prefillAvatar: vi.fn() }));
vi.mock("@calcom/features/auth/signup/utils/token", () => ({
findTokenByToken: (...args: unknown[]) => mockFindTokenByToken(...args),
throwIfTokenExpired: vi.fn(),
validateAndGetCorrectedUsernameForTeam: (...args: unknown[]) => mockValidateAndGetCorrectedUsernameForTeam(...args),
}));
// Import after mocks
import handler from "./selfHostedHandler";
import { runP2002TestSuite } from "@calcom/features/auth/signup/handlers/__tests__/p2002.test-suite";
function callHandler(body: SignupBody): ReturnType<typeof handler> {
return handler(body as unknown as Record<string, string>);
}
runP2002TestSuite("selfHostedHandler", callHandler, () => {
vi.clearAllMocks();
resetPrismaMock();
mockFindTokenByToken.mockResolvedValue(createMockFoundToken());
mockValidateAndGetCorrectedUsernameForTeam.mockResolvedValue("testuser");
prismaMock.team.findUnique.mockResolvedValue(createMockTeam() as never);
prismaMock.verificationToken.delete.mockResolvedValue({} as never);
});
@@ -0,0 +1,224 @@
import { NextResponse } from "next/server";
import { checkPremiumUsername } from "@calcom/ee/common/lib/checkPremiumUsername";
import { sendEmailVerification } from "@calcom/features/auth/lib/verifyEmail";
import { createOrUpdateMemberships } from "@calcom/features/auth/signup/utils/createOrUpdateMemberships";
import { validateAndGetCorrectedUsernameAndEmail } from "@calcom/features/auth/signup/utils/validateUsername";
import { hashPassword } from "@calcom/lib/auth/hashPassword";
import { IS_PREMIUM_USERNAME_ENABLED } from "@calcom/lib/constants";
import logger from "@calcom/lib/logger";
import { isPrismaError } from "@calcom/lib/server/getServerErrorFromUnknown";
import { isUsernameReservedDueToMigration } from "@calcom/lib/server/username";
import slugify from "@calcom/lib/slugify";
import prisma from "@calcom/prisma";
import { IdentityProvider } from "@calcom/prisma/enums";
import { signupSchema } from "@calcom/prisma/zod-utils";
import { joinAnyChildTeamOnOrgInvite } from "@calcom/features/auth/signup/utils/organization";
import { prefillAvatar } from "@calcom/features/auth/signup/utils/prefillAvatar";
import { SIGNUP_ERROR_CODES } from "@calcom/features/auth/signup/constants";
import {
findTokenByToken,
throwIfTokenExpired,
validateAndGetCorrectedUsernameForTeam,
} from "@calcom/features/auth/signup/utils/token";
export default async function handler(body: Record<string, string>) {
const { email, password, language, token } = signupSchema.parse(body);
const username = slugify(body.username);
const userEmail = email.toLowerCase();
if (!username) {
return NextResponse.json({ message: "Invalid username" }, { status: 422 });
}
let foundToken: { id: number; teamId: number | null; expires: Date } | null = null;
let correctedUsername = username;
if (token) {
foundToken = await findTokenByToken({ token });
throwIfTokenExpired(foundToken?.expires);
correctedUsername = await validateAndGetCorrectedUsernameForTeam({
username,
email: userEmail,
teamId: foundToken?.teamId,
isSignup: true,
});
if (foundToken?.teamId) {
const existingUser = await prisma.user.findUnique({
where: { email: userEmail },
select: { invitedTo: true },
});
if (existingUser && existingUser.invitedTo !== foundToken.teamId) {
return NextResponse.json({ message: SIGNUP_ERROR_CODES.USER_ALREADY_EXISTS }, { status: 409 });
}
}
} else {
const userValidation = await validateAndGetCorrectedUsernameAndEmail({
username,
email: userEmail,
isSignup: true,
});
if (!userValidation.isValid) {
logger.error("User validation failed", { userValidation });
return NextResponse.json({ message: "Username or email is already taken" }, { status: 409 });
}
if (!userValidation.username) {
return NextResponse.json({ message: "Invalid username" }, { status: 422 });
}
correctedUsername = userValidation.username;
}
const hashedPassword = await hashPassword(password);
if (foundToken && foundToken?.teamId) {
const team = await prisma.team.findUnique({
where: {
id: foundToken.teamId,
},
include: {
parent: {
select: {
id: true,
slug: true,
organizationSettings: true,
},
},
organizationSettings: true,
},
});
if (team) {
const isInviteForATeamInOrganization = !!team.parent;
const isCheckingUsernameInGlobalNamespace = !team.isOrganization && !isInviteForATeamInOrganization;
if (isCheckingUsernameInGlobalNamespace) {
const isUsernameAvailable = !(await isUsernameReservedDueToMigration(correctedUsername));
if (!isUsernameAvailable) {
return NextResponse.json({ message: "A user exists with that username" }, { status: 409 });
}
}
const organizationId = team.isOrganization ? team.id : team.parent?.id ?? null;
const existingUserByUsername = await prisma.user.findFirst({
where: {
username: correctedUsername,
organizationId,
NOT: { email: userEmail },
},
select: { id: true },
});
if (existingUserByUsername) {
return NextResponse.json({ message: SIGNUP_ERROR_CODES.USER_ALREADY_EXISTS }, { status: 409 });
}
let user: { id: number };
try {
user = await prisma.user.upsert({
where: { email: userEmail },
update: {
username: correctedUsername,
emailVerified: new Date(Date.now()),
identityProvider: IdentityProvider.CAL,
password: {
upsert: {
create: { hash: hashedPassword },
update: { hash: hashedPassword },
},
},
organizationId,
},
create: {
username: correctedUsername,
email: userEmail,
emailVerified: new Date(Date.now()),
identityProvider: IdentityProvider.CAL,
password: { create: { hash: hashedPassword } },
organizationId,
},
select: { id: true },
});
} catch (error) {
if (isPrismaError(error) && error.code === "P2002") {
const target = String(error.meta?.target ?? "");
if (target.includes("email") || target.includes("username")) {
return NextResponse.json({ message: SIGNUP_ERROR_CODES.USER_ALREADY_EXISTS }, { status: 409 });
}
}
throw error;
}
await createOrUpdateMemberships({
user,
team,
});
// Accept any child team invites for orgs.
if (team.parent) {
await joinAnyChildTeamOnOrgInvite({
userId: user.id,
org: team.parent,
});
}
}
// Cleanup token after use
await prisma.verificationToken.delete({
where: {
id: foundToken.id,
},
});
} else {
const isUsernameAvailable = !(await isUsernameReservedDueToMigration(correctedUsername));
if (!isUsernameAvailable) {
return NextResponse.json({ message: "A user exists with that username" }, { status: 409 });
}
if (IS_PREMIUM_USERNAME_ENABLED) {
const checkUsername = await checkPremiumUsername(correctedUsername);
if (checkUsername.premium) {
return NextResponse.json(
{ message: "Sign up from https://cal.com/signup to claim your premium username" },
{ status: 422 }
);
}
}
try {
await prisma.user.create({
data: {
username: correctedUsername,
email: userEmail,
password: { create: { hash: hashedPassword } },
identityProvider: IdentityProvider.CAL,
},
select: { id: true },
});
} catch (error) {
// Fallback for race conditions where user was created between our check and create
if (isPrismaError(error) && error.code === "P2002") {
const target = String(error.meta?.target ?? "");
if (target.includes("email") || target.includes("username")) {
return NextResponse.json(
{ message: SIGNUP_ERROR_CODES.USER_ALREADY_EXISTS },
{ status: 409 }
);
}
}
throw error;
}
if (process.env.AVATARAPI_USERNAME && process.env.AVATARAPI_PASSWORD) {
await prefillAvatar({ email: userEmail });
}
await sendEmailVerification({
email: userEmail,
username: correctedUsername,
language,
});
}
return NextResponse.json({ message: "Created user" }, { status: 201 });
}
+2 -2
View File
@@ -2,8 +2,8 @@ import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
import { parseRequestData } from "app/api/parseRequestData";
import { NextResponse, type NextRequest } from "next/server";
import calcomSignupHandler from "@calcom/feature-auth/signup/handlers/calcomHandler";
import selfHostedSignupHandler from "@calcom/feature-auth/signup/handlers/selfHostedHandler";
import calcomSignupHandler from "./handlers/calcomSignupHandler";
import selfHostedSignupHandler from "./handlers/selfHostedHandler";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import { IS_PREMIUM_USERNAME_ENABLED } from "@calcom/lib/constants";
@@ -1,4 +1,4 @@
import prismock from "../../../../../../../tests/libs/__mocks__/prisma";
import prismock from "@calcom/testing/lib/__mocks__/prisma";
import { describe, it, expect, beforeEach } from "vitest";
@@ -1,4 +1,4 @@
import prismock from "../../../../../../../tests/libs/__mocks__/prisma";
import prismock from "@calcom/testing/lib/__mocks__/prisma";
import "@calcom/lib/server/__mocks__/serviceAccountKey";
import { describe, it, expect, beforeEach, vi } from "vitest";
@@ -1,4 +1,4 @@
import "../../../../../../../tests/libs/__mocks__/prisma";
import "@calcom/testing/lib/__mocks__/prisma";
import { beforeEach, describe, it, expect, vi } from "vitest";
import { onSubmissionOfFormResponse } from "@calcom/app-store/routing-forms/lib/formSubmissionUtils";
@@ -1,4 +1,4 @@
import prismock from "../../../../tests/libs/__mocks__/prisma";
import prismock from "@calcom/testing/lib/__mocks__/prisma";
import { v4 } from "uuid";
import { describe, expect, it, vi, beforeEach } from "vitest";
+2 -2
View File
@@ -7,8 +7,8 @@ import type { ReadonlyURLSearchParams } from "next/navigation";
import { usePathname, useSearchParams } from "next/navigation";
import { NuqsAdapter } from "nuqs/adapters/next/app";
import DynamicPostHogProvider from "@calcom/features/ee/event-tracking/lib/posthog/providerDynamic";
import DynamicPostHogPageView from "@calcom/features/ee/event-tracking/lib/posthog/web/pageViewDynamic";
import DynamicPostHogProvider from "~/ee/posthog/providerDynamic";
import DynamicPostHogPageView from "~/ee/posthog/pageViewDynamic";
import { OrgBrandingProvider } from "@calcom/features/ee/organizations/context/provider";
import { FeatureProvider } from "@calcom/features/flags/context/provider";
import { useFlags } from "@calcom/features/flags/hooks";
@@ -6,8 +6,8 @@ import {
getMockBookingAttendee,
getOrganizer,
getBooker,
} from "@calcom/web/test/utils/bookingScenario/bookingScenario";
import { expectWebhookToHaveBeenCalledWith } from "@calcom/web/test/utils/bookingScenario/expects";
} from "@calcom/testing/lib/bookingScenario/bookingScenario";
import { expectWebhookToHaveBeenCalledWith } from "@calcom/testing/lib/bookingScenario/expects";
import { NextRequest } from "next/server";
import { createMocks } from "node-mocks-http";
@@ -6,7 +6,7 @@ import { Suspense } from "react";
import { Loader } from "@calcom/ui/components/skeleton";
const TroubleshooterClientOnly = dynamic(
() => import("@calcom/features/troubleshooter/Troubleshooter").then((mod) => mod.Troubleshooter),
() => import("@calcom/web/modules/troubleshooter/components/Troubleshooter").then((mod) => mod.Troubleshooter),
{
ssr: false,
}
@@ -4,7 +4,7 @@ import { useMemo, useEffect } from "react";
import dayjs from "@calcom/dayjs";
import { useTimePreferences } from "@calcom/features/bookings/lib";
import { Calendar } from "@calcom/features/calendars/weeklyview";
import { Calendar } from "@calcom/web/modules/calendars/weeklyview/components/Calendar";
import type { CalendarEvent } from "@calcom/features/calendars/weeklyview/types/events";
import { useGetTheme } from "@calcom/lib/hooks/useTheme";
import { useBanners } from "@calcom/web/modules/shell/banners/useBanners";
@@ -5,7 +5,7 @@ import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerSt
import { useAvailableTimeSlots } from "@calcom/features/bookings/Booker/components/hooks/useAvailableTimeSlots";
import { useBookerTime } from "@calcom/features/bookings/Booker/components/hooks/useBookerTime";
import type { BookerEvent } from "@calcom/features/bookings/types";
import { Calendar } from "@calcom/features/calendars/weeklyview";
import { Calendar } from "@calcom/web/modules/calendars/weeklyview/components/Calendar";
import type { CalendarEvent } from "@calcom/features/calendars/weeklyview/types/events";
import { localStorage } from "@calcom/lib/webstorage";
@@ -0,0 +1,160 @@
import { useEffect, useMemo } from "react";
import dayjs from "@calcom/dayjs";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { useBookerTime } from "@calcom/features/bookings/Booker/components/hooks/useBookerTime";
import type { BookerEvent } from "@calcom/features/bookings/types";
import { Calendar } from "@calcom/web/modules/calendars/weeklyview/components/Calendar";
import type { CalendarAvailableTimeslots } from "@calcom/features/calendars/weeklyview/types/state";
import { localStorage } from "@calcom/lib/webstorage";
import type { BookingStatus } from "@calcom/prisma/enums";
import { useBookings } from "@calcom/atoms/hooks/bookings/useBookings";
import { useCalendarsBusyTimes } from "@calcom/atoms/hooks/useCalendarsBusyTimes";
import { useConnectedCalendars } from "@calcom/atoms/hooks/useConnectedCalendars";
import { getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
export const LargeCalendar = ({
extraDays,
availableTimeslots,
isLoading,
event,
}: {
extraDays: number;
availableTimeslots?: CalendarAvailableTimeslots | undefined;
isLoading: boolean;
event?: {
data?: Pick<BookerEvent, "length" | "id"> | null;
};
}) => {
const selectedDate = useBookerStoreContext((state) => state.selectedDate);
const selectedEventDuration = useBookerStoreContext((state) => state.selectedDuration);
const displayOverlay =
getQueryParam("overlayCalendar") === "true" || localStorage?.getItem("overlayCalendarSwitchDefault");
const { timezone } = useBookerTime();
const eventDuration = selectedEventDuration || event?.data?.length || 30;
const availableSlots = availableTimeslots !== undefined ? availableTimeslots : undefined;
const startDate = selectedDate ? dayjs(selectedDate).toDate() : dayjs().toDate();
const endDate = dayjs(startDate)
.add(extraDays - 1, "day")
.toDate();
const { data: bookings, isPending: _isFetchingBookings } = useBookings({
take: 150,
skip: 0,
eventTypeId: event?.data?.id,
afterStart: startDate.toISOString(),
beforeEnd: endDate.toISOString(),
status: ["upcoming", "past", "recurring"],
});
const { data: connectedCalendars, isPending: isFetchingConnectedCalendars } = useConnectedCalendars({
enabled: true,
});
const calendarsToLoad = connectedCalendars?.connectedCalendars.flatMap((connectedCalendar) => {
return (
connectedCalendar.calendars
?.filter((calendar) => calendar.isSelected === true)
.map((cal) => ({
credentialId: cal.credentialId,
externalId: cal.externalId,
})) ?? []
);
});
const { data: overlayBusyDates } = useCalendarsBusyTimes({
loggedInUsersTz: timezone,
dateFrom: startDate.toISOString(),
dateTo: endDate.toISOString(),
calendarsToLoad: calendarsToLoad ?? [],
enabled: Boolean(!isFetchingConnectedCalendars && !!calendarsToLoad?.length),
});
// HACK: force rerender when overlay events change
// Sine we dont use react router here we need to force rerender (ATOM SUPPORT)
useEffect(() => {}, [displayOverlay]);
const sortedBookingRanges = useMemo(
() =>
(bookings ?? [])
.map((booking) => ({
booking,
startTime: dayjs(booking.start).valueOf(),
endTime: dayjs(booking.end).valueOf(),
}))
.sort((a, b) => a.startTime - b.startTime),
[bookings]
);
const filteredBusyDates = useMemo(() => {
const overlay = overlayBusyDates?.data ?? [];
if (!sortedBookingRanges.length) return overlay;
return overlay.filter((busy) => {
const busyStart = dayjs(busy.start).valueOf();
const busyEnd = dayjs(busy.end).valueOf();
for (const { startTime, endTime } of sortedBookingRanges) {
if (startTime >= busyEnd) break;
if (endTime <= busyStart) continue;
return false;
}
return true;
});
}, [overlayBusyDates?.data, sortedBookingRanges]);
const overlayEventsForDate = useMemo(() => {
const allBookings = bookings ?? [];
// since busy dates comes straight from the calendar, it contains slots have bookings and also slots that are marked as busy by user but are not bookings
// hence we filter overlayBusyDates to exclude anything that overlaps with bookings
const busyEvents = filteredBusyDates.map((busyData, index) => ({
id: index,
title: `Busy`,
start: new Date(busyData.start),
end: new Date(busyData.end),
options: {
status: "ACCEPTED" as BookingStatus,
"data-test-id": "troubleshooter-busy-event",
className: "border-[1.5px]",
},
}));
const bookingEvents = allBookings.map((booking) => ({
id: booking.id,
title: booking.title ?? `Busy`,
start: new Date(booking.start),
end: new Date(booking.end),
options: {
status: booking.status.toUpperCase() as BookingStatus,
"data-test-id": "troubleshooter-busy-event",
className: "border-[1.5px]",
},
}));
return [...bookingEvents, ...busyEvents];
}, [bookings, filteredBusyDates]);
return (
<div className="h-full [--calendar-dates-sticky-offset:66px]">
<Calendar
isPending={isLoading}
availableTimeslots={availableSlots}
startHour={0}
endHour={23}
events={overlayEventsForDate}
startDate={startDate}
endDate={endDate}
gridCellsPerHour={60 / eventDuration}
hoverEventDuration={eventDuration}
hideHeader
timezone={timezone}
/>
</div>
);
};
@@ -0,0 +1,39 @@
"use client";
import { usePathname, useSearchParams } from "next/navigation";
import { usePostHog } from "posthog-js/react";
import { useEffect } from "react";
const TRACKED_ROUTES = [
"/signup",
"/auth/verify-email",
"/getting-started",
"/onboarding/getting-started",
"/settings/teams/new",
"/settings/teams",
];
export default function PostHogPageView() {
const pathname = usePathname();
const searchParams = useSearchParams();
const posthog = usePostHog();
useEffect(() => {
const shouldTrack = TRACKED_ROUTES.some(route => pathname?.startsWith(route));
if (!shouldTrack) return;
// Track pageviews
if (pathname && posthog) {
let url = window.origin + pathname;
if (searchParams?.toString()) {
url = `${url}?${searchParams.toString()}`;
}
posthog.capture("$pageview", {
$current_url: url,
});
}
}, [pathname, searchParams, posthog]);
return null;
}
@@ -0,0 +1,7 @@
import dynamic from "next/dynamic";
const DynamicPostHogPageView = dynamic(() => import("./PostHogPageView"), {
ssr: false,
});
export default DynamicPostHogPageView;
+40
View File
@@ -0,0 +1,40 @@
"use client";
import posthog from "posthog-js";
import { PostHogProvider } from "posthog-js/react";
import { useEffect, useRef } from "react";
import { useGeo } from "@calcom/web/app/GeoContext";
function Provider({ children }: { children: React.ReactNode }) {
const initializeOnce = useRef(false);
const { country } = useGeo();
useEffect(() => {
if (!process.env.NEXT_PUBLIC_POSTHOG_KEY || initializeOnce.current) return;
initializeOnce.current = true;
const isUS = country === "US";
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST || "https://eu.i.posthog.com",
persistence: isUS ? "localStorage+cookie" : "memory",
autocapture: false,
person_profiles: "never",
request_batching: true,
capture_pageview: false,
capture_pageleave: false,
cookieless_mode: isUS ? undefined : "always",
disable_session_recording: true,
advanced_disable_flags: true,
loaded: (posthog) => {
if (process.env.NODE_ENV === "development") posthog.debug();
},
});
}, [country]);
return <PostHogProvider client={posthog}>{children}</PostHogProvider>;
}
export default Provider;
@@ -0,0 +1,14 @@
import dynamic from "next/dynamic";
import { Fragment } from "react";
const initPostProvider = () => {
// eslint-disable-next-line turbo/no-undeclared-env-vars
if (!process.env.NEXT_PUBLIC_POSTHOG_KEY) {
return Fragment;
}
return dynamic(() => import("./provider"));
};
const DynamicPostHogProvider = initPostProvider();
export default DynamicPostHogProvider;
@@ -4,7 +4,7 @@ import { vi } from "vitest";
import { MembershipRole } from "@calcom/prisma/enums";
import { EditMemberSheet } from "@calcom/web/modules/ee/teams/components/EditMemberSheet";
import type { MemberPermissions } from "@calcom/web/modules/users/components/UserTable/types";
import type { MemberPermissions } from "@calcom/features/pbac/lib/team-member-permissions";
import type { State, User } from "./MemberList";
@@ -19,7 +19,7 @@ import { Tooltip } from "@calcom/ui/components/tooltip";
import { DisplayInfo } from "@calcom/web/modules/users/components/UserTable/EditSheet/DisplayInfo";
import { SheetFooterControls } from "@calcom/web/modules/users/components/UserTable/EditSheet/SheetFooterControls";
import { useEditMode } from "@calcom/web/modules/users/components/UserTable/EditSheet/store";
import type { MemberPermissions } from "@calcom/web/modules/users/components/UserTable/types";
import type { MemberPermissions } from "@calcom/features/pbac/lib/team-member-permissions";
import { updateRoleInCache, getUpdatedUser } from "./MemberChangeRoleModal";
import type { Action, State, User } from "./MemberList";
@@ -56,7 +56,7 @@ import { showToast } from "@calcom/ui/components/toast";
import { Tooltip } from "@calcom/ui/components/tooltip";
import TeamAvailabilityModal from "@calcom/web/modules/ee/teams/components/TeamAvailabilityModal";
import { DynamicLink } from "@calcom/web/modules/users/components/UserTable/BulkActions/DynamicLink";
import type { MemberPermissions } from "@calcom/web/modules/users/components/UserTable/types";
import type { MemberPermissions } from "@calcom/features/pbac/lib/team-member-permissions";
import DeleteBulkTeamMembers from "./DeleteBulkTeamMembers";
import { EditMemberSheet } from "./EditMemberSheet";
@@ -5,7 +5,7 @@ import { useState } from "react";
import LicenseRequired from "~/ee/common/components/LicenseRequired";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { RouterOutputs } from "@calcom/trpc/react";
import type { MemberPermissions } from "@calcom/web/modules/users/components/UserTable/types";
import type { MemberPermissions } from "@calcom/features/pbac/lib/team-member-permissions";
import { MemberInvitationModalWithoutMembers } from "~/ee/teams/components/MemberInvitationModal";
+1 -1
View File
@@ -5,7 +5,7 @@ import LicenseRequired from "~/ee/common/components/LicenseRequired";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { UserListTable } from "@calcom/web/modules/users/components/UserTable/UserListTable";
import type { UserListTableProps } from "@calcom/web/modules/users/components/UserTable/UserListTable";
import type { MemberPermissions } from "@calcom/web/modules/users/components/UserTable/types";
import type { MemberPermissions } from "@calcom/features/pbac/lib/team-member-permissions";
export const MembersView = (props: UserListTableProps & { permissions?: MemberPermissions }) => {
const { t } = useLocale();
@@ -5,7 +5,7 @@ import { usePathname } from "next/navigation";
import { useMemo } from "react";
import dayjs from "@calcom/dayjs";
import { Calendar } from "@calcom/features/calendars/weeklyview";
import { Calendar } from "@calcom/web/modules/calendars/weeklyview/components/Calendar";
import type { CalendarComponentProps, Hours } from "@calcom/features/calendars/weeklyview/types/state";
import { weekdayDates } from "@calcom/features/calendars/weeklyview/utils";
import { CURRENT_TIMEZONE } from "@calcom/lib/timezoneConstants";
@@ -0,0 +1,40 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Badge } from "@calcom/ui/components/badge";
import { Button } from "@calcom/ui/components/button";
import { Switch } from "@calcom/ui/components/form";
import { TroubleshooterListItemContainer } from "./TroubleshooterListItemContainer";
function AvailabiltyItem() {
const { t } = useLocale();
return (
<TroubleshooterListItemContainer
title="Office Hours"
subtitle="Mon-Fri; 9:00 AM - 5:00 PM"
suffixSlot={
<div>
<Badge variant="green" withDot size="sm">
Connected
</Badge>
</div>
}>
<div className="flex flex-col gap-3">
<p className="text-subtle text-sm font-medium leading-none">{t("date_overrides")}</p>
<Switch label="[email protected]" />
</div>
</TroubleshooterListItemContainer>
);
}
export function AvailabiltySchedulesContainer() {
const { t } = useLocale();
return (
<div className="flex flex-col stack-y-3">
<p className="text-sm font-medium leading-none">{t("availabilty_schedules")}</p>
<AvailabiltyItem />
<Button color="secondary" className="justify-center gap-2">
{t("manage_availabilty_schedules")}
</Button>
</div>
);
}
@@ -0,0 +1,124 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Badge } from "@calcom/ui/components/badge";
import { Button } from "@calcom/ui/components/button";
import { Switch } from "@calcom/ui/components/form";
import { TroubleshooterListItemContainer } from "./TroubleshooterListItemContainer";
const SELECTION_COLORS = ["#f97316", "#84cc16", "#06b6d4", "#8b5cf6", "#ec4899", "#f43f5e"];
interface CalendarToggleItemProps {
title: string;
subtitle: string;
colorDot?: string;
status: "connected" | "not_found";
calendars?: {
active?: boolean;
name?: string;
}[];
}
function CalendarToggleItem(props: CalendarToggleItemProps) {
const badgeStatus = props.status === "connected" ? "green" : "orange";
const badgeText = props.status === "connected" ? "Connected" : "Not found";
return (
<TroubleshooterListItemContainer
title={props.title}
subtitle={props.subtitle}
prefixSlot={
<>
<div
className="h-4 w-4 self-center rounded-[4px]"
style={{
backgroundColor: props.colorDot,
}}
/>
</>
}
suffixSlot={
<div>
<Badge variant={badgeStatus} withDot size="sm">
{badgeText}
</Badge>
</div>
}>
<div className="[&>*]:text-emphasis flex flex-col gap-3">
{props.calendars?.map((calendar) => {
return <Switch key={calendar.name} checked={calendar.active} label={calendar.name} disabled />;
})}
</div>
</TroubleshooterListItemContainer>
);
}
function EmptyCalendarToggleItem() {
const { t } = useLocale();
return (
<TroubleshooterListItemContainer
title={t("installed", { count: 0 })}
subtitle={t("please_install_a_calendar")}
prefixSlot={
<>
<div className="h-4 w-4 self-center rounded-[4px] bg-blue-500" />
</>
}
suffixSlot={
<div>
<Badge variant="orange" withDot size="sm">
{t("unavailable")}
</Badge>
</div>
}>
<div className="flex flex-col gap-3">
<Button color="secondary" className="justify-center gap-2" href="/apps/categories/calendar">
{t("install_calendar")}
</Button>
</div>
</TroubleshooterListItemContainer>
);
}
export function CalendarToggleContainer() {
const { t } = useLocale();
const { data, isLoading } = trpc.viewer.calendars.connectedCalendars.useQuery();
const hasConnectedCalendars = data && data?.connectedCalendars.length > 0;
return (
<div className="flex flex-col stack-y-3">
<p className="text-sm font-medium leading-none">{t("calendars_were_checking_for_conflicts")}</p>
{hasConnectedCalendars && !isLoading ? (
<>
{data.connectedCalendars.map((calendar) => {
const foundPrimary = calendar.calendars?.find((item) => item.primary);
// Will be used when getAvailbility is modified to use externalId instead of appId for source.
// const color = SELECTION_COLORS[idx] || "#000000";
// // Add calendar to color map using externalId (what we use on the backend to determine source)
// addToColorMap(foundPrimary?.externalId, color);
return (
<CalendarToggleItem
key={calendar.credentialId}
title={calendar.integration.name}
colorDot="#000000"
subtitle={foundPrimary?.name ?? "Nameless Calendar"}
status={calendar.error ? "not_found" : "connected"}
calendars={calendar.calendars?.map((item) => {
return {
active: item.isSelected,
name: item.name,
};
})}
/>
);
})}
<Button color="secondary" className="justify-center gap-2" href="/settings/my-account/calendars">
{t("manage_calendars")}
</Button>
</>
) : (
<EmptyCalendarToggleItem />
)}
</div>
);
}
@@ -0,0 +1,38 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Badge } from "@calcom/ui/components/badge";
import { TroubleshooterListItemHeader } from "./TroubleshooterListItemContainer";
function ConnectedAppsItem() {
return (
<TroubleshooterListItemHeader
title="Google Cal"
subtitle="[email protected]"
prefixSlot={
<>
<div className="h-4 w-4 self-center rounded-[4px] bg-blue-500" />
</>
}
suffixSlot={
<div>
<Badge variant="green" withDot size="sm">
Connected
</Badge>
</div>
}
/>
);
}
export function ConnectedAppsContainer() {
const { t } = useLocale();
return (
<div className="flex flex-col stack-y-3">
<p className="text-sm font-medium leading-none">{t("other_apps")}</p>
<div className="[&>*:first-child]:rounded-t-md [&>*:last-child]:rounded-b-md [&>*:last-child]:border-b">
<ConnectedAppsItem />
<ConnectedAppsItem />
</div>
</div>
);
}
@@ -0,0 +1,43 @@
import Link from "next/link";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Badge } from "@calcom/ui/components/badge";
import { Label } from "@calcom/ui/components/form";
import { useTroubleshooterStore } from "@calcom/features/troubleshooter/store";
import { TroubleshooterListItemHeader } from "./TroubleshooterListItemContainer";
export function EventScheduleItem() {
const { t } = useLocale();
const selectedEventType = useTroubleshooterStore((state) => state.event);
const { data: schedule } = trpc.viewer.availability.schedule.getScheduleByEventSlug.useQuery(
{
eventSlug: selectedEventType?.slug as string,
},
{
enabled: !!selectedEventType?.slug,
}
);
return (
<div>
<Label>Availability Schedule</Label>
<TroubleshooterListItemHeader
className="group rounded-md border-b"
prefixSlot={<div className="w-4 rounded-[4px] bg-black" />}
title={schedule?.name ?? "Loading"}
suffixSlot={
schedule && (
<Link href={`/availability/${schedule.id}`} className="inline-flex">
<Badge color="orange" size="sm" className="invisible hover:cursor-pointer group-hover:visible">
{t("edit")}
</Badge>
</Link>
)
}
/>
</div>
);
}
@@ -0,0 +1,88 @@
import { useMemo, useEffect, startTransition } from "react";
import { shallow } from "zustand/shallow";
import { trpc } from "@calcom/trpc/react";
import { SelectField } from "@calcom/ui/components/form";
import { getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
import { useTroubleshooterStore } from "@calcom/features/troubleshooter/store";
export function EventTypeSelect() {
const { data: eventTypes, isPending } = trpc.viewer.eventTypes.listWithTeam.useQuery();
const { event: selectedEventType, setEvent: setSelectedEventType } = useTroubleshooterStore(
(state) => ({
event: state.event,
setEvent: state.setEvent,
}),
shallow
);
const options = useMemo(() => {
if (!eventTypes) return [];
return eventTypes.map((e) => ({
label: e.title,
value: e.id.toString(),
id: e.id,
duration: e.length,
}));
}, [eventTypes]);
// Initialize event type from query param or default to first event
useEffect(() => {
if (!eventTypes || eventTypes.length === 0) return;
const selectedEventIdParam = getQueryParam("eventTypeId");
const eventTypeId = selectedEventIdParam ? parseInt(selectedEventIdParam, 10) : null;
// If we already have a selected event that matches the query param, don't do anything
if (selectedEventType?.id === eventTypeId) return;
// If there's a query param, try to find and set that event
if (eventTypeId && !isNaN(eventTypeId)) {
startTransition(() => {
const foundEventType = eventTypes.find((et) => et.id === eventTypeId);
if (foundEventType) {
setSelectedEventType({
id: foundEventType.id,
slug: foundEventType.slug,
duration: foundEventType.length,
teamId: foundEventType.team?.id ?? null,
});
return;
}
});
}
// If no event is selected and no valid query param, default to first event
if (!selectedEventType && !eventTypeId) {
const firstEvent = eventTypes[0];
setSelectedEventType({
id: firstEvent.id,
slug: firstEvent.slug,
duration: firstEvent.length,
teamId: firstEvent.team?.id ?? null,
});
}
}, [eventTypes, selectedEventType, setSelectedEventType]);
return (
<SelectField
label="Event Type"
options={options}
isDisabled={isPending || options.length === 0}
value={options.find((option) => option.id === selectedEventType?.id) || options[0]}
onChange={(option) => {
if (!option) return;
const foundEventType = eventTypes?.find((et) => et.id === option.id);
if (foundEventType) {
setSelectedEventType({
id: foundEventType.id,
slug: foundEventType.slug,
duration: foundEventType.length,
teamId: foundEventType.team?.id ?? null,
});
}
}}
/>
);
}
@@ -0,0 +1,133 @@
import { useSession } from "next-auth/react";
import { useMemo } from "react";
import dayjs from "@calcom/dayjs";
import { useAvailableTimeSlots } from "@calcom/features/bookings/Booker/components/hooks/useAvailableTimeSlots";
import { Calendar } from "@calcom/web/modules/calendars/weeklyview/components/Calendar";
import { BookingStatus } from "@calcom/prisma/enums";
import { trpc } from "@calcom/trpc/react";
import { useTimePreferences } from "@calcom/features/bookings/lib/timePreferences";
import { useSchedule } from "@calcom/features/schedules/lib/use-schedule/useSchedule";
import { useTroubleshooterStore } from "@calcom/features/troubleshooter/store";
export const LargeCalendar = ({ extraDays }: { extraDays: number }) => {
const { timezone } = useTimePreferences();
const selectedDate = useTroubleshooterStore((state) => state.selectedDate);
const event = useTroubleshooterStore((state) => state.event);
const calendarToColorMap = useTroubleshooterStore((state) => state.calendarToColorMap);
const { data: session } = useSession();
const startDate = selectedDate ? dayjs(selectedDate) : dayjs();
const { data: busyEvents } = trpc.viewer.availability.user.useQuery(
{
username: session?.user?.username || "",
dateFrom: startDate.startOf("day").utc().format(),
dateTo: startDate
.endOf("day")
.add(extraDays - 1, "day")
.utc()
.format(),
eventTypeId: event?.id,
withSource: true,
},
{
enabled: !!session?.user?.username,
}
);
const isTeamEvent = !!event?.teamId;
const { data: schedule } = useSchedule({
username: session?.user.username || "",
// For team events, don't pass eventSlug to avoid slug lookup issues - use eventId instead
eventSlug: isTeamEvent ? null : event?.slug,
eventId: event?.id,
timezone,
month: startDate.format("YYYY-MM"),
orgSlug: session?.user.org?.slug,
isTeamEvent,
});
const endDate = dayjs(startDate)
.add(extraDays - 1, "day")
.toDate();
const availableSlots = useAvailableTimeSlots({ schedule, eventDuration: event?.duration ?? 30 });
const events = useMemo(() => {
if (!busyEvents?.busy) return [];
// TODO: Add buffer times in here as well just requires a bit of logic for fetching event type and then adding buffer time
// start: dayjs(startTime)
// .subtract((eventType?.beforeEventBuffer || 0) + (afterEventBuffer || 0), "minute")
// .toDate(),
// end: dayjs(endTime)
// .add((eventType?.afterEventBuffer || 0) + (beforeEventBuffer || 0), "minute")
// .toDate(),
const calendarEvents = busyEvents?.busy.map((event, idx) => {
return {
id: idx,
title: event.title ?? `Busy`,
start: new Date(event.start),
end: new Date(event.end),
options: {
color:
event.source && calendarToColorMap[event.source] ? calendarToColorMap[event.source] : undefined,
status: BookingStatus.ACCEPTED,
"data-test-id": "troubleshooter-busy-event",
},
};
});
if (busyEvents.dateOverrides) {
busyEvents.dateOverrides.forEach((dateOverride) => {
const dateOverrideStart = dayjs(dateOverride.start);
const dateOverrideEnd = dayjs(dateOverride.end);
if (!dateOverrideStart.isSame(dateOverrideEnd)) {
return;
}
const dayOfWeekNum = dateOverrideStart.day();
const workingHoursForDay = busyEvents.workingHours.find((workingHours) =>
workingHours.days.includes(dayOfWeekNum)
);
if (!workingHoursForDay) return;
calendarEvents.push({
id: calendarEvents.length,
title: "Date Override",
start: dateOverrideStart.add(workingHoursForDay.startTime, "minutes").toDate(),
end: dateOverrideEnd.add(workingHoursForDay.endTime, "minutes").toDate(),
options: {
color: "black",
status: BookingStatus.ACCEPTED,
"data-test-id": "troubleshooter-busy-time",
},
});
});
}
return calendarEvents;
}, [busyEvents, calendarToColorMap]);
return (
<div className="h-full [--calendar-dates-sticky-offset:66px]">
<Calendar
sortEvents
startHour={0}
endHour={23}
events={events}
availableTimeslots={availableSlots}
startDate={startDate.toDate()}
endDate={endDate}
gridCellsPerHour={60 / (event?.duration || 15)}
hoverEventDuration={30}
hideHeader
timezone={timezone}
/>
</div>
);
};
@@ -0,0 +1,72 @@
import { BookerStoreProvider } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import useMediaQuery from "@calcom/lib/hooks/useMediaQuery";
import classNames from "@calcom/ui/classNames";
import { LargeCalendar } from "./LargeCalendar";
import { TroubleshooterHeader } from "./TroubleshooterHeader";
import { TroubleshooterSidebar } from "./TroubleshooterSidebar";
import { useInitalizeTroubleshooterStore } from "@calcom/features/troubleshooter/store";
import type { TroubleshooterProps } from "@calcom/features/troubleshooter/types";
const extraDaysConfig = {
desktop: 7,
tablet: 4,
};
const TroubleshooterComponent = ({ month }: TroubleshooterProps) => {
const isMobile = useMediaQuery("(max-width: 768px)");
const isTablet = useMediaQuery("(max-width: 1024px)");
const extraDays = isTablet ? extraDaysConfig.tablet : extraDaysConfig.desktop;
useInitalizeTroubleshooterStore({
month: month,
});
return (
<>
<div
className={classNames(
"text-default flex min-h-full w-full flex-col items-center overflow-clip",
isMobile
? "[--troublehooster-meta-width:0px]"
: "[--troublehooster-meta-width:250px] lg:[--troubleshooter-meta-width:430px]"
)}>
<div
style={{
display: "grid",
width: "100vw",
minHeight: "100vh",
height: "auto",
gridTemplateAreas: `
"meta header header"
"meta main main"
`,
gridTemplateColumns: "var(--troubleshooter-meta-width) 1fr",
gridTemplateRows: "70px auto",
}}
className={classNames(
"bg-default dark:bg-cal-muted text-default flex min-h-full w-full flex-col items-center sm:transition-[width] sm:duration-300"
)}>
<div className="bg-default dark:bg-cal-muted sticky top-0 z-10 [grid-area:header]">
<TroubleshooterHeader extraDays={extraDays} isMobile={isMobile} />
</div>
<div className="sticky top-0 z-10 ps-6">
<TroubleshooterSidebar />
</div>
<div className="ml[-1px] border-subtle sticky top-0 [grid-area:main]">
<LargeCalendar extraDays={extraDays} />
</div>
</div>
</div>
</>
);
};
export const Troubleshooter = ({ month }: TroubleshooterProps) => {
return (
<BookerStoreProvider>
<TroubleshooterComponent month={month} />
</BookerStoreProvider>
);
};
@@ -0,0 +1,80 @@
import { useMemo } from "react";
import dayjs from "@calcom/dayjs";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
import { ButtonGroup } from "@calcom/ui/components/buttonGroup";
import { useTroubleshooterStore } from "@calcom/features/troubleshooter/store";
export function TroubleshooterHeader({ extraDays, isMobile }: { extraDays: number; isMobile: boolean }) {
const { t, i18n } = useLocale();
const selectedDateString = useTroubleshooterStore((state) => state.selectedDate);
const setSelectedDate = useTroubleshooterStore((state) => state.setSelectedDate);
const addToSelectedDate = useTroubleshooterStore((state) => state.addToSelectedDate);
const selectedDate = selectedDateString ? dayjs(selectedDateString) : dayjs();
const today = dayjs();
const selectedDateMin3DaysDifference = useMemo(() => {
const diff = today.diff(selectedDate, "days");
return diff > 3 || diff < -3;
}, [today, selectedDate]);
if (isMobile) return null;
const endDate = selectedDate.add(extraDays - 1, "days");
const isSameMonth = () => {
return selectedDate.format("MMM") === endDate.format("MMM");
};
const isSameYear = () => {
return selectedDate.format("YYYY") === endDate.format("YYYY");
};
const formattedMonth = new Intl.DateTimeFormat(i18n.language, { month: "short" });
const FormattedSelectedDateRange = () => {
return (
<h3 className="min-w-[150px] text-base font-semibold leading-4">
{formattedMonth.format(selectedDate.toDate())} {selectedDate.format("D")}
{!isSameYear() && <span className="text-subtle">, {selectedDate.format("YYYY")} </span>}-{" "}
{!isSameMonth() && formattedMonth.format(endDate.toDate())} {endDate.format("D")},{" "}
<span className="text-subtle">
{isSameYear() ? selectedDate.format("YYYY") : endDate.format("YYYY")}
</span>
</h3>
);
};
return (
<div className="border-default relative z-10 flex border-b px-5 py-4 ltr:border-l rtl:border-r">
<div className="flex items-center gap-5 rtl:grow">
<FormattedSelectedDateRange />
<ButtonGroup>
<Button
className="group rtl:ml-1 rtl:rotate-180"
variant="icon"
color="minimal"
StartIcon="chevron-left"
aria-label="Previous Day"
onClick={() => addToSelectedDate(-extraDays)}
/>
<Button
className="group rtl:mr-1 rtl:rotate-180"
variant="icon"
color="minimal"
StartIcon="chevron-right"
aria-label="Next Day"
onClick={() => addToSelectedDate(extraDays)}
/>
{selectedDateMin3DaysDifference && (
<Button
className="capitalize ltr:ml-2 rtl:mr-2"
color="secondary"
onClick={() => setSelectedDate(today.format("YYYY-MM-DD"))}>
{t("today")}
</Button>
)}
</ButtonGroup>
</div>
</div>
);
}
@@ -0,0 +1,42 @@
import type { PropsWithChildren } from "react";
import classNames from "@calcom/ui/classNames";
interface TroubleshooterListItemContainerProps {
title: string;
subtitle?: string;
suffixSlot?: React.ReactNode;
prefixSlot?: React.ReactNode;
className?: string;
}
export function TroubleshooterListItemHeader({
prefixSlot,
title,
subtitle,
suffixSlot,
className,
}: TroubleshooterListItemContainerProps) {
return (
<div className={classNames("border-subtle flex max-w-full gap-3 border border-b-0 px-4 py-2", className)}>
{prefixSlot}
<div className="flex h-full max-w-full flex-1 flex-col flex-nowrap truncate text-sm leading-4">
<p className="font-medium">{title}</p>
{subtitle && <p className="font-normal">{subtitle}</p>}
</div>
{suffixSlot}
</div>
);
}
export function TroubleshooterListItemContainer({
children,
...rest
}: PropsWithChildren<TroubleshooterListItemContainerProps>) {
return (
<div className="[&>*:first-child]:rounded-t-md ">
<TroubleshooterListItemHeader {...rest} />
<div className="border-subtle flex flex-col stack-y-3 rounded-b-md border p-4">{children}</div>
</div>
);
}
@@ -0,0 +1,42 @@
import Link from "next/link";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Icon } from "@calcom/ui/components/icon";
import { Skeleton } from "@calcom/ui/components/skeleton";
import { CalendarToggleContainer } from "./CalendarToggleContainer";
import { EventScheduleItem } from "./EventScheduleItem";
import { EventTypeSelect } from "./EventTypeSelect";
const BackButtonInSidebar = ({ name }: { name: string }) => {
return (
<Link
href="/availability"
className="hover:bg-subtle group-hover:text-default text-emphasis group flex h-6 max-h-6 w-full flex-row items-center rounded-md px-3 py-2 transition">
<Icon
name="arrow-left"
className="h-4 w-4 stroke-[2px] ltr:mr-[10px] rtl:ml-[10px] rtl:rotate-180 md:mt-0"
/>
<Skeleton
title={name}
as="p"
className="max-w-36 min-h-4 truncate font-semibold"
loadingClassName="ms-3">
{name}
</Skeleton>
</Link>
);
};
export const TroubleshooterSidebar = () => {
const { t } = useLocale();
return (
<div className="relative z-10 hidden h-screen w-full flex-col gap-6 overflow-y-auto py-6 pl-4 pr-6 sm:flex md:pl-0">
<BackButtonInSidebar name={t("troubleshooter")} />
<EventTypeSelect />
<EventScheduleItem />
<CalendarToggleContainer />
</div>
);
};
@@ -23,7 +23,7 @@ import { useOrgBranding } from "@calcom/features/ee/organizations/context/provid
import {
generateCsvRawForMembersTable,
generateHeaderFromReactTable,
} from "@calcom/features/users/lib/UserListTableUtils";
} from "@calcom/web/modules/users/lib/UserListTableUtils";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { downloadAsCsv } from "@calcom/lib/csvUtils";
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
@@ -48,7 +48,8 @@ import { EditUserSheet } from "./EditSheet/EditUserSheet";
import { ImpersonationMemberModal } from "./ImpersonationMemberModal";
import { InviteMemberModal } from "./InviteMemberModal";
import { TableActions } from "./UserTableActions";
import type { UserTableState, UserTableAction, UserTableUser, MemberPermissions } from "./types";
import type { UserTableState, UserTableAction, UserTableUser } from "./types";
import type { MemberPermissions } from "@calcom/features/pbac/lib/team-member-permissions";
const initialState: UserTableState = {
changeMemberRole: {
@@ -1,6 +1,7 @@
import type { RouterOutputs } from "@calcom/trpc/react";
export type UserTableUser = RouterOutputs["viewer"]["organizations"]["listMembers"]["rows"][number];
export type UserTableUser =
RouterOutputs["viewer"]["organizations"]["listMembers"]["rows"][number];
export type PlatformManagedUserTableUser = Omit<
UserTableUser,
@@ -12,11 +13,6 @@ export type UserTablePayload = {
user?: UserTableUser;
};
export type PlatformUserTablePayload = {
showModal: boolean;
user?: PlatformManagedUserTableUser;
};
export type UserTableState = {
changeMemberRole: UserTablePayload;
deleteMember: UserTablePayload;
@@ -25,10 +21,6 @@ export type UserTableState = {
editSheet: UserTablePayload & { user?: UserTableUser };
};
export type PlatforManagedUserTableState = {
deleteMember: UserTablePayload;
};
export type UserTableAction =
| {
type:
@@ -43,22 +35,3 @@ export type UserTableAction =
| {
type: "CLOSE_MODAL";
};
export type PlatformManagedUserTableAction =
| {
type: "SET_DELETE_ID";
payload: PlatformUserTablePayload;
}
| {
type: "CLOSE_MODAL";
};
export interface MemberPermissions {
canListMembers: boolean;
canInvite: boolean;
canChangeMemberRole: boolean;
canRemove: boolean;
canImpersonate: boolean;
canEditAttributesForUser?: boolean;
canViewAttributes?: boolean;
}
@@ -4,7 +4,7 @@ import { describe, it, expect, vi } from "vitest";
import {
generateCsvRawForMembersTable,
generateHeaderFromReactTable,
} from "@calcom/features/users/lib/UserListTableUtils";
} from "@calcom/web/modules/users/lib/UserListTableUtils";
import { MembershipRole } from "@calcom/prisma/enums";
import type { UserTableUser } from "@calcom/web/modules/users/components/UserTable/types";
@@ -0,0 +1,93 @@
import type { Table } from "@tanstack/react-table";
import { sanitizeValue } from "@calcom/lib/csvUtils";
import type { UserTableUser } from "@calcom/web/modules/users/components/UserTable/types";
export const generateHeaderFromReactTable = (table: Table<UserTableUser>): string[] | null => {
const headerGroups = table.getHeaderGroups();
if (!headerGroups.length) {
return null;
}
const { headers } = headerGroups[0];
const HEADER_IDS_TO_EXCLUDE = ["select", "actions"]; // these columns only make sense in web page
const filteredHeaders = headers.filter((header) => !HEADER_IDS_TO_EXCLUDE.includes(header.id));
const headerNames = filteredHeaders.map((header) => {
const h = header.column.columnDef.header;
if (typeof h === "string") {
return sanitizeValue(h);
}
if (typeof h === "function") {
return sanitizeValue(h(header.getContext()));
}
return "Unknown";
});
// Add "Link" column (member's public page)
const MEMBERS_COLUMN = "Members";
const LINK_COLUMN = "Link";
const memberIndex = headerNames.findIndex((name) => name === MEMBERS_COLUMN);
if (memberIndex > -1) {
headerNames.splice(memberIndex + 1, 0, LINK_COLUMN);
}
return headerNames;
};
export const generateCsvRawForMembersTable = (
headers: string[],
rows: UserTableUser[],
ATTRIBUTE_IDS: string[],
orgDomain: string
): string => {
if (!headers.length) {
throw new Error("The header is empty.");
}
const REQUIRED_HEADERS = ["Members", "Link", "Role", "Teams"] as const;
// Validate required headers are present and in correct order
const firstFourHeaders = headers.slice(0, REQUIRED_HEADERS.length);
if (!REQUIRED_HEADERS.every((header, index) => header === firstFourHeaders[index])) {
throw new Error(
`Invalid headers structure. Expected headers to start with: ${JSON.stringify(REQUIRED_HEADERS)}`
);
}
// Body formation
const csvRows = rows.map((row) => {
const { email, role, teams, username, attributes } = row;
// Create a map of attributeId to array of values
const attributeMap = (attributes ?? []).reduce((acc, attr) => {
if (!acc[attr.attributeId]) {
acc[attr.attributeId] = [];
}
acc[attr.attributeId].push({
value: attr.value,
weight: attr.weight ?? undefined,
});
return acc;
}, {} as Record<string, { value: string; weight: number | undefined }[]>);
const requiredColumns = [
email, // Members column
`${orgDomain}/${username}`, // Link column
role, // Role column
sanitizeValue(teams.map((team) => team.name).join(",")), // Teams column
];
// Add attribute columns
const attributeColumns = ATTRIBUTE_IDS.map((attrId) => {
const attributes = attributeMap[attrId];
if (!attributes?.length) return "";
return sanitizeValue(
attributes.map((attr) => (attr.weight ? `${attr.value} (${attr.weight}%)` : attr.value)).join(",")
);
});
return [...requiredColumns, ...attributeColumns];
});
return [headers.join(","), ...csvRows.map((row) => row.join(","))].join("\n");
};
+1
View File
@@ -152,6 +152,7 @@
"@babel/core": "7.26.10",
"@biomejs/biome": "2.3.10",
"@calcom/config": "workspace:*",
"@calcom/testing": "workspace:*",
"@calcom/types": "workspace:*",
"@microsoft/microsoft-graph-types-beta": "0.15.0-preview",
"@playwright/test": "1.57.0",
File diff suppressed because it is too large. Load diff
-31
View File
@@ -1,31 +0,0 @@
// my-test.ts
import { test as base } from "vitest";
import { getTestEmails } from "@calcom/lib/testEmails";
import { getTestSMS } from "@calcom/lib/testSMS";
export interface Fixtures {
emails: ReturnType<typeof getEmailsFixture>;
sms: ReturnType<typeof getSMSFixture>;
}
export const test = base.extend<Fixtures>({
emails: async ({}, use) => {
await use(getEmailsFixture());
},
sms: async ({}, use) => {
await use(getSMSFixture());
},
});
function getEmailsFixture() {
return {
get: getTestEmails,
};
}
function getSMSFixture() {
return {
get: getTestSMS,
};
}
@@ -1,5 +1,5 @@
import { getSampleUserInSession } from "../utils/bookingScenario/getSampleUserInSession";
import { setupAndTeardown } from "../utils/bookingScenario/setupAndTeardown";
import { getSampleUserInSession } from "@calcom/testing/lib/bookingScenario/getSampleUserInSession";
import { setupAndTeardown } from "@calcom/testing/lib/bookingScenario/setupAndTeardown";
import {
createBookingScenario,
getGoogleCalendarCredential,
@@ -10,8 +10,8 @@ import {
getMockBookingAttendee,
getDate,
mockCalendar,
} from "@calcom/web/test/utils/bookingScenario/bookingScenario";
import { expectBookingRequestRescheduledEmails } from "@calcom/web/test/utils/bookingScenario/expects";
} from "@calcom/testing/lib/bookingScenario/bookingScenario";
import { expectBookingRequestRescheduledEmails } from "@calcom/testing/lib/bookingScenario/expects";
import type { Request, Response } from "express";
import type { NextApiRequest, NextApiResponse } from "next";
@@ -21,7 +21,7 @@ import { SchedulingType, MembershipRole } from "@calcom/prisma/enums";
import { BookingStatus } from "@calcom/prisma/enums";
import type { TRequestRescheduleInputSchema } from "@calcom/trpc/server/routers/viewer/bookings/requestReschedule.schema";
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
import { test } from "@calcom/web/test/fixtures/fixtures";
import { test } from "@calcom/testing/lib/fixtures/fixtures";
export type CustomNextApiRequest = NextApiRequest & Request;
+1 -1
View File
@@ -4,7 +4,7 @@ import {
getScenarioData,
TestData,
mockSuccessfulVideoMeetingCreation,
} from "@calcom/web/test/utils/bookingScenario/bookingScenario";
} from "@calcom/testing/lib/bookingScenario/bookingScenario";
import { describe, it, beforeEach, vi, expect } from "vitest";
+2 -2
View File
@@ -1,4 +1,4 @@
import CalendarManagerMock from "../../../../tests/libs/__mocks__/CalendarManager";
import CalendarManagerMock from "@calcom/features/calendars/lib/__mocks__/CalendarManager";
import { constantsScenarios } from "@calcom/lib/__mocks__/constants";
import {
@@ -12,7 +12,7 @@ import {
TestData,
createCredentials,
mockCrmApp,
} from "../utils/bookingScenario/bookingScenario";
} from "@calcom/testing/lib/bookingScenario/bookingScenario";
import { describe, vi, test } from "vitest";
@@ -5,7 +5,7 @@ import {
Timezones,
TestData,
mockCalendar,
} from "../../utils/bookingScenario/bookingScenario";
} from "@calcom/testing/lib/bookingScenario/bookingScenario";
import { describe, test } from "vitest";
@@ -7,8 +7,8 @@ import {
createDelegationCredential,
createOrganization,
getOrganizer,
} from "../../utils/bookingScenario/bookingScenario";
import { expectNoAttemptToGetAvailability } from "../../utils/bookingScenario/expects";
} from "@calcom/testing/lib/bookingScenario/bookingScenario";
import { expectNoAttemptToGetAvailability } from "@calcom/testing/lib/bookingScenario/expects";
import { describe, test } from "vitest";
@@ -3,8 +3,8 @@ import {
Timezones,
createBookingScenario,
replaceDates,
} from "../../utils/bookingScenario/bookingScenario";
import type { ScenarioData } from "../../utils/bookingScenario/bookingScenario";
} from "@calcom/testing/lib/bookingScenario/bookingScenario";
import type { ScenarioData } from "@calcom/testing/lib/bookingScenario/bookingScenario";
import { describe, expect, vi, test } from "vitest";
@@ -1,11 +1,11 @@
import prismock from "../../../../../tests/libs/__mocks__/prisma";
import prismock from "@calcom/testing/lib/__mocks__/prisma";
import {
createBookingScenario,
Timezones,
TestData,
type ScenarioData,
} from "../../utils/bookingScenario/bookingScenario";
} from "@calcom/testing/lib/bookingScenario/bookingScenario";
import { describe, test, vi } from "vitest";
import type { z } from "zod";
@@ -5,7 +5,7 @@ import {
TestData,
mockCalendarToHaveNoBusySlots,
type ScenarioData,
} from "../../utils/bookingScenario/bookingScenario";
} from "@calcom/testing/lib/bookingScenario/bookingScenario";
import type { IncomingMessage } from "node:http";
import { describe, test, beforeEach, vi } from "vitest";
@@ -1,4 +1,4 @@
import prismock from "../../../../../tests/libs/__mocks__/prisma";
import prismock from "@calcom/testing/lib/__mocks__/prisma";
import { vi, beforeEach, afterEach } from "vitest";
+1 -1
View File
@@ -1,4 +1,4 @@
import { getDate } from "../../utils/bookingScenario/bookingScenario";
import { getDate } from "@calcom/testing/lib/bookingScenario/bookingScenario";
import { vi } from "vitest";
@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import prismaMock from "../../../../tests/libs/__mocks__/prismaMock";
import prismaMock from "@calcom/testing/lib/__mocks__/prismaMock";
import { describe, expect, it, vi } from "vitest";
@@ -1,92 +0,0 @@
import prismaMock from "../../../../../tests/libs/__mocks__/prisma";
import "vitest-fetch-mock";
import { sendAwaitingPaymentEmailAndSMS } from "@calcom/emails/email-manager";
import logger from "@calcom/lib/logger";
import type { Payment, Prisma, PaymentOption, Booking } from "@calcom/prisma/client";
import type { CalendarEvent } from "@calcom/types/Calendar";
import type { IAbstractPaymentService } from "@calcom/types/PaymentService";
export function getMockPaymentService() {
function createPaymentLink(/*{ paymentUid, name, email, date }*/) {
return "http://mock-payment.example.com/";
}
const paymentUid = "MOCK_PAYMENT_UID";
const externalId = "mock_payment_external_id";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
class MockPaymentService implements IAbstractPaymentService {
// TODO: We shouldn't need to implement adding a row to Payment table but that's a requirement right now.
// We should actually delegate table creation to the core app. Here, only the payment app specific logic should come
async create(
payment: Pick<Prisma.PaymentUncheckedCreateInput, "amount" | "currency">,
bookingId: Booking["id"],
userId: Booking["userId"],
username: string | null,
bookerName: string | null,
bookerEmail: string,
paymentOption: PaymentOption
) {
const paymentCreateData = {
id: 1,
uid: paymentUid,
appId: null,
bookingId,
// booking Booking? @relation(fields: [bookingId], references: [id], onDelete: Cascade)
fee: 10,
success: false,
refunded: false,
data: {},
externalId,
paymentOption,
amount: payment.amount,
currency: payment.currency,
};
const paymentData = await prismaMock.payment.create({
data: paymentCreateData,
});
logger.silly("Created mock payment", JSON.stringify({ paymentData }));
const verifyPayment = await prismaMock.payment.findFirst({
where: { externalId: paymentCreateData.externalId },
});
logger.silly("Verified payment exists", JSON.stringify({ verifyPayment }));
return paymentData;
}
async afterPayment(
event: CalendarEvent,
booking: {
user: { email: string | null; name: string | null; timeZone: string } | null;
id: number;
startTime: { toISOString: () => string };
uid: string;
},
paymentData: Payment
): Promise<void> {
// TODO: App implementing PaymentService is supposed to send email by itself at the moment.
await sendAwaitingPaymentEmailAndSMS({
...event,
paymentInfo: {
link: createPaymentLink(/*{
paymentUid: paymentData.uid,
name: booking.user?.name,
email: booking.user?.email,
date: booking.startTime.toISOString(),
}*/),
paymentOption: paymentData.paymentOption || "ON_BOOKING",
amount: paymentData.amount,
currency: paymentData.currency,
},
});
}
}
return {
paymentUid,
externalId,
MockPaymentService,
};
}
File diff suppressed because it is too large. Load diff
@@ -1,7 +0,0 @@
import { createMocks } from "node-mocks-http";
import type { CustomNextApiRequest, CustomNextApiResponse } from "./types";
export function createMockNextJsRequest(...args: Parameters<typeof createMocks>) {
return createMocks<CustomNextApiRequest, CustomNextApiResponse>(...args);
}
File diff suppressed because it is too large. Load diff
@@ -1,71 +0,0 @@
import { getDate } from "@calcom/web/test/utils/bookingScenario/bookingScenario";
import type { Tracking } from "@calcom/features/bookings/lib/handleNewBooking/types";
import type { SchedulingType } from "@calcom/prisma/client";
import type { CreationSource } from "@calcom/prisma/enums";
export const DEFAULT_TIMEZONE_BOOKER = "Asia/Kolkata";
export function getBasicMockRequestDataForBooking() {
return {
start: `${getDate({ dateIncrement: 1 }).dateString}T04:00:00.000Z`,
end: `${getDate({ dateIncrement: 1 }).dateString}T04:30:00.000Z`,
eventTypeSlug: "no-confirmation",
timeZone: DEFAULT_TIMEZONE_BOOKER,
language: "en",
user: "teampro",
metadata: {},
hasHashedBookingLink: false,
};
}
type CommonPropsMockRequestData = {
rescheduleUid?: string;
bookingUid?: string;
recurringEventId?: string;
recurringCount?: number;
rescheduledBy?: string;
cancelledBy?: string;
schedulingType?: SchedulingType;
guests?: string[];
responses: {
email: string;
name: string;
location?: { optionValue: ""; value: string };
attendeePhoneNumber?: string;
smsReminderNumber?: string;
};
_isDryRun?: boolean;
hashedLink?: string;
hasHashedBookingLink?: boolean;
};
export function getMockRequestDataForBooking({
data,
}: {
data: Partial<ReturnType<typeof getBasicMockRequestDataForBooking>> & {
eventTypeId: number;
user?: string;
creationSource?: CreationSource;
tracking?: Tracking;
} & CommonPropsMockRequestData;
}) {
return {
...getBasicMockRequestDataForBooking(),
...data,
};
}
export function getMockRequestDataForDynamicGroupBooking({
data,
}: {
data: Partial<ReturnType<typeof getBasicMockRequestDataForBooking>> & {
eventTypeId: 0;
eventTypeSlug: string;
user: string;
} & CommonPropsMockRequestData;
}) {
return {
...getBasicMockRequestDataForBooking(),
...data,
};
}
@@ -1,7 +0,0 @@
import type z from "zod";
import type { bookingCancelSchema } from "@calcom/prisma/zod-utils";
export function getMockRequestDataForCancelBooking(data: z.infer<typeof bookingCancelSchema>) {
return data;
}
@@ -1,45 +0,0 @@
import { IdentityProvider, UserPermissionRole } from "@calcom/prisma/enums";
export const getSampleUserInSession = function () {
return {
locale: "",
avatar: "",
organization: {
isOrgAdmin: false,
metadata: null,
id: 1,
requestedSlug: null,
},
profile: null,
defaultScheduleId: null,
name: "",
defaultBookerLayouts: null,
timeZone: "Asia/Kolkata",
selectedCalendars: [],
destinationCalendar: null,
emailVerified: new Date(),
allowDynamicBooking: false,
bio: "",
weekStart: "",
startTime: 0,
endTime: 0,
bufferTime: 0,
hideBranding: false,
timeFormat: 12,
twoFactorEnabled: false,
identityProvider: IdentityProvider.CAL,
brandColor: "#292929",
darkBrandColor: "#fafafa",
metadata: null,
role: UserPermissionRole.USER,
disableImpersonation: false,
organizationId: null,
theme: "",
appTheme: "",
createdDate: new Date(),
trialEndsAt: new Date(),
completedOnboarding: false,
allowSEOIndexing: false,
receiveMonthlyDigestEmail: false,
};
};
@@ -1,36 +0,0 @@
import {
enableEmailFeature,
mockNoTranslations,
} from "@calcom/web/test/utils/bookingScenario/bookingScenario";
import { beforeEach, afterEach } from "vitest";
export function setupAndTeardown() {
beforeEach(() => {
// Required to able to generate token in email in some cases
//@ts-expect-error - It is a readonly variable
process.env.CALENDSO_ENCRYPTION_KEY = "abcdefghjnmkljhjklmnhjklkmnbhjui";
//@ts-expect-error - It is a readonly variable
process.env.STRIPE_WEBHOOK_SECRET = "MOCK_STRIPE_WEBHOOK_SECRET";
// We are setting it in vitest.config.ts because otherwise it's too late to set it.
// process.env.DAILY_API_KEY = "MOCK_DAILY_API_KEY";
// Ensure that Rate Limiting isn't enforced for tests
delete process.env.UNKEY_ROOT_KEY;
mockNoTranslations();
// mockEnableEmailFeature();
enableEmailFeature();
globalThis.testEmails = [];
fetchMock.resetMocks();
});
afterEach(() => {
//@ts-expect-error - It is a readonly variable
delete process.env.CALENDSO_ENCRYPTION_KEY;
//@ts-expect-error - It is a readonly variable
delete process.env.STRIPE_WEBHOOK_SECRET;
delete process.env.DAILY_API_KEY;
globalThis.testEmails = [];
fetchMock.resetMocks();
// process.env.DAILY_API_KEY = "MOCK_DAILY_API_KEY";
});
}
@@ -1,71 +0,0 @@
import { createOrganization } from "@calcom/web/test/utils/bookingScenario/bookingScenario";
import { WEBSITE_URL } from "@calcom/lib/constants";
import { test } from "@calcom/web/test/fixtures/fixtures";
import type { Fixtures } from "@calcom/web/test/fixtures/fixtures";
type OrgContext = {
org: {
organization: { id: number | null };
urlOrigin?: string;
} | null;
};
const WEBSITE_PROTOCOL = new URL(WEBSITE_URL).protocol;
const _testWithAndWithoutOrg = (
description: string,
fn: (context: Fixtures & OrgContext) => Promise<void> | void,
timeout: number | undefined,
mode: "only" | "skip" | "run" = "run"
): void => {
const t = mode === "only" ? test.only : mode === "skip" ? test.skip : test;
t(
`${description} - With org`,
async ({ emails, sms }) => {
const org = await createOrganization({
name: "Test Org",
slug: "testorg",
});
await fn({
emails,
sms,
org: {
organization: org,
urlOrigin: `${WEBSITE_PROTOCOL}//${org.slug}.cal.local:3000`,
},
});
},
timeout
);
t(
`${description}`,
async ({ emails, sms }) => {
await fn({
emails,
sms,
org: null,
});
},
timeout
);
};
type TestFunctionWithOrg = (context: Fixtures & OrgContext) => Promise<void> | void;
export const testWithAndWithoutOrg = (
description: string,
fn: TestFunctionWithOrg,
timeout?: number
): void => {
_testWithAndWithoutOrg(description, fn, timeout, "run");
};
testWithAndWithoutOrg.only = ((description: string, fn: TestFunctionWithOrg, timeout?: number): void => {
_testWithAndWithoutOrg(description, fn, timeout, "only");
}) as typeof testWithAndWithoutOrg;
testWithAndWithoutOrg.skip = ((description: string, fn: TestFunctionWithOrg, timeout?: number): void => {
_testWithAndWithoutOrg(description, fn, timeout, "skip");
}) as typeof testWithAndWithoutOrg;
-6
View File
@@ -1,6 +0,0 @@
import type { Request, Response } from "express";
import type { NextApiRequest, NextApiResponse } from "next";
export type CustomNextApiRequest = NextApiRequest & Request;
export type CustomNextApiResponse = NextApiResponse & Response;
+1
View File
@@ -9,6 +9,7 @@
"@lib/*": ["lib/*"],
"@server/*": ["server/*"],
"@prisma/client/*": ["@calcom/prisma/client/*"],
"@calcom/testing/*": ["../../packages/testing/src/*"],
"@calcom/repository/*": ["@calcom/lib/server/repository/*"],
"@coss/ui/*": ["../../packages/coss-ui/src/*"]
},