Scheduling infrastructure for absolutely everyone.
test: Add Attributes Routing e2e and some more unit tests (#17032)
Hariom Balhara06429e27fb90
diff --git a/apps/web/playwright/fixtures/users.ts b/apps/web/playwright/fixtures/users.tsindex d7150cf16e9..26a4488d3c8 100644--- a/apps/web/playwright/fixtures/users.ts+++ b/apps/web/playwright/fixtures/users.ts@@ -153,6 +153,7 @@ const createTeamAndAddUser = async (isDnsSetup,index,orgRequestedSlug,+ schedulingType,}: {user: { id: number; email: string; username: string | null; role?: MembershipRole };isUnpublished?: boolean;@@ -163,6 +164,7 @@ const createTeamAndAddUser = async (organizationId?: number | null;index?: number;orgRequestedSlug?: string;+ schedulingType?: SchedulingType;},workerInfo: WorkerInfo) => {@@ -189,7 +191,9 @@ const createTeamAndAddUser = async (data.slug = !isUnpublished ? slug : undefined;if (isOrg && hasSubteam) {const team = await createTeamAndAddUser({ user }, workerInfo);- await createTeamEventType(user, team);+ await createTeamEventType(user, team, {+ schedulingType: schedulingType,+ });await createTeamWorkflow(user, team);data.children = { connect: [{ id: team.id }] };}@@ -532,6 +536,7 @@ export const createUsersFixture = (hasSubteam: scenario.hasSubteam,organizationId: opts?.organizationId,orgRequestedSlug: scenario.orgRequestedSlug,+ schedulingType: scenario.schedulingType,},workerInfo);diff --git a/packages/app-store/routing-forms/TODO.md b/packages/app-store/routing-forms/TODO.mdindex e7ce90225f1..0fee3b24fce 100644--- a/packages/app-store/routing-forms/TODO.md+++ b/packages/app-store/routing-forms/TODO.md@@ -13,6 +13,7 @@- [ ] Warnings are needed with recommendation to create new attribute instead in unsupported scenarios. We need to test for more such changes to Attribute types.- [ ] When choosing 'Value of Field' option in RAQB, show a warning somewhere if all options of the Form field aren't present in the attribute option.- So, if Form Field is 'What is Comapny Size' with options Enterprise, Large, Medium, Small and Attribute for which Value of 'What is compnay size' has options Enterprise, Large, Medium. It would show a warning that 'Small' option is not present in the attribute.+- [ ] When logic can't be built(Short text maps to an attribute with given set of options but the short text value doesn't match any of the options), the team member matching route throws error but Test Preview still shows the previous value - It show should the error in there.### Performance Tests and Improvements- [ ] Test with ~1000 team members and ~100 attributes.@@ -30,7 +31,7 @@- [x] Basic Tests- [ ] getAttributes- [ ] Querying Logic Test-- [ ] getRoutedUsers tests+- [x] getRoutedUsers tests- [ ] getAvailableSlots- [ ] should use routedTeamMemberIds in availability querydiff --git a/packages/app-store/routing-forms/pages/route-builder/[...appPages].tsx b/packages/app-store/routing-forms/pages/route-builder/[...appPages].tsxindex 1a1bfcf506a..15c90a6e035 100644--- a/packages/app-store/routing-forms/pages/route-builder/[...appPages].tsx+++ b/packages/app-store/routing-forms/pages/route-builder/[...appPages].tsx@@ -444,6 +444,7 @@ const Route = ({<div className="block w-full"><Selectrequired+ className="data-testid-eventTypeRedirectUrl-select"isDisabled={disabled}options={eventTypeRedirectUrlOptions}onChange={(option) => {diff --git a/packages/app-store/routing-forms/playwright/tests/basic.e2e.ts b/packages/app-store/routing-forms/playwright/tests/basic.e2e.tsindex a92b88d4e87..82080314eaa 100644--- a/packages/app-store/routing-forms/playwright/tests/basic.e2e.ts+++ b/packages/app-store/routing-forms/playwright/tests/basic.e2e.ts@@ -1,6 +1,8 @@-import type { Page } from "@playwright/test";+import type { Locator, Page } from "@playwright/test";import { expect } from "@playwright/test";+import { prisma } from "@calcom/prisma";+import { AttributeType, SchedulingType } from "@calcom/prisma/enums";import type { Fixtures } from "@calcom/web/playwright/lib/fixtures";import { test } from "@calcom/web/playwright/lib/fixtures";import { selectInteractions } from "@calcom/web/playwright/lib/pageObject";@@ -25,6 +27,53 @@ const Identifiers = {selectNewFormat: "test-select-new-format",};+async function enableContactOwnerOverride(page: Page) {+ await page.click("text=Contact owner will be the Round Robin host");+}++async function selectFirstAttributeOption({ fromLocator }: { fromLocator: Locator }) {+ await selectOptionUsingLocator({+ locator: fromLocator,+ option: 1+ });+}++async function selectFirstValueForAttributeValue({ fromLocator, option }: { fromLocator: Locator, option: number }) {+ await selectOptionUsingLocator({+ locator: fromLocator,+ option+ });+}++async function addAttributeRoutingRule(page: Page) {+ // TODO: Use a better selector maybe?+ await page.locator('text="Add rule"').nth(1).click();+ const attributeQueryBuilder = page.locator(".group-container").nth(1);+ const attributeSelectorFirstRule = attributeQueryBuilder.locator(".rule--field").nth(0);+ await selectFirstAttributeOption({+ fromLocator: attributeSelectorFirstRule,+ });++ const attributeValueSelector = attributeQueryBuilder.locator(".rule--value").nth(0);+ const numOfOptionsInAttribute = 3;+ await selectFirstValueForAttributeValue({+ fromLocator: attributeValueSelector,+ // Select 'Value of Field Short Text' option+ option: numOfOptionsInAttribute + 1+ });+}++async function selectFirstEventRedirectOption(page: Page) {+ await selectOption({+ selector: {+ selector: ".data-testid-eventTypeRedirectUrl-select",+ nth: 0,+ },+ option: 2,+ page,+ });+}+test.describe("Routing Forms", () => {test.describe("Zero State Routing Forms", () => {test("should be able to add a new form and view it", async ({ page }) => {@@ -45,7 +94,7 @@ test.describe("Routing Forms", () => {await expect(page.getByTestId(`404-page`)).toBeVisible();});- test("should be able to edit the form", async ({ page }) => {+ test("should be able to edit a newly created form", async ({ page }) => {const formId = await addForm(page);const description = "Test Description";@@ -432,6 +481,110 @@ test.describe("Routing Forms", () => {expect(route).toBe("Fallback Message");});});++ test.describe("Form with Attribute Routing - Team Form", () => {+ test.beforeEach(async ({ page, users }) => {+ const userFixture = await users.create(+ { username: "routing-forms" },+ {+ hasTeam: true,+ isOrg: true,+ hasSubteam: true,+ schedulingType: SchedulingType.ROUND_ROBIN,+ }+ );++ const orgMembership = await userFixture.getOrgMembership();++ const createdAttribute = await prisma.attribute.create({+ data: {+ teamId: orgMembership.teamId,+ type: AttributeType.SINGLE_SELECT,+ name: "Company Size",+ slug: `company-size-orgId-${orgMembership.teamId}`,+ options: {+ create: [+ {+ slug: "large",+ value: "large",+ },+ {+ slug: "medium",+ value: "medium",+ },+ {+ slug: "small",+ value: "small",+ },+ ],+ },+ },+ include: {+ options: true,+ },+ });++ await prisma.attributeToUser.create({+ data: {+ member: {+ connect: {+ userId_teamId: {+ userId: userFixture.id,+ teamId: orgMembership.teamId,+ },+ },+ },+ attributeOption: {+ connect: {+ id: createdAttribute.options[0].id,+ },+ },+ },+ });+ await userFixture.apiLogin();+ });++ test.afterEach(async ({ users }) => {+ // This also delete forms on cascade+ await users.deleteAll();+ });++ test("should be able to add attribute routing to a newly created team form", async ({ page }) => {+ const formId = await addForm(page, {+ forTeam: true,+ });++ await addShortTextFieldAndSaveForm({+ page,+ formId,+ });++ await page.click('[href*="/route-builder/"]');+ await selectNewRoute(page);+ // This would select Round Robin event that we created above+ await selectFirstEventRedirectOption(page);+ await enableContactOwnerOverride(page);+ await addAttributeRoutingRule(page);+ await saveCurrentForm(page);++ await (async function testPreviewWhereThereIsMatch() {+ await page.click('[data-testid="test-preview"]');+ await page.fill('[data-testid="form-field-short-text"]', "large");+ await page.click('[data-testid="test-routing"]');+ await page.waitForSelector('[email protected]');+ await page.click('[data-testid="dialog-rejection"]');+ })();++ await (async function testPreviewWhereThereIsNoMatch() {+ await page.click('[data-testid="test-preview"]');+ await page.fill('[data-testid="form-field-short-text"]', "medium");+ await page.click('[data-testid="test-routing"]');+ await page.waitForSelector('text=No matching members.');+ await page.click('[data-testid="dialog-rejection"]');++ })();+ });+ });});async function disableForm(page: Page) {@@ -569,6 +722,15 @@ async function addAllTypesOfFieldsAndSaveForm(};}+async function addShortTextFieldAndSaveForm({ page, formId }: { page: Page; formId: string }) {+ await page.goto(`apps/routing-forms/form-edit/${formId}`);+ await page.click('[data-testid="add-field"]');+ await page.locator(".data-testid-field-type").nth(0).click();+ await page.fill(`[name="fields.0.label"]`, "Short Text");+ await page.fill(`[name="fields.0.identifier"]`, "short-text");+ await saveCurrentForm(page);+}+async function selectOption({page,selector,@@ -589,6 +751,17 @@ async function selectOption({.click();}+export async function selectOptionUsingLocator({+ locator,+ option,+}: {+ locator: Locator;+ option: number;+}) {+ await locator.click();+ await locator.locator('[id*="react-select-"][aria-disabled]').nth(option - 1).click();+}+async function verifyFieldOptionsInRule(options: string[], page: Page) {await verifySelectOptions({diff --git a/packages/app-store/routing-forms/playwright/tests/testUtils.ts b/packages/app-store/routing-forms/playwright/tests/testUtils.tsindex 81bcb5d90c1..7f86e19721c 100644--- a/packages/app-store/routing-forms/playwright/tests/testUtils.ts+++ b/packages/app-store/routing-forms/playwright/tests/testUtils.ts@@ -1,11 +1,25 @@import type { Page } from "@playwright/test";import { expect } from "@playwright/test";-export async function addForm(page: Page, { name = "Test Form Name" } = {}) {+export async function addForm(+ page: Page,+ {+ name = "Test Form Name",+ forTeam,+ }: {+ name?: string;+ forTeam?: boolean;+ } = {}+) {await page.goto(`/routing-forms/forms`);await page.click('[data-testid="new-routing-form"]');- // Choose to create the Form for the user(which is the first option) and not the team- await page.click('[data-testid="option-0"]');++ if (forTeam) {+ await page.click('[data-testid="option-team-1"]');+ } else {+ await page.click('[data-testid="option-0"]');+ }+await page.fill("input[name]", name);await page.click('[data-testid="add-form"]');await page.waitForSelector('[data-testid="add-field"]');diff --git a/packages/lib/bookings/getRoutedUsers.test.ts b/packages/lib/bookings/getRoutedUsers.test.tsnew file mode 100644index 00000000000..9bf10ffdf0a--- /dev/null+++ b/packages/lib/bookings/getRoutedUsers.test.ts@@ -0,0 +1,128 @@+import { describe, it, expect } from "vitest";++import {+ getRoutedHostsWithContactOwnerAndFixedHosts,+ getRoutedUsersWithContactOwnerAndFixedUsers,+} from "./getRoutedUsers";++describe("getRoutedHostsWithContactOwnerAndFixedHosts", () => {+ const hosts = [+ { user: { id: 1, email: "[email protected]" }, isFixed: false },+ { user: { id: 2, email: "[email protected]" }, isFixed: true },+ { user: { id: 3, email: "[email protected]" }, isFixed: false },+ { user: { id: 4, email: "[email protected]" }, isFixed: false },+ ];++ const hostsWithoutFixedHosts = hosts.map((host) => ({ ...host, isFixed: false }));++ it("should return all hosts when routedTeamMemberIds is null", () => {+ const result = getRoutedHostsWithContactOwnerAndFixedHosts({+ routedTeamMemberIds: null,+ hosts,+ contactOwnerEmail: "[email protected]",+ });+ expect(result).toEqual(hosts);+ });++ it("should return all hosts when routedTeamMemberIds is empty - We don't want to enter a scenario where we have no team members to be booked", () => {+ const result = getRoutedHostsWithContactOwnerAndFixedHosts({+ routedTeamMemberIds: [],+ hosts,+ contactOwnerEmail: "[email protected]",+ });+ expect(result).toEqual(hosts);+ });++ it("should filter hosts based on routedTeamMemberIds, isFixed, and contactOwnerEmail", () => {+ const result = getRoutedHostsWithContactOwnerAndFixedHosts({+ routedTeamMemberIds: [1, 3],+ hosts,+ contactOwnerEmail: "[email protected]",+ });+ expect(result).toEqual([+ { user: { id: 1, email: "[email protected]" }, isFixed: false },+ { user: { id: 2, email: "[email protected]" }, isFixed: true },+ { user: { id: 3, email: "[email protected]" }, isFixed: false },+ { user: { id: 4, email: "[email protected]" }, isFixed: false },+ ]);+ });++ it("should return an empty array when no hosts match the criteria", () => {+ const result = getRoutedHostsWithContactOwnerAndFixedHosts({+ routedTeamMemberIds: [5],+ hosts: hostsWithoutFixedHosts,+ contactOwnerEmail: "[email protected]",+ });+ expect(result).toEqual([]);+ });++ it("should return fixed hosts even if routedTeamMemberIds and contactOwnerEmail are invalid ", () => {+ const result = getRoutedHostsWithContactOwnerAndFixedHosts({+ routedTeamMemberIds: [5],+ hosts,+ contactOwnerEmail: "[email protected]",+ });+ expect(result).toEqual([{ user: { id: 2, email: "[email protected]" }, isFixed: true }]);+ });+});++describe("getRoutedUsersWithContactOwnerAndFixedUsers", () => {+ const users = [+ { id: 1, email: "[email protected]", isFixed: false },+ { id: 2, email: "[email protected]", isFixed: true },+ { id: 3, email: "[email protected]", isFixed: false },+ { id: 4, email: "[email protected]", isFixed: false },+ ];++ const usersWithoutFixedHosts = users.map((user) => ({ ...user, isFixed: false }));++ it("should return all users when routedTeamMemberIds is null", () => {+ const result = getRoutedUsersWithContactOwnerAndFixedUsers({+ routedTeamMemberIds: null,+ users,+ contactOwnerEmail: "[email protected]",+ });+ expect(result).toEqual(users);+ });++ it("should return all users when routedTeamMemberIds is empty - We don't want to enter a scenario where we have no team members to be booked", () => {+ const result = getRoutedUsersWithContactOwnerAndFixedUsers({+ routedTeamMemberIds: [],+ users,+ contactOwnerEmail: "[email protected]",+ });+ expect(result).toEqual(users);+ });++ it("should filter users based on routedTeamMemberIds, isFixed, and contactOwnerEmail", () => {+ const result = getRoutedUsersWithContactOwnerAndFixedUsers({+ routedTeamMemberIds: [1, 3],+ users,+ contactOwnerEmail: "[email protected]",+ });+ expect(result).toEqual([+ { id: 1, email: "[email protected]", isFixed: false },+ { id: 2, email: "[email protected]", isFixed: true },+ { id: 3, email: "[email protected]", isFixed: false },+ { id: 4, email: "[email protected]", isFixed: false },+ ]);+ });++ it("should return an empty array when neither fixed, nor routedTeamMemberIds, nor contactOwnerEmail match", () => {+ const result = getRoutedUsersWithContactOwnerAndFixedUsers({+ routedTeamMemberIds: [5],+ users: usersWithoutFixedHosts,+ contactOwnerEmail: "[email protected]",+ });+ expect(result).toEqual([]);+ });++ it("should return fixed hosts even if routedTeamMemberIds and contactOwnerEmail are invalid ", () => {+ const result = getRoutedUsersWithContactOwnerAndFixedUsers({+ routedTeamMemberIds: [5],+ users,+ contactOwnerEmail: "[email protected]",+ });+ expect(result).toEqual([{ id: 2, email: "[email protected]", isFixed: true }]);+ });+});diff --git a/packages/trpc/server/routers/viewer/slots/util.test.ts b/packages/trpc/server/routers/viewer/slots/util.test.tsnew file mode 100644index 00000000000..b3ede3d45e4--- /dev/null+++ b/packages/trpc/server/routers/viewer/slots/util.test.ts@@ -0,0 +1,90 @@+import { describe, expect, it } from "vitest";++import type { GetAvailabilityUser } from "@calcom/core/getUserAvailability";++import { getUsersWithCredentialsConsideringContactOwner } from "./util";++describe("getUsersWithCredentialsConsideringContactOwner", () => {+ const createMockUser = (email: string): GetAvailabilityUser => ({+ id: Math.random(),+ email,+ name: email.split("@")[0],+ username: email.split("@")[0],+ timeZone: "UTC",+ weekStart: "Monday",+ defaultScheduleId: null,+ bufferTime: 0,+ locale: "en",+ });++ it("should return all hosts when contact owner does not exist", () => {+ const hosts = [+ { isFixed: true, user: createMockUser("[email protected]") },+ { isFixed: false, user: createMockUser("[email protected]") },+ ];+ const result = getUsersWithCredentialsConsideringContactOwner({+ contactOwnerEmail: "[email protected]",+ hosts,+ });+ expect(result).toHaveLength(2);+ expect(result.map((u) => u.email)).toEqual(["[email protected]", "[email protected]"]);+ });++ it("should return all hosts when contact owner is a fixed host", () => {+ const hosts = [+ { isFixed: true, user: createMockUser("[email protected]") },+ { isFixed: false, user: createMockUser("[email protected]") },+ ];+ const result = getUsersWithCredentialsConsideringContactOwner({+ contactOwnerEmail: "[email protected]",+ hosts,+ });+ expect(result).toHaveLength(2);+ expect(result.map((u) => u.email)).toEqual(["[email protected]", "[email protected]"]);+ });++ it("should return contact owner and fixed hosts when contact owner is not fixed", () => {+ const hosts = [+ { isFixed: true, user: createMockUser("[email protected]") },+ { isFixed: false, user: createMockUser("[email protected]") },+ { isFixed: false, user: createMockUser("[email protected]") },+ ];+ const result = getUsersWithCredentialsConsideringContactOwner({+ contactOwnerEmail: "[email protected]",+ hosts,+ });+ expect(result).toHaveLength(2);+ expect(result.map((u) => u.email)).toEqual(["[email protected]", "[email protected]"]);+ });++ it("should return all hosts when contactOwnerEmail is null", () => {+ const hosts = [+ { isFixed: true, user: createMockUser("[email protected]") },+ { isFixed: false, user: createMockUser("[email protected]") },+ ];+ const result = getUsersWithCredentialsConsideringContactOwner({+ contactOwnerEmail: null,+ hosts,+ });+ expect(result).toHaveLength(2);+ expect(result.map((u) => u.email)).toEqual(["[email protected]", "[email protected]"]);+ });++ it("should return only fixed hosts when there's no contact owner", () => {+ const hosts = [+ { isFixed: true, user: createMockUser("[email protected]") },+ { isFixed: false, user: createMockUser("[email protected]") },+ { isFixed: true, user: createMockUser("[email protected]") },+ ];+ const result = getUsersWithCredentialsConsideringContactOwner({+ contactOwnerEmail: null,+ hosts,+ });+ expect(result).toHaveLength(3);+ expect(result.map((u) => u.email)).toEqual([+ "[email protected]",+ "[email protected]",+ "[email protected]",+ ]);+ });+});diff --git a/packages/trpc/server/routers/viewer/slots/util.ts b/packages/trpc/server/routers/viewer/slots/util.tsindex a22fa3f8996..33daf98bd62 100644--- a/packages/trpc/server/routers/viewer/slots/util.ts+++ b/packages/trpc/server/routers/viewer/slots/util.ts@@ -346,7 +346,7 @@ export interface IGetAvailableSlots {/*** Returns (Contact Owner plus Fixed Hosts) OR All Hosts*/-function getUsersWithCredentialsConsideringContactOwner({+export function getUsersWithCredentialsConsideringContactOwner({contactOwnerEmail,hosts,}: {@@ -481,7 +481,9 @@ export async function getAvailableSlots({ input, ctx }: GetScheduleOptions): ProuserId: true,},});- routedHostsWithContactOwnerAndFixedHosts = routedHostsWithContactOwnerAndFixedHosts.filter((host) => host.user.id === originalRescheduledBooking?.userId || 0);+ routedHostsWithContactOwnerAndFixedHosts = routedHostsWithContactOwnerAndFixedHosts.filter(+ (host) => host.user.id === originalRescheduledBooking?.userId || 0+ );}const usersWithCredentials = getUsersWithCredentialsConsideringContactOwner({