diff --git a/apps/api/v2/package.json b/apps/api/v2/package.json index ff7f629703..6e55f6588c 100644 --- a/apps/api/v2/package.json +++ b/apps/api/v2/package.json @@ -37,7 +37,7 @@ "@axiomhq/winston": "^1.2.0", "@calcom/platform-constants": "*", "@calcom/platform-enums": "*", - "@calcom/platform-libraries": "npm:@calcom/platform-libraries@0.0.218", + "@calcom/platform-libraries": "npm:@calcom/platform-libraries@0.0.220", "@calcom/platform-libraries-0.0.2": "npm:@calcom/platform-libraries@0.0.2", "@calcom/platform-types": "*", "@calcom/platform-utils": "*", diff --git a/apps/api/v2/src/modules/auth/guards/workflows/is-workflow-in-team.ts b/apps/api/v2/src/modules/auth/guards/workflows/is-workflow-in-team.ts new file mode 100644 index 0000000000..8c26a1ea7f --- /dev/null +++ b/apps/api/v2/src/modules/auth/guards/workflows/is-workflow-in-team.ts @@ -0,0 +1,56 @@ +import { WorkflowsRepository, WorkflowType } from "@/modules/workflows/workflows.repository"; +import { + Injectable, + CanActivate, + ExecutionContext, + ForbiddenException, + NotFoundException, +} from "@nestjs/common"; +import { Request } from "express"; + +@Injectable() +export class IsWorkflowInTeam implements CanActivate { + constructor(private workflowsRepository: WorkflowsRepository) {} + + async canActivate(context: ExecutionContext): Promise { + const request = context.switchToHttp().getRequest(); + const teamId: string = request.params.teamId; + const workflowId: string = request.params.workflowId; + + if (!workflowId) { + throw new ForbiddenException("IsWorkflowInTeam - No workflow found in request params."); + } + + if (!teamId) { + throw new ForbiddenException("IsWorkflowInTeam - No team id found in request params."); + } + + const { canAccess, workflow } = await this.checkIfWorkflowIsInTeam(teamId, workflowId); + + if (!canAccess) { + throw new ForbiddenException( + `IsTeamInOrg - Workflow with id=${workflowId} is not part of the team with id=${teamId}.` + ); + } + + request.workflow = workflow; + return true; + } + + async checkIfWorkflowIsInTeam( + teamId: string, + workflowId: string + ): Promise<{ canAccess: boolean; workflow?: WorkflowType }> { + const workflow = await this.workflowsRepository.getTeamWorkflowById(Number(teamId), Number(workflowId)); + + if (!workflow) { + throw new NotFoundException(`IsWorkflowInTeam - workflow (${workflowId}) not found.`); + } + + if (workflow.teamId === Number(teamId)) { + return { canAccess: true, workflow }; + } + + return { canAccess: false }; + } +} diff --git a/apps/api/v2/src/modules/organizations/organizations.module.ts b/apps/api/v2/src/modules/organizations/organizations.module.ts index b5d6b5569c..32d9389675 100644 --- a/apps/api/v2/src/modules/organizations/organizations.module.ts +++ b/apps/api/v2/src/modules/organizations/organizations.module.ts @@ -48,6 +48,7 @@ import { OrganizationsTeamsMembershipsRepository } from "@/modules/organizations import { OrganizationsTeamsMembershipsService } from "@/modules/organizations/teams/memberships/services/organizations-teams-memberships.service"; import { OrganizationsTeamsRoutingFormsModule } from "@/modules/organizations/teams/routing-forms/organizations-teams-routing-forms.module"; import { OrganizationsTeamsSchedulesController } from "@/modules/organizations/teams/schedules/organizations-teams-schedules.controller"; +import { OrganizationTeamWorkflowsController } from "@/modules/organizations/teams/workflows/controllers/org-team-workflows.controller"; import { OrganizationsUsersController } from "@/modules/organizations/users/index/controllers/organizations-users.controller"; import { OrganizationsUsersRepository } from "@/modules/organizations/users/index/organizations-users.repository"; import { OrganizationsUsersService } from "@/modules/organizations/users/index/services/organizations-users-service"; @@ -65,8 +66,13 @@ import { TeamsEventTypesModule } from "@/modules/teams/event-types/teams-event-t import { TeamsModule } from "@/modules/teams/teams/teams.module"; import { TokensRepository } from "@/modules/tokens/tokens.repository"; import { UsersModule } from "@/modules/users/users.module"; +import { TeamsVerifiedResourcesRepository } from "@/modules/verified-resources/teams-verified-resources.repository"; import { WebhooksService } from "@/modules/webhooks/services/webhooks.service"; import { WebhooksRepository } from "@/modules/webhooks/webhooks.repository"; +import { TeamWorkflowsService } from "@/modules/workflows/services/team-workflows.service"; +import { WorkflowsInputService } from "@/modules/workflows/services/workflows.input.service"; +import { WorkflowsOutputService } from "@/modules/workflows/services/workflows.output.service"; +import { WorkflowsRepository } from "@/modules/workflows/workflows.repository"; import { Module } from "@nestjs/common"; @Module({ @@ -130,6 +136,11 @@ import { Module } from "@nestjs/common"; ZoomVideoService, Office365VideoService, TokensRepository, + TeamsVerifiedResourcesRepository, + WorkflowsRepository, + TeamWorkflowsService, + WorkflowsInputService, + WorkflowsOutputService, ], exports: [ OrganizationsService, @@ -165,6 +176,7 @@ import { Module } from "@nestjs/common"; OrganizationsWebhooksController, OrganizationsTeamsSchedulesController, OrganizationsUsersOOOController, + OrganizationTeamWorkflowsController, ], }) export class OrganizationsModule {} diff --git a/apps/api/v2/src/modules/organizations/teams/workflows/controllers/org-team-workflows.controller.e2e-spec.ts b/apps/api/v2/src/modules/organizations/teams/workflows/controllers/org-team-workflows.controller.e2e-spec.ts new file mode 100644 index 0000000000..27adea6639 --- /dev/null +++ b/apps/api/v2/src/modules/organizations/teams/workflows/controllers/org-team-workflows.controller.e2e-spec.ts @@ -0,0 +1,411 @@ +import { bootstrap } from "@/app"; +// Assuming this is your main app bootstrapper +import { AppModule } from "@/app.module"; +import { PrismaModule } from "@/modules/prisma/prisma.module"; +import { TokensModule } from "@/modules/tokens/tokens.module"; +import { UsersModule } from "@/modules/users/users.module"; +import { CreateWorkflowDto } from "@/modules/workflows/inputs/create-workflow.input"; +import { + ATTENDEE, + REMINDER, + PHONE_NUMBER, + EMAIL, + WorkflowEmailAttendeeStepDto, +} from "@/modules/workflows/inputs/workflow-step.input"; +import { BEFORE_EVENT, DAY } from "@/modules/workflows/inputs/workflow-trigger.input"; +// Adjust path if needed +import { GetWorkflowOutput, GetWorkflowsOutput } from "@/modules/workflows/outputs/workflow.output"; +import { INestApplication } from "@nestjs/common"; +import { NestExpressApplication } from "@nestjs/platform-express"; +import { Test } from "@nestjs/testing"; +import { User, Team } from "@prisma/client"; +import * as request from "supertest"; +import { ApiKeysRepositoryFixture } from "test/fixtures/repository/api-keys.repository.fixture"; +import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture"; +import { OrganizationRepositoryFixture } from "test/fixtures/repository/organization.repository.fixture"; +import { ProfileRepositoryFixture } from "test/fixtures/repository/profiles.repository.fixture"; +import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture"; +import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture"; +import { VerifiedResourcesRepositoryFixtures } from "test/fixtures/repository/verified-resources.repository.fixture"; +import { WorkflowRepositoryFixture } from "test/fixtures/repository/workflow.repository.fixture"; +import { randomString } from "test/utils/randomString"; + +import { SUCCESS_STATUS } from "@calcom/platform-constants"; + +describe("OrganizationsTeamsWorkflowsController (E2E)", () => { + let app: INestApplication; + let verifiedResourcesRepositoryFixtures: VerifiedResourcesRepositoryFixtures; + let userRepositoryFixture: UserRepositoryFixture; + let organizationsRepositoryFixture: OrganizationRepositoryFixture; + let teamsRepositoryFixture: TeamRepositoryFixture; + let profileRepositoryFixture: ProfileRepositoryFixture; + let apiKeysRepositoryFixture: ApiKeysRepositoryFixture; + let membershipsRepositoryFixture: MembershipRepositoryFixture; + let workflowsRepositoryFixture: WorkflowRepositoryFixture; + let basePath = ""; + let org: Team; + let orgTeam: Team; + let createdWorkflowId: number; + const authEmail = `org-teams-workflows-user-${randomString()}@example.com`; + let user: User; + let apiKeyString: string; + let verifiedPhoneId: number; + let verifiedEmailId: number; + let createdWorkflow: GetWorkflowOutput["data"]; + + let sampleCreateWorkflowDto: CreateWorkflowDto = { + name: `E2E Test Workflow ${randomString()}`, + activation: { + isActiveOnAllEventTypes: true, + activeOnEventTypeIds: [], + }, + trigger: { + type: BEFORE_EVENT, + offset: { + value: 1, + unit: DAY, + }, + }, + steps: [], + }; + + beforeAll(async () => { + const moduleRef = await Test.createTestingModule({ + imports: [AppModule, PrismaModule, UsersModule, TokensModule], + }).compile(); + + // Instantiate Fixtures + userRepositoryFixture = new UserRepositoryFixture(moduleRef); + organizationsRepositoryFixture = new OrganizationRepositoryFixture(moduleRef); + teamsRepositoryFixture = new TeamRepositoryFixture(moduleRef); + profileRepositoryFixture = new ProfileRepositoryFixture(moduleRef); + apiKeysRepositoryFixture = new ApiKeysRepositoryFixture(moduleRef); + membershipsRepositoryFixture = new MembershipRepositoryFixture(moduleRef); + workflowsRepositoryFixture = new WorkflowRepositoryFixture(moduleRef); + verifiedResourcesRepositoryFixtures = new VerifiedResourcesRepositoryFixtures(moduleRef); + + org = await organizationsRepositoryFixture.create({ + name: `org-teams-workflows-org-${randomString()}`, + slug: `org-teams-workflows-org-${randomString()}`, + isOrganization: true, + platformBilling: { + create: { + customerId: "cus_999", + plan: "SCALE", + subscriptionId: "sub_999", + }, + }, + }); + + user = await userRepositoryFixture.create({ + email: authEmail, + username: authEmail.split("@")[0], + }); + + const apiKey = await apiKeysRepositoryFixture.createApiKey(user.id, null); + apiKeyString = apiKey.keyString; + + orgTeam = await teamsRepositoryFixture.create({ + name: `org-teams-workflows-team-${randomString()}`, + isOrganization: false, + parent: { connect: { id: org.id } }, + }); + + await membershipsRepositoryFixture.create({ + role: "ADMIN", + user: { connect: { id: user.id } }, + accepted: true, + team: { connect: { id: org.id } }, + }); + await membershipsRepositoryFixture.create({ + role: "ADMIN", + user: { connect: { id: user.id } }, + accepted: true, + team: { connect: { id: orgTeam.id } }, + }); + + await profileRepositoryFixture.create({ + uid: `usr-${user.id}`, + username: authEmail.split("@")[0], + organization: { + connect: { + id: org.id, + }, + }, + user: { + connect: { + id: user.id, + }, + }, + }); + + const verifiedPhone = await verifiedResourcesRepositoryFixtures.createPhone({ + user: { connect: { id: user.id } }, + phoneNumber: "+37255555555", + team: { connect: { id: orgTeam.id } }, + }); + const verifiedEmail = await verifiedResourcesRepositoryFixtures.createEmail({ + user: { connect: { id: user.id } }, + email: authEmail, + team: { connect: { id: orgTeam.id } }, + }); + verifiedEmailId = verifiedEmail.id; + verifiedPhoneId = verifiedPhone.id; + + sampleCreateWorkflowDto = { + name: `E2E Test Workflow ${randomString()}`, + activation: { + isActiveOnAllEventTypes: true, + activeOnEventTypeIds: [], + }, + trigger: { + type: BEFORE_EVENT, + offset: { + value: 1, + unit: DAY, + }, + }, + steps: [ + { + stepNumber: 1, + action: "email_attendee", + recipient: ATTENDEE, + template: REMINDER, + sender: "CalcomE2EStep1", + includeCalendarEvent: true, + message: { + subject: "Upcoming: {EVENT_NAME}", + html: "

Reminder for your event {EVENT_NAME}.

", + }, + }, + { + stepNumber: 2, + action: "sms_number", + recipient: PHONE_NUMBER, + template: REMINDER, + verifiedPhoneId: verifiedPhoneId, + sender: "CalcomE2EStep2", + message: { + subject: "Upcoming: {EVENT_NAME}", + text: "Reminder for your event {EVENT_NAME}.", + }, + }, + { + stepNumber: 3, + action: "email_address", + recipient: EMAIL, + template: REMINDER, + verifiedEmailId: verifiedEmailId, + sender: "CalcomE2EStep3", + includeCalendarEvent: true, + message: { + subject: "Upcoming: {EVENT_NAME}", + html: "

Reminder for your event {EVENT_NAME}.

", + }, + }, + ], + }; + basePath = `/v2/organizations/${org.id}/teams/${orgTeam.id}/workflows`; + app = moduleRef.createNestApplication(); + bootstrap(app as NestExpressApplication); + await app.init(); + }); + + afterAll(async () => { + if (createdWorkflowId) { + try { + await workflowsRepositoryFixture.delete(createdWorkflowId); + } catch (error) {} + } + + await userRepositoryFixture.deleteByEmail(user.email); + await teamsRepositoryFixture.delete(orgTeam.id); + await organizationsRepositoryFixture.delete(org.id); + + await app.close(); + }); + + describe(`POST ${basePath}`, () => { + it("should create a new workflow", async () => { + return request(app.getHttpServer()) + .post(basePath) + .set({ Authorization: `Bearer cal_test_${apiKeyString}` }) + .send(sampleCreateWorkflowDto) + .expect(201) + .then((response) => { + const responseBody: GetWorkflowOutput = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(responseBody.data.name).toEqual(sampleCreateWorkflowDto.name); + expect(responseBody.data.activation.isActiveOnAllEventTypes).toEqual( + sampleCreateWorkflowDto.activation.isActiveOnAllEventTypes + ); + expect(responseBody.data.trigger.type).toEqual(sampleCreateWorkflowDto.trigger.type); + expect(responseBody.data.steps).toHaveLength(sampleCreateWorkflowDto.steps.length); + expect(responseBody.data.steps.find((step) => step.stepNumber === 1)?.id).toBeDefined(); + expect(responseBody.data.steps.find((step) => step.stepNumber === 2)?.id).toBeDefined(); + expect(responseBody.data.steps.find((step) => step.stepNumber === 3)?.id).toBeDefined(); + expect(responseBody.data.steps.find((step) => step.stepNumber === 1)?.sender).toEqual( + "CalcomE2EStep1" + ); + expect(responseBody.data.steps.find((step) => step.stepNumber === 2)?.sender).toEqual( + "CalcomE2EStep2" + ); + expect(responseBody.data.steps.find((step) => step.stepNumber === 2)?.phone).toEqual( + "+37255555555" + ); + expect(responseBody.data.steps.find((step) => step.stepNumber === 3)?.email).toEqual(authEmail); + createdWorkflowId = responseBody.data.id; + createdWorkflow = responseBody.data; + }); + }); + + it("should return 401 if not authenticated", async () => { + return request(app.getHttpServer()).post(basePath).send(sampleCreateWorkflowDto).expect(401); + }); + + it("should return 400 for invalid data (e.g. missing name)", async () => { + const invalidDto = { ...sampleCreateWorkflowDto, name: undefined }; + return request(app.getHttpServer()) + .post(basePath) + .set({ Authorization: `Bearer cal_test_${apiKeyString}` }) + .send(invalidDto) + .expect(400); + }); + }); + + describe(`GET ${basePath}`, () => { + it("should get a list of workflows for the team", async () => { + return request(app.getHttpServer()) + .get(`${basePath}?skip=0&take=10`) + .set({ Authorization: `Bearer cal_test_${apiKeyString}` }) + .expect(200) + .then((response) => { + const responseBody: GetWorkflowsOutput = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeInstanceOf(Array); + expect(responseBody.data.length).toBeGreaterThanOrEqual(1); + expect(responseBody.data.some((wf) => wf.id === createdWorkflowId)).toBe(true); + }); + }); + + it("should return 401 if not authenticated", async () => { + return request(app.getHttpServer()).get(basePath).expect(401); + }); + }); + + describe(`GET ${basePath}/:workflowId`, () => { + it("should get a specific workflow by ID", async () => { + expect(createdWorkflowId).toBeDefined(); + return request(app.getHttpServer()) + .get(`${basePath}/${createdWorkflowId}`) + .set({ Authorization: `Bearer cal_test_${apiKeyString}` }) + .expect(200) + .then((response) => { + const responseBody: GetWorkflowOutput = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(responseBody.data.id).toEqual(createdWorkflowId); + }); + }); + + it("should return 404 for a non-existent workflow ID", async () => { + return request(app.getHttpServer()) + .get(`${basePath}/999999`) + .set({ Authorization: `Bearer cal_test_${apiKeyString}` }) + .expect(404); + }); + + it("should return 401 if not authenticated", async () => { + expect(createdWorkflowId).toBeDefined(); + return request(app.getHttpServer()).get(`${basePath}/${createdWorkflowId}`).expect(401); + }); + }); + + describe(`PATCH ${basePath}/:workflowId`, () => { + const updatedName = `Updated Workflow Name ${randomString()}`; + + it("should update an existing workflow, update the first step and discard other steps", async () => { + const step1 = createdWorkflow.steps.find((step) => step.stepNumber === 1); + expect(step1).toBeDefined(); + const partialUpdateDto: Partial = { + name: updatedName, + steps: step1 ? [{ ...step1, sender: "updatedSender" } as WorkflowEmailAttendeeStepDto] : [], + }; + expect(createdWorkflowId).toBeDefined(); + expect(createdWorkflow).toBeDefined(); + return request(app.getHttpServer()) + .patch(`${basePath}/${createdWorkflowId}`) + .set({ Authorization: `Bearer cal_test_${apiKeyString}` }) + .send(partialUpdateDto) + .expect(200) + .then((response) => { + const responseBody: GetWorkflowOutput = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(responseBody.data.id).toEqual(createdWorkflowId); + expect(responseBody.data.name).toEqual(updatedName); + step1 && expect(responseBody.data.steps[0].id).toEqual(step1.id); + expect(responseBody.data.steps[0].sender).toEqual("updatedSender"); + expect(responseBody.data.steps[1]?.id).toBeUndefined(); + }); + }); + + it("should return 404 for updating a non-existent workflow ID", async () => { + const partialUpdateDto: Partial = { + name: updatedName, + steps: [{ ...createdWorkflow.steps[0], sender: "updatedSender" } as WorkflowEmailAttendeeStepDto], + }; + return request(app.getHttpServer()) + .patch(`${basePath}/999999`) + .set({ Authorization: `Bearer cal_test_${apiKeyString}` }) + .send(partialUpdateDto) + .expect(404); + }); + + it("should return 401 if not authenticated", async () => { + const partialUpdateDto: Partial = { + name: updatedName, + steps: [{ ...createdWorkflow.steps[0], sender: "updatedSender" } as WorkflowEmailAttendeeStepDto], + }; + expect(createdWorkflowId).toBeDefined(); + return request(app.getHttpServer()) + .patch(`${basePath}/${createdWorkflowId}`) + .send(partialUpdateDto) + .expect(401); + }); + }); + + describe(`DELETE ${basePath}/:workflowId`, () => { + let workflowToDeleteId: number; + + beforeEach(async () => { + const res = await request(app.getHttpServer()) + .post(basePath) + .set({ Authorization: `Bearer cal_test_${apiKeyString}` }) + .send({ ...sampleCreateWorkflowDto, name: `Workflow To Delete ${randomString()}` }); + workflowToDeleteId = res.body.data.id; + }); + + it("should delete an existing workflow", async () => { + return request(app.getHttpServer()) + .delete(`${basePath}/${workflowToDeleteId}`) + .set({ Authorization: `Bearer cal_test_${apiKeyString}` }) + .expect(200) + .then((response) => { + expect(response.body.status).toEqual(SUCCESS_STATUS); + }); + }); + + it("should return 404 when trying to delete a non-existent workflow ID", async () => { + return request(app.getHttpServer()) + .delete(`${basePath}/999999`) + .set({ Authorization: `Bearer cal_test_${apiKeyString}` }) + .expect(404); + }); + + it("should return 401 if not authenticated", async () => { + return request(app.getHttpServer()).delete(`${basePath}/${workflowToDeleteId}`).expect(401); + }); + }); +}); diff --git a/apps/api/v2/src/modules/organizations/teams/workflows/controllers/org-team-workflows.controller.ts b/apps/api/v2/src/modules/organizations/teams/workflows/controllers/org-team-workflows.controller.ts new file mode 100644 index 0000000000..7baf973f9c --- /dev/null +++ b/apps/api/v2/src/modules/organizations/teams/workflows/controllers/org-team-workflows.controller.ts @@ -0,0 +1,121 @@ +import { API_VERSIONS_VALUES } from "@/lib/api-versions"; +import { + OPTIONAL_API_KEY_HEADER, + OPTIONAL_X_CAL_CLIENT_ID_HEADER, + OPTIONAL_X_CAL_SECRET_KEY_HEADER, +} from "@/lib/docs/headers"; +import { PlatformPlan } from "@/modules/auth/decorators/billing/platform-plan.decorator"; +import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator"; +import { Roles } from "@/modules/auth/decorators/roles/roles.decorator"; +import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard"; +import { PlatformPlanGuard } from "@/modules/auth/guards/billing/platform-plan.guard"; +import { IsAdminAPIEnabledGuard } from "@/modules/auth/guards/organizations/is-admin-api-enabled.guard"; +import { IsOrgGuard } from "@/modules/auth/guards/organizations/is-org.guard"; +import { RolesGuard } from "@/modules/auth/guards/roles/roles.guard"; +import { IsTeamInOrg } from "@/modules/auth/guards/teams/is-team-in-org.guard"; +import { IsWorkflowInTeam } from "@/modules/auth/guards/workflows/is-workflow-in-team"; +import { UserWithProfile } from "@/modules/users/users.repository"; +import { CreateWorkflowDto } from "@/modules/workflows/inputs/create-workflow.input"; +import { UpdateWorkflowDto } from "@/modules/workflows/inputs/update-workflow.input"; +import { GetWorkflowOutput, GetWorkflowsOutput } from "@/modules/workflows/outputs/workflow.output"; +import { TeamWorkflowsService } from "@/modules/workflows/services/team-workflows.service"; +import { + Controller, + Get, + Patch, + Post, + Param, + ParseIntPipe, + Query, + UseGuards, + Body, + Delete, +} from "@nestjs/common"; +import { ApiHeader, ApiOperation, ApiTags } from "@nestjs/swagger"; + +import { SUCCESS_STATUS } from "@calcom/platform-constants"; +import { SkipTakePagination } from "@calcom/platform-types"; + +@Controller({ + path: "/v2/organizations/:orgId/teams/:teamId/workflows", + version: API_VERSIONS_VALUES, +}) +@ApiTags("Orgs / Teams / Workflows") +@UseGuards(ApiAuthGuard, IsOrgGuard, IsTeamInOrg, PlatformPlanGuard, RolesGuard, IsAdminAPIEnabledGuard) +@ApiHeader(OPTIONAL_X_CAL_CLIENT_ID_HEADER) +@ApiHeader(OPTIONAL_X_CAL_SECRET_KEY_HEADER) +@ApiHeader(OPTIONAL_API_KEY_HEADER) +export class OrganizationTeamWorkflowsController { + constructor(private readonly workflowsService: TeamWorkflowsService) {} + + @Get("/") + @ApiOperation({ summary: "Get organization team workflows" }) + @Roles("TEAM_ADMIN") + @PlatformPlan("SCALE") + async getWorkflows( + @Param("orgId", ParseIntPipe) orgId: number, + @Param("teamId", ParseIntPipe) teamId: number, + @Query() queryParams: SkipTakePagination + ): Promise { + const { skip, take } = queryParams; + + const workflows = await this.workflowsService.getTeamWorkflows(teamId, skip, take); + + return { data: workflows, status: SUCCESS_STATUS }; + } + + @Get("/:workflowId") + @UseGuards(IsWorkflowInTeam) + @ApiOperation({ summary: "Get organization team workflow" }) + @Roles("TEAM_ADMIN") + @PlatformPlan("SCALE") + async getWorkflowById( + @Param("teamId", ParseIntPipe) teamId: number, + @Param("workflowId", ParseIntPipe) workflowId: number + ): Promise { + const workflow = await this.workflowsService.getTeamWorkflowById(teamId, workflowId); + + return { data: workflow, status: SUCCESS_STATUS }; + } + + @Post("/") + @ApiOperation({ summary: "Create organization team workflow" }) + @Roles("TEAM_ADMIN") + @PlatformPlan("SCALE") + async createWorkflow( + @GetUser() user: UserWithProfile, + @Param("teamId", ParseIntPipe) teamId: number, + @Body() data: CreateWorkflowDto + ): Promise { + const workflow = await this.workflowsService.createTeamWorkflow(user, teamId, data); + return { data: workflow, status: SUCCESS_STATUS }; + } + + @Patch("/:workflowId") + @UseGuards(IsWorkflowInTeam) + @ApiOperation({ summary: "Update workflow" }) + @Roles("TEAM_ADMIN") + @PlatformPlan("SCALE") + async updateWorkflow( + @Param("teamId", ParseIntPipe) teamId: number, + @Param("workflowId", ParseIntPipe) workflowId: number, + @GetUser() user: UserWithProfile, + @Body() data: UpdateWorkflowDto + ): Promise { + const workflow = await this.workflowsService.updateTeamWorkflow(user, teamId, workflowId, data); + return { data: workflow, status: SUCCESS_STATUS }; + } + + @Delete("/:workflowId") + @UseGuards(IsWorkflowInTeam) + @ApiOperation({ summary: "Delete organization team workflow" }) + @Roles("TEAM_ADMIN") + @PlatformPlan("SCALE") + async deleteWorkflow( + @Param("teamId", ParseIntPipe) teamId: number, + @Param("workflowId") workflowId: number + ): Promise<{ status: typeof SUCCESS_STATUS }> { + await this.workflowsService.deleteTeamWorkflow(teamId, workflowId); + return { status: SUCCESS_STATUS }; + } +} diff --git a/apps/api/v2/src/modules/workflows/inputs/create-workflow.input.ts b/apps/api/v2/src/modules/workflows/inputs/create-workflow.input.ts new file mode 100644 index 0000000000..d309a9ac43 --- /dev/null +++ b/apps/api/v2/src/modules/workflows/inputs/create-workflow.input.ts @@ -0,0 +1,164 @@ +import { ApiProperty, ApiPropertyOptional, getSchemaPath } from "@nestjs/swagger"; +import { Type } from "class-transformer"; +import { + IsBoolean, + ArrayMinSize, + IsNumber, + IsOptional, + IsString, + ValidateNested, + ValidateIf, +} from "class-validator"; + +import { + BaseWorkflowStepDto, + EMAIL_ADDRESS, + EMAIL_ATTENDEE, + EMAIL_HOST, + SMS_ATTENDEE, + SMS_NUMBER, + WHATSAPP_ATTENDEE, + WHATSAPP_NUMBER, + WorkflowEmailAddressStepDto, + WorkflowEmailAttendeeStepDto, + WorkflowEmailHostStepDto, + WorkflowPhoneAttendeeStepDto, + WorkflowPhoneNumberStepDto, + WorkflowPhoneWhatsAppAttendeeStepDto, + WorkflowPhoneWhatsAppNumberStepDto, +} from "./workflow-step.input"; +import { + AFTER_EVENT, + AFTER_GUESTS_CAL_VIDEO_NO_SHOW, + AFTER_HOSTS_CAL_VIDEO_NO_SHOW, + BaseWorkflowTriggerDto, + BEFORE_EVENT, + EVENT_CANCELLED, + NEW_EVENT, + OnAfterCalVideoGuestsNoShowTriggerDto, + OnAfterCalVideoHostsNoShowTriggerDto, + OnAfterEventTriggerDto, + OnBeforeEventTriggerDto, + OnCancelTriggerDto, + OnCreationTriggerDto, + OnRescheduleTriggerDto, + RESCHEDULE_EVENT, +} from "./workflow-trigger.input"; + +export class WorkflowActivationDto { + @ApiProperty({ + description: "Whether the workflow is active for all the event-types", + example: false, + type: Boolean, + }) + @IsBoolean() + isActiveOnAllEventTypes = false; + + @ApiPropertyOptional({ + description: + "List of event-types IDs the workflow applies to, required if isActiveOnAllEventTypes is false", + example: [698191], + type: [Number], + }) + @ValidateIf((o) => !Boolean(o.isActiveOnAllEventTypes)) + @IsOptional() + @IsNumber({}, { each: true }) + activeOnEventTypeIds: number[] = []; +} + +export type TriggerDtoType = + | OnAfterEventTriggerDto + | OnBeforeEventTriggerDto + | OnCreationTriggerDto + | OnRescheduleTriggerDto + | OnCancelTriggerDto + | OnAfterCalVideoGuestsNoShowTriggerDto + | OnAfterCalVideoHostsNoShowTriggerDto; +export class CreateWorkflowDto { + @ApiProperty({ description: "Name of the workflow", example: "Platform Test Workflow" }) + @IsString() + name!: string; + + @ApiProperty({ description: "Activation settings for the workflow", type: WorkflowActivationDto }) + @ValidateNested() + @Type(() => WorkflowActivationDto) + activation!: WorkflowActivationDto; + + @ApiProperty({ + description: "Trigger configuration for the workflow", + items: { + oneOf: [ + { $ref: getSchemaPath(OnBeforeEventTriggerDto) }, + { $ref: getSchemaPath(OnAfterEventTriggerDto) }, + { $ref: getSchemaPath(OnCancelTriggerDto) }, + { $ref: getSchemaPath(OnCreationTriggerDto) }, + { $ref: getSchemaPath(OnRescheduleTriggerDto) }, + { $ref: getSchemaPath(OnAfterCalVideoGuestsNoShowTriggerDto) }, + { $ref: getSchemaPath(OnAfterCalVideoHostsNoShowTriggerDto) }, + ], + }, + }) + @ValidateNested() + @Type(() => BaseWorkflowTriggerDto, { + discriminator: { + property: "type", + subTypes: [ + { value: OnBeforeEventTriggerDto, name: BEFORE_EVENT }, + { value: OnAfterEventTriggerDto, name: AFTER_EVENT }, + { value: OnCancelTriggerDto, name: EVENT_CANCELLED }, + { value: OnCreationTriggerDto, name: NEW_EVENT }, + { value: OnRescheduleTriggerDto, name: RESCHEDULE_EVENT }, + { value: OnAfterCalVideoGuestsNoShowTriggerDto, name: AFTER_GUESTS_CAL_VIDEO_NO_SHOW }, + { value: OnAfterCalVideoHostsNoShowTriggerDto, name: AFTER_HOSTS_CAL_VIDEO_NO_SHOW }, + ], + }, + }) + trigger!: + | OnAfterEventTriggerDto + | OnBeforeEventTriggerDto + | OnCreationTriggerDto + | OnRescheduleTriggerDto + | OnCancelTriggerDto + | OnAfterCalVideoGuestsNoShowTriggerDto + | OnAfterCalVideoHostsNoShowTriggerDto; + + @ApiProperty({ + description: "Steps to execute as part of the workflow", + items: { + oneOf: [ + { $ref: getSchemaPath(WorkflowEmailAddressStepDto) }, + { $ref: getSchemaPath(WorkflowEmailAttendeeStepDto) }, + { $ref: getSchemaPath(WorkflowEmailHostStepDto) }, + { $ref: getSchemaPath(WorkflowPhoneWhatsAppAttendeeStepDto) }, + { $ref: getSchemaPath(WorkflowPhoneWhatsAppNumberStepDto) }, + { $ref: getSchemaPath(WorkflowPhoneNumberStepDto) }, + { $ref: getSchemaPath(WorkflowPhoneAttendeeStepDto) }, + ], + }, + }) + @ValidateNested({ each: true }) + @ArrayMinSize(1, { message: "Your workflow must contain at least one step." }) + @Type(() => BaseWorkflowStepDto, { + discriminator: { + property: "action", + subTypes: [ + { value: WorkflowEmailAddressStepDto, name: EMAIL_ADDRESS }, + { value: WorkflowEmailAttendeeStepDto, name: EMAIL_ATTENDEE }, + { value: WorkflowEmailHostStepDto, name: EMAIL_HOST }, + { value: WorkflowPhoneWhatsAppAttendeeStepDto, name: WHATSAPP_ATTENDEE }, + { value: WorkflowPhoneWhatsAppNumberStepDto, name: WHATSAPP_NUMBER }, + { value: WorkflowPhoneNumberStepDto, name: SMS_NUMBER }, + { value: WorkflowPhoneAttendeeStepDto, name: SMS_ATTENDEE }, + ], + }, + }) + steps!: ( + | WorkflowEmailAddressStepDto + | WorkflowEmailAttendeeStepDto + | WorkflowEmailHostStepDto + | WorkflowPhoneWhatsAppAttendeeStepDto + | WorkflowPhoneWhatsAppNumberStepDto + | WorkflowPhoneNumberStepDto + | WorkflowPhoneAttendeeStepDto + )[]; +} diff --git a/apps/api/v2/src/modules/workflows/inputs/update-workflow.input.ts b/apps/api/v2/src/modules/workflows/inputs/update-workflow.input.ts new file mode 100644 index 0000000000..af16adbcc5 --- /dev/null +++ b/apps/api/v2/src/modules/workflows/inputs/update-workflow.input.ts @@ -0,0 +1,193 @@ +import { ApiProperty, ApiPropertyOptional, getSchemaPath } from "@nestjs/swagger"; +import { Type } from "class-transformer"; +import { IsNumber, IsString, IsOptional, ValidateNested, ArrayMinSize } from "class-validator"; + +import { WorkflowActivationDto } from "./create-workflow.input"; +import { + WorkflowEmailAttendeeStepDto, + WorkflowEmailAddressStepDto, + WorkflowEmailHostStepDto, + WorkflowPhoneWhatsAppNumberStepDto, + WorkflowPhoneAttendeeStepDto, + WorkflowPhoneNumberStepDto, + WorkflowPhoneWhatsAppAttendeeStepDto, + BaseWorkflowStepDto, + EMAIL_ADDRESS, + EMAIL_ATTENDEE, + EMAIL_HOST, + WHATSAPP_ATTENDEE, + WHATSAPP_NUMBER, + SMS_NUMBER, + SMS_ATTENDEE, +} from "./workflow-step.input"; +import { + BaseWorkflowTriggerDto, + OnBeforeEventTriggerDto, + BEFORE_EVENT, + OnAfterEventTriggerDto, + AFTER_EVENT, + OnCancelTriggerDto, + EVENT_CANCELLED, + OnCreationTriggerDto, + NEW_EVENT, + OnRescheduleTriggerDto, + RESCHEDULE_EVENT, + OnAfterCalVideoGuestsNoShowTriggerDto, + AFTER_GUESTS_CAL_VIDEO_NO_SHOW, + OnAfterCalVideoHostsNoShowTriggerDto, + AFTER_HOSTS_CAL_VIDEO_NO_SHOW, +} from "./workflow-trigger.input"; + +export type UpdateWorkflowStepDto = + | UpdateEmailAttendeeWorkflowStepDto + | UpdateEmailAddressWorkflowStepDto + | UpdateEmailHostWorkflowStepDto + | UpdateWhatsAppAttendeePhoneWorkflowStepDto + | UpdatePhoneWhatsAppNumberWorkflowStepDto + | UpdatePhoneAttendeeWorkflowStepDto + | UpdatePhoneNumberWorkflowStepDto; +export class UpdateEmailAttendeeWorkflowStepDto extends WorkflowEmailAttendeeStepDto { + @ApiProperty({ + description: + "Unique identifier of the step you want to update, if adding a new step do not provide this id", + example: 67244, + }) + @IsNumber() + id?: number; +} + +export class UpdateEmailAddressWorkflowStepDto extends WorkflowEmailAddressStepDto { + @ApiProperty({ + description: + "Unique identifier of the step you want to update, if adding a new step do not provide this id", + example: 67244, + }) + @IsNumber() + id?: number; +} + +export class UpdateEmailHostWorkflowStepDto extends WorkflowEmailHostStepDto { + @ApiProperty({ + description: + "Unique identifier of the step you want to update, if adding a new step do not provide this id", + example: 67244, + }) + @IsNumber() + id?: number; +} + +export class UpdatePhoneWhatsAppNumberWorkflowStepDto extends WorkflowPhoneWhatsAppNumberStepDto { + @ApiProperty({ + description: + "Unique identifier of the step you want to update, if adding a new step do not provide this id", + example: 67244, + }) + @IsNumber() + id?: number; +} +export class UpdatePhoneAttendeeWorkflowStepDto extends WorkflowPhoneAttendeeStepDto { + @ApiProperty({ + description: + "Unique identifier of the step you want to update, if adding a new step do not provide this id", + example: 67244, + }) + @IsNumber() + id?: number; +} +export class UpdatePhoneNumberWorkflowStepDto extends WorkflowPhoneNumberStepDto { + @ApiProperty({ + description: + "Unique identifier of the step you want to update, if adding a new step do not provide this id", + example: 67244, + }) + @IsNumber() + id?: number; +} +export class UpdateWhatsAppAttendeePhoneWorkflowStepDto extends WorkflowPhoneWhatsAppAttendeeStepDto { + @ApiProperty({ + description: + "Unique identifier of the step you want to update, if adding a new step do not provide this id", + example: 67244, + }) + @IsNumber() + id?: number; +} + +export class UpdateWorkflowDto { + @ApiPropertyOptional({ description: "Name of the workflow", example: "Platform Test Workflow" }) + @IsString() + @IsOptional() + name?: string; + + @ApiPropertyOptional({ + description: "Activation settings for the workflow, the action that will trigger the workflow.", + type: WorkflowActivationDto, + }) + @ValidateNested() + @Type(() => WorkflowActivationDto) + @IsOptional() + activation?: WorkflowActivationDto; + + @Type(() => BaseWorkflowTriggerDto, { + discriminator: { + property: "type", + subTypes: [ + { value: OnBeforeEventTriggerDto, name: BEFORE_EVENT }, + { value: OnAfterEventTriggerDto, name: AFTER_EVENT }, + { value: OnCancelTriggerDto, name: EVENT_CANCELLED }, + { value: OnCreationTriggerDto, name: NEW_EVENT }, + { value: OnRescheduleTriggerDto, name: RESCHEDULE_EVENT }, + { value: OnAfterCalVideoGuestsNoShowTriggerDto, name: AFTER_GUESTS_CAL_VIDEO_NO_SHOW }, + { value: OnAfterCalVideoHostsNoShowTriggerDto, name: AFTER_HOSTS_CAL_VIDEO_NO_SHOW }, + ], + }, + }) + trigger!: + | OnAfterEventTriggerDto + | OnBeforeEventTriggerDto + | OnCreationTriggerDto + | OnRescheduleTriggerDto + | OnCancelTriggerDto + | OnAfterCalVideoGuestsNoShowTriggerDto + | OnAfterCalVideoHostsNoShowTriggerDto; + @ApiPropertyOptional({ + description: "Steps to execute as part of the workflow", + items: { + oneOf: [ + { $ref: getSchemaPath(UpdateEmailAddressWorkflowStepDto) }, + { $ref: getSchemaPath(UpdateEmailAttendeeWorkflowStepDto) }, + { $ref: getSchemaPath(UpdateEmailHostWorkflowStepDto) }, + { $ref: getSchemaPath(UpdatePhoneAttendeeWorkflowStepDto) }, + { $ref: getSchemaPath(UpdatePhoneWhatsAppNumberWorkflowStepDto) }, + { $ref: getSchemaPath(UpdateWhatsAppAttendeePhoneWorkflowStepDto) }, + { $ref: getSchemaPath(UpdatePhoneNumberWorkflowStepDto) }, + ], + }, + }) + @ValidateNested({ each: true }) + @ArrayMinSize(1, { message: "Your workflow must contain at least one step." }) + @IsOptional() + @Type(() => BaseWorkflowStepDto, { + discriminator: { + property: "action", + subTypes: [ + { value: UpdateEmailAddressWorkflowStepDto, name: EMAIL_ADDRESS }, + { value: UpdateEmailAttendeeWorkflowStepDto, name: EMAIL_ATTENDEE }, + { value: UpdateEmailHostWorkflowStepDto, name: EMAIL_HOST }, + { value: UpdateWhatsAppAttendeePhoneWorkflowStepDto, name: WHATSAPP_ATTENDEE }, + { value: UpdatePhoneWhatsAppNumberWorkflowStepDto, name: WHATSAPP_NUMBER }, + { value: UpdatePhoneNumberWorkflowStepDto, name: SMS_NUMBER }, + { value: UpdatePhoneAttendeeWorkflowStepDto, name: SMS_ATTENDEE }, + ], + }, + }) + steps?: ( + | UpdateEmailAddressWorkflowStepDto + | UpdateEmailAttendeeWorkflowStepDto + | UpdateEmailHostWorkflowStepDto + | UpdatePhoneAttendeeWorkflowStepDto + | UpdatePhoneWhatsAppNumberWorkflowStepDto + | UpdateWhatsAppAttendeePhoneWorkflowStepDto + | UpdatePhoneNumberWorkflowStepDto + )[]; +} diff --git a/apps/api/v2/src/modules/workflows/inputs/workflow-step.input.ts b/apps/api/v2/src/modules/workflows/inputs/workflow-step.input.ts new file mode 100644 index 0000000000..9630700bb3 --- /dev/null +++ b/apps/api/v2/src/modules/workflows/inputs/workflow-step.input.ts @@ -0,0 +1,300 @@ +import { ApiProperty } from "@nestjs/swagger"; +import { WorkflowActions, WorkflowTemplates } from "@prisma/client"; +import { Type } from "class-transformer"; +import { IsNumber, IsBoolean, IsString, ValidateNested, IsIn } from "class-validator"; + +export const EMAIL_HOST = "email_host"; +export const EMAIL_ATTENDEE = "email_attendee"; +export const EMAIL_ADDRESS = "email_address"; +export const SMS_ATTENDEE = "sms_attendee"; +export const SMS_NUMBER = "sms_number"; +export const WHATSAPP_ATTENDEE = "whatsapp_attendee"; +export const WHATSAPP_NUMBER = "whatsapp_number"; + +export const STEP_ACTIONS = [ + EMAIL_HOST, + EMAIL_ATTENDEE, + EMAIL_ADDRESS, + SMS_ATTENDEE, + SMS_NUMBER, + WHATSAPP_ATTENDEE, + WHATSAPP_NUMBER, +] as const; + +export const STEP_ACTIONS_TO_ENUM = { + [EMAIL_HOST]: WorkflowActions.EMAIL_HOST, + [EMAIL_ATTENDEE]: WorkflowActions.EMAIL_ATTENDEE, + [EMAIL_ADDRESS]: WorkflowActions.EMAIL_ADDRESS, + [SMS_ATTENDEE]: WorkflowActions.SMS_ATTENDEE, + [WHATSAPP_ATTENDEE]: WorkflowActions.WHATSAPP_ATTENDEE, + [WHATSAPP_NUMBER]: WorkflowActions.WHATSAPP_NUMBER, + [SMS_NUMBER]: WorkflowActions.SMS_NUMBER, +} as const; + +export const ENUM_TO_STEP_ACTIONS = { + [WorkflowActions.EMAIL_HOST]: EMAIL_HOST, + [WorkflowActions.EMAIL_ATTENDEE]: EMAIL_ATTENDEE, + [WorkflowActions.EMAIL_ADDRESS]: EMAIL_ADDRESS, + [WorkflowActions.SMS_ATTENDEE]: SMS_ATTENDEE, + [WorkflowActions.WHATSAPP_ATTENDEE]: WHATSAPP_ATTENDEE, + [WorkflowActions.WHATSAPP_NUMBER]: WHATSAPP_NUMBER, + [WorkflowActions.SMS_NUMBER]: SMS_NUMBER, +} as const; + +export type StepAction = (typeof STEP_ACTIONS)[number]; +export type StepActionsType = (typeof STEP_ACTIONS)[number]; + +export const REMINDER = "reminder"; +export const CUSTOM = "custom"; +export const CANCELLED = "cancelled"; +export const RESCHEDULED = "rescheduled"; +export const COMPLETED = "completed"; +export const RATING = "rating"; +export const TEMPLATES = [REMINDER, CUSTOM, RESCHEDULED, COMPLETED, RATING, CANCELLED] as const; +export const TEMPLATES_TO_ENUM = { + [WorkflowTemplates.REMINDER]: REMINDER, + [CUSTOM]: WorkflowTemplates.CUSTOM, + [RESCHEDULED]: WorkflowTemplates.RESCHEDULED, + [CANCELLED]: WorkflowTemplates.CANCELLED, + [COMPLETED]: WorkflowTemplates.COMPLETED, + [RATING]: WorkflowTemplates.RATING, +} as const; + +export const ENUM_TO_TEMPLATES = { + [WorkflowTemplates.REMINDER]: REMINDER, + [WorkflowTemplates.CUSTOM]: CUSTOM, + [WorkflowTemplates.RESCHEDULED]: RESCHEDULED, + [WorkflowTemplates.CANCELLED]: CANCELLED, + [WorkflowTemplates.COMPLETED]: COMPLETED, + [WorkflowTemplates.RATING]: RATING, +} as const; + +export type TemplateType = (typeof TEMPLATES)[number]; + +export const HOST = "const"; +export const ATTENDEE = "attendee"; +export const EMAIL = "email"; +export const PHONE_NUMBER = "phone_number"; + +export const RECIPIENT_TYPES = [HOST, ATTENDEE, EMAIL, PHONE_NUMBER]; +export type RecipientType = (typeof RECIPIENT_TYPES)[number]; + +export class BaseWorkflowMessageDto { + @ApiProperty({ + description: "Subject of the message", + example: "Reminder: Your Meeting {EVENT_NAME} - {EVENT_DATE_ddd, MMM D, YYYY h:mma} with Cal.com", + }) + @IsString() + subject!: string; +} + +export class HtmlWorkflowMessageDto extends BaseWorkflowMessageDto { + @ApiProperty({ + description: "HTML content of the message (used for Emails)", + example: + "

This is a reminder from {ORGANIZER} of {EVENT_NAME} to {ATTENDEE} starting here {LOCATION} {MEETING_URL} at {START_TIME_h:mma} {TIMEZONE}.

", + }) + @IsString() + html!: string; +} + +export class TextWorkflowMessageDto extends BaseWorkflowMessageDto { + @ApiProperty({ + description: "Text content of the message (used for SMS)", + example: + "This is a reminder message from {ORGANIZER} of {EVENT_NAME} to {ATTENDEE} starting here {LOCATION} {MEETING_URL} at {START_TIME_h:mma} {TIMEZONE}.", + }) + @IsString() + text!: string; +} + +export class BaseWorkflowStepDto { + @ApiProperty({ description: "Action to perform", example: EMAIL_HOST, enum: STEP_ACTIONS }) + @IsString() + @IsIn(STEP_ACTIONS) + action!: StepAction; + + @ApiProperty({ description: "Step number in the workflow sequence", example: 1 }) + @IsNumber() + stepNumber!: number; + + @ApiProperty({ description: "Recipient type", example: ATTENDEE, enum: RECIPIENT_TYPES }) + recipient!: RecipientType; + + @ApiProperty({ description: "Template type for the step", example: REMINDER, enum: TEMPLATES }) + template!: TemplateType; + + @ApiProperty({ description: "Displayed sender name.", type: String }) + @IsString() + sender!: string; +} + +export class WorkflowEmailHostStepDto extends BaseWorkflowStepDto { + @ApiProperty({ + description: "Action to perform, send an email to the host of the event", + example: EMAIL_HOST, + enum: STEP_ACTIONS, + }) + @IsString() + @IsIn(STEP_ACTIONS) + action: typeof EMAIL_HOST = EMAIL_HOST; + + @ApiProperty({ + description: `Whether to include a calendar event in the notification, can be included with actions ${EMAIL_HOST}, ${EMAIL_ATTENDEE}, ${EMAIL_ADDRESS}`, + example: true, + }) + @IsBoolean() + includeCalendarEvent = false; + + @ApiProperty({ description: "Message content for this step", type: HtmlWorkflowMessageDto }) + @ValidateNested() + @Type(() => HtmlWorkflowMessageDto) + message!: HtmlWorkflowMessageDto; +} + +export class WorkflowEmailAddressStepDto extends BaseWorkflowStepDto { + @ApiProperty({ + description: "Action to perform, send an email to a specific email address", + example: EMAIL_ADDRESS, + enum: STEP_ACTIONS, + }) + @IsString() + @IsIn(STEP_ACTIONS) + action: typeof EMAIL_ADDRESS = EMAIL_ADDRESS; + + @ApiProperty({ + description: "Email address if recipient is EMAIL, required for action EMAIL_ADDRESS", + example: "31214", + externalDocs: { + url: "https://cal.com/docs/api-reference/v2/organization-team-verified-resources/verify-an-email-for-an-org-team", + }, + }) + @IsNumber() + verifiedEmailId!: number; + + @ApiProperty({ + description: `Whether to include a calendar event in the notification, can be included with actions ${EMAIL_HOST}, ${EMAIL_ATTENDEE}, ${EMAIL_ADDRESS}`, + example: true, + }) + @IsBoolean() + includeCalendarEvent = false; + + @ApiProperty({ description: "Message content for this step", type: HtmlWorkflowMessageDto }) + @ValidateNested() + @Type(() => HtmlWorkflowMessageDto) + message!: HtmlWorkflowMessageDto; +} + +export class WorkflowEmailAttendeeStepDto extends BaseWorkflowStepDto { + @ApiProperty({ + description: "Action to perform, send an email to the attendees of the event", + example: EMAIL_ATTENDEE, + enum: STEP_ACTIONS, + }) + @IsString() + @IsIn(STEP_ACTIONS) + action: typeof EMAIL_ATTENDEE = EMAIL_ATTENDEE; + + @ApiProperty({ + description: `Whether to include a calendar event in the notification, can be included with actions ${EMAIL_HOST}, ${EMAIL_ATTENDEE}, ${EMAIL_ADDRESS}`, + example: true, + }) + @IsBoolean() + includeCalendarEvent = false; + + @ApiProperty({ description: "Message content for this step", type: HtmlWorkflowMessageDto }) + @ValidateNested() + @Type(() => HtmlWorkflowMessageDto) + message!: HtmlWorkflowMessageDto; +} + +export class WorkflowPhoneWhatsAppNumberStepDto extends BaseWorkflowStepDto { + @ApiProperty({ + description: "Action to perform, send a text message via whatsapp to a specific phone number", + example: WHATSAPP_NUMBER, + }) + @IsString() + @IsIn(STEP_ACTIONS) + action: typeof WHATSAPP_NUMBER = WHATSAPP_NUMBER; + + @ApiProperty({ + description: + "Phone number if recipient is PHONE_NUMBER, required for actions SMS_NUMBER and WHATSAPP_NUMBER", + example: "3243434", + externalDocs: { + url: "https://cal.com/docs/api-reference/v2/organization-team-verified-resources/verify-a-phone-number-for-an-org-team", + }, + }) + @IsNumber() + verifiedPhoneId!: number; + + @ApiProperty({ description: "Message content for this step", type: TextWorkflowMessageDto }) + @ValidateNested() + @Type(() => TextWorkflowMessageDto) + message!: TextWorkflowMessageDto; +} + +export class WorkflowPhoneAttendeeStepDto extends BaseWorkflowStepDto { + @ApiProperty({ + description: "Action to perform, send a text message to the phone numbers of the attendees", + example: SMS_ATTENDEE, + }) + @IsString() + @IsIn(STEP_ACTIONS) + action: typeof SMS_ATTENDEE = SMS_ATTENDEE; + + @ApiProperty({ + description: + "Phone number if recipient is PHONE_NUMBER, required for actions SMS_NUMBER and WHATSAPP_NUMBER", + example: "3243434", + externalDocs: { + url: "https://cal.com/docs/api-reference/v2/organization-team-verified-resources/verify-a-phone-number-for-an-org-team", + }, + }) + @ApiProperty({ description: "Message content for this step", type: TextWorkflowMessageDto }) + @ValidateNested() + @Type(() => TextWorkflowMessageDto) + message!: TextWorkflowMessageDto; +} + +export class WorkflowPhoneNumberStepDto extends BaseWorkflowStepDto { + @ApiProperty({ + description: "Action to perform, send a text message to a specific phone number", + example: SMS_NUMBER, + }) + @IsString() + @IsIn(STEP_ACTIONS) + action: typeof SMS_NUMBER = SMS_NUMBER; + + @ApiProperty({ + description: + "Phone number if recipient is PHONE_NUMBER, required for actions SMS_NUMBER and WHATSAPP_NUMBER", + example: "3243434", + externalDocs: { + url: "https://cal.com/docs/api-reference/v2/organization-team-verified-resources/verify-a-phone-number-for-an-org-team", + }, + }) + @IsNumber() + verifiedPhoneId!: number; + + @ApiProperty({ description: "Message content for this step", type: TextWorkflowMessageDto }) + @ValidateNested() + @Type(() => TextWorkflowMessageDto) + message!: TextWorkflowMessageDto; +} + +export class WorkflowPhoneWhatsAppAttendeeStepDto extends BaseWorkflowStepDto { + @ApiProperty({ description: "Action to perform", example: WHATSAPP_ATTENDEE }) + @IsString() + @IsIn(STEP_ACTIONS) + action: typeof WHATSAPP_ATTENDEE = WHATSAPP_ATTENDEE; + + @ApiProperty({ + description: + "Message content for this step, send a text message via whatsapp to the phone numbers of the attendees", + type: TextWorkflowMessageDto, + }) + @ValidateNested() + @Type(() => TextWorkflowMessageDto) + message!: TextWorkflowMessageDto; +} diff --git a/apps/api/v2/src/modules/workflows/inputs/workflow-trigger.input.ts b/apps/api/v2/src/modules/workflows/inputs/workflow-trigger.input.ts new file mode 100644 index 0000000000..08d3bdfdb6 --- /dev/null +++ b/apps/api/v2/src/modules/workflows/inputs/workflow-trigger.input.ts @@ -0,0 +1,141 @@ +import { ApiProperty } from "@nestjs/swagger"; +import { TimeUnit, WorkflowTriggerEvents } from "@prisma/client"; +import { Type } from "class-transformer"; +import { IsNumber, ValidateNested } from "class-validator"; + +export const BEFORE_EVENT = "beforeEvent"; +export const EVENT_CANCELLED = "eventCancelled"; +export const NEW_EVENT = "newEvent"; +export const AFTER_EVENT = "afterEvent"; +export const RESCHEDULE_EVENT = "rescheduleEvent"; +export const AFTER_HOSTS_CAL_VIDEO_NO_SHOW = "afterHostsCalVideoNoShow"; +export const AFTER_GUESTS_CAL_VIDEO_NO_SHOW = "afterGuestsCalVideoNoShow"; +export const WORKFLOW_TRIGGER_TYPES = [ + BEFORE_EVENT, + EVENT_CANCELLED, + NEW_EVENT, + AFTER_EVENT, + RESCHEDULE_EVENT, + AFTER_HOSTS_CAL_VIDEO_NO_SHOW, + AFTER_GUESTS_CAL_VIDEO_NO_SHOW, +] as const; + +export const WORKFLOW_TRIGGER_TO_ENUM = { + [BEFORE_EVENT]: WorkflowTriggerEvents.BEFORE_EVENT, + [EVENT_CANCELLED]: WorkflowTriggerEvents.EVENT_CANCELLED, + [NEW_EVENT]: WorkflowTriggerEvents.NEW_EVENT, + [AFTER_EVENT]: WorkflowTriggerEvents.AFTER_EVENT, + [RESCHEDULE_EVENT]: WorkflowTriggerEvents.RESCHEDULE_EVENT, + [AFTER_HOSTS_CAL_VIDEO_NO_SHOW]: WorkflowTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW, + [AFTER_GUESTS_CAL_VIDEO_NO_SHOW]: WorkflowTriggerEvents.AFTER_GUESTS_CAL_VIDEO_NO_SHOW, +} as const; + +export const ENUM_TO_WORKFLOW_TRIGGER = { + [WorkflowTriggerEvents.BEFORE_EVENT]: BEFORE_EVENT, + [WorkflowTriggerEvents.EVENT_CANCELLED]: EVENT_CANCELLED, + [WorkflowTriggerEvents.NEW_EVENT]: NEW_EVENT, + [WorkflowTriggerEvents.AFTER_EVENT]: AFTER_EVENT, + [WorkflowTriggerEvents.RESCHEDULE_EVENT]: RESCHEDULE_EVENT, + [WorkflowTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW]: AFTER_HOSTS_CAL_VIDEO_NO_SHOW, + [WorkflowTriggerEvents.AFTER_GUESTS_CAL_VIDEO_NO_SHOW]: AFTER_GUESTS_CAL_VIDEO_NO_SHOW, +} as const; + +export const HOUR = "hour"; +export const MINUTE = "minute"; +export const DAY = "day"; + +export const TIME_UNITS = [HOUR, MINUTE, DAY] as const; + +export type TimeUnitType = (typeof TIME_UNITS)[number]; + +export const TIME_UNIT_TO_ENUM = { + [HOUR]: TimeUnit.HOUR, + [MINUTE]: TimeUnit.MINUTE, + [DAY]: TimeUnit.DAY, +} as const; + +export const ENUM_TO_TIME_UNIT = { + [TimeUnit.HOUR]: HOUR, + [TimeUnit.MINUTE]: MINUTE, + [TimeUnit.DAY]: DAY, +} as const; + +export type WorkflowTriggerType = (typeof WORKFLOW_TRIGGER_TYPES)[number]; + +export class WorkflowTriggerOffsetDto { + @ApiProperty({ description: "Time value for offset before/after event trigger", example: 24, type: Number }) + @IsNumber() + value!: number; + + @ApiProperty({ description: "Unit for the offset time", example: HOUR }) + unit!: TimeUnitType; +} + +export class BaseWorkflowTriggerDto { + @ApiProperty({ + description: "Trigger type for the workflow", + }) + type!: WorkflowTriggerType; +} + +export class OnCreationTriggerDto { + @ApiProperty({ + description: "Trigger type for the workflow", + }) + type: typeof NEW_EVENT = NEW_EVENT; +} + +export class OnRescheduleTriggerDto { + @ApiProperty({ + description: "Trigger type for the workflow", + }) + type: typeof RESCHEDULE_EVENT = RESCHEDULE_EVENT; +} +export class OnCancelTriggerDto { + @ApiProperty({ + description: "Trigger type for the workflow", + }) + type: typeof EVENT_CANCELLED = EVENT_CANCELLED; +} + +export class TriggerOffsetDTO { + @ApiProperty({ + description: "Offset before/after the trigger time; required for BEFORE_EVENT and AFTER_EVENT only", + type: WorkflowTriggerOffsetDto, + }) + @ValidateNested() + @Type(() => WorkflowTriggerOffsetDto) + offset!: WorkflowTriggerOffsetDto; +} + +export class OnBeforeEventTriggerDto extends TriggerOffsetDTO { + @ApiProperty({ + description: "Trigger type for the workflow", + example: BEFORE_EVENT, + }) + type: typeof BEFORE_EVENT = BEFORE_EVENT; +} + +export class OnAfterEventTriggerDto extends TriggerOffsetDTO { + @ApiProperty({ + description: "Trigger type for the workflow", + example: AFTER_EVENT, + }) + type: typeof AFTER_EVENT = AFTER_EVENT; +} + +export class OnAfterCalVideoGuestsNoShowTriggerDto extends TriggerOffsetDTO { + @ApiProperty({ + description: "Trigger type for the workflow", + example: AFTER_GUESTS_CAL_VIDEO_NO_SHOW, + }) + type: typeof AFTER_GUESTS_CAL_VIDEO_NO_SHOW = AFTER_GUESTS_CAL_VIDEO_NO_SHOW; +} + +export class OnAfterCalVideoHostsNoShowTriggerDto extends TriggerOffsetDTO { + @ApiProperty({ + description: "Trigger type for the workflow", + example: AFTER_HOSTS_CAL_VIDEO_NO_SHOW, + }) + type: typeof AFTER_HOSTS_CAL_VIDEO_NO_SHOW = AFTER_HOSTS_CAL_VIDEO_NO_SHOW; +} diff --git a/apps/api/v2/src/modules/workflows/outputs/workflow.output.ts b/apps/api/v2/src/modules/workflows/outputs/workflow.output.ts new file mode 100644 index 0000000000..5a58d92a9b --- /dev/null +++ b/apps/api/v2/src/modules/workflows/outputs/workflow.output.ts @@ -0,0 +1,241 @@ +import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger"; +import { Expose, Type } from "class-transformer"; +import { IsArray, IsEnum, ValidateNested } from "class-validator"; + +import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants"; + +import { + EMAIL_HOST, + HOST, + RECIPIENT_TYPES, + RecipientType, + REMINDER, + STEP_ACTIONS, + StepAction, + TEMPLATES, + TemplateType, +} from "../inputs/workflow-step.input"; +import { + BEFORE_EVENT, + HOUR, + TIME_UNITS, + TimeUnitType, + WORKFLOW_TRIGGER_TYPES, + WorkflowTriggerType, +} from "../inputs/workflow-trigger.input"; + +export class WorkflowMessageOutputDto { + @ApiProperty({ + description: "Subject of the message", + example: "Reminder: Your Meeting {EVENT_NAME} - {EVENT_DATE_ddd, MMM D, YYYY h:mma} with Cal.com", + }) + @Expose() + subject!: string; + + @ApiPropertyOptional({ + description: "HTML content of the message", + example: "

Reminder for {EVENT_NAME}.

", + }) + @Expose() + html?: string; + + @ApiPropertyOptional({ + description: "Text content of the message (used for SMS/WhatsApp)", + example: "Reminder for {EVENT_NAME}.", + }) + @Expose() + text?: string; +} + +export class WorkflowStepOutputDto { + @ApiProperty({ description: "Unique identifier of the step", example: 67244 }) + @Expose() + id!: number; + + @ApiProperty({ description: "Step number in the workflow sequence", example: 1 }) + @Expose() + stepNumber!: number; + + @ApiProperty({ description: "Action to perform", example: EMAIL_HOST, enum: STEP_ACTIONS }) + @Expose() + action!: StepAction; + + @ApiProperty({ description: "Intended recipient type", example: HOST, enum: RECIPIENT_TYPES }) + @Expose() + recipient!: RecipientType; + + @ApiPropertyOptional({ description: "Verified Email if action is EMAIL_ADDRESS", example: 31214 }) + @Expose() + email?: string; + + @ApiPropertyOptional({ + description: "Verified Phone if action is SMS_NUMBER or WHATSAPP_NUMBER", + }) + @Expose() + phone?: string; + + @ApiProperty({ description: "Template type used", example: REMINDER, enum: TEMPLATES }) + @Expose() + template!: TemplateType; + + @ApiPropertyOptional({ + description: "Whether a calendar event (.ics) was included (for email actions)", + example: true, + }) + @Expose() + includeCalendarEvent = false; + + @ApiProperty({ description: "Displayed sender name used for this step", example: "Cal.com Notifications" }) + @Expose() + sender!: string; + + @ApiProperty({ description: "Message content for this step", type: WorkflowMessageOutputDto }) + @Expose() + @ValidateNested() + @Type(() => WorkflowMessageOutputDto) + message!: WorkflowMessageOutputDto; +} + +export class WorkflowTriggerOffsetOutputDto { + @ApiProperty({ description: "Time value for offset", example: 24 }) + @Expose() + value!: number; + + @ApiProperty({ + description: "Unit for the offset time", + example: HOUR, + enum: TIME_UNITS, + }) + @Expose() + unit!: TimeUnitType; +} + +export class WorkflowTriggerOutputDto { + @ApiProperty({ + description: "Trigger type for the workflow", + example: BEFORE_EVENT, + enum: WORKFLOW_TRIGGER_TYPES, + }) + @Expose() + type!: WorkflowTriggerType; + + @ApiPropertyOptional({ + description: "Offset details (present for BEFORE_EVENT/AFTER_EVENT)", + type: WorkflowTriggerOffsetOutputDto, + }) + @Expose() + @ValidateNested() + @Type(() => WorkflowTriggerOffsetOutputDto) + offset?: WorkflowTriggerOffsetOutputDto; +} + +export class WorkflowActivationOutputDto { + @ApiProperty({ + description: "Whether the workflow is active for all event types associated with the team/user", + example: false, + }) + @Expose() + isActiveOnAllEventTypes?: boolean = false; + + @ApiPropertyOptional({ + description: "List of Event Type IDs the workflow is specifically active on (if not active on all)", + example: [698191, 698192], + }) + @Expose() + @IsArray() + activeOnEventTypeIds?: number[]; +} + +// --- Main Workflow Output DTO --- + +export class WorkflowOutput { + @ApiProperty({ description: "Unique identifier of the workflow", example: 101 }) + @Expose() + id!: number; + + @ApiProperty({ description: "Name of the workflow", example: "Platform Test Workflow" }) + @Expose() + name!: string; + + @ApiPropertyOptional({ + description: "ID of the user who owns the workflow (if not team-owned)", + example: 2313, + }) + @Expose() + userId?: number; + + @ApiPropertyOptional({ description: "ID of the team owning the workflow", example: 4214321 }) + @Expose() + teamId?: number; + + @ApiProperty({ description: "Activation settings (scope)", type: WorkflowActivationOutputDto }) + @Expose() + @ValidateNested() + @Type(() => WorkflowActivationOutputDto) + activation!: WorkflowActivationOutputDto; + + @ApiProperty({ description: "Trigger configuration", type: WorkflowTriggerOutputDto }) + @Expose() + @ValidateNested() + @Type(() => WorkflowTriggerOutputDto) + trigger!: WorkflowTriggerOutputDto; + + @ApiProperty({ description: "Steps comprising the workflow", type: [WorkflowStepOutputDto] }) + @Expose() + @IsArray() + @ValidateNested({ each: true }) + @Type(() => WorkflowStepOutputDto) + steps!: WorkflowStepOutputDto[]; + + @ApiPropertyOptional({ description: "Timestamp of creation", example: "2024-05-12T10:00:00.000Z" }) + @Expose() + createdAt?: Date | string; + + @ApiPropertyOptional({ description: "Timestamp of last update", example: "2024-05-12T11:30:00.000Z" }) + @Expose() + updatedAt?: Date | string; +} + +// --- List Response Output DTO --- + +export class GetWorkflowsOutput { + @ApiProperty({ + description: "Indicates the status of the response", + example: SUCCESS_STATUS, + enum: [SUCCESS_STATUS, ERROR_STATUS], + }) + @Expose() + @IsEnum([SUCCESS_STATUS, ERROR_STATUS]) + status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS; + + @ApiProperty({ + description: "List of workflows", + type: [WorkflowOutput], + }) + @Expose() + @IsArray() + @ValidateNested({ each: true }) + @Type(() => WorkflowOutput) + data!: WorkflowOutput[]; +} + +export class GetWorkflowOutput { + @ApiProperty({ + description: "Indicates the status of the response", + example: SUCCESS_STATUS, + enum: [SUCCESS_STATUS, ERROR_STATUS], + }) + @Expose() + @IsEnum([SUCCESS_STATUS, ERROR_STATUS]) + status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS; + + @ApiProperty({ + description: "workflow", + type: [WorkflowOutput], + }) + @Expose() + @IsArray() + @ValidateNested({ each: true }) + @Type(() => WorkflowOutput) + data!: WorkflowOutput; +} diff --git a/apps/api/v2/src/modules/workflows/services/team-workflows.service.ts b/apps/api/v2/src/modules/workflows/services/team-workflows.service.ts new file mode 100644 index 0000000000..1cbcd1f01a --- /dev/null +++ b/apps/api/v2/src/modules/workflows/services/team-workflows.service.ts @@ -0,0 +1,92 @@ +import { UserWithProfile } from "@/modules/users/users.repository"; +import { TeamsVerifiedResourcesRepository } from "@/modules/verified-resources/teams-verified-resources.repository"; +import { CreateWorkflowDto } from "@/modules/workflows/inputs/create-workflow.input"; +import { UpdateWorkflowDto } from "@/modules/workflows/inputs/update-workflow.input"; +import { WorkflowsInputService } from "@/modules/workflows/services/workflows.input.service"; +import { WorkflowsOutputService } from "@/modules/workflows/services/workflows.output.service"; +import { WorkflowsRepository } from "@/modules/workflows/workflows.repository"; +import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common"; + +@Injectable() +export class TeamWorkflowsService { + constructor( + private readonly workflowsRepository: WorkflowsRepository, + private readonly teamsVerifiedResourcesRepository: TeamsVerifiedResourcesRepository, + private readonly workflowInputService: WorkflowsInputService, + private readonly workflowOutputService: WorkflowsOutputService + ) {} + + async getTeamWorkflows(teamId: number, skip: number, take: number) { + const workflows = await this.workflowsRepository.getTeamWorkflows(teamId, skip, take); + + return workflows.map((workflow) => this.workflowOutputService.toOutputDto(workflow)); + } + + async getTeamWorkflowById(teamId: number, workflowId: number) { + const workflow = await this.workflowsRepository.getTeamWorkflowById(teamId, workflowId); + + if (!workflow) { + throw new NotFoundException(`Workflow with ID ${workflowId} not found for team ${teamId}`); + } + + return this.workflowOutputService.toOutputDto(workflow); + } + + async createTeamWorkflow(user: UserWithProfile, teamId: number, data: CreateWorkflowDto) { + const workflowHusk = await this.workflowsRepository.createTeamWorkflowHusk(teamId); + const mappedData = await this.workflowInputService.mapUpdateDtoToZodUpdateSchema( + data, + workflowHusk.id, + teamId, + workflowHusk + ); + + const createdWorkflow = await this.workflowsRepository.updateTeamWorkflow( + user, + teamId, + workflowHusk.id, + mappedData + ); + if (!createdWorkflow) { + throw new BadRequestException(`Could not create Workflow in team ${teamId}`); + } + + return this.workflowOutputService.toOutputDto(createdWorkflow); + } + + async updateTeamWorkflow( + user: UserWithProfile, + teamId: number, + workflowId: number, + data: UpdateWorkflowDto + ) { + const currentWorkflow = await this.workflowsRepository.getTeamWorkflowById(teamId, workflowId); + + if (!currentWorkflow) { + throw new NotFoundException(`Workflow with ID ${workflowId} not found for team ${teamId}`); + } + const mappedData = await this.workflowInputService.mapUpdateDtoToZodUpdateSchema( + data, + workflowId, + teamId, + currentWorkflow + ); + + const updatedWorkflow = await this.workflowsRepository.updateTeamWorkflow( + user, + teamId, + workflowId, + mappedData + ); + + if (!updatedWorkflow) { + throw new BadRequestException(`Could not update Workflow with ID ${workflowId} in team ${teamId}`); + } + + return this.workflowOutputService.toOutputDto(updatedWorkflow); + } + + async deleteTeamWorkflow(teamId: number, workflowId: number) { + return await this.workflowsRepository.deleteTeamWorkflowById(teamId, workflowId); + } +} diff --git a/apps/api/v2/src/modules/workflows/services/workflows.input.service.ts b/apps/api/v2/src/modules/workflows/services/workflows.input.service.ts new file mode 100644 index 0000000000..64acd80814 --- /dev/null +++ b/apps/api/v2/src/modules/workflows/services/workflows.input.service.ts @@ -0,0 +1,163 @@ +import { TeamsVerifiedResourcesRepository } from "@/modules/verified-resources/teams-verified-resources.repository"; +import { + UpdateWorkflowDto, + UpdateWorkflowStepDto, + UpdateEmailAttendeeWorkflowStepDto, + UpdateEmailAddressWorkflowStepDto, + UpdateEmailHostWorkflowStepDto, +} from "@/modules/workflows/inputs/update-workflow.input"; +import { WorkflowType } from "@/modules/workflows/workflows.repository"; +import { BadRequestException, Injectable } from "@nestjs/common"; + +import { TUpdateInputSchema } from "@calcom/platform-libraries/workflows"; + +import { + EMAIL_ADDRESS, + EMAIL_ATTENDEE, + EMAIL_HOST, + HtmlWorkflowMessageDto, + SMS_ATTENDEE, + SMS_NUMBER, + STEP_ACTIONS_TO_ENUM, + TemplateType, + TextWorkflowMessageDto, + WHATSAPP_ATTENDEE, + WHATSAPP_NUMBER, + WorkflowPhoneNumberStepDto, + WorkflowPhoneWhatsAppNumberStepDto, +} from "../inputs/workflow-step.input"; +import { + OnAfterEventTriggerDto, + OnBeforeEventTriggerDto, + TIME_UNIT_TO_ENUM, + WORKFLOW_TRIGGER_TO_ENUM, +} from "../inputs/workflow-trigger.input"; + +@Injectable() +export class WorkflowsInputService { + constructor(private readonly teamsVerifiedResourcesRepository: TeamsVerifiedResourcesRepository) {} + + private async mapUpdateWorkflowStepToZodUpdateSchema( + stepDto: UpdateWorkflowStepDto, + index: number, + teamId: number, + workflowIdToUse: number + ) { + let reminderBody: string | null = null; + let sendTo: string | null = null; + const html = stepDto.message instanceof HtmlWorkflowMessageDto ? stepDto.message.html : null; + const text = stepDto.message instanceof TextWorkflowMessageDto ? stepDto.message.text : null; + const includeCalendarEvent = + stepDto instanceof UpdateEmailAddressWorkflowStepDto || + stepDto instanceof UpdateEmailAttendeeWorkflowStepDto || + stepDto instanceof UpdateEmailHostWorkflowStepDto + ? stepDto.includeCalendarEvent + : false; + + switch (stepDto.action) { + case EMAIL_HOST: + case EMAIL_ATTENDEE: + case EMAIL_ADDRESS: + reminderBody = html ?? null; + break; + case SMS_ATTENDEE: + case SMS_NUMBER: + case WHATSAPP_ATTENDEE: + case WHATSAPP_NUMBER: + reminderBody = text ?? null; + break; + } + if (stepDto.action === EMAIL_ADDRESS) { + if (stepDto.verifiedEmailId) { + const emailResource = await this.teamsVerifiedResourcesRepository.getTeamVerifiedEmailById( + stepDto.verifiedEmailId, + teamId + ); + if (!emailResource?.email) { + throw new BadRequestException("Invalid Verified Email Id."); + } + sendTo = emailResource.email; + } + } else if (stepDto.action === SMS_NUMBER || stepDto.action === WHATSAPP_NUMBER) { + if ( + stepDto instanceof WorkflowPhoneNumberStepDto || + stepDto instanceof WorkflowPhoneWhatsAppNumberStepDto + ) { + if (stepDto.verifiedPhoneId) { + const phoneResource = await this.teamsVerifiedResourcesRepository.getTeamVerifiedPhoneNumberById( + stepDto.verifiedPhoneId, + teamId + ); + + if (!phoneResource?.phoneNumber) { + throw new BadRequestException("Invalid Verified Phone Id."); + } + + sendTo = phoneResource.phoneNumber; + } + } + } + + const actionForZod = STEP_ACTIONS_TO_ENUM[stepDto.action]; + const templateForZod = stepDto.template as unknown as Uppercase; + + return { + id: stepDto.id ?? -(index + 1), + stepNumber: stepDto.stepNumber, + action: actionForZod, + workflowId: workflowIdToUse, + sendTo: sendTo, + reminderBody: reminderBody, + emailSubject: stepDto.message.subject ?? null, + template: templateForZod, + numberRequired: null, + sender: stepDto.sender ?? null, + senderName: stepDto.sender ?? null, + includeCalendarEvent: includeCalendarEvent, + }; + } + + async mapUpdateDtoToZodUpdateSchema( + updateDto: UpdateWorkflowDto, + workflowIdToUse: number, + teamId: number, + currentData: WorkflowType + ): Promise { + const mappedSteps = updateDto?.steps + ? await Promise.all( + updateDto.steps.map(async (stepDto: UpdateWorkflowStepDto, index: number) => + this.mapUpdateWorkflowStepToZodUpdateSchema(stepDto, index, teamId, workflowIdToUse) + ) + ) + : currentData.steps.map((step) => ({ ...step, senderName: step.sender })); + + const triggerForZod = updateDto?.trigger?.type + ? WORKFLOW_TRIGGER_TO_ENUM[updateDto?.trigger?.type] + : currentData.trigger; + const timeUnitForZod = + updateDto.trigger instanceof OnBeforeEventTriggerDto || + updateDto.trigger instanceof OnAfterEventTriggerDto + ? updateDto?.trigger?.offset?.unit ?? currentData.timeUnit ?? null + : undefined; + + const updateData: TUpdateInputSchema = { + id: workflowIdToUse, + name: updateDto.name ?? currentData.name, + activeOn: + updateDto?.activation?.activeOnEventTypeIds ?? + currentData?.activeOn.map((active) => active.eventTypeId) ?? + [], + steps: mappedSteps, + trigger: triggerForZod, + time: + updateDto.trigger instanceof OnBeforeEventTriggerDto || + updateDto.trigger instanceof OnAfterEventTriggerDto + ? updateDto?.trigger?.offset?.value ?? currentData?.time ?? null + : null, + timeUnit: timeUnitForZod ? TIME_UNIT_TO_ENUM[timeUnitForZod] : null, + isActiveOnAll: updateDto?.activation?.isActiveOnAllEventTypes ?? currentData.isActiveOnAll ?? false, + } as const satisfies TUpdateInputSchema; + + return updateData; + } +} diff --git a/apps/api/v2/src/modules/workflows/services/workflows.output.service.ts b/apps/api/v2/src/modules/workflows/services/workflows.output.service.ts new file mode 100644 index 0000000000..312dd70adf --- /dev/null +++ b/apps/api/v2/src/modules/workflows/services/workflows.output.service.ts @@ -0,0 +1,119 @@ +import { WorkflowActivationDto, TriggerDtoType } from "@/modules/workflows/inputs/create-workflow.input"; +import { WorkflowOutput, WorkflowStepOutputDto } from "@/modules/workflows/outputs/workflow.output"; +import { WorkflowType } from "@/modules/workflows/workflows.repository"; +import { Injectable } from "@nestjs/common"; + +import { + ATTENDEE, + EMAIL, + EMAIL_ADDRESS, + EMAIL_ATTENDEE, + EMAIL_HOST, + ENUM_TO_STEP_ACTIONS, + ENUM_TO_TEMPLATES, + HOST, + PHONE_NUMBER, + RecipientType, + SMS_ATTENDEE, + SMS_NUMBER, + WHATSAPP_ATTENDEE, + WHATSAPP_NUMBER, +} from "../inputs/workflow-step.input"; +import { + AFTER_EVENT, + AFTER_GUESTS_CAL_VIDEO_NO_SHOW, + AFTER_HOSTS_CAL_VIDEO_NO_SHOW, + BEFORE_EVENT, + ENUM_TO_TIME_UNIT, + ENUM_TO_WORKFLOW_TRIGGER, + HOUR, + WORKFLOW_TRIGGER_TO_ENUM, +} from "../inputs/workflow-trigger.input"; + +@Injectable() +export class WorkflowsOutputService { + toOutputDto(workflow: WorkflowType): WorkflowOutput { + const activation: WorkflowActivationDto = { + isActiveOnAllEventTypes: workflow.isActiveOnAll, + activeOnEventTypeIds: workflow.activeOn?.map((relation) => relation.eventTypeId) ?? [], + }; + + const trigger: TriggerDtoType = + workflow.trigger === WORKFLOW_TRIGGER_TO_ENUM[BEFORE_EVENT] || + workflow.trigger === WORKFLOW_TRIGGER_TO_ENUM[AFTER_EVENT] || + workflow.trigger === WORKFLOW_TRIGGER_TO_ENUM[AFTER_GUESTS_CAL_VIDEO_NO_SHOW] || + workflow.trigger === WORKFLOW_TRIGGER_TO_ENUM[AFTER_HOSTS_CAL_VIDEO_NO_SHOW] + ? { + type: ENUM_TO_WORKFLOW_TRIGGER[workflow.trigger], + offset: { + value: workflow.time ?? 1, + unit: workflow.timeUnit ? ENUM_TO_TIME_UNIT[workflow.timeUnit] : HOUR, + }, + } + : { type: ENUM_TO_WORKFLOW_TRIGGER[workflow.trigger] }; + + const steps: WorkflowStepOutputDto[] = workflow.steps.map((step) => { + let recipient: RecipientType; + let email = ""; + let phone = ""; + let text; + let html; + switch (ENUM_TO_STEP_ACTIONS[step.action]) { + case EMAIL_HOST: + recipient = HOST; + html = step.reminderBody ?? ""; + break; + case EMAIL_ATTENDEE: + html = step.reminderBody ?? ""; + recipient = ATTENDEE; + break; + case SMS_ATTENDEE: + text = step.reminderBody ?? ""; + recipient = ATTENDEE; + break; + case WHATSAPP_ATTENDEE: + text = step.reminderBody ?? ""; + recipient = ATTENDEE; + break; + case EMAIL_ADDRESS: + html = step.reminderBody ?? ""; + recipient = EMAIL; + email = step.sendTo ?? ""; + break; + case SMS_NUMBER: + case WHATSAPP_NUMBER: + text = step.reminderBody ?? ""; + recipient = PHONE_NUMBER; + phone = step.sendTo ?? ""; + break; + default: + recipient = ATTENDEE; + } + + return { + id: step.id, + stepNumber: step.stepNumber, + action: ENUM_TO_STEP_ACTIONS[step.action], + recipient: recipient, + email, + phone, + template: ENUM_TO_TEMPLATES[step.template], + includeCalendarEvent: step.includeCalendarEvent, + sender: step.sender ?? "Default Sender", + message: { + subject: step.emailSubject ?? "", + text, + html, + }, + }; + }); + + return { + id: workflow.id, + name: workflow.name, + activation: activation, + trigger: trigger, + steps: steps.sort((stepA, stepB) => stepA.stepNumber - stepB.stepNumber), + }; + } +} diff --git a/apps/api/v2/src/modules/workflows/workflows.repository.ts b/apps/api/v2/src/modules/workflows/workflows.repository.ts new file mode 100644 index 0000000000..411be2f8e8 --- /dev/null +++ b/apps/api/v2/src/modules/workflows/workflows.repository.ts @@ -0,0 +1,82 @@ +import { PrismaReadService } from "@/modules/prisma/prisma-read.service"; +import { PrismaWriteService } from "@/modules/prisma/prisma-write.service"; +import { UserWithProfile } from "@/modules/users/users.repository"; +import { Injectable } from "@nestjs/common"; +import { TimeUnit, Workflow, WorkflowStep, WorkflowTriggerEvents } from "@prisma/client"; + +import { TUpdateInputSchema } from "@calcom/platform-libraries/workflows"; +import { updateWorkflow } from "@calcom/platform-libraries/workflows"; +import { PrismaClient } from "@calcom/prisma"; + +export type WorkflowType = Workflow & { activeOn: { eventTypeId: number }[]; steps: WorkflowStep[] }; + +@Injectable() +export class WorkflowsRepository { + constructor(private readonly dbRead: PrismaReadService, private readonly dbWrite: PrismaWriteService) {} + + async deleteTeamWorkflowById(teamId: number, workflowId: number) { + return await this.dbWrite.prisma.workflow.delete({ where: { id: workflowId, teamId } }); + } + + async getTeamWorkflowById(teamId: number, id: number): Promise { + const workflow = await this.dbRead.prisma.workflow.findUnique({ + where: { + id: id, + teamId: teamId, + }, + include: { + steps: true, + activeOn: { select: { eventTypeId: true } }, + }, + }); + + return workflow; + } + + async getTeamWorkflows(teamId: number, skip: number, take: number): Promise { + const workflows = await this.dbRead.prisma.workflow.findMany({ + where: { + teamId: teamId, + }, + include: { + steps: true, + activeOn: { select: { eventTypeId: true } }, + }, + skip, + take, + }); + + return workflows; + } + + async createTeamWorkflowHusk(teamId: number) { + return this.dbWrite.prisma.workflow.create({ + data: { + name: "", + trigger: WorkflowTriggerEvents.BEFORE_EVENT, + time: 24, + timeUnit: TimeUnit.HOUR, + teamId, + }, + include: { activeOn: true, steps: true }, + }); + } + + async updateTeamWorkflow( + user: UserWithProfile, + teamId: number, + workflowId: number, + data: TUpdateInputSchema + ) { + await updateWorkflow({ + ctx: { + user: { ...user, locale: user?.locale ?? "en" }, + prisma: this.dbWrite.prisma as unknown as PrismaClient, + }, + input: data, + }); + + const workflow = await this.getTeamWorkflowById(teamId, workflowId); + return workflow; + } +} diff --git a/apps/api/v2/swagger/documentation.json b/apps/api/v2/swagger/documentation.json index eb450cbca7..71e0cb3d29 100644 --- a/apps/api/v2/swagger/documentation.json +++ b/apps/api/v2/swagger/documentation.json @@ -5071,6 +5071,360 @@ ] } }, + "/v2/organizations/{orgId}/teams/{teamId}/workflows": { + "get": { + "operationId": "OrganizationTeamWorkflowsController_getWorkflows", + "summary": "Get organization team workflows", + "parameters": [ + { + "name": "Authorization", + "in": "header", + "description": "For non-platform customers - value must be `Bearer ` where `` is api key prefixed with cal_", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "x-cal-secret-key", + "in": "header", + "description": "For platform customers - OAuth client secret key", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "x-cal-client-id", + "in": "header", + "description": "For platform customers - OAuth client ID", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "orgId", + "required": true, + "in": "path", + "schema": { + "type": "number" + } + }, + { + "name": "teamId", + "required": true, + "in": "path", + "schema": { + "type": "number" + } + }, + { + "name": "take", + "required": false, + "in": "query", + "description": "Maximum number of items to return", + "example": 25, + "schema": { + "minimum": 1, + "maximum": 250, + "default": 250, + "type": "number" + } + }, + { + "name": "skip", + "required": false, + "in": "query", + "description": "Number of items to skip", + "example": 0, + "schema": { + "minimum": 0, + "default": 0, + "type": "number" + } + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GetWorkflowsOutput" + } + } + } + } + }, + "tags": [ + "Orgs / Teams / Workflows" + ] + }, + "post": { + "operationId": "OrganizationTeamWorkflowsController_createWorkflow", + "summary": "Create organization team workflow", + "parameters": [ + { + "name": "Authorization", + "in": "header", + "description": "For non-platform customers - value must be `Bearer ` where `` is api key prefixed with cal_", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "x-cal-secret-key", + "in": "header", + "description": "For platform customers - OAuth client secret key", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "x-cal-client-id", + "in": "header", + "description": "For platform customers - OAuth client ID", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "teamId", + "required": true, + "in": "path", + "schema": { + "type": "number" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateWorkflowDto" + } + } + } + }, + "responses": { + "201": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GetWorkflowOutput" + } + } + } + } + }, + "tags": [ + "Orgs / Teams / Workflows" + ] + } + }, + "/v2/organizations/{orgId}/teams/{teamId}/workflows/{workflowId}": { + "get": { + "operationId": "OrganizationTeamWorkflowsController_getWorkflowById", + "summary": "Get organization team workflow", + "parameters": [ + { + "name": "Authorization", + "in": "header", + "description": "For non-platform customers - value must be `Bearer ` where `` is api key prefixed with cal_", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "x-cal-secret-key", + "in": "header", + "description": "For platform customers - OAuth client secret key", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "x-cal-client-id", + "in": "header", + "description": "For platform customers - OAuth client ID", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "teamId", + "required": true, + "in": "path", + "schema": { + "type": "number" + } + }, + { + "name": "workflowId", + "required": true, + "in": "path", + "schema": { + "type": "number" + } + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GetWorkflowOutput" + } + } + } + } + }, + "tags": [ + "Orgs / Teams / Workflows" + ] + }, + "patch": { + "operationId": "OrganizationTeamWorkflowsController_updateWorkflow", + "summary": "Update workflow", + "parameters": [ + { + "name": "Authorization", + "in": "header", + "description": "For non-platform customers - value must be `Bearer ` where `` is api key prefixed with cal_", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "x-cal-secret-key", + "in": "header", + "description": "For platform customers - OAuth client secret key", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "x-cal-client-id", + "in": "header", + "description": "For platform customers - OAuth client ID", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "teamId", + "required": true, + "in": "path", + "schema": { + "type": "number" + } + }, + { + "name": "workflowId", + "required": true, + "in": "path", + "schema": { + "type": "number" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateWorkflowDto" + } + } + } + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GetWorkflowOutput" + } + } + } + } + }, + "tags": [ + "Orgs / Teams / Workflows" + ] + }, + "delete": { + "operationId": "OrganizationTeamWorkflowsController_deleteWorkflow", + "summary": "Delete organization team workflow", + "parameters": [ + { + "name": "Authorization", + "in": "header", + "description": "For non-platform customers - value must be `Bearer ` where `` is api key prefixed with cal_", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "x-cal-secret-key", + "in": "header", + "description": "For platform customers - OAuth client secret key", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "x-cal-client-id", + "in": "header", + "description": "For platform customers - OAuth client ID", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "teamId", + "required": true, + "in": "path", + "schema": { + "type": "number" + } + }, + { + "name": "workflowId", + "required": true, + "in": "path", + "schema": { + "type": "number" + } + } + ], + "responses": { + "200": { + "description": "" + } + }, + "tags": [ + "Orgs / Teams / Workflows" + ] + } + }, "/v2/organizations/{orgId}/users": { "get": { "operationId": "OrganizationsUsersController_getOrganizationsUsers", @@ -21059,6 +21413,426 @@ } } }, + "WorkflowActivationOutputDto": { + "type": "object", + "properties": { + "isActiveOnAllEventTypes": { + "type": "boolean", + "default": false, + "description": "Whether the workflow is active for all event types associated with the team/user", + "example": false + }, + "activeOnEventTypeIds": { + "description": "List of Event Type IDs the workflow is specifically active on (if not active on all)", + "example": [ + 698191, + 698192 + ], + "type": "array", + "items": { + "type": "number" + } + } + } + }, + "WorkflowTriggerOffsetOutputDto": { + "type": "object", + "properties": { + "value": { + "type": "number", + "description": "Time value for offset", + "example": 24 + }, + "unit": { + "type": "string", + "description": "Unit for the offset time", + "example": "hour", + "enum": [ + "hour", + "minute", + "day" + ] + } + }, + "required": [ + "value", + "unit" + ] + }, + "WorkflowTriggerOutputDto": { + "type": "object", + "properties": { + "type": { + "type": "string", + "description": "Trigger type for the workflow", + "example": "beforeEvent", + "enum": [ + "beforeEvent", + "eventCancelled", + "newEvent", + "afterEvent", + "rescheduleEvent", + "afterHostsCalVideoNoShow", + "afterGuestsCalVideoNoShow" + ] + }, + "offset": { + "description": "Offset details (present for BEFORE_EVENT/AFTER_EVENT)", + "allOf": [ + { + "$ref": "#/components/schemas/WorkflowTriggerOffsetOutputDto" + } + ] + } + }, + "required": [ + "type" + ] + }, + "WorkflowMessageOutputDto": { + "type": "object", + "properties": { + "subject": { + "type": "string", + "description": "Subject of the message", + "example": "Reminder: Your Meeting {EVENT_NAME} - {EVENT_DATE_ddd, MMM D, YYYY h:mma} with Cal.com" + }, + "html": { + "type": "string", + "description": "HTML content of the message", + "example": "

Reminder for {EVENT_NAME}.

" + }, + "text": { + "type": "string", + "description": "Text content of the message (used for SMS/WhatsApp)", + "example": "Reminder for {EVENT_NAME}." + } + }, + "required": [ + "subject" + ] + }, + "WorkflowStepOutputDto": { + "type": "object", + "properties": { + "id": { + "type": "number", + "description": "Unique identifier of the step", + "example": 67244 + }, + "stepNumber": { + "type": "number", + "description": "Step number in the workflow sequence", + "example": 1 + }, + "action": { + "type": "string", + "description": "Action to perform", + "example": "email_host", + "enum": [ + "email_host", + "email_attendee", + "email_address", + "sms_attendee", + "sms_number", + "whatsapp_attendee", + "whatsapp_number" + ] + }, + "recipient": { + "type": "string", + "description": "Intended recipient type", + "example": "const", + "enum": [ + "const", + "attendee", + "email", + "phone_number" + ] + }, + "email": { + "type": "string", + "description": "Verified Email if action is EMAIL_ADDRESS", + "example": 31214 + }, + "phone": { + "type": "string", + "description": "Verified Phone if action is SMS_NUMBER or WHATSAPP_NUMBER" + }, + "template": { + "type": "string", + "description": "Template type used", + "example": "reminder", + "enum": [ + "reminder", + "custom", + "rescheduled", + "completed", + "rating", + "cancelled" + ] + }, + "includeCalendarEvent": { + "type": "object", + "default": false, + "description": "Whether a calendar event (.ics) was included (for email actions)", + "example": true + }, + "sender": { + "type": "string", + "description": "Displayed sender name used for this step", + "example": "Cal.com Notifications" + }, + "message": { + "description": "Message content for this step", + "allOf": [ + { + "$ref": "#/components/schemas/WorkflowMessageOutputDto" + } + ] + } + }, + "required": [ + "id", + "stepNumber", + "action", + "recipient", + "template", + "sender", + "message" + ] + }, + "WorkflowOutput": { + "type": "object", + "properties": { + "id": { + "type": "number", + "description": "Unique identifier of the workflow", + "example": 101 + }, + "name": { + "type": "string", + "description": "Name of the workflow", + "example": "Platform Test Workflow" + }, + "userId": { + "type": "number", + "description": "ID of the user who owns the workflow (if not team-owned)", + "example": 2313 + }, + "teamId": { + "type": "number", + "description": "ID of the team owning the workflow", + "example": 4214321 + }, + "activation": { + "description": "Activation settings (scope)", + "allOf": [ + { + "$ref": "#/components/schemas/WorkflowActivationOutputDto" + } + ] + }, + "trigger": { + "description": "Trigger configuration", + "allOf": [ + { + "$ref": "#/components/schemas/WorkflowTriggerOutputDto" + } + ] + }, + "steps": { + "description": "Steps comprising the workflow", + "type": "array", + "items": { + "$ref": "#/components/schemas/WorkflowStepOutputDto" + } + }, + "createdAt": { + "type": "object", + "description": "Timestamp of creation", + "example": "2024-05-12T10:00:00.000Z" + }, + "updatedAt": { + "type": "object", + "description": "Timestamp of last update", + "example": "2024-05-12T11:30:00.000Z" + } + }, + "required": [ + "id", + "name", + "activation", + "trigger", + "steps" + ] + }, + "GetWorkflowsOutput": { + "type": "object", + "properties": { + "status": { + "type": "string", + "description": "Indicates the status of the response", + "example": "success", + "enum": [ + "success", + "error" + ] + }, + "data": { + "description": "List of workflows", + "type": "array", + "items": { + "$ref": "#/components/schemas/WorkflowOutput" + } + } + }, + "required": [ + "status", + "data" + ] + }, + "GetWorkflowOutput": { + "type": "object", + "properties": { + "status": { + "type": "string", + "description": "Indicates the status of the response", + "example": "success", + "enum": [ + "success", + "error" + ] + }, + "data": { + "description": "workflow", + "type": "array", + "items": { + "$ref": "#/components/schemas/WorkflowOutput" + } + } + }, + "required": [ + "status", + "data" + ] + }, + "WorkflowActivationDto": { + "type": "object", + "properties": { + "isActiveOnAllEventTypes": { + "type": "boolean", + "default": false, + "description": "Whether the workflow is active for all the event-types", + "example": false + }, + "activeOnEventTypeIds": { + "default": [], + "description": "List of event-types IDs the workflow applies to, required if isActiveOnAllEventTypes is false", + "example": [ + 698191 + ], + "type": "array", + "items": { + "type": "number" + } + } + }, + "required": [ + "isActiveOnAllEventTypes" + ] + }, + "CreateWorkflowDto": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Name of the workflow", + "example": "Platform Test Workflow" + }, + "activation": { + "description": "Activation settings for the workflow", + "allOf": [ + { + "$ref": "#/components/schemas/WorkflowActivationDto" + } + ] + }, + "trigger": { + "type": "object", + "description": "Trigger configuration for the workflow", + "items": { + "oneOf": [ + { + "$ref": "#/components/schemas/OnBeforeEventTriggerDto" + }, + { + "$ref": "#/components/schemas/OnAfterEventTriggerDto" + }, + { + "$ref": "#/components/schemas/OnCancelTriggerDto" + }, + { + "$ref": "#/components/schemas/OnCreationTriggerDto" + }, + { + "$ref": "#/components/schemas/OnRescheduleTriggerDto" + }, + { + "$ref": "#/components/schemas/OnAfterCalVideoGuestsNoShowTriggerDto" + }, + { + "$ref": "#/components/schemas/OnAfterCalVideoHostsNoShowTriggerDto" + } + ] + } + }, + "steps": { + "description": "Steps to execute as part of the workflow", + "items": { + "type": "object" + }, + "type": "array" + } + }, + "required": [ + "name", + "activation", + "trigger", + "steps" + ] + }, + "UpdateWorkflowDto": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Name of the workflow", + "example": "Platform Test Workflow" + }, + "activation": { + "description": "Activation settings for the workflow, the action that will trigger the workflow.", + "allOf": [ + { + "$ref": "#/components/schemas/WorkflowActivationDto" + } + ] + }, + "steps": { + "description": "Steps to execute as part of the workflow", + "items": { + "type": "object" + }, + "type": "array" + }, + "trigger": { + "type": "object" + } + }, + "required": [ + "trigger" + ] + }, "StripConnectOutputDto": { "type": "object", "properties": { diff --git a/apps/api/v2/test/fixtures/repository/verified-resources.repository.fixture.ts b/apps/api/v2/test/fixtures/repository/verified-resources.repository.fixture.ts index 72c8b1722a..763ccb02c9 100644 --- a/apps/api/v2/test/fixtures/repository/verified-resources.repository.fixture.ts +++ b/apps/api/v2/test/fixtures/repository/verified-resources.repository.fixture.ts @@ -16,6 +16,10 @@ export class VerifiedResourcesRepositoryFixtures { return this.prismaWriteClient.verifiedNumber.create({ data }); } + async createEmail(data: Prisma.VerifiedEmailCreateInput) { + return this.prismaWriteClient.verifiedEmail.create({ data }); + } + async deleteEmailById(id: number) { return this.prismaWriteClient.verifiedEmail.delete({ where: { id } }); } diff --git a/apps/api/v2/tsconfig.json b/apps/api/v2/tsconfig.json index 0b64e49d82..947a676283 100644 --- a/apps/api/v2/tsconfig.json +++ b/apps/api/v2/tsconfig.json @@ -23,7 +23,8 @@ "@calcom/platform-libraries/slots": ["../../../packages/platform/libraries/slots.ts"], "@calcom/platform-libraries/emails": ["../../../packages/platform/libraries/emails.ts"], "@calcom/platform-libraries/schedules": ["../../../packages/platform/libraries/schedules.ts"], - "@calcom/platform-libraries/app-store": ["../../../packages/platform/libraries/app-store.ts"] + "@calcom/platform-libraries/app-store": ["../../../packages/platform/libraries/app-store.ts"], + "@calcom/platform-libraries/workflows": ["../../../packages/platform/libraries/workflows.ts"] }, "incremental": true, "skipLibCheck": true, diff --git a/docs/api-reference/v2/openapi.json b/docs/api-reference/v2/openapi.json index e75f7b0c77..e248185be3 100644 --- a/docs/api-reference/v2/openapi.json +++ b/docs/api-reference/v2/openapi.json @@ -4855,6 +4855,350 @@ "tags": ["Orgs / Teams / Users / Schedules"] } }, + "/v2/organizations/{orgId}/teams/{teamId}/workflows": { + "get": { + "operationId": "OrganizationTeamWorkflowsController_getWorkflows", + "summary": "Get organization team workflows", + "parameters": [ + { + "name": "Authorization", + "in": "header", + "description": "For non-platform customers - value must be `Bearer ` where `` is api key prefixed with cal_", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "x-cal-secret-key", + "in": "header", + "description": "For platform customers - OAuth client secret key", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "x-cal-client-id", + "in": "header", + "description": "For platform customers - OAuth client ID", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "orgId", + "required": true, + "in": "path", + "schema": { + "type": "number" + } + }, + { + "name": "teamId", + "required": true, + "in": "path", + "schema": { + "type": "number" + } + }, + { + "name": "take", + "required": false, + "in": "query", + "description": "Maximum number of items to return", + "example": 25, + "schema": { + "minimum": 1, + "maximum": 250, + "default": 250, + "type": "number" + } + }, + { + "name": "skip", + "required": false, + "in": "query", + "description": "Number of items to skip", + "example": 0, + "schema": { + "minimum": 0, + "default": 0, + "type": "number" + } + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GetWorkflowsOutput" + } + } + } + } + }, + "tags": ["Orgs / Teams / Workflows"] + }, + "post": { + "operationId": "OrganizationTeamWorkflowsController_createWorkflow", + "summary": "Create organization team workflow", + "parameters": [ + { + "name": "Authorization", + "in": "header", + "description": "For non-platform customers - value must be `Bearer ` where `` is api key prefixed with cal_", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "x-cal-secret-key", + "in": "header", + "description": "For platform customers - OAuth client secret key", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "x-cal-client-id", + "in": "header", + "description": "For platform customers - OAuth client ID", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "teamId", + "required": true, + "in": "path", + "schema": { + "type": "number" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateWorkflowDto" + } + } + } + }, + "responses": { + "201": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GetWorkflowOutput" + } + } + } + } + }, + "tags": ["Orgs / Teams / Workflows"] + } + }, + "/v2/organizations/{orgId}/teams/{teamId}/workflows/{workflowId}": { + "get": { + "operationId": "OrganizationTeamWorkflowsController_getWorkflowById", + "summary": "Get organization team workflow", + "parameters": [ + { + "name": "Authorization", + "in": "header", + "description": "For non-platform customers - value must be `Bearer ` where `` is api key prefixed with cal_", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "x-cal-secret-key", + "in": "header", + "description": "For platform customers - OAuth client secret key", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "x-cal-client-id", + "in": "header", + "description": "For platform customers - OAuth client ID", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "teamId", + "required": true, + "in": "path", + "schema": { + "type": "number" + } + }, + { + "name": "workflowId", + "required": true, + "in": "path", + "schema": { + "type": "number" + } + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GetWorkflowOutput" + } + } + } + } + }, + "tags": ["Orgs / Teams / Workflows"] + }, + "patch": { + "operationId": "OrganizationTeamWorkflowsController_updateWorkflow", + "summary": "Update workflow", + "parameters": [ + { + "name": "Authorization", + "in": "header", + "description": "For non-platform customers - value must be `Bearer ` where `` is api key prefixed with cal_", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "x-cal-secret-key", + "in": "header", + "description": "For platform customers - OAuth client secret key", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "x-cal-client-id", + "in": "header", + "description": "For platform customers - OAuth client ID", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "teamId", + "required": true, + "in": "path", + "schema": { + "type": "number" + } + }, + { + "name": "workflowId", + "required": true, + "in": "path", + "schema": { + "type": "number" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateWorkflowDto" + } + } + } + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GetWorkflowOutput" + } + } + } + } + }, + "tags": ["Orgs / Teams / Workflows"] + }, + "delete": { + "operationId": "OrganizationTeamWorkflowsController_deleteWorkflow", + "summary": "Delete organization team workflow", + "parameters": [ + { + "name": "Authorization", + "in": "header", + "description": "For non-platform customers - value must be `Bearer ` where `` is api key prefixed with cal_", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "x-cal-secret-key", + "in": "header", + "description": "For platform customers - OAuth client secret key", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "x-cal-client-id", + "in": "header", + "description": "For platform customers - OAuth client ID", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "teamId", + "required": true, + "in": "path", + "schema": { + "type": "number" + } + }, + { + "name": "workflowId", + "required": true, + "in": "path", + "schema": { + "type": "number" + } + } + ], + "responses": { + "200": { + "description": "" + } + }, + "tags": ["Orgs / Teams / Workflows"] + } + }, "/v2/organizations/{orgId}/users": { "get": { "operationId": "OrganizationsUsersController_getOrganizationsUsers", @@ -19406,6 +19750,363 @@ } } }, + "WorkflowActivationOutputDto": { + "type": "object", + "properties": { + "isActiveOnAllEventTypes": { + "type": "boolean", + "default": false, + "description": "Whether the workflow is active for all event types associated with the team/user", + "example": false + }, + "activeOnEventTypeIds": { + "description": "List of Event Type IDs the workflow is specifically active on (if not active on all)", + "example": [698191, 698192], + "type": "array", + "items": { + "type": "number" + } + } + } + }, + "WorkflowTriggerOffsetOutputDto": { + "type": "object", + "properties": { + "value": { + "type": "number", + "description": "Time value for offset", + "example": 24 + }, + "unit": { + "type": "string", + "description": "Unit for the offset time", + "example": "hour", + "enum": ["hour", "minute", "day"] + } + }, + "required": ["value", "unit"] + }, + "WorkflowTriggerOutputDto": { + "type": "object", + "properties": { + "type": { + "type": "string", + "description": "Trigger type for the workflow", + "example": "beforeEvent", + "enum": [ + "beforeEvent", + "eventCancelled", + "newEvent", + "afterEvent", + "rescheduleEvent", + "afterHostsCalVideoNoShow", + "afterGuestsCalVideoNoShow" + ] + }, + "offset": { + "description": "Offset details (present for BEFORE_EVENT/AFTER_EVENT)", + "allOf": [ + { + "$ref": "#/components/schemas/WorkflowTriggerOffsetOutputDto" + } + ] + } + }, + "required": ["type"] + }, + "WorkflowMessageOutputDto": { + "type": "object", + "properties": { + "subject": { + "type": "string", + "description": "Subject of the message", + "example": "Reminder: Your Meeting {EVENT_NAME} - {EVENT_DATE_ddd, MMM D, YYYY h:mma} with Cal.com" + }, + "html": { + "type": "string", + "description": "HTML content of the message", + "example": "

Reminder for {EVENT_NAME}.

" + }, + "text": { + "type": "string", + "description": "Text content of the message (used for SMS/WhatsApp)", + "example": "Reminder for {EVENT_NAME}." + } + }, + "required": ["subject"] + }, + "WorkflowStepOutputDto": { + "type": "object", + "properties": { + "id": { + "type": "number", + "description": "Unique identifier of the step", + "example": 67244 + }, + "stepNumber": { + "type": "number", + "description": "Step number in the workflow sequence", + "example": 1 + }, + "action": { + "type": "string", + "description": "Action to perform", + "example": "email_host", + "enum": [ + "email_host", + "email_attendee", + "email_address", + "sms_attendee", + "sms_number", + "whatsapp_attendee", + "whatsapp_number" + ] + }, + "recipient": { + "type": "string", + "description": "Intended recipient type", + "example": "const", + "enum": ["const", "attendee", "email", "phone_number"] + }, + "email": { + "type": "string", + "description": "Verified Email if action is EMAIL_ADDRESS", + "example": 31214 + }, + "phone": { + "type": "string", + "description": "Verified Phone if action is SMS_NUMBER or WHATSAPP_NUMBER" + }, + "template": { + "type": "string", + "description": "Template type used", + "example": "reminder", + "enum": ["reminder", "custom", "rescheduled", "completed", "rating", "cancelled"] + }, + "includeCalendarEvent": { + "type": "object", + "default": false, + "description": "Whether a calendar event (.ics) was included (for email actions)", + "example": true + }, + "sender": { + "type": "string", + "description": "Displayed sender name used for this step", + "example": "Cal.com Notifications" + }, + "message": { + "description": "Message content for this step", + "allOf": [ + { + "$ref": "#/components/schemas/WorkflowMessageOutputDto" + } + ] + } + }, + "required": ["id", "stepNumber", "action", "recipient", "template", "sender", "message"] + }, + "WorkflowOutput": { + "type": "object", + "properties": { + "id": { + "type": "number", + "description": "Unique identifier of the workflow", + "example": 101 + }, + "name": { + "type": "string", + "description": "Name of the workflow", + "example": "Platform Test Workflow" + }, + "userId": { + "type": "number", + "description": "ID of the user who owns the workflow (if not team-owned)", + "example": 2313 + }, + "teamId": { + "type": "number", + "description": "ID of the team owning the workflow", + "example": 4214321 + }, + "activation": { + "description": "Activation settings (scope)", + "allOf": [ + { + "$ref": "#/components/schemas/WorkflowActivationOutputDto" + } + ] + }, + "trigger": { + "description": "Trigger configuration", + "allOf": [ + { + "$ref": "#/components/schemas/WorkflowTriggerOutputDto" + } + ] + }, + "steps": { + "description": "Steps comprising the workflow", + "type": "array", + "items": { + "$ref": "#/components/schemas/WorkflowStepOutputDto" + } + }, + "createdAt": { + "type": "object", + "description": "Timestamp of creation", + "example": "2024-05-12T10:00:00.000Z" + }, + "updatedAt": { + "type": "object", + "description": "Timestamp of last update", + "example": "2024-05-12T11:30:00.000Z" + } + }, + "required": ["id", "name", "activation", "trigger", "steps"] + }, + "GetWorkflowsOutput": { + "type": "object", + "properties": { + "status": { + "type": "string", + "description": "Indicates the status of the response", + "example": "success", + "enum": ["success", "error"] + }, + "data": { + "description": "List of workflows", + "type": "array", + "items": { + "$ref": "#/components/schemas/WorkflowOutput" + } + } + }, + "required": ["status", "data"] + }, + "GetWorkflowOutput": { + "type": "object", + "properties": { + "status": { + "type": "string", + "description": "Indicates the status of the response", + "example": "success", + "enum": ["success", "error"] + }, + "data": { + "description": "workflow", + "type": "array", + "items": { + "$ref": "#/components/schemas/WorkflowOutput" + } + } + }, + "required": ["status", "data"] + }, + "WorkflowActivationDto": { + "type": "object", + "properties": { + "isActiveOnAllEventTypes": { + "type": "boolean", + "default": false, + "description": "Whether the workflow is active for all the event-types", + "example": false + }, + "activeOnEventTypeIds": { + "default": [], + "description": "List of event-types IDs the workflow applies to, required if isActiveOnAllEventTypes is false", + "example": [698191], + "type": "array", + "items": { + "type": "number" + } + } + }, + "required": ["isActiveOnAllEventTypes"] + }, + "CreateWorkflowDto": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Name of the workflow", + "example": "Platform Test Workflow" + }, + "activation": { + "description": "Activation settings for the workflow", + "allOf": [ + { + "$ref": "#/components/schemas/WorkflowActivationDto" + } + ] + }, + "trigger": { + "type": "object", + "description": "Trigger configuration for the workflow", + "items": { + "oneOf": [ + { + "$ref": "#/components/schemas/OnBeforeEventTriggerDto" + }, + { + "$ref": "#/components/schemas/OnAfterEventTriggerDto" + }, + { + "$ref": "#/components/schemas/OnCancelTriggerDto" + }, + { + "$ref": "#/components/schemas/OnCreationTriggerDto" + }, + { + "$ref": "#/components/schemas/OnRescheduleTriggerDto" + }, + { + "$ref": "#/components/schemas/OnAfterCalVideoGuestsNoShowTriggerDto" + }, + { + "$ref": "#/components/schemas/OnAfterCalVideoHostsNoShowTriggerDto" + } + ] + } + }, + "steps": { + "description": "Steps to execute as part of the workflow", + "items": { + "type": "object" + }, + "type": "array" + } + }, + "required": ["name", "activation", "trigger", "steps"] + }, + "UpdateWorkflowDto": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Name of the workflow", + "example": "Platform Test Workflow" + }, + "activation": { + "description": "Activation settings for the workflow, the action that will trigger the workflow.", + "allOf": [ + { + "$ref": "#/components/schemas/WorkflowActivationDto" + } + ] + }, + "steps": { + "description": "Steps to execute as part of the workflow", + "items": { + "type": "object" + }, + "type": "array" + }, + "trigger": { + "type": "object" + } + }, + "required": ["trigger"] + }, "StripConnectOutputDto": { "type": "object", "properties": { diff --git a/packages/platform/libraries/package.json b/packages/platform/libraries/package.json index 3a4f6bdfa5..426f6083bf 100644 --- a/packages/platform/libraries/package.json +++ b/packages/platform/libraries/package.json @@ -29,6 +29,11 @@ "vite-plugin-environment": "^1.1.3" }, "exports": { + "./workflows": { + "import": "./dist/workflows.js", + "require": "./dist/workflows.cjs", + "types": "./dist/workflows.d.ts" + }, "./app-store": { "import": "./dist/app-store.js", "require": "./dist/app-store.cjs", @@ -76,6 +81,9 @@ ], "schedules": [ "dist/schedules.d.ts" + ], + "workflows": [ + "dist/workflows.d.ts" ] } } diff --git a/packages/platform/libraries/vite.config.js b/packages/platform/libraries/vite.config.js index 0b56b0596c..743f8b4128 100644 --- a/packages/platform/libraries/vite.config.js +++ b/packages/platform/libraries/vite.config.js @@ -22,6 +22,7 @@ export default defineConfig({ emails: resolve(__dirname, "./emails.ts"), "event-types": resolve(__dirname, "./event-types.ts"), "app-store": resolve(__dirname, "./app-store.ts"), + workflows: resolve(__dirname, "./workflows.ts"), slots: resolve(__dirname, "./slots.ts"), }, name: "calcom-lib", diff --git a/packages/platform/libraries/workflows.ts b/packages/platform/libraries/workflows.ts new file mode 100644 index 0000000000..f8238e8649 --- /dev/null +++ b/packages/platform/libraries/workflows.ts @@ -0,0 +1,2 @@ +export { updateHandler as updateWorkflow } from "@calcom/trpc/server/routers/viewer/workflows/update.handler"; +export type { TUpdateInputSchema } from "@calcom/trpc/server/routers/viewer/workflows/update.schema"; diff --git a/packages/trpc/server/routers/viewer/teams/hasActiveTeamPlan.handler.ts b/packages/trpc/server/routers/viewer/teams/hasActiveTeamPlan.handler.ts index 6dfa9b681e..4ea1c99549 100644 --- a/packages/trpc/server/routers/viewer/teams/hasActiveTeamPlan.handler.ts +++ b/packages/trpc/server/routers/viewer/teams/hasActiveTeamPlan.handler.ts @@ -5,7 +5,7 @@ import type { TrpcSessionUser } from "@calcom/trpc/server/types"; type HasActiveTeamPlanOptions = { ctx: { - user: NonNullable; + user: Pick, "id">; }; }; @@ -28,6 +28,12 @@ export const hasActiveTeamPlanHandler = async ({ ctx }: HasActiveTeamPlanOptions let isTrial = false; // check if user has at least on membership with an active plan for (const team of teams) { + if (team.isPlatform && team.isOrganization) { + const platformBilling = await prisma.platformBilling.findFirst({ where: { id: team.id } }); + if (platformBilling && platformBilling.plan !== "none" && platformBilling.plan !== "FREE") { + return { isActive: true, isTrial: false }; + } + } const teamBillingService = new InternalTeamBilling(team); const subscriptionStatus = await teamBillingService.getSubscriptionStatus(); diff --git a/packages/trpc/server/routers/viewer/workflows/update.handler.ts b/packages/trpc/server/routers/viewer/workflows/update.handler.ts index 59721980d2..a186888d58 100755 --- a/packages/trpc/server/routers/viewer/workflows/update.handler.ts +++ b/packages/trpc/server/routers/viewer/workflows/update.handler.ts @@ -26,7 +26,7 @@ import { type UpdateOptions = { ctx: { - user: NonNullable; + user: Pick, "id" | "metadata" | "locale" | "timeFormat">; prisma: PrismaClient; }; input: TUpdateInputSchema;