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,11 +1,11 @@
import { expect } from "@playwright/test";
import type { Page, Browser, Route, Response } from "@playwright/test";
import type { Team, EventType, User } from "@prisma/client";
import type { z } from "zod";
import { CalendarCacheRepository } from "@calcom/features/calendar-cache/calendar-cache.repository";
import { getTimeMin, getTimeMax } from "@calcom/features/calendar-cache/lib/datesForCache";
import { prisma } from "@calcom/prisma";
import type { Team, EventType, User } from "@calcom/prisma/client";
import { MembershipRole, SchedulingType } from "@calcom/prisma/enums";
import type { teamMetadataSchema } from "@calcom/prisma/zod-utils";
+1 -1
View File
@@ -1,7 +1,7 @@
import { expect } from "@playwright/test";
import type { Page } from "@playwright/test";
import prisma from "@calcom/prisma";
import { prisma } from "@calcom/prisma";
import { BookingStatus, MembershipRole, SchedulingType } from "@calcom/prisma/enums";
import { addFilter } from "./filter-helpers";
@@ -1,5 +1,6 @@
import { expect } from "@playwright/test";
import type Prisma from "@prisma/client";
import type Prisma from "@calcom/prisma/client";
import { test } from "./lib/fixtures";
import { IS_STRIPE_ENABLED, selectFirstAvailableTimeSlotNextMonth } from "./lib/testUtils";
+1 -1
View File
@@ -1,10 +1,10 @@
import type { Page, WorkerInfo } from "@playwright/test";
import type { Booking, Prisma } from "@prisma/client";
import short from "short-uuid";
import { v5 as uuidv5 } from "uuid";
import _dayjs from "@calcom/dayjs";
import { prisma } from "@calcom/prisma";
import type { Booking, Prisma } from "@calcom/prisma/client";
const translator = short();
+1 -1
View File
@@ -1,8 +1,8 @@
import type { Page } from "@playwright/test";
import type { Feature } from "@prisma/client";
import type { AppFlags } from "@calcom/features/flags/config";
import { prisma } from "@calcom/prisma";
import type { Feature } from "@calcom/prisma/client";
type FeatureSlugs = keyof AppFlags;
+1 -1
View File
@@ -1,7 +1,7 @@
import type { Page } from "@playwright/test";
import type { Team } from "@prisma/client";
import { prisma } from "@calcom/prisma";
import type { Team } from "@calcom/prisma/client";
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
const getRandomSlug = () => `org-${Math.random().toString(36).substring(7)}`;
+1 -1
View File
@@ -1,8 +1,8 @@
import type { Page } from "@playwright/test";
import type { Payment } from "@prisma/client";
import { v4 as uuidv4 } from "uuid";
import { prisma } from "@calcom/prisma";
import type { Payment } from "@calcom/prisma/client";
type PaymentFixture = ReturnType<typeof createPaymentFixture>;
+7 -7
View File
@@ -1,8 +1,5 @@
import type { Browser, Page, WorkerInfo } from "@playwright/test";
import { expect } from "@playwright/test";
import type Prisma from "@prisma/client";
import type { Team } from "@prisma/client";
import { Prisma as PrismaType } from "@prisma/client";
import { hashSync as hash } from "bcryptjs";
import { uuid } from "short-uuid";
import { v4 } from "uuid";
@@ -13,6 +10,9 @@ import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "@calcom/lib/avail
import { WEBAPP_URL } from "@calcom/lib/constants";
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
import { prisma } from "@calcom/prisma";
import type Prisma from "@calcom/prisma/client";
import type { Team } from "@calcom/prisma/client";
import type { Prisma as PrismaType } from "@calcom/prisma/client";
import { MembershipRole, SchedulingType, TimeUnit, WorkflowTriggerEvents } from "@calcom/prisma/enums";
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
import type { Schedule } from "@calcom/types/schedule";
@@ -32,12 +32,12 @@ type UserFixture = ReturnType<typeof createUserFixture>;
export type CreateUsersFixture = ReturnType<typeof createUsersFixture>;
const userIncludes = PrismaType.validator<PrismaType.UserInclude>()({
const userIncludes = {
eventTypes: true,
workflows: true,
credentials: true,
routingForms: true,
});
} satisfies PrismaType.UserInclude;
type InstallStripeParamsSkipTrue = {
eventTypeIds?: number[];
@@ -63,9 +63,9 @@ type InstallStripeParams = InstallStripeParamsUnion & {
page: Page;
};
const userWithEventTypes = PrismaType.validator<PrismaType.UserArgs>()({
const userWithEventTypes = {
include: userIncludes,
});
} satisfies PrismaType.UserDefaultArgs;
const seededForm = {
id: "948ae412-d995-4865-875a-48302588de03",
@@ -1,7 +1,7 @@
import { expect } from "@playwright/test";
import type Prisma from "@prisma/client";
import prisma from "@calcom/prisma";
import type Prisma from "@calcom/prisma/client";
import { SchedulingType } from "@calcom/prisma/enums";
import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/prisma/zod-utils";
+1 -2
View File
@@ -1,6 +1,5 @@
import type { Prisma } from "@prisma/client";
import prisma from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
/**
* @deprecated
@@ -1,334 +0,0 @@
import prismock from "../../../../../../tests/libs/__mocks__/prisma";
import { expect, describe, it, beforeEach, afterEach, vi } from "vitest";
import { createAttributes } from "../organizationHelpers";
// Mock console.log to avoid noise in tests
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {
// Intentionally empty to suppress console output in tests
});
// Default mock attributes matching the original hardcoded values
const mockAttributes = [
{
name: "Department",
type: "SINGLE_SELECT" as const,
options: ["Engineering", "Sales", "Marketing", "Product", "Design"],
},
{
name: "Location",
type: "SINGLE_SELECT" as const,
options: ["New York", "London", "Tokyo", "Berlin", "Remote"],
},
{
name: "Skills",
type: "MULTI_SELECT" as const,
options: ["JavaScript", "React", "Node.js", "Python", "Design", "Sales"],
},
{
name: "Years of Experience",
type: "NUMBER" as const,
},
{
name: "Bio",
type: "TEXT" as const,
},
];
// Default assignments matching the original hardcoded behavior
const mockAssignments = [
{
memberIndex: 0,
attributeValues: {
Location: ["New York"],
Skills: ["JavaScript"],
},
},
{
memberIndex: 1,
attributeValues: {
Location: ["London"],
Skills: ["React", "JavaScript"],
},
},
];
describe("createAttributes", () => {
beforeEach(async () => {
// Reset prismock state between tests
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await (prismock as any).reset();
consoleSpy.mockClear();
});
afterEach(async () => {
consoleSpy.mockRestore();
});
it("should create all 5 mock attributes for an organization", async () => {
const orgId = 1;
// Create a membership for the organization
await prismock.membership.create({
data: {
id: 1,
userId: 1,
teamId: orgId,
role: "OWNER",
accepted: true,
},
});
const result = await createAttributes({
orgId,
attributes: mockAttributes,
assignments: mockAssignments,
});
// Verify all attributes were created
const attributes = await prismock.attribute.findMany({
where: { teamId: orgId },
include: { options: true },
});
expect(attributes).toHaveLength(5);
expect(result).toHaveLength(5);
// Check specific attributes
const departmentAttr = attributes.find((attr) => attr.name === "Department");
const locationAttr = attributes.find((attr) => attr.name === "Location");
const skillsAttr = attributes.find((attr) => attr.name === "Skills");
const experienceAttr = attributes.find((attr) => attr.name === "Years of Experience");
const bioAttr = attributes.find((attr) => attr.name === "Bio");
expect(departmentAttr).toBeDefined();
expect(departmentAttr?.type).toBe("SINGLE_SELECT");
expect(departmentAttr?.options).toHaveLength(5);
expect(locationAttr).toBeDefined();
expect(locationAttr?.type).toBe("SINGLE_SELECT");
expect(locationAttr?.options).toHaveLength(5);
expect(skillsAttr).toBeDefined();
expect(skillsAttr?.type).toBe("MULTI_SELECT");
expect(skillsAttr?.options).toHaveLength(6);
expect(experienceAttr).toBeDefined();
expect(experienceAttr?.type).toBe("NUMBER");
expect(experienceAttr?.options).toHaveLength(0); // No options created for NUMBER type
expect(bioAttr).toBeDefined();
expect(bioAttr?.type).toBe("TEXT");
expect(bioAttr?.options).toHaveLength(0); // No options created for TEXT type
});
it("should assign attribute values to all organization members", async () => {
const orgId = 1;
// Create multiple memberships
await prismock.membership.createMany({
data: [
{ id: 1, userId: 1, teamId: orgId, role: "OWNER", accepted: true },
{ id: 2, userId: 2, teamId: orgId, role: "MEMBER", accepted: true },
{ id: 3, userId: 3, teamId: orgId, role: "MEMBER", accepted: true },
],
});
await createAttributes({
orgId,
attributes: mockAttributes,
assignments: mockAssignments,
});
// Check that attribute assignments were created
const attributeAssignments = await prismock.attributeToUser.findMany();
const attributeOptions = await prismock.attributeOption.findMany({
include: { assignedUsers: true },
});
// Should have assignments only for specific first two members
// Member 1: Location (New York) + Skills (JavaScript) = 2 assignments
// Member 2: Location (London) + Skills (React + JavaScript) = 3 assignments
// Total = 5 assignments (no random assignments for other members/attributes)
expect(attributeAssignments.length).toBe(5);
// Should have 4 options with assigned users:
// Location: New York (assigned to user 1) + London (assigned to user 2) = 2 options
// Skills: JavaScript (assigned to user 1) + React & JavaScript (assigned to user 2) = 2 unique options
const customOptions = attributeOptions.filter((opt) => opt.assignedUsers.length > 0);
expect(customOptions.length).toBe(4);
});
it("should skip seeding if attributes already exist", async () => {
const orgId = 1;
// Create a membership
await prismock.membership.create({
data: {
id: 1,
userId: 1,
teamId: orgId,
role: "OWNER",
accepted: true,
},
});
// Pre-create one of the attributes
await prismock.attribute.create({
data: {
id: "attr-1",
name: "Department",
slug: "department",
type: "SINGLE_SELECT",
teamId: orgId,
enabled: true,
},
});
const result = await createAttributes({
orgId,
attributes: mockAttributes,
assignments: mockAssignments,
});
// Should return early and not create more attributes
expect(result).toBeUndefined();
const attributes = await prismock.attribute.findMany({
where: { teamId: orgId },
});
// Should still only have the 1 pre-existing attribute
expect(attributes).toHaveLength(1);
});
it("should handle organization with no members gracefully", async () => {
const orgId = 1;
// Don't create any memberships
const result = await createAttributes({
orgId,
attributes: mockAttributes,
assignments: mockAssignments,
});
// Should still create attributes
const attributes = await prismock.attribute.findMany({
where: { teamId: orgId },
});
expect(attributes).toHaveLength(5);
expect(result).toHaveLength(5);
// But no attribute assignments should be created
const attributeAssignments = await prismock.attributeToUser.findMany();
expect(attributeAssignments).toHaveLength(0);
});
it("should assign specific skills and locations to first two members", async () => {
const orgId = 1;
// Create exactly two memberships to test specific assignments
await prismock.membership.createMany({
data: [
{ id: 1, userId: 1, teamId: orgId, role: "OWNER", accepted: true },
{ id: 2, userId: 2, teamId: orgId, role: "MEMBER", accepted: true },
],
});
await createAttributes({
orgId,
attributes: mockAttributes,
assignments: mockAssignments,
});
// Get the attributes and their options
const skillsAttr = await prismock.attribute.findFirst({
where: { teamId: orgId, name: "Skills" },
include: { options: true },
});
const locationAttr = await prismock.attribute.findFirst({
where: { teamId: orgId, name: "Location" },
include: { options: true },
});
expect(skillsAttr).toBeDefined();
expect(locationAttr).toBeDefined();
// Check assignments for first member (should have JavaScript skill and New York location)
const firstMemberAssignments = await prismock.attributeToUser.findMany({
where: { memberId: 1 },
include: { attributeOption: true },
});
const firstMemberSkills = firstMemberAssignments
.filter((a) => a.attributeOption.attributeId === skillsAttr!.id)
.map((a) => a.attributeOption.value);
const firstMemberLocation = firstMemberAssignments
.filter((a) => a.attributeOption.attributeId === locationAttr!.id)
.map((a) => a.attributeOption.value);
expect(firstMemberSkills).toContain("JavaScript");
expect(firstMemberLocation).toContain("New York");
// Check assignments for second member (should have React and JavaScript skills, London location)
const secondMemberAssignments = await prismock.attributeToUser.findMany({
where: { memberId: 2 },
include: { attributeOption: true },
});
const secondMemberSkills = secondMemberAssignments
.filter((a) => a.attributeOption.attributeId === skillsAttr!.id)
.map((a) => a.attributeOption.value);
const secondMemberLocation = secondMemberAssignments
.filter((a) => a.attributeOption.attributeId === locationAttr!.id)
.map((a) => a.attributeOption.value);
expect(secondMemberSkills).toContain("JavaScript");
expect(secondMemberSkills).toContain("React");
expect(secondMemberLocation).toContain("London");
});
it("should generate correct slugs and enable all attributes", async () => {
const orgId = 123;
// Create a membership
await prismock.membership.create({
data: {
id: 1,
userId: 1,
teamId: orgId,
role: "OWNER",
accepted: true,
},
});
await createAttributes({
orgId,
attributes: mockAttributes,
assignments: mockAssignments,
});
const attributes = await prismock.attribute.findMany({
where: { teamId: orgId },
});
attributes.forEach((attr) => {
// All should be enabled
expect(attr.enabled).toBe(true);
// Should have correct slug format
expect(attr.slug).toMatch(/^org:123-/);
// Specific slug checks
if (attr.name === "Years of Experience") {
expect(attr.slug).toBe("org:123-years-of-experience");
}
});
});
});
@@ -1,377 +0,0 @@
import prismock from "../../../../../../tests/libs/__mocks__/prisma";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createRoutingForm } from "../routingFormHelpers";
// Mock console.log to avoid noise in tests
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {
// Intentionally empty to suppress console output during tests
});
describe("createRoutingForm", () => {
beforeEach(async () => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
await prismock.reset();
consoleSpy.mockClear();
});
// Common attribute routing config for tests
const defaultAttributeRoutingConfig = {
attributes: [
{
name: "Department",
type: "SINGLE_SELECT" as const,
options: ["Engineering", "Sales", "Marketing", "Product", "Design"],
},
{
name: "Location",
type: "SINGLE_SELECT" as const,
options: ["New York", "London", "Tokyo", "Berlin", "Remote"],
},
{
name: "Skills",
type: "MULTI_SELECT" as const,
options: ["JavaScript", "React", "Node.js", "Python", "Design", "Sales"],
},
{
name: "Years of Experience",
type: "NUMBER" as const,
},
{
name: "Bio",
type: "TEXT" as const,
},
],
assignments: [
{
memberIndex: 0,
attributeValues: {
Location: ["New York"],
Skills: ["JavaScript"],
},
},
{
memberIndex: 1,
attributeValues: {
Location: ["London"],
Skills: ["React", "JavaScript"],
},
},
],
teamEvents: [
{
title: "Team Sales",
slug: "team-sales",
schedulingType: "ROUND_ROBIN" as const,
assignAllTeamMembers: true,
length: 60,
description: "Team Sales",
},
{
title: "Team Javascript",
slug: "team-javascript",
schedulingType: "ROUND_ROBIN" as const,
assignAllTeamMembers: true,
length: 60,
description: "Team Javascript",
},
],
};
describe("Default routing form", () => {
beforeEach(async () => {
// Create a test user for default form tests
await prismock.user.create({
data: {
id: 1,
username: "test-user",
email: "[email protected]",
name: "Test User",
},
});
});
it("should create a basic routing form", async () => {
const userId = 1;
const teamId = 1;
const form = await createRoutingForm({
userId,
teamId,
formType: "default",
});
expect(form).toBeDefined();
expect(form.name).toBe("Fixture Routing Form");
expect(form.userId).toBe(userId);
});
it("should create form with multiple route types", async () => {
const userId = 1;
const teamId = 1;
const form = await createRoutingForm({
userId,
teamId,
formType: "default",
});
expect(form.routes).toBeDefined();
const routes = form.routes as any[];
// Should have event redirect, custom page, external redirect, and multiselect routes
expect(routes.length).toBeGreaterThan(4);
const eventRedirectRoute = routes.find((r) => r.action?.type === "eventTypeRedirectUrl");
const customPageRoute = routes.find((r) => r.action?.type === "customPageMessage");
const externalRedirectRoute = routes.find((r) => r.action?.type === "externalRedirectUrl");
const fallbackRoute = routes.find((r) => r.isFallback === true);
expect(eventRedirectRoute).toBeDefined();
expect(customPageRoute).toBeDefined();
expect(externalRedirectRoute).toBeDefined();
expect(fallbackRoute).toBeDefined();
});
it("should create form with various field types", async () => {
const userId = 1;
const teamId = 1;
const form = await createRoutingForm({
userId,
teamId,
formType: "default",
});
const fields = form.fields as any[];
expect(fields).toBeDefined();
expect(fields.length).toBeGreaterThan(3);
const textField = fields.find((f) => f.type === "text");
const multiselectField = fields.find((f) => f.type === "multiselect");
const selectField = fields.find((f) => f.type === "select");
expect(textField).toBeDefined();
expect(multiselectField).toBeDefined();
expect(selectField).toBeDefined();
});
});
describe("Attribute routing form", () => {
beforeEach(async () => {
// Create a test user
await prismock.user.create({
data: {
id: 1,
username: "test-user",
email: "[email protected]",
name: "Test User",
},
});
// Setup organization and team structure for attribute routing
await prismock.team.createMany({
data: [
{ id: 100, name: "Test Org", isOrganization: true, slug: "test-org" },
{ id: 1, name: "Test Team", isOrganization: false, slug: "test-team", parentId: 100 },
],
});
await prismock.membership.createMany({
data: [
{ id: 1, userId: 1, teamId: 100, role: "OWNER", accepted: true }, // Org membership
{ id: 2, userId: 1, teamId: 1, role: "OWNER", accepted: true }, // Team membership
],
});
});
it("should create routing form with attribute routing", async () => {
const userId = 1;
const teamId = 1;
const result = await createRoutingForm({
userId,
teamId,
formType: "attributeRouting",
attributeRouting: defaultAttributeRoutingConfig,
});
expect(result).toBeDefined();
expect(result!.name).toBe("Form with Attribute Routing");
expect(result!.userId).toBe(userId);
expect(result!.teamId).toBe(teamId);
});
it("should create team event types for attribute routing", async () => {
const userId = 1;
const teamId = 1;
await createRoutingForm({
userId,
teamId,
formType: "attributeRouting",
attributeRouting: defaultAttributeRoutingConfig,
});
// Check that team event types were created
const salesEvent = await prismock.eventType.findFirst({
where: { slug: "team-sales", teamId },
});
const javascriptEvent = await prismock.eventType.findFirst({
where: { slug: "team-javascript", teamId },
});
expect(salesEvent).toBeDefined();
expect(salesEvent?.title).toBe("Team Sales");
expect(salesEvent?.schedulingType).toBe("ROUND_ROBIN");
expect(javascriptEvent).toBeDefined();
expect(javascriptEvent?.title).toBe("Team Javascript");
expect(javascriptEvent?.schedulingType).toBe("ROUND_ROBIN");
});
it("should create attributes for the organization", async () => {
const userId = 1;
const teamId = 1;
await createRoutingForm({
userId,
teamId,
formType: "attributeRouting",
attributeRouting: defaultAttributeRoutingConfig,
});
// Check that attributes were created for the organization
const attributes = await prismock.attribute.findMany({
where: { teamId: 100 }, // Organization ID
include: { options: true },
});
expect(attributes.length).toBeGreaterThan(0);
const skillsAttribute = attributes.find((attr) => attr.name === "Skills");
const locationAttribute = attributes.find((attr) => attr.name === "Location");
expect(skillsAttribute).toBeDefined();
expect(locationAttribute).toBeDefined();
});
it("should create routes with attribute-based routing logic", async () => {
const userId = 1;
const teamId = 1;
const result = await createRoutingForm({
userId,
teamId,
formType: "attributeRouting",
attributeRouting: defaultAttributeRoutingConfig,
});
const routes = result!.routes as any[];
expect(routes).toBeDefined();
expect(routes.length).toBeGreaterThanOrEqual(3);
// Should have routes with attributesQueryValue
const attributeRoutes = routes.filter((route) => route.attributesQueryValue);
expect(attributeRoutes.length).toBeGreaterThanOrEqual(2);
// Should have fallback route
const fallbackRoute = routes.find((route) => route.isFallback === true);
expect(fallbackRoute).toBeDefined();
});
it("should create form fields matching attributes", async () => {
const userId = 1;
const teamId = 1;
const result = await createRoutingForm({
userId,
teamId,
formType: "attributeRouting",
attributeRouting: defaultAttributeRoutingConfig,
});
const fields = result!.fields as any[];
expect(fields).toBeDefined();
expect(fields.length).toBe(5);
const locationField = fields.find((f) => f.label === "Location");
const skillsField = fields.find((f) => f.label === "skills");
const emailField = fields.find((f) => f.label === "Email");
const nameField = fields.find((f) => f.label === "Name");
const ratingField = fields.find((f) => f.label === "Rating");
expect(locationField?.type).toBe("select");
expect(skillsField?.type).toBe("multiselect");
expect(emailField?.type).toBe("email");
expect(nameField?.type).toBe("text");
expect(ratingField?.type).toBe("number");
// Check required fields
expect(locationField?.required).toBe(true);
expect(skillsField?.required).toBe(true);
expect(emailField?.required).toBe(true);
expect(nameField?.required).toBe(false);
expect(ratingField?.required).toBe(false);
});
it("should handle missing attributeRouting config", async () => {
const userId = 1;
const teamId = 1;
await expect(
createRoutingForm({
userId,
teamId,
formType: "attributeRouting",
})
).rejects.toThrow("attributeRouting config is required when formType is 'attributeRouting'");
});
it("should handle missing organization membership", async () => {
const userId = 2; // User without org membership
const teamId = 1;
// Create a test user without org membership
await prismock.user.create({
data: {
id: 2,
username: "test-user-2",
email: "[email protected]",
name: "Test User 2",
},
});
// Only create team membership, not org membership
await prismock.membership.create({
data: { id: 3, userId: 2, teamId: 1, role: "MEMBER", accepted: true },
});
await expect(
createRoutingForm({
userId,
teamId,
formType: "attributeRouting",
attributeRouting: defaultAttributeRoutingConfig,
})
).rejects.toThrow();
});
it("should handle missing team", async () => {
const userId = 1;
const teamId = 999; // Non-existent team
await expect(
createRoutingForm({
userId,
teamId,
formType: "attributeRouting",
attributeRouting: defaultAttributeRoutingConfig,
})
).rejects.toThrow();
});
});
});
@@ -1,6 +1,5 @@
import type { Prisma as PrismaType } from "@prisma/client";
import { prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
/**
* Creates a team event type and assigns all team members as hosts
@@ -13,7 +12,7 @@ export async function createRoundRobinTeamEventType({
eventType,
}: {
teamId: number;
eventType: PrismaType.EventTypeCreateInput;
eventType: Prisma.EventTypeCreateInput;
}) {
const createdEventType = await prisma.eventType.create({
data: {