feat: org-wide workflows (#15083)

* add org to create workflow button

* add save button for testing in dev mode

* add select all to multi select dropdown

* fix select all

* pass isOrg to WorkflowDetailsPage

* add checkbox to apply to all including future

* fix count text on select

* WIP schema

* shows teams in dropdown

* add team option to UI

* [WIP] refactor for update handler

* filter out "all" from activeOn

* fix type error

* create more helper functions

* create reusable function for scheduling all booking reminders

* finish update workflows for orgs (without testing)

* fix isAuthorized check for orgs

* fix getting newActiveOn

* move all helper functions to util file

* more code clean up

* fix deleting reminders for org workflows

* fix adding and editing steps

* update form data when workflow is saved

* code clean up

* fixing creating/deleting reminders when user is member of several teams

* fix setting activeOn for teams in useffect

* add on delete cascade

* make multiSelectSchenbox searchable

* set activeOn correctly when checkbox true

* WIP

* fix type errors in MultiSelectCheckboxes

* implemented scheduling org-wide workfow notifications (not yet tested)

* fix type errors

* type error

* add missing changes from merge conflict

* remote not needed include statement

* fix type errors

* code clean up + some todo comments

* support org workflows for cancelled workflows

* delete reminders from removed members

* remove reminders if isActiveOnAll is turned off

* fix unti test and type error

* code clean up

* create basis for testing to book org team event

* create org workflow with active team

* fix getting active org workflows on team + test setup

* fix creating workflow step for tests

* fix first org test

* add test for user event type with org workflow active

* use deleteAllWorkflowReminders everywhere

* add test for deleteRemindersFromRemovedActiveOn

* fix type errors

* make all tests pass

* fix type error

* fix getSchedule test

* code clean up

* add missing import

* fix type error

* fix tests

* code clean up

* fix imports

* update reminders when trigger was changed

* check for teamId before userId in reminderScheduler

* move getOrgIdFromMemberOrTeamId to different folder

* code clean up

* fix tests

* test setup for scheduleBookingReminders

* fix typo

* add tests for scheduleBookingReminders

* fix prisma default import

* fix workflowStep type

* add scheduleBookingReminders test for sms

* return dummy sid for scheduleSMS testMode

* clean up + fixes

* add lost changes from merge

* get teamId and userId from incoming evt object

* removing not needed select

* add org support for scheduleMandatory email reminder

* add other teams to dropdown

* move getAllWorkflows to seperate file and call it in parent function

* include org wide workflows in createNewSeat

* some fixes + code clean up

* add new team to select text count when including future teams is checked

* fix upsert and remove sms reminder field

* correctly update activeOn if 'including future ...' is enabled

* list active Org workflows in event workflows settings

* fix sms reminder field in all handlers

* add helper function to check if step was edited

* fix active on badge on workflow

* fix type error

* fix double reminders

* add teamId: null for userWorkflow query

* fix activeOnAll with managed event types

* add missing teamId in getAllWorkflows

* add a dafaut to prisma param

* fix managed event types on select all user workflows

* code clean up

* better variable name

* small fixes in update handler

* fix test name to match function name

* add info badge

* fix workflow count in event type settings

* fix getting bookings from children manged event types

* delete reminders when user is not part of any time no more

* implement feedback

* fix disbale workflow in event type settings

* fix remove member

* create new function getAllWorkflowsFromEventType

* add some removed code

* use promise.allSettled when deleting workflow reminders

* create new function deleteWorkflowRemindersOfRemovedMember.ts

* fix userId param

* delete org worklfows when team is disbanded

* don't trigger active on all workflow if not part of any team

* fix active on count badge

* add test for deleteWorkflowRemidnersOfRemovedMember

* trigger workflow also if not member of any subteam

* fix failing test

* remove unused code

* use testId for go back button

* fixes for managed event types & activateEventTypeHandler

* code clean up

* don't activate workflow on locked managed event type

* fix type error

* type error

* more type fixes

* feedback

---------

Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: Hariom Balhara <[email protected]>
Co-authored-by: Keith Williams <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-07-08 17:44:11 +05:30
1 parent dca2922ef8
commit c4104af8a2
66 files changed
+3633 -1341

No files matched your search

@@ -4,8 +4,8 @@ import { OrganizationsTeamsController } from "@/modules/organizations/controller
import { OrganizationsSchedulesController } from "@/modules/organizations/controllers/schedules/organizations-schedules.controller";
import { OrganizationsRepository } from "@/modules/organizations/organizations.repository";
import { OrganizationSchedulesRepository } from "@/modules/organizations/repositories/organizations-schedules.repository";
import { OrganizationsSchedulesService } from "@/modules/organizations/services/organizations-schedules.service";
import { OrganizationsTeamsRepository } from "@/modules/organizations/repositories/organizations-teams.repository";
import { OrganizationsSchedulesService } from "@/modules/organizations/services/organizations-schedules.service";
import { OrganizationsTeamsService } from "@/modules/organizations/services/organizations-teams.service";
import { OrganizationsService } from "@/modules/organizations/services/organizations.service";
import { PrismaModule } from "@/modules/prisma/prisma.module";
+2 -4
View File
@@ -1,5 +1,6 @@
import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/getBookingFields";
import { bookingResponsesDbSchema } from "@calcom/features/bookings/lib/getBookingResponsesSchema";
import { workflowSelect } from "@calcom/features/ee/workflows/lib/getAllWorkflows";
import prisma from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { BookingStatus } from "@calcom/prisma/enums";
@@ -61,10 +62,7 @@ export const getEventTypesFromDB = async (id: number) => {
workflows: {
select: {
workflow: {
select: {
id: true,
steps: true,
},
select: workflowSelect,
},
},
},
@@ -14,6 +14,7 @@ import { z } from "zod";
import checkForMultiplePaymentApps from "@calcom/app-store/_utils/payments/checkForMultiplePaymentApps";
import { getEventLocationType } from "@calcom/app-store/locations";
import { validateCustomEventName } from "@calcom/core/event";
import type { Workflow } from "@calcom/features/ee/workflows/lib/types";
import type { ChildrenEventType } from "@calcom/features/eventtypes/components/ChildrenEventTypeSelect";
import type { FormValues } from "@calcom/features/eventtypes/lib/types";
import { validateIntervalLimitOrder } from "@calcom/lib";
@@ -144,7 +145,7 @@ const querySchema = z.object({
export type EventTypeSetupProps = RouterOutputs["viewer"]["eventTypes"]["get"];
export type EventTypeSetup = RouterOutputs["viewer"]["eventTypes"]["get"]["eventType"];
const EventTypePage = (props: EventTypeSetupProps) => {
const EventTypePage = (props: EventTypeSetupProps & { allActiveWorkflows?: Workflow[] }) => {
const { t } = useLocale();
const utils = trpc.useUtils();
const telemetry = useTelemetry();
@@ -464,11 +465,10 @@ const EventTypePage = (props: EventTypeSetupProps) => {
instant: <EventInstantTab eventType={eventType} isTeamEvent={!!team} />,
recurring: <EventRecurringTab eventType={eventType} />,
apps: <EventAppsTab eventType={{ ...eventType, URL: permalink }} />,
workflows: (
<EventWorkflowsTab
eventType={eventType}
workflows={eventType.workflows.map((workflowOnEventType) => workflowOnEventType.workflow)}
/>
workflows: props.allActiveWorkflows ? (
<EventWorkflowsTab eventType={eventType} workflows={props.allActiveWorkflows} />
) : (
<></>
),
webhooks: <EventWebhooksTab eventType={eventType} />,
ai: <EventAITab eventType={eventType} isTeamEvent={!!team} />,
@@ -705,7 +705,7 @@ const EventTypePage = (props: EventTypeSetupProps) => {
<EventTypeSingleLayout
enabledAppsNumber={numberOfActiveApps}
installedAppsNumber={eventTypeApps?.items.length || 0}
enabledWorkflowsNumber={eventType.workflows.length}
enabledWorkflowsNumber={props.allActiveWorkflows ? props.allActiveWorkflows.length : 0}
eventType={eventType}
activeWebhooksNumber={eventType.webhooks.filter((webhook) => webhook.active).length}
team={team}
@@ -853,7 +853,25 @@ const EventTypePageWrapper: React.FC<PageProps> & {
const { data } = trpc.viewer.eventTypes.get.useQuery({ id: props.type });
if (!data) return null;
return <EventTypePage {...(data as EventTypeSetupProps)} />;
const eventType = data.eventType;
const { data: workflows } = trpc.viewer.workflows.getAllActiveWorkflows.useQuery({
eventType: {
workflows: eventType.workflows,
teamId: eventType.teamId,
userId: eventType.userId,
parent: eventType.parent,
metadata: eventType.metadata,
},
});
const propsData = {
...(data as EventTypeSetupProps),
allActiveWorkflows: workflows,
};
return <EventTypePage {...propsData} />;
};
export default EventTypePageWrapper;
+1 -1
View File
@@ -119,7 +119,7 @@ test.describe("Availablity", () => {
await expect(page.getByTestId("availablity-title")).toHaveValue("More working hours");
});
await test.step("Can delete a schedule", async () => {
await page.getByRole("button", { name: /Go Back/i }).click();
await page.getByTestId("go-back-button").click();
await page.locator('[data-testid="schedules"] > li').nth(1).getByTestId("schedule-more").click();
await page.locator('[data-testid="delete-schedule"]').click();
const toast = await page.waitForSelector('[data-testid="toast-success"]');
+2 -1
View File
@@ -30,6 +30,7 @@ export function createWorkflowPageFixture(page: Page) {
await selectEventType("30 min");
}
await saveWorkflow();
await page.getByTestId("go-back-button").click();
};
const saveWorkflow = async () => {
@@ -71,7 +72,7 @@ export function createWorkflowPageFixture(page: Page) {
};
const selectEventType = async (name: string) => {
await page.getByText("Select...").click();
await page.getByTestId("multi-select-check-boxes").click();
await page.getByText(name, { exact: true }).click();
};
+2 -1
View File
@@ -19,12 +19,13 @@ test.describe("Workflow Tab - Event Type", () => {
await assertListCount(3);
});
test("Editing an existing workflow", async ({ workflowPage }) => {
test("Editing an existing workflow", async ({ workflowPage, page }) => {
const { saveWorkflow, fillNameInput, editSelectedWorkflow, hasWorkflowInList } = workflowPage;
await editSelectedWorkflow("Test Workflow");
await fillNameInput("Edited Workflow");
await saveWorkflow();
await page.getByTestId("go-back-button").click();
await hasWorkflowInList("Edited Workflow");
});
@@ -1239,6 +1239,8 @@
"may_require_confirmation": "May require confirmation",
"nr_event_type_one": "{{count}} event type",
"nr_event_type_other": "{{count}} event types",
"count_team_one": "{{count}} team",
"count_team_other": "{{count}} teams",
"add_action": "Add action",
"set_whereby_link": "Set Whereby link",
"invalid_whereby_link": "Please enter a valid Whereby Link",
@@ -1276,7 +1278,12 @@
"problem_updating_calendar": "There was a problem updating your calendar",
"active_on_event_types_one": "Active on {{count}} event type",
"active_on_event_types_other": "Active on {{count}} event types",
"active_on_teams_one": "Active on {{count}} team",
"active_on_teams_other": "Active on {{count}} teams",
"active_on_all_event_types": "Active on all event types",
"active_on_all_teams": "Active on all teams",
"no_active_event_types": "No active event types",
"no_active_teams": "No active teams",
"new_seat_subject": "New Attendee {{name}} on {{eventType}} at {{date}}",
"new_seat_title": "Someone has added themselves to an event",
"variable": "Variable",
@@ -1342,6 +1349,9 @@
"2fa_required": "Two factor authentication required",
"incorrect_2fa": "Incorrect two factor authentication code",
"which_event_type_apply": "Which event type will this apply to?",
"apply_to_all_event_types": "Apply to all, including future event types",
"apply_to_all_teams": "Apply to all team and user event types",
"which_team_apply": "Which team will this apply to?",
"no_workflows_description": "Workflows enable simple automation to send notifications & reminders enabling you to build processes around your events.",
"timeformat_profile_hint": "This is an internal setting and will not affect how times are displayed on public booking pages for you or anyone booking you.",
"create_workflow": "Create a workflow",
@@ -2480,6 +2490,7 @@
"mark_as_no_show_title": "Mark as no show",
"x_marked_as_no_show": "{{x}} marked as no-show",
"x_unmarked_as_no_show": "{{x}} unmarked as no-show",
"team_select_info": "triggers for all team event types and all team members' personal event types",
"no_show_updated": "No-show status updated for attendees",
"email_copied": "Email copied",
"USER_PENDING_MEMBER_OF_THE_ORG": "User is a pending member of the organization",
+15 -18
View File
@@ -1419,24 +1419,21 @@ describe("getSchedule", () => {
});
const scenario = await createBookingScenario(
getScenarioData(
{
eventTypes: [
{
id: 1,
slotInterval: 45,
length: 45,
users: [
{
id: 101,
},
],
},
],
organizer,
},
{ id: org.id }
)
getScenarioData({
eventTypes: [
{
id: 1,
slotInterval: 45,
length: 45,
users: [
{
id: 101,
},
],
},
],
organizer,
})
);
const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });
@@ -18,7 +18,7 @@ import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
import type { WorkflowActions, WorkflowTemplates, WorkflowTriggerEvents } from "@calcom/prisma/client";
import type { SchedulingType, SMSLockState } from "@calcom/prisma/enums";
import type { SchedulingType, SMSLockState, TimeUnit } from "@calcom/prisma/enums";
import type { BookingStatus } from "@calcom/prisma/enums";
import type { teamMetadataSchema } from "@calcom/prisma/zod-utils";
import type { userMetadataType } from "@calcom/prisma/zod-utils";
@@ -46,10 +46,14 @@ type InputWorkflow = {
userId?: number | null;
teamId?: number | null;
name?: string;
activeEventTypeId?: number;
activeOn?: number[];
activeOnTeams?: number[];
trigger: WorkflowTriggerEvents;
action: WorkflowActions;
template: WorkflowTemplates;
time?: number | null;
timeUnit?: TimeUnit | null;
sendTo?: string;
};
type InputHost = {
@@ -95,6 +99,7 @@ type InputUser = Omit<typeof TestData.users.example, "defaultScheduleId"> & {
id: number;
name: string;
slug: string;
parentId?: number;
};
}[];
schedules: {
@@ -130,6 +135,10 @@ export type InputEventType = {
beforeEventBuffer?: number;
afterEventBuffer?: number;
teamId?: number | null;
team?: {
id?: number | null;
parentId?: number | null;
};
requiresConfirmation?: boolean;
destinationCalendar?: Prisma.DestinationCalendarCreateInput;
schedule?: InputUser["schedules"][number];
@@ -444,32 +453,75 @@ async function addWebhooks(webhooks: InputWebhook[]) {
}
async function addWorkflowsToDb(workflows: InputWorkflow[]) {
await prismock.$transaction(
workflows.map((workflow) => {
return prismock.workflow.create({
await Promise.all(
workflows.map(async (workflow) => {
const team = await prismock.team.findFirst({
where: {
id: workflow.teamId ?? 0,
},
});
if (workflow.teamId && !team) {
throw new Error(`Team with ID ${workflow.teamId} not found`);
}
const isOrg = team?.isOrganization;
// Create the workflow first
const createdWorkflow = await prismock.workflow.create({
data: {
userId: workflow.userId,
teamId: workflow.teamId,
trigger: workflow.trigger,
name: workflow.name ? workflow.name : "Test Workflow",
steps: {
create: {
stepNumber: 1,
action: workflow.action,
template: workflow.template,
numberVerificationPending: false,
includeCalendarEvent: false,
},
},
activeOn: {
create: workflow.activeEventTypeId ? { eventTypeId: workflow.activeEventTypeId } : undefined,
},
time: workflow.time,
timeUnit: workflow.timeUnit,
},
include: {
activeOn: true,
steps: true,
},
});
await prismock.workflowStep.create({
data: {
stepNumber: 1,
action: workflow.action,
template: workflow.template,
numberVerificationPending: false,
includeCalendarEvent: false,
sendTo: workflow.sendTo,
workflow: {
connect: {
id: createdWorkflow.id,
},
},
},
});
//activate event types and teams on workflows
if (isOrg && workflow.activeOnTeams) {
await Promise.all(
workflow.activeOnTeams.map((id) =>
prismock.workflowsOnTeams.create({
data: {
workflowId: createdWorkflow.id,
teamId: id,
},
})
)
);
} else if (workflow.activeOn) {
await Promise.all(
workflow.activeOn.map((id) =>
prismock.workflowsOnEventTypes.create({
data: {
workflowId: createdWorkflow.id,
eventTypeId: id,
},
})
)
);
}
})
);
}
@@ -510,9 +562,25 @@ export async function addUsersToDb(
export async function addTeamsToDb(teams: NonNullable<InputUser["teams"]>[number]["team"][]) {
log.silly("TestData: Creating Teams", JSON.stringify(teams));
await prismock.team.createMany({
data: teams,
});
for (const team of teams) {
const teamsWithParentId = {
...team,
parentId: team.parentId,
};
await prismock.team.upsert({
where: {
id: teamsWithParentId.id,
},
update: {
...teamsWithParentId,
},
create: {
...teamsWithParentId,
},
});
}
const addedTeams = await prismock.team.findMany({
where: {
id: {
@@ -643,17 +711,34 @@ export async function createOrganization(orgData: {
name: string;
slug: string;
metadata?: z.infer<typeof teamMetadataSchema>;
withTeam?: boolean;
}) {
const org = await prismock.team.create({
data: {
name: orgData.name,
slug: orgData.slug,
isOrganization: true,
metadata: {
...(orgData.metadata || {}),
isOrganization: true,
},
},
});
if (orgData.withTeam) {
await prismock.team.create({
data: {
name: "Org Team",
slug: "org-team",
isOrganization: false,
parent: {
connect: {
id: org.id,
},
},
},
});
}
return org;
}
@@ -1125,6 +1210,10 @@ export function getScenarioData(
return {
...eventType,
teamId: eventType.teamId || null,
team: {
id: eventType.teamId,
parentId: org ? org.id : null,
},
title: `Test Event Type - ${index + 1}`,
description: `It's a test event type - ${index + 1}`,
};
+35 -14
View File
@@ -350,33 +350,54 @@ export function expectWorkflowToBeNotTriggered({
export function expectSMSWorkflowToBeTriggered({
sms,
toNumber,
includedString,
}: {
sms: Fixtures["sms"];
toNumber: string;
includedString?: string;
}) {
expect(sms.get()).toEqual(
expect.arrayContaining([
expect.objectContaining({
to: toNumber,
}),
])
);
const allSMS = sms.get();
if (includedString) {
const messageWithIncludedString = allSMS.find((sms) => sms.message.includes(includedString));
expect(messageWithIncludedString?.to).toBe(toNumber);
} else {
expect(allSMS).toEqual(
expect.arrayContaining([
expect.objectContaining({
to: toNumber,
}),
])
);
}
}
export function expectSMSWorkflowToBeNotTriggered({
sms,
toNumber,
includedString,
}: {
sms: Fixtures["sms"];
toNumber: string;
includedString?: string;
}) {
expect(sms.get()).not.toEqual(
expect.arrayContaining([
expect.objectContaining({
to: toNumber,
}),
])
);
const allSMS = sms.get();
if (includedString) {
const messageWithIncludedString = allSMS.find((sms) => sms.message.includes(includedString));
if (messageWithIncludedString) {
expect(messageWithIncludedString?.to).not.toBe(toNumber);
}
} else {
expect(allSMS).not.toEqual(
expect.arrayContaining([
expect.objectContaining({
to: toNumber,
}),
])
);
}
}
export async function expectBookingToBeInDatabase(