Files
calendar/packages/features/ee/workflows/lib/test/workflows.test.ts
T
c28eb90928 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 <zomars@me.com>

* 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 <zomars@me.com>

* WIP

Signed-off-by: Omar López <zomars@me.com>

* Update getPublicEvent.ts

* Update imports

Signed-off-by: Omar López <zomars@me.com>

* Update gitignore

Signed-off-by: Omar López <zomars@me.com>

* update remaining imports

Signed-off-by: Omar López <zomars@me.com>

* 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 <zomars@me.com>

* patches prismock

Signed-off-by: Omar López <zomars@me.com>

* Update reschedule.test.ts

* Update prisma.ts

* patch prismock

Signed-off-by: Omar López <zomars@me.com>

* fix enums imports

Signed-off-by: Omar López <zomars@me.com>

* 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 <zomars@me.com>

* fixes

Signed-off-by: Omar López <zomars@me.com>

* chore: bump platform libraries

* Update yarn.lock

* more fixes

Signed-off-by: Omar López <zomars@me.com>

* fixes

Signed-off-by: Omar López <zomars@me.com>

* 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 <zomars@me.com>
Co-authored-by: Alex van Andel <me@alexvanandel.com>
Co-authored-by: Joe Au-Yeung <j.auyeung419@gmail.com>
Co-authored-by: supalarry <laurisskraucis@gmail.com>
Co-authored-by: cal.com <morgan@cal.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
Co-authored-by: Benny Joo <sldisek783@gmail.com>
2025-09-11 15:27:50 +01:00

1103 lines
27 KiB
TypeScript

import prismock from "../../../../../../tests/libs/__mocks__/prisma";
import {
getOrganizer,
getScenarioData,
TestData,
createBookingScenario,
createOrganization,
} from "@calcom/web/test/utils/bookingScenario/bookingScenario";
import {
expectSMSWorkflowToBeTriggered,
expectSMSWorkflowToBeNotTriggered,
} from "@calcom/web/test/utils/bookingScenario/expects";
import { setupAndTeardown } from "@calcom/web/test/utils/bookingScenario/setupAndTeardown";
import { v4 as uuidv4 } from "uuid";
import { describe, expect, beforeAll, vi, beforeEach } from "vitest";
import dayjs from "@calcom/dayjs";
import type { Prisma } from "@calcom/prisma/client";
import {
BookingStatus,
WorkflowMethods,
TimeUnit,
WorkflowTriggerEvents,
WorkflowActions,
} from "@calcom/prisma/enums";
import {
deleteRemindersOfActiveOnIds,
scheduleBookingReminders,
bookingSelect,
} from "@calcom/trpc/server/routers/viewer/workflows/util";
import { test } from "@calcom/web/test/fixtures/fixtures";
import { deleteWorkfowRemindersOfRemovedMember } from "../../../teams/lib/deleteWorkflowRemindersOfRemovedMember";
import { scheduleEmailReminder } from "../reminders/emailReminderManager";
import * as emailProvider from "../reminders/providers/emailProvider";
const workflowSelect = {
id: true,
userId: true,
isActiveOnAll: true,
trigger: true,
time: true,
timeUnit: true,
team: {
select: {
isOrganization: true,
},
},
teamId: true,
user: {
select: {
teams: true,
},
},
steps: true,
activeOn: true,
activeOnTeams: true,
} satisfies Prisma.WorkflowSelect;
beforeAll(() => {
vi.setSystemTime(new Date("2024-05-20T11:59:59Z"));
});
const mockEventTypes = [
{
id: 1,
slotInterval: 30,
length: 30,
useEventTypeDestinationCalendarEmail: true,
owner: 101,
users: [
{
id: 101,
},
],
},
{
id: 2,
slotInterval: 30,
length: 30,
useEventTypeDestinationCalendarEmail: true,
owner: 101,
users: [
{
id: 101,
},
],
},
];
//2024-05-20T11:59:59Z
const mockBookings = [
{
uid: "jK7Rf8iYsOpmQUw9hB1vZxP",
eventTypeId: 1,
userId: 101,
status: BookingStatus.ACCEPTED,
startTime: `2024-05-21T09:00:00.000Z`,
endTime: `2024-05-21T09:15:00.000Z`,
attendees: [{ email: "attendee@example.com", locale: "en" }],
},
{
uid: "mL4Dx9jTkQbnWEu3pR7yNcF",
eventTypeId: 1,
userId: 101,
status: BookingStatus.ACCEPTED,
startTime: `2024-05-21T09:15:00.000Z`,
endTime: `2024-05-21T09:30:00.000Z`,
attendees: [{ email: "attendee@example.com", locale: "en" }],
},
{
uid: "Fd9Rf8iYsOpmQUw9hB1vKd8",
eventTypeId: 2,
userId: 101,
status: BookingStatus.ACCEPTED,
startTime: `2024-06-01T04:30:00.000Z`,
endTime: `2024-06-01T05:00:00.000Z`,
attendees: [{ email: "attendee@example.com", locale: "en" }],
},
{
uid: "Kd8Dx9jTkQbnWEu3pR7yKdl",
eventTypeId: 2,
userId: 101,
status: BookingStatus.ACCEPTED,
startTime: `2024-06-02T04:30:00.000Z`,
endTime: `2024-06-02T05:00:00.000Z`,
attendees: [{ email: "attendee@example.com", locale: "en" }],
},
];
async function createWorkflowRemindersAndTasksForWorkflow(workflowName: string) {
const workflow = await prismock.workflow.findFirst({
where: {
name: workflowName,
},
select: {
steps: {
select: {
id: true,
stepNumber: true,
action: true,
workflowId: true,
sendTo: true,
reminderBody: true,
emailSubject: true,
template: true,
numberRequired: true,
sender: true,
numberVerificationPending: true,
includeCalendarEvent: true,
verifiedAt: true,
},
},
},
});
const workflowRemindersData: Prisma.WorkflowReminderCreateInput[] = [
{
booking: {
connect: {
uid: "jK7Rf8iYsOpmQUw9hB1vZxP",
},
},
uuid: uuidv4(),
workflowStep: {
connect: {
id: workflow?.steps[0]?.id,
},
},
method: WorkflowMethods.EMAIL,
scheduledDate: `2024-05-22T06:00:00.000Z`,
scheduled: false,
retryCount: 0,
},
{
booking: {
connect: {
uid: "mL4Dx9jTkQbnWEu3pR7yNcF",
},
},
uuid: uuidv4(),
workflowStep: {
connect: {
id: workflow?.steps[0]?.id,
},
},
method: WorkflowMethods.EMAIL,
scheduledDate: `2024-05-22T06:30:00.000Z`,
scheduled: false,
retryCount: 0,
},
{
booking: {
connect: {
uid: "Fd9Rf8iYsOpmQUw9hB1vKd8",
},
},
uuid: uuidv4(),
workflowStep: {
connect: {
id: workflow?.steps[0]?.id,
},
},
method: WorkflowMethods.EMAIL,
scheduledDate: `2024-05-22T06:30:00.000Z`,
scheduled: false,
retryCount: 0,
},
{
booking: {
connect: {
uid: "Kd8Dx9jTkQbnWEu3pR7yKdl",
},
},
uuid: uuidv4(),
workflowStep: {
connect: {
id: workflow?.steps[0]?.id,
},
},
method: WorkflowMethods.EMAIL,
scheduledDate: `2024-05-22T06:30:00.000Z`,
scheduled: false,
retryCount: 0,
},
];
const tasksData = workflowRemindersData.map((reminder) => ({
type: "sendWorkflowEmails",
createdAt: new Date(),
updatedAt: new Date(),
referenceUid: reminder.uuid,
payload: "",
scheduledAt: reminder.scheduledDate,
attempts: 0,
maxAttempts: 3,
}));
for (const data of workflowRemindersData) {
await prismock.workflowReminder.create({
data,
});
}
for (const data of tasksData) {
await prismock.task.create({
data,
});
}
return workflow;
}
vi.mock("@calcom/lib/constants", async () => {
const actual = (await vi.importActual("@calcom/lib/constants")) as typeof import("@calcom/lib/constants");
return {
...actual,
IS_SMS_CREDITS_ENABLED: false,
};
});
describe("deleteRemindersOfActiveOnIds", () => {
test("should delete all reminders and tasks from removed event types", async ({}) => {
const organizer = getOrganizer({
name: "Organizer",
email: "organizer@example.com",
id: 101,
schedules: [TestData.schedules.IstWorkHours],
});
await createBookingScenario(
getScenarioData({
workflows: [
{
name: "User Workflow",
userId: organizer.id,
trigger: "BEFORE_EVENT",
time: 1,
timeUnit: TimeUnit.HOUR,
action: "EMAIL_HOST",
template: "REMINDER",
activeOn: [1],
},
],
eventTypes: mockEventTypes,
bookings: mockBookings,
organizer,
})
);
const workflow = await createWorkflowRemindersAndTasksForWorkflow("User Workflow");
const removedActiveOnIds = [1];
const activeOnIds = [2];
await deleteRemindersOfActiveOnIds({
removedActiveOnIds,
workflowSteps: workflow?.steps || [],
isOrg: false,
activeOnIds,
});
const workflowReminders = await prismock.workflowReminder.findMany({
select: {
uuid: true,
booking: {
select: {
eventTypeId: true,
},
},
},
});
expect(workflowReminders.filter((reminder) => reminder.booking?.eventTypeId === 1).length).toBe(0);
expect(workflowReminders.filter((reminder) => reminder.booking?.eventTypeId === 2).length).toBe(2);
const tasks = await prismock.task.findMany({
where: {
type: "sendWorkflowEmails",
},
});
expect(tasks.map((task) => task.referenceUid)).toEqual(
workflowReminders.map((reminder) => reminder.uuid)
);
});
test("should delete all reminders from removed event types (org workflow)", async ({}) => {
const org = await createOrganization({
name: "Test Org",
slug: "testorg",
withTeam: true,
});
// organizer is part of org and two teams
const organizer = getOrganizer({
name: "Organizer",
email: "organizer@example.com",
id: 101,
defaultScheduleId: null,
organizationId: org.id,
teams: [
{
membership: {
accepted: true,
},
team: {
id: 3,
name: "Team 1",
slug: "team-1",
parentId: org.id,
},
},
{
membership: {
accepted: true,
},
team: {
id: 4,
name: "Team 2",
slug: "team-2",
parentId: org.id,
},
},
],
schedules: [TestData.schedules.IstMorningShift],
});
await createBookingScenario(
getScenarioData({
workflows: [
{
name: "Org Workflow",
teamId: 1,
trigger: "BEFORE_EVENT",
action: "EMAIL_HOST",
template: "REMINDER",
activeOnTeams: [2, 3, 4],
},
],
eventTypes: mockEventTypes,
bookings: mockBookings,
organizer,
})
);
const workflow = await createWorkflowRemindersAndTasksForWorkflow("Org Workflow");
let removedActiveOnIds = [1];
const activeOnIds = [2];
//workflow removed from team 2, but still active on team 3 --> so reminder should not be removed
await deleteRemindersOfActiveOnIds({
removedActiveOnIds,
workflowSteps: workflow?.steps || [],
isOrg: true,
activeOnIds,
});
// get all reminders from organizer's bookings
const workflowRemindersWithOneTeamActive = await prismock.workflowReminder.findMany({
where: {
booking: {
userId: organizer.id,
},
},
});
removedActiveOnIds = [3];
// should still be active on all 4 bookings
expect(workflowRemindersWithOneTeamActive.length).toBe(4);
const tasksWithOneTeamActive = await prismock.task.findMany({
where: {
type: "sendWorkflowEmails",
},
});
expect(tasksWithOneTeamActive.map((task) => task.referenceUid)).toEqual(
workflowRemindersWithOneTeamActive.map((reminder) => reminder.uuid)
);
await deleteRemindersOfActiveOnIds({
removedActiveOnIds,
workflowSteps: workflow?.steps || [],
isOrg: true,
activeOnIds,
});
const workflowRemindersWithNoTeamActive = await prismock.workflowReminder.findMany({
where: {
booking: {
userId: organizer.id,
},
},
});
expect(workflowRemindersWithNoTeamActive.length).toBe(0);
const tasksWithNoTeamActive = await prismock.task.findMany({
where: {
type: "sendWorkflowEmails",
},
});
expect(tasksWithNoTeamActive.map((task) => task.referenceUid)).toEqual(
workflowRemindersWithNoTeamActive.map((reminder) => reminder.uuid)
);
});
});
describe("scheduleBookingReminders", () => {
setupAndTeardown();
test("schedules workflow notifications with before event trigger and email to host action", async ({}) => {
// organizer is part of org and two teams
const organizer = getOrganizer({
name: "Organizer",
email: "organizer@example.com",
id: 101,
defaultScheduleId: null,
schedules: [TestData.schedules.IstMorningShift],
});
await createBookingScenario(
getScenarioData({
workflows: [
{
name: "Workflow",
userId: 101,
trigger: "BEFORE_EVENT",
action: "EMAIL_HOST",
template: "REMINDER",
activeOn: [],
time: 1,
timeUnit: TimeUnit.HOUR,
},
],
eventTypes: mockEventTypes,
bookings: mockBookings,
organizer,
})
);
const workflow = await prismock.workflow.findFirst({
select: workflowSelect,
});
const bookings = await prismock.booking.findMany({
where: {
userId: organizer.id,
},
select: bookingSelect,
});
expect(workflow).not.toBeNull();
if (!workflow) return;
await scheduleBookingReminders(
bookings,
workflow.steps,
workflow.time,
workflow.timeUnit,
workflow.trigger,
organizer.id,
null, //teamId
false //isOrg
);
const scheduledWorkflowReminders = await prismock.workflowReminder.findMany({
where: {
workflowStep: {
workflowId: workflow.id,
},
},
});
const tasks = await prismock.task.findMany({
where: {
type: "sendWorkflowEmails",
},
});
scheduledWorkflowReminders.sort((a, b) =>
dayjs(a.scheduledDate).isBefore(dayjs(b.scheduledDate)) ? -1 : 1
);
const expectedScheduledDates = [
new Date("2024-05-21T08:00:00.000"),
new Date("2024-05-21T08:15:00.000Z"),
new Date("2024-06-01T03:30:00.000Z"),
new Date("2024-06-02T03:30:00.000Z"),
];
expect(tasks.length).toBe(scheduledWorkflowReminders.length);
scheduledWorkflowReminders.forEach((reminder, index) => {
expect(expectedScheduledDates[index].toISOString()).toStrictEqual(reminder.scheduledDate.toISOString());
expect(reminder.method).toBe(WorkflowMethods.EMAIL);
expect(reminder.scheduled).toBe(true);
const task = tasks.find((task) => reminder.uuid === task.referenceUid);
expect(task).not.toBeNull();
expect(task?.scheduledAt.toISOString()).toStrictEqual(expectedScheduledDates[index].toISOString());
});
});
test("schedules workflow notifications with after event trigger and email to host action", async ({}) => {
// organizer is part of org and two teams
const organizer = getOrganizer({
name: "Organizer",
email: "organizer@example.com",
id: 101,
defaultScheduleId: null,
schedules: [TestData.schedules.IstMorningShift],
});
await createBookingScenario(
getScenarioData({
workflows: [
{
name: "Workflow",
userId: 101,
trigger: "AFTER_EVENT",
action: "EMAIL_HOST",
template: "REMINDER",
activeOn: [],
time: 1,
timeUnit: TimeUnit.HOUR,
},
],
eventTypes: mockEventTypes,
bookings: mockBookings,
organizer,
})
);
const workflow = await prismock.workflow.findFirst({
select: workflowSelect,
});
const bookings = await prismock.booking.findMany({
where: {
userId: organizer.id,
},
select: bookingSelect,
});
expect(workflow).not.toBeNull();
if (!workflow) return;
await scheduleBookingReminders(
bookings,
workflow.steps,
workflow.time,
workflow.timeUnit,
workflow.trigger,
organizer.id,
null, //teamId
false //orgId
);
const scheduledWorkflowReminders = await prismock.workflowReminder.findMany({
where: {
workflowStep: {
workflowId: workflow.id,
},
},
});
scheduledWorkflowReminders.sort((a, b) =>
dayjs(a.scheduledDate).isBefore(dayjs(b.scheduledDate)) ? -1 : 1
);
const expectedScheduledDates = [
new Date("2024-05-21T10:15:00.000"),
new Date("2024-05-21T10:30:00.000Z"),
new Date("2024-06-01T06:00:00.000Z"),
new Date("2024-06-02T06:00:00.000Z"),
];
const tasks = await prismock.task.findMany({
where: {
type: "sendWorkflowEmails",
},
});
scheduledWorkflowReminders.forEach((reminder, index) => {
expect(expectedScheduledDates[index].toISOString()).toStrictEqual(reminder.scheduledDate.toISOString());
expect(reminder.method).toBe(WorkflowMethods.EMAIL);
expect(reminder.scheduled).toBe(true);
const task = tasks.find((task) => reminder.uuid === task.referenceUid);
expect(task).not.toBeNull();
expect(task?.scheduledAt.toISOString()).toStrictEqual(expectedScheduledDates[index].toISOString());
});
});
test("send sms to specific number for bookings", async ({ sms }) => {
// organizer is part of org and two teams
const organizer = getOrganizer({
name: "Organizer",
email: "organizer@example.com",
id: 101,
defaultScheduleId: null,
schedules: [TestData.schedules.IstMorningShift],
});
await createBookingScenario(
getScenarioData({
workflows: [
{
name: "Workflow",
userId: 101,
trigger: "BEFORE_EVENT",
action: "SMS_NUMBER",
template: "REMINDER",
activeOn: [],
time: 20,
timeUnit: TimeUnit.HOUR,
sendTo: "000",
},
],
eventTypes: mockEventTypes,
bookings: mockBookings,
organizer,
})
);
const workflow = await prismock.workflow.findFirst({
select: workflowSelect,
});
const bookings = await prismock.booking.findMany({
where: {
userId: organizer.id,
},
select: bookingSelect,
});
expect(workflow).not.toBeNull();
if (!workflow) return;
await scheduleBookingReminders(
bookings,
workflow.steps,
workflow.time,
workflow.timeUnit,
workflow.trigger,
organizer.id,
null, //teamId,
true
);
// number is not verified, so sms should not send
expectSMSWorkflowToBeNotTriggered({
sms,
toNumber: "000",
});
await prismock.verifiedNumber.create({
data: {
userId: organizer.id,
phoneNumber: "000",
},
});
await scheduleBookingReminders(
bookings,
workflow.steps,
workflow.time,
workflow.timeUnit,
workflow.trigger,
organizer.id,
null, //teamId
true
);
// two sms should be scheduled
expectSMSWorkflowToBeTriggered({
sms,
toNumber: "000",
includedString: "2024 May 21 at 2:30pm Asia/Kolkata",
});
expectSMSWorkflowToBeTriggered({
sms,
toNumber: "000",
includedString: "2024 May 21 at 2:45pm Asia/Kolkata",
});
// sms are too far in future
expectSMSWorkflowToBeNotTriggered({
sms,
toNumber: "000",
includedString: "2024 June 1 at 10:00am Asia/Kolkata",
});
expectSMSWorkflowToBeNotTriggered({
sms,
toNumber: "000",
includedString: "2024 June 2 at 10:00am Asia/Kolkata",
});
const scheduledWorkflowReminders = await prismock.workflowReminder.findMany({
where: {
workflowStep: {
workflowId: workflow.id,
},
},
});
scheduledWorkflowReminders.sort((a, b) =>
dayjs(a.scheduledDate).isBefore(dayjs(b.scheduledDate)) ? -1 : 1
);
const expectedScheduledDates = [
new Date("2024-05-20T13:00:00.000"),
new Date("2024-05-20T13:15:00.000Z"),
new Date("2024-05-31T08:30:00.000Z"),
new Date("2024-06-01T08:30:00.000Z"),
];
scheduledWorkflowReminders.forEach((reminder, index) => {
expect(expectedScheduledDates[index].toISOString()).toStrictEqual(reminder.scheduledDate.toISOString());
expect(reminder.method).toBe(WorkflowMethods.SMS);
if (index < 2) {
expect(reminder.scheduled).toBe(true);
} else {
expect(reminder.scheduled).toBe(false);
}
});
});
test("should not schedule reminders if date is already in the past", async ({}) => {
const organizer = getOrganizer({
name: "Organizer",
email: "organizer@example.com",
id: 101,
defaultScheduleId: null,
schedules: [TestData.schedules.IstMorningShift],
});
const pastBooking = {
uid: "past-booking-uid",
eventTypeId: 1,
userId: 101,
status: BookingStatus.ACCEPTED,
startTime: `2024-05-21T09:00:00.000Z`,
endTime: `2024-05-21T09:15:00.000Z`,
attendees: [{ email: "attendee@example.com", locale: "en" }],
};
await createBookingScenario(
getScenarioData({
workflows: [
{
name: "Past Workflow",
userId: 101,
trigger: "BEFORE_EVENT",
action: "EMAIL_HOST",
template: "REMINDER",
activeOn: [],
time: 5,
timeUnit: TimeUnit.DAY,
},
],
eventTypes: mockEventTypes,
bookings: [pastBooking],
organizer,
})
);
const workflow = await prismock.workflow.findFirst({
select: workflowSelect,
});
const bookings = await prismock.booking.findMany({
where: {
userId: organizer.id,
},
select: bookingSelect,
});
expect(workflow).not.toBeNull();
if (!workflow) return;
await scheduleBookingReminders(
bookings,
workflow.steps,
workflow.time,
workflow.timeUnit,
workflow.trigger,
organizer.id,
null, //teamId
false //isOrg
);
const tasks = await prismock.task.findMany({
where: {
type: "sendWorkflowEmails",
},
});
// No tasks should be created for past reminders
expect(tasks.length).toBe(0);
});
});
describe("deleteWorkfowRemindersOfRemovedMember", () => {
test("deletes all workflow reminders when member is removed from org", async ({}) => {
const org = await createOrganization({
name: "Test Org",
slug: "testorg",
withTeam: true,
});
// organizer is part of org and two teams
const organizer = getOrganizer({
name: "Organizer",
email: "organizer@example.com",
id: 101,
defaultScheduleId: null,
organizationId: org.id,
teams: [
{
membership: {
accepted: true,
},
team: {
id: 3,
name: "Team 1",
slug: "team-1",
parentId: org.id,
},
},
{
membership: {
accepted: true,
},
team: {
id: 4,
name: "Team 2",
slug: "team-2",
parentId: org.id,
},
},
],
schedules: [TestData.schedules.IstMorningShift],
});
await createBookingScenario(
getScenarioData({
workflows: [
{
name: "Org Workflow",
teamId: 1,
trigger: "BEFORE_EVENT",
action: "EMAIL_HOST",
template: "REMINDER",
activeOnTeams: [2, 3, 4],
},
],
eventTypes: mockEventTypes,
bookings: mockBookings,
organizer,
})
);
await createWorkflowRemindersAndTasksForWorkflow("Org Workflow");
await deleteWorkfowRemindersOfRemovedMember(org, 101, true);
const workflowReminders = await prismock.workflowReminder.findMany();
expect(workflowReminders.length).toBe(0);
const tasks = await prismock.task.findMany({
where: {
type: "sendWorkflowEmails",
},
});
expect(tasks.length).toBe(0);
});
test("deletes reminders if member is removed from an org team ", async ({}) => {
const org = await createOrganization({
name: "Test Org",
slug: "testorg",
withTeam: true,
});
// organizer is part of org and two teams
const organizer = getOrganizer({
name: "Organizer",
email: "organizer@example.com",
id: 101,
defaultScheduleId: null,
organizationId: org.id,
teams: [
{
membership: {
accepted: true,
},
team: {
id: 2,
name: "Team 1",
slug: "team-1",
parentId: org.id,
},
},
{
membership: {
accepted: true,
},
team: {
id: 3,
name: "Team 2",
slug: "team-2",
parentId: org.id,
},
},
{
membership: {
accepted: true,
},
team: {
id: 4,
name: "Team 3",
slug: "team-3",
parentId: org.id,
},
},
],
schedules: [TestData.schedules.IstMorningShift],
});
await createBookingScenario(
getScenarioData({
workflows: [
{
name: "Org Workflow 1",
teamId: 1,
trigger: "BEFORE_EVENT",
action: "EMAIL_HOST",
template: "REMINDER",
activeOnTeams: [2, 3, 4],
},
{
name: "Org Workflow 2",
teamId: 1,
trigger: "BEFORE_EVENT",
action: "EMAIL_HOST",
template: "REMINDER",
activeOnTeams: [2],
},
],
eventTypes: mockEventTypes,
bookings: mockBookings,
organizer,
})
);
await createWorkflowRemindersAndTasksForWorkflow("Org Workflow 1");
await createWorkflowRemindersAndTasksForWorkflow("Org Workflow 2");
await prismock.membership.delete({
where: {
userId_teamId: {
teamId: 2, // removing from team 2
userId: 101, // organizer's userId
},
},
});
await deleteWorkfowRemindersOfRemovedMember({ id: 2, parentId: org.id }, 101, false);
const workflowReminders = await prismock.workflowReminder.findMany({
select: {
uuid: true,
workflowStep: {
select: {
workflow: {
select: {
name: true,
},
},
},
},
},
});
const workflow1Reminders = workflowReminders.filter(
(reminder) => reminder.workflowStep?.workflow.name === "Org Workflow 1"
);
const workflow2Reminders = workflowReminders.filter(
(reminder) => reminder.workflowStep?.workflow.name === "Org Workflow 2"
);
expect(workflow1Reminders.length).toBe(4);
expect(workflow2Reminders.length).toBe(0);
const tasks = await prismock.task.findMany({
where: {
type: "sendWorkflowEmails",
},
});
expect(tasks.length).toBe(4);
expect(tasks.map((task) => task.referenceUid)).toEqual(
workflowReminders.map((reminder) => reminder.uuid)
);
});
});
describe("Workflow SMTP Emails Feature Flag", () => {
vi.spyOn(emailProvider, "sendOrScheduleWorkflowEmails");
const mockEvt = {
uid: "test-uid",
title: "Test Event",
startTime: new Date().toISOString(),
endTime: new Date().toISOString(),
bookerUrl: "https://cal.com",
attendees: [
{
name: "Test Attendee",
email: "attendee@test.com",
timeZone: "UTC",
language: { locale: "en" },
},
],
organizer: {
name: "Test Organizer",
email: "organizer@test.com",
timeZone: "UTC",
language: { locale: "en" },
},
};
const baseArgs = {
evt: mockEvt,
triggerEvent: WorkflowTriggerEvents.NEW_EVENT,
timeSpan: { time: 1, timeUnit: TimeUnit.HOUR },
sendTo: ["test@example.com"],
action: WorkflowActions.EMAIL_ATTENDEE,
verifiedAt: new Date(),
};
beforeEach(() => {
vi.clearAllMocks();
});
test("should use SMTP", async () => {
await scheduleEmailReminder(baseArgs);
expect(emailProvider.sendOrScheduleWorkflowEmails).toHaveBeenCalled();
});
});