refactor: Cal.diy (#28903)
* feat: Cal.diy — community-driven MIT-licensed fork of Cal.com This squashed commit contains all Cal.diy changes applied on top of calcom/cal.com main: - Rebrand Cal.com to Cal.diy across the entire codebase - Remove Enterprise Edition (EE) features, license checks, and AGPL restrictions - Switch license from AGPL-3.0 to MIT - Remove docs/ directory (migrated to Nextra at cal.diy) - Remove dead code: org tests, EE tips, platform nav, premium username, SAML/SSO, etc. - Clean up .env.example for self-hosted Cal.diy - Update Docker image references to calcom/cal.diy - Update README, CONTRIBUTING.md, and issue templates for Cal.diy community fork - Add PR welcome bot for Cal.diy contributors - Fix API v2 breaking changes oasdiff ignore entries - Replace Blacksmith CI runners with default GitHub Actions 3893 files changed, 20789 insertions(+), 411020 deletions(-) Co-Authored-By: [email protected] <[email protected]> * refactor: remove org-specific /organizations/:orgId endpoints from API v2 atoms controllers (#1701) Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix: revert Cal.diy Inc to Cal.com, Inc. in license files, copyright notices, and package metadata (#1702) Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * rip out org related comments in api v2 --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
a17f28e9ab
commit
ab21c7f805
4080 files changed
+14403
-404922
No files matched your search
@@ -46,11 +46,9 @@ STRIPE_WEBHOOK_SECRET=
|
||||
|
||||
# used to know where to direct people when managing platform billing
|
||||
WEB_APP_URL=http://localhost:3000/
|
||||
# to setup license key see apps/api/v2/README.md
|
||||
CALCOM_LICENSE_KEY=
|
||||
# Cal.diy is fully open source — no license key is required.
|
||||
# when request is authenticated with an api key we need to remove the prefix. See code in api-auth.strategy.ts
|
||||
API_KEY_PREFIX=cal_
|
||||
GET_LICENSE_KEY_URL="https://goblin.cal.com/v1/license"
|
||||
# we disable workers when running e2e and enable them while running locally
|
||||
IS_E2E=false
|
||||
DOCS_URL=
|
||||
@@ -74,4 +72,4 @@ REWRITE_API_V2_PREFIX="1"
|
||||
ENABLE_ASYNC_TASKER="false" # set to "true" to enable
|
||||
TRIGGER_SECRET_KEY=
|
||||
TRIGGER_API_URL=https://api.trigger.dev
|
||||
TRIGGER_DEV_PROJECT_REF=
|
||||
TRIGGER_DEV_PROJECT_REF=
|
||||
@@ -1,4 +1,4 @@
|
||||
Cal.com api v2 is a [Nest.js](https://github.com/nestjs/nest) project.
|
||||
Cal.diy api v2 is a [Nest.js](https://github.com/nestjs/nest) project.
|
||||
|
||||
# Local development
|
||||
This setup will allow you to develop with api v2 locally. If you want to also test atoms locally with platform's example app,
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"name": "@calcom/api-v2",
|
||||
"version": "0.0.1",
|
||||
"description": "Platform API for Cal.com",
|
||||
"author": "Cal.com Inc.",
|
||||
"description": "Platform API for Cal.diy",
|
||||
"author": "Cal.com, Inc.",
|
||||
"license": "UNLICENSED",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
|
||||
@@ -12,7 +12,7 @@ import { RateLimitRepositoryFixture } from "test/fixtures/repository/rate-limit.
|
||||
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
|
||||
import { randomString } from "test/utils/randomString";
|
||||
import { AppModule } from "@/app.module";
|
||||
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
|
||||
import { SchedulesModule_2024_04_15 } from "@/platform/schedules/schedules_2024_04_15/schedules.module";
|
||||
import { CustomThrottlerGuard } from "@/lib/throttler-guard";
|
||||
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||
import { TokensModule } from "@/modules/tokens/tokens.module";
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
The Cal.com Commercial License (the “Commercial License”)
|
||||
Copyright (c) 2020-present Cal.com, Inc
|
||||
|
||||
With regard to the Cal.com Software:
|
||||
|
||||
This software and associated documentation files (the "Software") may only be
|
||||
used in production, if you (and any entity that you represent) have agreed to,
|
||||
and are in compliance with, the Cal.com Subscription Terms available
|
||||
at https://cal.com/terms, or other agreements governing
|
||||
the use of the Software, as mutually agreed by you and Cal.com, Inc ("Cal.com"),
|
||||
and otherwise have a valid Cal.com Commercial License ("Commercial License")
|
||||
for the correct number of hosts as defined in the "Commercial Terms ("Hosts"). Subject to the foregoing sentence,
|
||||
you are free to modify this Software and publish patches to the Software. You agree
|
||||
that Cal.com and/or its licensors (as applicable) retain all right, title and interest in
|
||||
and to all such modifications and/or patches, and all such modifications and/or
|
||||
patches may only be used, copied, modified, displayed, distributed, or otherwise
|
||||
exploited with a valid Commercial License for the correct number of hosts.
|
||||
Notwithstanding the foregoing, you may copy and modify the Software for development
|
||||
and testing purposes, without requiring a subscription. You agree that Cal.com and/or
|
||||
its licensors (as applicable) retain all right, title and interest in and to all such
|
||||
modifications. You are not granted any other rights beyond what is expressly stated herein.
|
||||
Subject to the foregoing, it is forbidden to copy, merge, publish, distribute, sublicense,
|
||||
and/or sell the Software.
|
||||
|
||||
This Commercial License applies only to the part of this Software that is not distributed under
|
||||
the AGPLv3 license. Any part of this Software distributed under the MIT license or which
|
||||
is served client-side as an image, font, cascading stylesheet (CSS), file which produces
|
||||
or is compiled, arranged, augmented, or combined into client-side JavaScript, in whole or
|
||||
in part, is copyrighted under the AGPLv3 license. The full text of this Commercial License shall
|
||||
be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
For all third party components incorporated into the Cal.com Software, those
|
||||
components are licensed under the original license provided by the owner of the
|
||||
applicable component.
|
||||
@@ -1,18 +0,0 @@
|
||||
<!-- PROJECT LOGO -->
|
||||
<div align="center">
|
||||
<a href="https://cal.com/enterprise">
|
||||
<img src="https://user-images.githubusercontent.com/8019099/133430653-24422d2a-3c8d-4052-9ad6-0580597151ee.png" alt="Logo">
|
||||
</a>
|
||||
|
||||
<a href="https://go.cal.com/get-license">Get a License Key</a>
|
||||
</div>
|
||||
|
||||
# Commercial License of API
|
||||
|
||||
Welcome to the Commercial License of the Cal.com API.
|
||||
|
||||
Our philosophy is simple, all "Singleplayer APIs" are open-source under AGPLv3. All "Multiplayer APIs" are under a commercial license.
|
||||
|
||||
The [/ee](https://github.com/calcom/cal.com/tree/main/apps/api/v2/ee) subfolder is the place for all the **Commercial License** features from our [hosted](https://cal.com/pricing) plan.
|
||||
|
||||
> _❗ WARNING: This repository is copyrighted (unlike our [main repo](https://github.com/calcom/cal.com)). You are not allowed to use this code to host your own version of app.cal.com without obtaining a proper [license](https://go.cal.com/get-license) first❗_
|
||||
@@ -1,542 +0,0 @@
|
||||
import { SUCCESS_STATUS } from "@calcom/platform-constants";
|
||||
import type { BookingResponse } from "@calcom/platform-libraries";
|
||||
import type { RegularBookingCreateResult } from "@calcom/platform-libraries/bookings";
|
||||
import type { ApiSuccessResponse } from "@calcom/platform-types";
|
||||
import type { PlatformOAuthClient, Team, User } from "@calcom/prisma/client";
|
||||
import { INestApplication } from "@nestjs/common";
|
||||
import { NestExpressApplication } from "@nestjs/platform-express";
|
||||
import { Test } from "@nestjs/testing";
|
||||
import request from "supertest";
|
||||
import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture";
|
||||
import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.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 { BookingsRepositoryFixture } from "test/fixtures/repository/bookings.repository.fixture";
|
||||
import { EventTypesRepositoryFixture } from "test/fixtures/repository/event-types.repository.fixture";
|
||||
import { randomString } from "test/utils/randomString";
|
||||
import { withApiAuth } from "test/utils/withApiAuth";
|
||||
import { AppModule } from "@/app.module";
|
||||
import { bootstrap } from "@/bootstrap";
|
||||
import { CreateBookingInput_2024_04_15 } from "@/ee/bookings/2024-04-15/inputs/create-booking.input";
|
||||
import { CreateRecurringBookingInput_2024_04_15 } from "@/ee/bookings/2024-04-15/inputs/create-recurring-booking.input";
|
||||
import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input";
|
||||
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
|
||||
import { SchedulesService_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/services/schedules.service";
|
||||
import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard";
|
||||
import { BillingService } from "@/modules/billing/services/billing.service";
|
||||
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||
import { UsersModule } from "@/modules/users/users.module";
|
||||
|
||||
const CLIENT_REDIRECT_URI = "http://localhost:4321";
|
||||
|
||||
describe("Bookings Billing E2E - 2024-04-15", () => {
|
||||
describe("Regular user (non-platform-managed)", () => {
|
||||
jest.setTimeout(30000);
|
||||
let app: INestApplication;
|
||||
let userRepositoryFixture: UserRepositoryFixture;
|
||||
let bookingsRepositoryFixture: BookingsRepositoryFixture;
|
||||
let schedulesService: SchedulesService_2024_04_15;
|
||||
let eventTypesRepositoryFixture: EventTypesRepositoryFixture;
|
||||
let billingService: BillingService;
|
||||
let increaseUsageSpy: jest.SpyInstance;
|
||||
let cancelUsageSpy: jest.SpyInstance;
|
||||
|
||||
const userEmail = `billing-regular-user-${randomString()}@api.com`;
|
||||
let user: User;
|
||||
let eventTypeId: number;
|
||||
let recEventTypeId: number;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await withApiAuth(
|
||||
userEmail,
|
||||
Test.createTestingModule({
|
||||
imports: [AppModule, PrismaModule, UsersModule, SchedulesModule_2024_04_15],
|
||||
})
|
||||
)
|
||||
.overrideGuard(PermissionsGuard)
|
||||
.useValue({
|
||||
canActivate: () => true,
|
||||
})
|
||||
.compile();
|
||||
|
||||
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
|
||||
bookingsRepositoryFixture = new BookingsRepositoryFixture(moduleRef);
|
||||
eventTypesRepositoryFixture = new EventTypesRepositoryFixture(moduleRef);
|
||||
schedulesService = moduleRef.get<SchedulesService_2024_04_15>(SchedulesService_2024_04_15);
|
||||
billingService = moduleRef.get<BillingService>(BillingService);
|
||||
|
||||
// Spy on the billing service methods
|
||||
increaseUsageSpy = jest.spyOn(billingService, "increaseUsageByUserId");
|
||||
cancelUsageSpy = jest.spyOn(billingService, "cancelUsageByBookingUid");
|
||||
|
||||
// Create a regular user (not platform-managed)
|
||||
user = await userRepositoryFixture.create({
|
||||
email: userEmail,
|
||||
isPlatformManaged: false,
|
||||
});
|
||||
|
||||
const userSchedule: CreateScheduleInput_2024_04_15 = {
|
||||
name: `billing-test-schedule-${randomString()}`,
|
||||
timeZone: "Europe/Rome",
|
||||
isDefault: true,
|
||||
};
|
||||
await schedulesService.createUserSchedule(user.id, userSchedule);
|
||||
|
||||
const event = await eventTypesRepositoryFixture.create(
|
||||
{
|
||||
title: `billing-test-event-type-${randomString()}`,
|
||||
slug: `billing-test-event-type-${randomString()}`,
|
||||
length: 60,
|
||||
},
|
||||
user.id
|
||||
);
|
||||
eventTypeId = event.id;
|
||||
|
||||
const recEventType = await eventTypesRepositoryFixture.create(
|
||||
{
|
||||
title: `billing-rec-event-type-${randomString()}`,
|
||||
slug: `billing-rec-event-type-${randomString()}`,
|
||||
length: 60,
|
||||
recurringEvent: { freq: 2, count: 4, interval: 1 },
|
||||
},
|
||||
user.id
|
||||
);
|
||||
recEventTypeId = recEventType.id;
|
||||
|
||||
app = moduleRef.createNestApplication();
|
||||
bootstrap(app as NestExpressApplication);
|
||||
await app.init();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await bookingsRepositoryFixture.deleteAllBookings(user.id, user.email);
|
||||
await userRepositoryFixture.deleteByEmail(user.email);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("should NOT call billing service when creating a booking for a regular user", async () => {
|
||||
increaseUsageSpy.mockClear();
|
||||
|
||||
const body: CreateBookingInput_2024_04_15 = {
|
||||
start: "2040-05-21T09:30:00.000Z",
|
||||
end: "2040-05-21T10:30:00.000Z",
|
||||
eventTypeId: eventTypeId,
|
||||
timeZone: "Europe/London",
|
||||
language: "en",
|
||||
metadata: {},
|
||||
hashedLink: "",
|
||||
responses: {
|
||||
name: "Test Attendee",
|
||||
email: "[email protected]",
|
||||
location: {
|
||||
value: "link",
|
||||
optionValue: "",
|
||||
},
|
||||
notes: "test booking for billing",
|
||||
},
|
||||
};
|
||||
|
||||
const response = await request(app.getHttpServer()).post("/v2/bookings").send(body).expect(201);
|
||||
|
||||
const responseBody: ApiSuccessResponse<RegularBookingCreateResult> = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data).toBeDefined();
|
||||
expect(responseBody.data.id).toBeDefined();
|
||||
|
||||
// Verify billing service was NOT called for regular user
|
||||
expect(increaseUsageSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should NOT call billing cancel service when cancelling a booking for a regular user", async () => {
|
||||
// First create a booking
|
||||
const createBody: CreateBookingInput_2024_04_15 = {
|
||||
start: "2040-05-22T09:30:00.000Z",
|
||||
end: "2040-05-22T10:30:00.000Z",
|
||||
eventTypeId: eventTypeId,
|
||||
timeZone: "Europe/London",
|
||||
language: "en",
|
||||
metadata: {},
|
||||
hashedLink: "",
|
||||
responses: {
|
||||
name: "Test Attendee Cancel",
|
||||
email: "[email protected]",
|
||||
location: {
|
||||
value: "link",
|
||||
optionValue: "",
|
||||
},
|
||||
notes: "test booking for cancel billing",
|
||||
},
|
||||
};
|
||||
|
||||
const createResponse = await request(app.getHttpServer())
|
||||
.post("/v2/bookings")
|
||||
.send(createBody)
|
||||
.expect(201);
|
||||
|
||||
const createResponseBody: ApiSuccessResponse<RegularBookingCreateResult> = createResponse.body;
|
||||
const bookingUid = createResponseBody.data.uid;
|
||||
|
||||
// Clear the spy before cancelling
|
||||
cancelUsageSpy.mockClear();
|
||||
|
||||
// Cancel the booking (returns 201 Created)
|
||||
await request(app.getHttpServer()).post(`/v2/bookings/${bookingUid}/cancel`).send({}).expect(201);
|
||||
|
||||
// Verify billing cancel service was NOT called for regular user
|
||||
expect(cancelUsageSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should NOT call billing service when creating recurring bookings for a regular user", async () => {
|
||||
increaseUsageSpy.mockClear();
|
||||
|
||||
const body: CreateRecurringBookingInput_2024_04_15[] = [
|
||||
{
|
||||
start: "2040-06-21T09:30:00.000Z",
|
||||
end: "2040-06-21T10:30:00.000Z",
|
||||
eventTypeId: recEventTypeId,
|
||||
timeZone: "Europe/London",
|
||||
language: "en",
|
||||
metadata: {},
|
||||
hashedLink: "",
|
||||
responses: {
|
||||
name: "Test Attendee Recurring",
|
||||
email: "[email protected]",
|
||||
location: {
|
||||
value: "link",
|
||||
optionValue: "",
|
||||
},
|
||||
notes: "test recurring booking for billing",
|
||||
},
|
||||
recurringEventId: `test-recurring-${randomString()}`,
|
||||
},
|
||||
{
|
||||
start: "2040-06-28T09:30:00.000Z",
|
||||
end: "2040-06-28T10:30:00.000Z",
|
||||
eventTypeId: recEventTypeId,
|
||||
timeZone: "Europe/London",
|
||||
language: "en",
|
||||
metadata: {},
|
||||
hashedLink: "",
|
||||
responses: {
|
||||
name: "Test Attendee Recurring",
|
||||
email: "[email protected]",
|
||||
location: {
|
||||
value: "link",
|
||||
optionValue: "",
|
||||
},
|
||||
notes: "test recurring booking for billing",
|
||||
},
|
||||
recurringEventId: `test-recurring-${randomString()}`,
|
||||
},
|
||||
];
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post("/v2/bookings/recurring")
|
||||
.send(body)
|
||||
.expect(201);
|
||||
|
||||
const responseBody: ApiSuccessResponse<BookingResponse[]> = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data).toBeDefined();
|
||||
expect(responseBody.data.length).toBeGreaterThan(0);
|
||||
|
||||
// Verify billing service was NOT called for regular user recurring bookings
|
||||
expect(increaseUsageSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Platform-managed user", () => {
|
||||
jest.setTimeout(30000);
|
||||
let app: INestApplication;
|
||||
let userRepositoryFixture: UserRepositoryFixture;
|
||||
let bookingsRepositoryFixture: BookingsRepositoryFixture;
|
||||
let schedulesService: SchedulesService_2024_04_15;
|
||||
let eventTypesRepositoryFixture: EventTypesRepositoryFixture;
|
||||
let oauthClientRepositoryFixture: OAuthClientRepositoryFixture;
|
||||
let teamRepositoryFixture: TeamRepositoryFixture;
|
||||
let profilesRepositoryFixture: ProfileRepositoryFixture;
|
||||
let membershipsRepositoryFixture: MembershipRepositoryFixture;
|
||||
let billingService: BillingService;
|
||||
let increaseUsageSpy: jest.SpyInstance;
|
||||
let cancelUsageSpy: jest.SpyInstance;
|
||||
|
||||
const platformAdminEmail = `billing-platform-admin-${randomString()}@api.com`;
|
||||
const managedUserEmail = `billing-managed-user-${randomString()}@api.com`;
|
||||
let platformAdmin: User;
|
||||
let managedUser: User;
|
||||
let organization: Team;
|
||||
let oAuthClient: PlatformOAuthClient;
|
||||
let eventTypeId: number;
|
||||
let recEventTypeId: number;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await withApiAuth(
|
||||
managedUserEmail,
|
||||
Test.createTestingModule({
|
||||
imports: [AppModule, PrismaModule, UsersModule, SchedulesModule_2024_04_15],
|
||||
})
|
||||
)
|
||||
.overrideGuard(PermissionsGuard)
|
||||
.useValue({
|
||||
canActivate: () => true,
|
||||
})
|
||||
.compile();
|
||||
|
||||
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
|
||||
bookingsRepositoryFixture = new BookingsRepositoryFixture(moduleRef);
|
||||
eventTypesRepositoryFixture = new EventTypesRepositoryFixture(moduleRef);
|
||||
schedulesService = moduleRef.get<SchedulesService_2024_04_15>(SchedulesService_2024_04_15);
|
||||
oauthClientRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef);
|
||||
teamRepositoryFixture = new TeamRepositoryFixture(moduleRef);
|
||||
profilesRepositoryFixture = new ProfileRepositoryFixture(moduleRef);
|
||||
membershipsRepositoryFixture = new MembershipRepositoryFixture(moduleRef);
|
||||
billingService = moduleRef.get<BillingService>(BillingService);
|
||||
|
||||
// Spy on the billing service methods
|
||||
increaseUsageSpy = jest.spyOn(billingService, "increaseUsageByUserId");
|
||||
cancelUsageSpy = jest.spyOn(billingService, "cancelUsageByBookingUid");
|
||||
|
||||
// Create platform admin
|
||||
platformAdmin = await userRepositoryFixture.create({ email: platformAdminEmail });
|
||||
|
||||
// Create organization
|
||||
organization = await teamRepositoryFixture.create({
|
||||
name: `billing-test-organization-${randomString()}`,
|
||||
isPlatform: true,
|
||||
isOrganization: true,
|
||||
});
|
||||
|
||||
// Create OAuth client
|
||||
oAuthClient = await oauthClientRepositoryFixture.create(
|
||||
organization.id,
|
||||
{
|
||||
logo: "logo-url",
|
||||
name: "billing-test-oauth-client",
|
||||
redirectUris: [CLIENT_REDIRECT_URI],
|
||||
permissions: 1023,
|
||||
},
|
||||
"secret"
|
||||
);
|
||||
|
||||
// Create profile for platform admin
|
||||
await profilesRepositoryFixture.create({
|
||||
uid: `billing-test-profile-${randomString()}`,
|
||||
username: platformAdminEmail,
|
||||
organization: { connect: { id: organization.id } },
|
||||
user: { connect: { id: platformAdmin.id } },
|
||||
});
|
||||
|
||||
// Create membership for platform admin
|
||||
await membershipsRepositoryFixture.create({
|
||||
role: "OWNER",
|
||||
user: { connect: { id: platformAdmin.id } },
|
||||
team: { connect: { id: organization.id } },
|
||||
accepted: true,
|
||||
});
|
||||
|
||||
// Create a platform-managed user
|
||||
managedUser = await userRepositoryFixture.create({
|
||||
email: managedUserEmail,
|
||||
isPlatformManaged: true,
|
||||
platformOAuthClients: {
|
||||
connect: { id: oAuthClient.id },
|
||||
},
|
||||
});
|
||||
|
||||
// Create profile for managed user
|
||||
await profilesRepositoryFixture.create({
|
||||
uid: `billing-managed-user-profile-${randomString()}`,
|
||||
username: managedUserEmail,
|
||||
organization: { connect: { id: organization.id } },
|
||||
user: { connect: { id: managedUser.id } },
|
||||
});
|
||||
|
||||
// Create membership for managed user
|
||||
await membershipsRepositoryFixture.create({
|
||||
role: "MEMBER",
|
||||
user: { connect: { id: managedUser.id } },
|
||||
team: { connect: { id: organization.id } },
|
||||
accepted: true,
|
||||
});
|
||||
|
||||
const userSchedule: CreateScheduleInput_2024_04_15 = {
|
||||
name: `billing-managed-user-schedule-${randomString()}`,
|
||||
timeZone: "Europe/Rome",
|
||||
isDefault: true,
|
||||
};
|
||||
await schedulesService.createUserSchedule(managedUser.id, userSchedule);
|
||||
|
||||
const event = await eventTypesRepositoryFixture.create(
|
||||
{
|
||||
title: `billing-managed-user-event-type-${randomString()}`,
|
||||
slug: `billing-managed-user-event-type-${randomString()}`,
|
||||
length: 60,
|
||||
},
|
||||
managedUser.id
|
||||
);
|
||||
eventTypeId = event.id;
|
||||
|
||||
const recEventType = await eventTypesRepositoryFixture.create(
|
||||
{
|
||||
title: `billing-managed-rec-event-type-${randomString()}`,
|
||||
slug: `billing-managed-rec-event-type-${randomString()}`,
|
||||
length: 60,
|
||||
recurringEvent: { freq: 2, count: 4, interval: 1 },
|
||||
},
|
||||
managedUser.id
|
||||
);
|
||||
recEventTypeId = recEventType.id;
|
||||
|
||||
app = moduleRef.createNestApplication();
|
||||
bootstrap(app as NestExpressApplication);
|
||||
await app.init();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await bookingsRepositoryFixture.deleteAllBookings(managedUser.id, managedUser.email);
|
||||
await userRepositoryFixture.deleteByEmail(managedUser.email);
|
||||
await userRepositoryFixture.deleteByEmail(platformAdmin.email);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("should call billing service when creating a booking for a platform-managed user", async () => {
|
||||
increaseUsageSpy.mockClear();
|
||||
|
||||
const body: CreateBookingInput_2024_04_15 = {
|
||||
start: "2040-05-21T09:30:00.000Z",
|
||||
end: "2040-05-21T10:30:00.000Z",
|
||||
eventTypeId: eventTypeId,
|
||||
timeZone: "Europe/London",
|
||||
language: "en",
|
||||
metadata: {},
|
||||
hashedLink: "",
|
||||
responses: {
|
||||
name: "Test Attendee",
|
||||
email: "[email protected]",
|
||||
location: {
|
||||
value: "link",
|
||||
optionValue: "",
|
||||
},
|
||||
notes: "test booking for billing",
|
||||
},
|
||||
};
|
||||
|
||||
const response = await request(app.getHttpServer()).post("/v2/bookings").send(body).expect(201);
|
||||
|
||||
const responseBody: ApiSuccessResponse<RegularBookingCreateResult> = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data).toBeDefined();
|
||||
expect(responseBody.data.id).toBeDefined();
|
||||
|
||||
// Verify billing service WAS called for platform-managed user
|
||||
expect(increaseUsageSpy).toHaveBeenCalledTimes(1);
|
||||
expect(increaseUsageSpy).toHaveBeenCalledWith(
|
||||
managedUser.id,
|
||||
expect.objectContaining({
|
||||
uid: responseBody.data.uid,
|
||||
startTime: expect.any(Date),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should call billing cancel service when cancelling a booking for a platform-managed user", async () => {
|
||||
// First create a booking
|
||||
const createBody: CreateBookingInput_2024_04_15 = {
|
||||
start: "2040-05-22T09:30:00.000Z",
|
||||
end: "2040-05-22T10:30:00.000Z",
|
||||
eventTypeId: eventTypeId,
|
||||
timeZone: "Europe/London",
|
||||
language: "en",
|
||||
metadata: {},
|
||||
hashedLink: "",
|
||||
responses: {
|
||||
name: "Test Attendee Cancel",
|
||||
email: "[email protected]",
|
||||
location: {
|
||||
value: "link",
|
||||
optionValue: "",
|
||||
},
|
||||
notes: "test booking for cancel billing",
|
||||
},
|
||||
};
|
||||
|
||||
const createResponse = await request(app.getHttpServer())
|
||||
.post("/v2/bookings")
|
||||
.send(createBody)
|
||||
.expect(201);
|
||||
|
||||
const createResponseBody: ApiSuccessResponse<RegularBookingCreateResult> = createResponse.body;
|
||||
const bookingUid = createResponseBody.data.uid;
|
||||
|
||||
// Clear the spy before cancelling
|
||||
cancelUsageSpy.mockClear();
|
||||
|
||||
// Cancel the booking (returns 201 Created)
|
||||
await request(app.getHttpServer()).post(`/v2/bookings/${bookingUid}/cancel`).send({}).expect(201);
|
||||
|
||||
// Verify billing cancel service WAS called for platform-managed user
|
||||
expect(cancelUsageSpy).toHaveBeenCalledTimes(1);
|
||||
expect(cancelUsageSpy).toHaveBeenCalledWith(bookingUid);
|
||||
});
|
||||
|
||||
it("should call billing service when creating recurring bookings for a platform-managed user", async () => {
|
||||
increaseUsageSpy.mockClear();
|
||||
|
||||
const body: CreateRecurringBookingInput_2024_04_15[] = [
|
||||
{
|
||||
start: "2040-06-21T09:30:00.000Z",
|
||||
end: "2040-06-21T10:30:00.000Z",
|
||||
eventTypeId: recEventTypeId,
|
||||
timeZone: "Europe/London",
|
||||
language: "en",
|
||||
metadata: {},
|
||||
hashedLink: "",
|
||||
responses: {
|
||||
name: "Test Attendee Recurring Managed",
|
||||
email: "[email protected]",
|
||||
location: {
|
||||
value: "link",
|
||||
optionValue: "",
|
||||
},
|
||||
notes: "test recurring booking for billing",
|
||||
},
|
||||
recurringEventId: `test-recurring-managed-${randomString()}`,
|
||||
},
|
||||
{
|
||||
start: "2040-06-28T09:30:00.000Z",
|
||||
end: "2040-06-28T10:30:00.000Z",
|
||||
eventTypeId: recEventTypeId,
|
||||
timeZone: "Europe/London",
|
||||
language: "en",
|
||||
metadata: {},
|
||||
hashedLink: "",
|
||||
responses: {
|
||||
name: "Test Attendee Recurring Managed",
|
||||
email: "[email protected]",
|
||||
location: {
|
||||
value: "link",
|
||||
optionValue: "",
|
||||
},
|
||||
notes: "test recurring booking for billing",
|
||||
},
|
||||
recurringEventId: `test-recurring-managed-${randomString()}`,
|
||||
},
|
||||
];
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post("/v2/bookings/recurring")
|
||||
.send(body)
|
||||
.expect(201);
|
||||
|
||||
const responseBody: ApiSuccessResponse<BookingResponse[]> = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data).toBeDefined();
|
||||
expect(responseBody.data.length).toBeGreaterThan(0);
|
||||
|
||||
// Verify billing service WAS called for platform-managed user recurring bookings
|
||||
// Should be called once for each booking created
|
||||
expect(increaseUsageSpy).toHaveBeenCalledTimes(responseBody.data.length);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,462 +0,0 @@
|
||||
import { CAL_API_VERSION_HEADER, SUCCESS_STATUS, VERSION_2024_06_14 } from "@calcom/platform-constants";
|
||||
import {
|
||||
ApiSuccessResponse,
|
||||
CreateEventTypeInput_2024_06_14,
|
||||
EventTypeOutput_2024_06_14,
|
||||
} from "@calcom/platform-types";
|
||||
import type { PlatformOAuthClient, Team, User } from "@calcom/prisma/client";
|
||||
import { INestApplication } from "@nestjs/common";
|
||||
import { NestExpressApplication } from "@nestjs/platform-express";
|
||||
import { Test } from "@nestjs/testing";
|
||||
import request from "supertest";
|
||||
import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture";
|
||||
import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.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 { randomString } from "test/utils/randomString";
|
||||
import { AppModule } from "@/app.module";
|
||||
import { bootstrap } from "@/bootstrap";
|
||||
import { CreateBookingInput_2024_04_15 } from "@/ee/bookings/2024-04-15/inputs/create-booking.input";
|
||||
import {
|
||||
GetBookingsDataEntry,
|
||||
GetBookingsOutput_2024_04_15,
|
||||
} from "@/ee/bookings/2024-04-15/outputs/get-bookings.output";
|
||||
import { HttpExceptionFilter } from "@/filters/http-exception.filter";
|
||||
import { PrismaExceptionFilter } from "@/filters/prisma-exception.filter";
|
||||
import { Locales } from "@/lib/enums/locales";
|
||||
import {
|
||||
CreateManagedUserData,
|
||||
CreateManagedUserOutput,
|
||||
} from "@/modules/oauth-clients/controllers/oauth-client-users/outputs/create-managed-user.output";
|
||||
import { OAuthClientUsersService } from "@/modules/oauth-clients/services/oauth-clients-users.service";
|
||||
import { CreateManagedUserInput } from "@/modules/users/inputs/create-managed-user.input";
|
||||
import { UsersModule } from "@/modules/users/users.module";
|
||||
|
||||
const CLIENT_REDIRECT_URI = "http://localhost:4321";
|
||||
|
||||
describe("Managed user bookings 2024-04-15", () => {
|
||||
let app: INestApplication;
|
||||
|
||||
let oAuthClient: PlatformOAuthClient;
|
||||
let organization: Team;
|
||||
let userRepositoryFixture: UserRepositoryFixture;
|
||||
let oauthClientRepositoryFixture: OAuthClientRepositoryFixture;
|
||||
let teamRepositoryFixture: TeamRepositoryFixture;
|
||||
let profilesRepositoryFixture: ProfileRepositoryFixture;
|
||||
let membershipsRepositoryFixture: MembershipRepositoryFixture;
|
||||
|
||||
const platformAdminEmail = `managed-users-bookings-admin-${randomString()}@api.com`;
|
||||
let platformAdmin: User;
|
||||
|
||||
const managedUsersTimeZone = "Europe/Rome";
|
||||
const firstManagedUserEmail = `[email protected]`;
|
||||
const secondManagedUserEmail = `[email protected]`;
|
||||
const thirdManagedUserEmail = `[email protected]`;
|
||||
|
||||
let firstManagedUser: CreateManagedUserData;
|
||||
let secondManagedUser: CreateManagedUserData;
|
||||
let thirdManagedUser: CreateManagedUserData;
|
||||
|
||||
let firstManagedUserEventTypeId: number;
|
||||
|
||||
let firstManagedUserBookingsCount = 0;
|
||||
let secondManagedUserBookingsCount = 0;
|
||||
let thirdManagedUserBookingsCount = 0;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
providers: [PrismaExceptionFilter, HttpExceptionFilter],
|
||||
imports: [AppModule, UsersModule],
|
||||
}).compile();
|
||||
|
||||
app = moduleRef.createNestApplication();
|
||||
bootstrap(app as NestExpressApplication);
|
||||
|
||||
oauthClientRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef);
|
||||
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
|
||||
teamRepositoryFixture = new TeamRepositoryFixture(moduleRef);
|
||||
profilesRepositoryFixture = new ProfileRepositoryFixture(moduleRef);
|
||||
membershipsRepositoryFixture = new MembershipRepositoryFixture(moduleRef);
|
||||
|
||||
platformAdmin = await userRepositoryFixture.create({ email: platformAdminEmail });
|
||||
|
||||
organization = await teamRepositoryFixture.create({
|
||||
name: `oauth-client-users-organization-${randomString()}`,
|
||||
isPlatform: true,
|
||||
isOrganization: true,
|
||||
});
|
||||
oAuthClient = await createOAuthClient(organization.id);
|
||||
|
||||
await profilesRepositoryFixture.create({
|
||||
uid: "asd1qwwqeqw-asddsadasd",
|
||||
username: platformAdminEmail,
|
||||
organization: { connect: { id: organization.id } },
|
||||
user: {
|
||||
connect: { id: platformAdmin.id },
|
||||
},
|
||||
});
|
||||
|
||||
await membershipsRepositoryFixture.create({
|
||||
role: "OWNER",
|
||||
user: { connect: { id: platformAdmin.id } },
|
||||
team: { connect: { id: organization.id } },
|
||||
accepted: true,
|
||||
});
|
||||
|
||||
await app.init();
|
||||
});
|
||||
|
||||
async function createOAuthClient(organizationId: number) {
|
||||
const data = {
|
||||
logo: "logo-url",
|
||||
name: "name",
|
||||
redirectUris: [CLIENT_REDIRECT_URI],
|
||||
permissions: 1023,
|
||||
};
|
||||
const secret = "secret";
|
||||
|
||||
const client = await oauthClientRepositoryFixture.create(organizationId, data, secret);
|
||||
return client;
|
||||
}
|
||||
|
||||
it(`should create first managed user`, async () => {
|
||||
const requestBody: CreateManagedUserInput = {
|
||||
email: firstManagedUserEmail,
|
||||
timeZone: managedUsersTimeZone,
|
||||
weekStart: "Monday",
|
||||
timeFormat: 24,
|
||||
locale: Locales.FR,
|
||||
name: "Alice Smith",
|
||||
avatarUrl: "https://cal.com/api/avatar/2b735186-b01b-46d3-87da-019b8f61776b.png",
|
||||
};
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post(`/api/v2/oauth-clients/${oAuthClient.id}/users`)
|
||||
.set("x-cal-secret-key", oAuthClient.secret)
|
||||
.send(requestBody)
|
||||
.expect(201);
|
||||
|
||||
const responseBody: CreateManagedUserOutput = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data).toBeDefined();
|
||||
expect(responseBody.data.user.email).toEqual(
|
||||
OAuthClientUsersService.getOAuthUserEmail(oAuthClient.id, requestBody.email)
|
||||
);
|
||||
expect(responseBody.data.accessToken).toBeDefined();
|
||||
expect(responseBody.data.refreshToken).toBeDefined();
|
||||
|
||||
firstManagedUser = responseBody.data;
|
||||
});
|
||||
|
||||
it("should create an event type for managed user", async () => {
|
||||
const body: CreateEventTypeInput_2024_06_14 = {
|
||||
title: "Managed user bookings first managed user event type",
|
||||
slug: "managed-user-bookings-first-managed-user-event-type",
|
||||
description: "Managed user bookings first managed user event type description",
|
||||
lengthInMinutes: 30,
|
||||
};
|
||||
|
||||
return request(app.getHttpServer())
|
||||
.post("/api/v2/event-types")
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_06_14)
|
||||
.set("Authorization", `Bearer ${firstManagedUser.accessToken}`)
|
||||
.send(body)
|
||||
.expect(201)
|
||||
.then(async (response) => {
|
||||
const responseBody: ApiSuccessResponse<EventTypeOutput_2024_06_14> = response.body;
|
||||
const createdEventType = responseBody.data;
|
||||
expect(createdEventType).toHaveProperty("id");
|
||||
expect(createdEventType.title).toEqual(body.title);
|
||||
expect(createdEventType.description).toEqual(body.description);
|
||||
expect(createdEventType.lengthInMinutes).toEqual(body.lengthInMinutes);
|
||||
expect(createdEventType.ownerId).toEqual(firstManagedUser.user.id);
|
||||
firstManagedUserEventTypeId = createdEventType.id;
|
||||
});
|
||||
});
|
||||
|
||||
it(`should create second managed user`, async () => {
|
||||
const requestBody: CreateManagedUserInput = {
|
||||
email: secondManagedUserEmail,
|
||||
timeZone: managedUsersTimeZone,
|
||||
weekStart: "Monday",
|
||||
timeFormat: 24,
|
||||
locale: Locales.FR,
|
||||
name: "Bob Smith",
|
||||
avatarUrl: "https://cal.com/api/avatar/2b735186-b01b-46d3-87da-019b8f61776b.png",
|
||||
};
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post(`/api/v2/oauth-clients/${oAuthClient.id}/users`)
|
||||
.set("x-cal-secret-key", oAuthClient.secret)
|
||||
.send(requestBody)
|
||||
.expect(201);
|
||||
|
||||
const responseBody: CreateManagedUserOutput = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data).toBeDefined();
|
||||
expect(responseBody.data.user.email).toEqual(
|
||||
OAuthClientUsersService.getOAuthUserEmail(oAuthClient.id, requestBody.email)
|
||||
);
|
||||
expect(responseBody.data.accessToken).toBeDefined();
|
||||
expect(responseBody.data.refreshToken).toBeDefined();
|
||||
|
||||
secondManagedUser = responseBody.data;
|
||||
});
|
||||
|
||||
it(`should create third managed user`, async () => {
|
||||
const requestBody: CreateManagedUserInput = {
|
||||
email: thirdManagedUserEmail,
|
||||
timeZone: managedUsersTimeZone,
|
||||
weekStart: "Monday",
|
||||
timeFormat: 24,
|
||||
locale: Locales.FR,
|
||||
name: "Charlie Smith",
|
||||
avatarUrl: "https://cal.com/api/avatar/2b735186-b01b-46d3-87da-019b8f61776b.png",
|
||||
};
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post(`/api/v2/oauth-clients/${oAuthClient.id}/users`)
|
||||
.set("x-cal-secret-key", oAuthClient.secret)
|
||||
.send(requestBody)
|
||||
.expect(201);
|
||||
|
||||
const responseBody: CreateManagedUserOutput = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data).toBeDefined();
|
||||
expect(responseBody.data.user.email).toEqual(
|
||||
OAuthClientUsersService.getOAuthUserEmail(oAuthClient.id, requestBody.email)
|
||||
);
|
||||
expect(responseBody.data.accessToken).toBeDefined();
|
||||
expect(responseBody.data.refreshToken).toBeDefined();
|
||||
|
||||
thirdManagedUser = responseBody.data;
|
||||
});
|
||||
|
||||
describe("bookings using original emails", () => {
|
||||
it("managed user should be booked by managed user attendee and booking shows up in both users' bookings", async () => {
|
||||
const body: CreateBookingInput_2024_04_15 = {
|
||||
start: "2040-05-21T09:30:00.000Z",
|
||||
end: "2040-05-21T10:00:00.000Z",
|
||||
eventTypeId: firstManagedUserEventTypeId,
|
||||
timeZone: "Europe/London",
|
||||
language: "en",
|
||||
metadata: {},
|
||||
hashedLink: "",
|
||||
responses: {
|
||||
name: secondManagedUser.user.name || "unknown-name",
|
||||
email: secondManagedUserEmail,
|
||||
location: {
|
||||
value: "attendeeInPerson",
|
||||
optionValue: "rome",
|
||||
},
|
||||
notes: "test",
|
||||
guests: [],
|
||||
},
|
||||
};
|
||||
|
||||
await request(app.getHttpServer()).post("/v2/bookings").send(body).expect(201);
|
||||
|
||||
firstManagedUserBookingsCount += 1;
|
||||
secondManagedUserBookingsCount += 1;
|
||||
|
||||
const getFirstManagedUserBookings = await request(app.getHttpServer())
|
||||
.get("/v2/bookings")
|
||||
.set("Authorization", `Bearer ${firstManagedUser.accessToken}`)
|
||||
.expect(200);
|
||||
|
||||
const firstManagedUserBookingsResponseBody: GetBookingsOutput_2024_04_15 =
|
||||
getFirstManagedUserBookings.body;
|
||||
const firstManagedUserBookings: GetBookingsDataEntry[] =
|
||||
firstManagedUserBookingsResponseBody.data.bookings;
|
||||
expect(firstManagedUserBookings.length).toEqual(firstManagedUserBookingsCount);
|
||||
|
||||
const getSecondManagedUserBookings = await request(app.getHttpServer())
|
||||
.get("/v2/bookings")
|
||||
.set("Authorization", `Bearer ${secondManagedUser.accessToken}`)
|
||||
.expect(200);
|
||||
const secondManagedUserBookingsResponseBody: GetBookingsOutput_2024_04_15 =
|
||||
getSecondManagedUserBookings.body;
|
||||
const secondManagedUserBookings: GetBookingsDataEntry[] =
|
||||
secondManagedUserBookingsResponseBody.data.bookings;
|
||||
expect(secondManagedUserBookings.length).toEqual(secondManagedUserBookingsCount);
|
||||
});
|
||||
|
||||
it("managed user should be booked by managed user attendee and managed user as a guest and booking shows up in all three users' bookings", async () => {
|
||||
const body: CreateBookingInput_2024_04_15 = {
|
||||
start: "2040-05-21T10:30:00.000Z",
|
||||
end: "2040-05-21T11:00:00.000Z",
|
||||
eventTypeId: firstManagedUserEventTypeId,
|
||||
timeZone: "Europe/London",
|
||||
language: "en",
|
||||
metadata: {},
|
||||
hashedLink: "",
|
||||
responses: {
|
||||
name: thirdManagedUser.user.name || "unknown-name",
|
||||
email: thirdManagedUserEmail,
|
||||
location: {
|
||||
value: "attendeeInPerson",
|
||||
optionValue: "rome",
|
||||
},
|
||||
notes: "test",
|
||||
guests: [secondManagedUserEmail],
|
||||
},
|
||||
};
|
||||
|
||||
await request(app.getHttpServer()).post("/v2/bookings").send(body).expect(201);
|
||||
|
||||
firstManagedUserBookingsCount += 1;
|
||||
secondManagedUserBookingsCount += 1;
|
||||
thirdManagedUserBookingsCount += 1;
|
||||
|
||||
const getFirstManagedUserBookings = await request(app.getHttpServer())
|
||||
.get("/v2/bookings")
|
||||
.set("Authorization", `Bearer ${firstManagedUser.accessToken}`)
|
||||
.expect(200);
|
||||
const firstManagedUserBookingsResponseBody: GetBookingsOutput_2024_04_15 =
|
||||
getFirstManagedUserBookings.body;
|
||||
const firstManagedUserBookings: GetBookingsDataEntry[] =
|
||||
firstManagedUserBookingsResponseBody.data.bookings;
|
||||
expect(firstManagedUserBookings.length).toEqual(firstManagedUserBookingsCount);
|
||||
|
||||
const getSecondManagedUserBookings = await request(app.getHttpServer())
|
||||
.get("/v2/bookings")
|
||||
.set("Authorization", `Bearer ${secondManagedUser.accessToken}`)
|
||||
.expect(200);
|
||||
const secondManagedUserBookingsResponseBody: GetBookingsOutput_2024_04_15 =
|
||||
getSecondManagedUserBookings.body;
|
||||
const secondManagedUserBookings: GetBookingsDataEntry[] =
|
||||
secondManagedUserBookingsResponseBody.data.bookings;
|
||||
expect(secondManagedUserBookings.length).toEqual(secondManagedUserBookingsCount);
|
||||
|
||||
const getThirdManagedUserBookings = await request(app.getHttpServer())
|
||||
.get("/v2/bookings")
|
||||
.set("Authorization", `Bearer ${thirdManagedUser.accessToken}`)
|
||||
.expect(200);
|
||||
const thirdManagedUserBookingsResponseBody: GetBookingsOutput_2024_04_15 =
|
||||
getThirdManagedUserBookings.body;
|
||||
const thirdManagedUserBookings: GetBookingsDataEntry[] =
|
||||
thirdManagedUserBookingsResponseBody.data.bookings;
|
||||
expect(thirdManagedUserBookings.length).toEqual(thirdManagedUserBookingsCount);
|
||||
});
|
||||
});
|
||||
|
||||
describe("bookings using OAuth client emails", () => {
|
||||
it("managed user should be booked by managed user attendee and booking shows up in both users' bookings", async () => {
|
||||
const body: CreateBookingInput_2024_04_15 = {
|
||||
start: "2040-05-21T12:00:00.000Z",
|
||||
end: "2040-05-21T12:30:00.000Z",
|
||||
eventTypeId: firstManagedUserEventTypeId,
|
||||
timeZone: "Europe/London",
|
||||
language: "en",
|
||||
metadata: {},
|
||||
hashedLink: "",
|
||||
responses: {
|
||||
name: secondManagedUser.user.name || "unknown-name",
|
||||
email: secondManagedUser.user.email,
|
||||
location: {
|
||||
value: "attendeeInPerson",
|
||||
optionValue: "rome",
|
||||
},
|
||||
notes: "test",
|
||||
guests: [],
|
||||
},
|
||||
};
|
||||
|
||||
await request(app.getHttpServer()).post("/v2/bookings").send(body).expect(201);
|
||||
|
||||
firstManagedUserBookingsCount += 1;
|
||||
secondManagedUserBookingsCount += 1;
|
||||
|
||||
const getFirstManagedUserBookings = await request(app.getHttpServer())
|
||||
.get("/v2/bookings")
|
||||
.set("Authorization", `Bearer ${firstManagedUser.accessToken}`)
|
||||
.expect(200);
|
||||
|
||||
const firstManagedUserBookingsResponseBody: GetBookingsOutput_2024_04_15 =
|
||||
getFirstManagedUserBookings.body;
|
||||
const firstManagedUserBookings: GetBookingsDataEntry[] =
|
||||
firstManagedUserBookingsResponseBody.data.bookings;
|
||||
expect(firstManagedUserBookings.length).toEqual(firstManagedUserBookingsCount);
|
||||
|
||||
const getSecondManagedUserBookings = await request(app.getHttpServer())
|
||||
.get("/v2/bookings")
|
||||
.set("Authorization", `Bearer ${secondManagedUser.accessToken}`)
|
||||
.expect(200);
|
||||
|
||||
const secondManagedUserBookingsResponseBody: GetBookingsOutput_2024_04_15 =
|
||||
getSecondManagedUserBookings.body;
|
||||
const secondManagedUserBookings: GetBookingsDataEntry[] =
|
||||
secondManagedUserBookingsResponseBody.data.bookings;
|
||||
expect(secondManagedUserBookings.length).toEqual(secondManagedUserBookingsCount);
|
||||
});
|
||||
|
||||
it("managed user should be booked by managed user attendee and managed user as a guest and booking shows up in all three users' bookings", async () => {
|
||||
const body: CreateBookingInput_2024_04_15 = {
|
||||
start: "2040-05-21T13:00:00.000Z",
|
||||
end: "2040-05-21T13:30:00.000Z",
|
||||
eventTypeId: firstManagedUserEventTypeId,
|
||||
timeZone: "Europe/London",
|
||||
language: "en",
|
||||
metadata: {},
|
||||
hashedLink: "",
|
||||
responses: {
|
||||
name: thirdManagedUser.user.name || "unknown-name",
|
||||
email: thirdManagedUser.user.email,
|
||||
location: {
|
||||
value: "attendeeInPerson",
|
||||
optionValue: "rome",
|
||||
},
|
||||
notes: "test",
|
||||
guests: [secondManagedUser.user.email],
|
||||
},
|
||||
};
|
||||
|
||||
await request(app.getHttpServer()).post("/v2/bookings").send(body).expect(201);
|
||||
|
||||
firstManagedUserBookingsCount += 1;
|
||||
secondManagedUserBookingsCount += 1;
|
||||
thirdManagedUserBookingsCount += 1;
|
||||
|
||||
const getFirstManagedUserBookings = await request(app.getHttpServer())
|
||||
.get("/v2/bookings")
|
||||
.set("Authorization", `Bearer ${firstManagedUser.accessToken}`)
|
||||
.expect(200);
|
||||
const firstManagedUserBookingsResponseBody: GetBookingsOutput_2024_04_15 =
|
||||
getFirstManagedUserBookings.body;
|
||||
const firstManagedUserBookings: GetBookingsDataEntry[] =
|
||||
firstManagedUserBookingsResponseBody.data.bookings;
|
||||
expect(firstManagedUserBookings.length).toEqual(firstManagedUserBookingsCount);
|
||||
|
||||
const getSecondManagedUserBookings = await request(app.getHttpServer())
|
||||
.get("/v2/bookings")
|
||||
.set("Authorization", `Bearer ${secondManagedUser.accessToken}`)
|
||||
.expect(200);
|
||||
const secondManagedUserBookingsResponseBody: GetBookingsOutput_2024_04_15 =
|
||||
getSecondManagedUserBookings.body;
|
||||
const secondManagedUserBookings: GetBookingsDataEntry[] =
|
||||
secondManagedUserBookingsResponseBody.data.bookings;
|
||||
expect(secondManagedUserBookings.length).toEqual(secondManagedUserBookingsCount);
|
||||
|
||||
const getThirdManagedUserBookings = await request(app.getHttpServer())
|
||||
.get("/v2/bookings")
|
||||
.set("Authorization", `Bearer ${thirdManagedUser.accessToken}`)
|
||||
.expect(200);
|
||||
const thirdManagedUserBookingsResponseBody: GetBookingsOutput_2024_04_15 =
|
||||
getThirdManagedUserBookings.body;
|
||||
const thirdManagedUserBookings: GetBookingsDataEntry[] =
|
||||
thirdManagedUserBookingsResponseBody.data.bookings;
|
||||
expect(thirdManagedUserBookings.length).toEqual(thirdManagedUserBookingsCount);
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await userRepositoryFixture.delete(firstManagedUser.user.id);
|
||||
await userRepositoryFixture.delete(secondManagedUser.user.id);
|
||||
await userRepositoryFixture.delete(thirdManagedUser.user.id);
|
||||
await userRepositoryFixture.delete(platformAdmin.id);
|
||||
await oauthClientRepositoryFixture.delete(oAuthClient.id);
|
||||
await teamRepositoryFixture.delete(organization.id);
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
@@ -1,132 +0,0 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { BookingAttendeesController_2024_08_13 } from "@/ee/bookings/2024-08-13/controllers/booking-attendees.controller";
|
||||
import { BookingGuestsController_2024_08_13 } from "@/ee/bookings/2024-08-13/controllers/booking-guests.controller";
|
||||
import { BookingLocationController_2024_08_13 } from "@/ee/bookings/2024-08-13/controllers/booking-location.controller";
|
||||
import { BookingsController_2024_08_13 } from "@/ee/bookings/2024-08-13/controllers/bookings.controller";
|
||||
import { BookingPbacGuard } from "@/ee/bookings/2024-08-13/guards/booking-pbac.guard";
|
||||
import { BookingReferencesRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/booking-references.repository";
|
||||
import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/bookings.repository";
|
||||
import { BookingAttendeesService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-attendees.service";
|
||||
import { BookingGuestsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-guests.service";
|
||||
import { BookingLocationCalendarSyncService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-location-calendar-sync.service";
|
||||
import { BookingLocationCredentialService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-location-credential.service";
|
||||
import { BookingLocationIntegrationService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-location-integration.service";
|
||||
import { BookingLocationService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-location.service";
|
||||
import { BookingVideoService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-video.service";
|
||||
import { BookingReferencesService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-references.service";
|
||||
import { BookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/bookings.service";
|
||||
import { CalVideoOutputService } from "@/ee/bookings/2024-08-13/services/cal-video.output.service";
|
||||
import { CalVideoService } from "@/ee/bookings/2024-08-13/services/cal-video.service";
|
||||
import { ErrorsBookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/errors.service";
|
||||
import { InputBookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/input.service";
|
||||
import { OutputBookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/output.service";
|
||||
import { OutputBookingReferencesService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/output-booking-references.service";
|
||||
import { PlatformBookingsService } from "@/ee/bookings/shared/platform-bookings.service";
|
||||
import { CalendarsRepository } from "@/ee/calendars/calendars.repository";
|
||||
import { CalendarsService } from "@/ee/calendars/services/calendars.service";
|
||||
import { CalendarsCacheService } from "@/ee/calendars/services/calendars-cache.service";
|
||||
import { EventTypesModule_2024_04_15 } from "@/ee/event-types/event-types_2024_04_15/event-types.module";
|
||||
import { EventTypesModule_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.module";
|
||||
import { EventTypesRepository_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.repository";
|
||||
import { OutputEventTypesService_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/services/output-event-types.service";
|
||||
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
|
||||
import { BookingAttendeesModule } from "@/lib/modules/booking-attendees.module";
|
||||
import { BookingEventHandlerModule } from "@/lib/modules/booking-event-handler.module";
|
||||
import { InstantBookingModule } from "@/lib/modules/instant-booking.module";
|
||||
import { RecurringBookingModule } from "@/lib/modules/recurring-booking.module";
|
||||
import { RegularBookingModule } from "@/lib/modules/regular-booking.module";
|
||||
import { PrismaFeaturesRepository } from "@/lib/repositories/prisma-features.repository";
|
||||
import { ApiKeysRepository } from "@/modules/api-keys/api-keys-repository";
|
||||
import { AppsRepository } from "@/modules/apps/apps.repository";
|
||||
import { BillingModule } from "@/modules/billing/billing.module";
|
||||
import { BookingSeatModule } from "@/modules/booking-seat/booking-seat.module";
|
||||
import { BookingSeatRepository } from "@/modules/booking-seat/booking-seat.repository";
|
||||
import { CredentialsRepository } from "@/modules/credentials/credentials.repository";
|
||||
import { KyselyModule } from "@/modules/kysely/kysely.module";
|
||||
import { MembershipsModule } from "@/modules/memberships/memberships.module";
|
||||
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
|
||||
import { OAuthClientUsersService } from "@/modules/oauth-clients/services/oauth-clients-users.service";
|
||||
import { OAuthFlowService } from "@/modules/oauth-clients/services/oauth-flow.service";
|
||||
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
|
||||
import { OrganizationsTeamsRepository } from "@/modules/organizations/teams/index/organizations-teams.repository";
|
||||
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||
import { ProfilesModule } from "@/modules/profiles/profiles.module";
|
||||
import { RedisModule } from "@/modules/redis/redis.module";
|
||||
import { SelectedCalendarsRepository } from "@/modules/selected-calendars/selected-calendars.repository";
|
||||
import { StripeModule } from "@/modules/stripe/stripe.module";
|
||||
import { TeamsEventTypesModule } from "@/modules/teams/event-types/teams-event-types.module";
|
||||
import { TeamsModule } from "@/modules/teams/teams/teams.module";
|
||||
import { TokensModule } from "@/modules/tokens/tokens.module";
|
||||
import { TokensRepository } from "@/modules/tokens/tokens.repository";
|
||||
import { UsersModule } from "@/modules/users/users.module";
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
PrismaModule,
|
||||
KyselyModule,
|
||||
RedisModule,
|
||||
TokensModule,
|
||||
BillingModule,
|
||||
UsersModule,
|
||||
BookingSeatModule,
|
||||
SchedulesModule_2024_04_15,
|
||||
EventTypesModule_2024_04_15,
|
||||
EventTypesModule_2024_06_14,
|
||||
StripeModule,
|
||||
TeamsModule,
|
||||
TeamsEventTypesModule,
|
||||
MembershipsModule,
|
||||
ProfilesModule,
|
||||
RegularBookingModule,
|
||||
RecurringBookingModule,
|
||||
InstantBookingModule,
|
||||
BookingEventHandlerModule,
|
||||
BookingAttendeesModule,
|
||||
],
|
||||
providers: [
|
||||
TokensRepository,
|
||||
OAuthFlowService,
|
||||
OAuthClientRepository,
|
||||
OAuthClientUsersService,
|
||||
BookingsService_2024_08_13,
|
||||
BookingAttendeesService_2024_08_13,
|
||||
BookingGuestsService_2024_08_13,
|
||||
InputBookingsService_2024_08_13,
|
||||
OutputBookingsService_2024_08_13,
|
||||
OutputBookingReferencesService_2024_08_13,
|
||||
OutputEventTypesService_2024_06_14,
|
||||
BookingsRepository_2024_08_13,
|
||||
EventTypesRepository_2024_06_14,
|
||||
BookingSeatRepository,
|
||||
ApiKeysRepository,
|
||||
PlatformBookingsService,
|
||||
CalendarsService,
|
||||
CalendarsCacheService,
|
||||
CredentialsRepository,
|
||||
AppsRepository,
|
||||
CalendarsRepository,
|
||||
SelectedCalendarsRepository,
|
||||
OrganizationsTeamsRepository,
|
||||
OrganizationsRepository,
|
||||
ErrorsBookingsService_2024_08_13,
|
||||
BookingReferencesService_2024_08_13,
|
||||
BookingReferencesRepository_2024_08_13,
|
||||
CalVideoService,
|
||||
CalVideoOutputService,
|
||||
BookingPbacGuard,
|
||||
BookingLocationCalendarSyncService_2024_08_13,
|
||||
BookingLocationCredentialService_2024_08_13,
|
||||
BookingLocationIntegrationService_2024_08_13,
|
||||
BookingLocationService_2024_08_13,
|
||||
BookingVideoService_2024_08_13,
|
||||
PrismaFeaturesRepository,
|
||||
],
|
||||
controllers: [
|
||||
BookingsController_2024_08_13,
|
||||
BookingAttendeesController_2024_08_13,
|
||||
BookingGuestsController_2024_08_13,
|
||||
BookingLocationController_2024_08_13,
|
||||
],
|
||||
exports: [InputBookingsService_2024_08_13, OutputBookingsService_2024_08_13, BookingsService_2024_08_13],
|
||||
})
|
||||
export class BookingsModule_2024_08_13 {}
|
||||
@@ -1,415 +0,0 @@
|
||||
import { CAL_API_VERSION_HEADER, SUCCESS_STATUS, VERSION_2024_08_13 } from "@calcom/platform-constants";
|
||||
import {
|
||||
AttendeeAddGuestsEmail,
|
||||
AttendeeScheduledEmail,
|
||||
OrganizerAddGuestsEmail,
|
||||
} from "@calcom/platform-libraries/emails";
|
||||
import type { BookingOutput_2024_08_13, CreateBookingInput_2024_08_13 } from "@calcom/platform-types";
|
||||
import type { Team, User } from "@calcom/prisma/client";
|
||||
import { INestApplication } from "@nestjs/common";
|
||||
import { NestExpressApplication } from "@nestjs/platform-express";
|
||||
import { Test } from "@nestjs/testing";
|
||||
import request from "supertest";
|
||||
import { BookingsRepositoryFixture } from "test/fixtures/repository/bookings.repository.fixture";
|
||||
import { EventTypesRepositoryFixture } from "test/fixtures/repository/event-types.repository.fixture";
|
||||
import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.repository.fixture";
|
||||
import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture";
|
||||
import { TokensRepositoryFixture } from "test/fixtures/repository/tokens.repository.fixture";
|
||||
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
|
||||
import { randomString } from "test/utils/randomString";
|
||||
import { mockThrottlerGuard } from "test/utils/withNoThrottler";
|
||||
import { AppModule } from "@/app.module";
|
||||
import { bootstrap } from "@/bootstrap";
|
||||
import { AddAttendeeOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/add-attendee.output";
|
||||
import { CreateBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/create-booking.output";
|
||||
import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input";
|
||||
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
|
||||
import { SchedulesService_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/services/schedules.service";
|
||||
import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard";
|
||||
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||
import { UsersModule } from "@/modules/users/users.module";
|
||||
|
||||
const attendeeAddGuestsEmailSpy = jest
|
||||
.spyOn(AttendeeAddGuestsEmail.prototype, "getHtml")
|
||||
.mockImplementation(() => Promise.resolve("<p>email</p>"));
|
||||
const organizerAddGuestsEmailSpy = jest
|
||||
.spyOn(OrganizerAddGuestsEmail.prototype, "getHtml")
|
||||
.mockImplementation(() => Promise.resolve("<p>email</p>"));
|
||||
const attendeeScheduledEmailSpy = jest
|
||||
.spyOn(AttendeeScheduledEmail.prototype, "getHtml")
|
||||
.mockImplementation(() => Promise.resolve("<p>email</p>"));
|
||||
|
||||
type TestUser = {
|
||||
user: User;
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
};
|
||||
|
||||
type TestSetup = {
|
||||
organizer: TestUser;
|
||||
unrelatedUser: TestUser;
|
||||
eventTypeId: number;
|
||||
bookingUid: string;
|
||||
bookingId: number;
|
||||
};
|
||||
|
||||
describe("Bookings Endpoints 2024-08-13 add attendee", () => {
|
||||
let app: INestApplication;
|
||||
let organization: Team;
|
||||
|
||||
let userRepositoryFixture: UserRepositoryFixture;
|
||||
let bookingsRepositoryFixture: BookingsRepositoryFixture;
|
||||
let schedulesService: SchedulesService_2024_04_15;
|
||||
let eventTypesRepositoryFixture: EventTypesRepositoryFixture;
|
||||
let oauthClientRepositoryFixture: OAuthClientRepositoryFixture;
|
||||
let teamRepositoryFixture: TeamRepositoryFixture;
|
||||
let tokensRepositoryFixture: TokensRepositoryFixture;
|
||||
|
||||
let testSetup: TestSetup;
|
||||
|
||||
beforeAll(async () => {
|
||||
mockThrottlerGuard();
|
||||
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [AppModule, PrismaModule, UsersModule, SchedulesModule_2024_04_15],
|
||||
})
|
||||
.overrideGuard(PermissionsGuard)
|
||||
.useValue({
|
||||
canActivate: () => true,
|
||||
})
|
||||
.compile();
|
||||
|
||||
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
|
||||
bookingsRepositoryFixture = new BookingsRepositoryFixture(moduleRef);
|
||||
eventTypesRepositoryFixture = new EventTypesRepositoryFixture(moduleRef);
|
||||
oauthClientRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef);
|
||||
teamRepositoryFixture = new TeamRepositoryFixture(moduleRef);
|
||||
schedulesService = moduleRef.get<SchedulesService_2024_04_15>(SchedulesService_2024_04_15);
|
||||
tokensRepositoryFixture = new TokensRepositoryFixture(moduleRef);
|
||||
|
||||
organization = await teamRepositoryFixture.create({
|
||||
name: `add-attendee-2024-08-13-organization-${randomString()}`,
|
||||
});
|
||||
|
||||
await setupTestData();
|
||||
|
||||
app = moduleRef.createNestApplication();
|
||||
bootstrap(app as NestExpressApplication);
|
||||
|
||||
await app.init();
|
||||
});
|
||||
|
||||
async function setupTestData() {
|
||||
const oAuthClient = await createOAuthClient(organization.id, true);
|
||||
|
||||
const organizerUser = await userRepositoryFixture.create({
|
||||
email: `add-attendee-2024-08-13-organizer-${randomString()}@api.com`,
|
||||
platformOAuthClients: {
|
||||
connect: { id: oAuthClient.id },
|
||||
},
|
||||
});
|
||||
|
||||
const unrelatedUserData = await userRepositoryFixture.create({
|
||||
email: `add-attendee-2024-08-13-unrelated-${randomString()}@api.com`,
|
||||
platformOAuthClients: {
|
||||
connect: { id: oAuthClient.id },
|
||||
},
|
||||
});
|
||||
|
||||
const organizerTokens = await tokensRepositoryFixture.createTokens(organizerUser.id, oAuthClient.id);
|
||||
const unrelatedUserTokens = await tokensRepositoryFixture.createTokens(
|
||||
unrelatedUserData.id,
|
||||
oAuthClient.id
|
||||
);
|
||||
|
||||
const schedule: CreateScheduleInput_2024_04_15 = {
|
||||
name: `add-attendee-2024-08-13-schedule-${randomString()}`,
|
||||
timeZone: "Europe/Rome",
|
||||
isDefault: true,
|
||||
};
|
||||
await schedulesService.createUserSchedule(organizerUser.id, schedule);
|
||||
|
||||
const eventType = await eventTypesRepositoryFixture.create(
|
||||
{
|
||||
title: `add-attendee-2024-08-13-event-type-${randomString()}`,
|
||||
slug: `add-attendee-2024-08-13-event-type-${randomString()}`,
|
||||
length: 60,
|
||||
},
|
||||
organizerUser.id
|
||||
);
|
||||
|
||||
testSetup = {
|
||||
organizer: {
|
||||
user: organizerUser,
|
||||
accessToken: organizerTokens.accessToken,
|
||||
refreshToken: organizerTokens.refreshToken,
|
||||
},
|
||||
unrelatedUser: {
|
||||
user: unrelatedUserData,
|
||||
accessToken: unrelatedUserTokens.accessToken,
|
||||
refreshToken: unrelatedUserTokens.refreshToken,
|
||||
},
|
||||
eventTypeId: eventType.id,
|
||||
bookingUid: "",
|
||||
bookingId: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function createOAuthClient(organizationId: number, emailsEnabled: boolean) {
|
||||
const data = {
|
||||
logo: "logo-url",
|
||||
name: "name",
|
||||
redirectUris: ["http://localhost:5555"],
|
||||
permissions: 32,
|
||||
areEmailsEnabled: emailsEnabled,
|
||||
};
|
||||
const secret = "secret";
|
||||
|
||||
const client = await oauthClientRepositoryFixture.create(organizationId, data, secret);
|
||||
return client;
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
attendeeAddGuestsEmailSpy.mockClear();
|
||||
organizerAddGuestsEmailSpy.mockClear();
|
||||
attendeeScheduledEmailSpy.mockClear();
|
||||
});
|
||||
|
||||
describe("POST /v2/bookings/:bookingUid/attendees", () => {
|
||||
beforeAll(async () => {
|
||||
const createBookingBody: CreateBookingInput_2024_08_13 = {
|
||||
start: new Date(Date.UTC(2030, 0, 10, 13, 0, 0)).toISOString(),
|
||||
eventTypeId: testSetup.eventTypeId,
|
||||
attendee: {
|
||||
name: "Original Attendee",
|
||||
email: "[email protected]",
|
||||
timeZone: "Europe/Rome",
|
||||
language: "it",
|
||||
},
|
||||
location: "https://meet.google.com/abc-def-ghi",
|
||||
bookingFieldsResponses: {
|
||||
customField: "customValue",
|
||||
},
|
||||
metadata: {
|
||||
userId: "100",
|
||||
},
|
||||
};
|
||||
|
||||
const createBookingResponse = await request(app.getHttpServer())
|
||||
.post("/v2/bookings")
|
||||
.send(createBookingBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.expect(201);
|
||||
|
||||
const createBookingResponseBody: CreateBookingOutput_2024_08_13 = createBookingResponse.body;
|
||||
expect(createBookingResponseBody.status).toEqual(SUCCESS_STATUS);
|
||||
|
||||
if (!responseDataIsBooking(createBookingResponseBody.data)) {
|
||||
throw new Error(
|
||||
"Invalid response data - expected booking but received array of possibly recurring bookings"
|
||||
);
|
||||
}
|
||||
|
||||
testSetup.bookingUid = createBookingResponseBody.data.uid;
|
||||
testSetup.bookingId = createBookingResponseBody.data.id;
|
||||
});
|
||||
|
||||
describe("Authentication", () => {
|
||||
it("should return 401 when adding attendee without authentication", async () => {
|
||||
const addAttendeeBody = {
|
||||
email: "[email protected]",
|
||||
name: "Unauthenticated Attendee",
|
||||
timeZone: "Europe/London",
|
||||
};
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${testSetup.bookingUid}/attendees`)
|
||||
.send(addAttendeeBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13);
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Authorization", () => {
|
||||
it("should allow booking organizer to add an attendee", async () => {
|
||||
const addAttendeeBody = {
|
||||
email: "[email protected]",
|
||||
name: "New Attendee",
|
||||
timeZone: "Europe/London",
|
||||
};
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${testSetup.bookingUid}/attendees`)
|
||||
.send(addAttendeeBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.set("Authorization", `Bearer ${testSetup.organizer.accessToken}`)
|
||||
.expect(201);
|
||||
|
||||
const responseBody: AddAttendeeOutput_2024_08_13 = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data).toBeDefined();
|
||||
expect(responseBody.data.email).toEqual(addAttendeeBody.email);
|
||||
expect(responseBody.data.name).toEqual(addAttendeeBody.name);
|
||||
expect(responseBody.data.timeZone).toEqual(addAttendeeBody.timeZone);
|
||||
expect(responseBody.data.bookingId).toEqual(testSetup.bookingId);
|
||||
expect(responseBody.data.id).toBeDefined();
|
||||
});
|
||||
|
||||
it("should return 403 when unrelated user tries to add attendee", async () => {
|
||||
const addAttendeeBody = {
|
||||
email: "[email protected]",
|
||||
name: "Unauthorized Attendee",
|
||||
timeZone: "America/New_York",
|
||||
};
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${testSetup.bookingUid}/attendees`)
|
||||
.send(addAttendeeBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.set("Authorization", `Bearer ${testSetup.unrelatedUser.accessToken}`)
|
||||
.expect(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Response format", () => {
|
||||
it("should return attendee with correct structure", async () => {
|
||||
const addAttendeeBody = {
|
||||
email: "[email protected]",
|
||||
name: "Structure Test Attendee",
|
||||
timeZone: "Asia/Tokyo",
|
||||
};
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${testSetup.bookingUid}/attendees`)
|
||||
.send(addAttendeeBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.set("Authorization", `Bearer ${testSetup.organizer.accessToken}`)
|
||||
.expect(201);
|
||||
|
||||
const responseBody: AddAttendeeOutput_2024_08_13 = response.body;
|
||||
|
||||
expect(responseBody).toHaveProperty("status", SUCCESS_STATUS);
|
||||
expect(responseBody).toHaveProperty("data");
|
||||
expect(responseBody.data).toHaveProperty("id");
|
||||
expect(responseBody.data).toHaveProperty("bookingId");
|
||||
expect(responseBody.data).toHaveProperty("name");
|
||||
expect(responseBody.data).toHaveProperty("email");
|
||||
expect(responseBody.data).toHaveProperty("timeZone");
|
||||
|
||||
expect(typeof responseBody.data.id).toBe("number");
|
||||
expect(typeof responseBody.data.bookingId).toBe("number");
|
||||
expect(typeof responseBody.data.name).toBe("string");
|
||||
expect(typeof responseBody.data.email).toBe("string");
|
||||
expect(typeof responseBody.data.timeZone).toBe("string");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Validation", () => {
|
||||
it("should return 400 when email is missing", async () => {
|
||||
const addAttendeeBody = {
|
||||
name: "No Email Attendee",
|
||||
timeZone: "Europe/London",
|
||||
};
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${testSetup.bookingUid}/attendees`)
|
||||
.send(addAttendeeBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.set("Authorization", `Bearer ${testSetup.organizer.accessToken}`)
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it("should return 400 when email is invalid", async () => {
|
||||
const addAttendeeBody = {
|
||||
email: "invalid-email",
|
||||
name: "Invalid Email Attendee",
|
||||
timeZone: "Europe/London",
|
||||
};
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${testSetup.bookingUid}/attendees`)
|
||||
.send(addAttendeeBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.set("Authorization", `Bearer ${testSetup.organizer.accessToken}`)
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it("should return 400 when name is missing", async () => {
|
||||
const addAttendeeBody = {
|
||||
email: "[email protected]",
|
||||
timeZone: "Europe/London",
|
||||
};
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${testSetup.bookingUid}/attendees`)
|
||||
.send(addAttendeeBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.set("Authorization", `Bearer ${testSetup.organizer.accessToken}`)
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it("should return 400 when timeZone is missing", async () => {
|
||||
const addAttendeeBody = {
|
||||
email: "[email protected]",
|
||||
name: "No TimeZone Attendee",
|
||||
};
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${testSetup.bookingUid}/attendees`)
|
||||
.send(addAttendeeBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.set("Authorization", `Bearer ${testSetup.organizer.accessToken}`)
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it("should return 400 when timeZone is invalid", async () => {
|
||||
const addAttendeeBody = {
|
||||
email: "[email protected]",
|
||||
name: "Invalid TimeZone Attendee",
|
||||
timeZone: "Invalid/TimeZone",
|
||||
};
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${testSetup.bookingUid}/attendees`)
|
||||
.send(addAttendeeBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.set("Authorization", `Bearer ${testSetup.organizer.accessToken}`)
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it("should return 403 when booking does not exist", async () => {
|
||||
const addAttendeeBody = {
|
||||
email: "[email protected]",
|
||||
name: "Nonexistent Booking Attendee",
|
||||
timeZone: "Europe/London",
|
||||
};
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/non-existent-booking-uid/attendees`)
|
||||
.send(addAttendeeBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.set("Authorization", `Bearer ${testSetup.organizer.accessToken}`)
|
||||
.expect(403);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await teamRepositoryFixture.delete(organization.id);
|
||||
|
||||
await userRepositoryFixture.deleteByEmail(testSetup.organizer.user.email);
|
||||
await userRepositoryFixture.deleteByEmail(testSetup.unrelatedUser.user.email);
|
||||
|
||||
await bookingsRepositoryFixture.deleteAllBookings(
|
||||
testSetup.organizer.user.id,
|
||||
testSetup.organizer.user.email
|
||||
);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
function responseDataIsBooking(data: unknown): data is BookingOutput_2024_08_13 {
|
||||
return !Array.isArray(data) && typeof data === "object" && data !== null && "id" in data;
|
||||
}
|
||||
});
|
||||
@@ -1,392 +0,0 @@
|
||||
import { CAL_API_VERSION_HEADER, SUCCESS_STATUS, VERSION_2024_08_13 } from "@calcom/platform-constants";
|
||||
import type { BookingOutput_2024_08_13, CreateBookingInput_2024_08_13 } from "@calcom/platform-types";
|
||||
import type { PlatformOAuthClient, Team, User } from "@calcom/prisma/client";
|
||||
import { INestApplication } from "@nestjs/common";
|
||||
import { NestExpressApplication } from "@nestjs/platform-express";
|
||||
import { Test } from "@nestjs/testing";
|
||||
import request from "supertest";
|
||||
import { BookingsRepositoryFixture } from "test/fixtures/repository/bookings.repository.fixture";
|
||||
import { EventTypesRepositoryFixture } from "test/fixtures/repository/event-types.repository.fixture";
|
||||
import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture";
|
||||
import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.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 { randomString } from "test/utils/randomString";
|
||||
import { withApiAuth } from "test/utils/withApiAuth";
|
||||
import { AppModule } from "@/app.module";
|
||||
import { bootstrap } from "@/bootstrap";
|
||||
import { CreateBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/create-booking.output";
|
||||
import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input";
|
||||
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
|
||||
import { SchedulesService_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/services/schedules.service";
|
||||
import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard";
|
||||
import { BillingService } from "@/modules/billing/services/billing.service";
|
||||
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||
import { UsersModule } from "@/modules/users/users.module";
|
||||
|
||||
const CLIENT_REDIRECT_URI = "http://localhost:4321";
|
||||
|
||||
describe("Bookings Billing E2E - 2024-08-13", () => {
|
||||
describe("Regular user (non-platform-managed)", () => {
|
||||
jest.setTimeout(30000);
|
||||
let app: INestApplication;
|
||||
let userRepositoryFixture: UserRepositoryFixture;
|
||||
let bookingsRepositoryFixture: BookingsRepositoryFixture;
|
||||
let schedulesService: SchedulesService_2024_04_15;
|
||||
let eventTypesRepositoryFixture: EventTypesRepositoryFixture;
|
||||
let billingService: BillingService;
|
||||
let increaseUsageSpy: jest.SpyInstance;
|
||||
let cancelUsageSpy: jest.SpyInstance;
|
||||
|
||||
const userEmail = `billing-regular-user-2024-08-13-${randomString()}@api.com`;
|
||||
let user: User;
|
||||
let eventTypeId: number;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await withApiAuth(
|
||||
userEmail,
|
||||
Test.createTestingModule({
|
||||
imports: [AppModule, PrismaModule, UsersModule, SchedulesModule_2024_04_15],
|
||||
})
|
||||
)
|
||||
.overrideGuard(PermissionsGuard)
|
||||
.useValue({
|
||||
canActivate: () => true,
|
||||
})
|
||||
.compile();
|
||||
|
||||
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
|
||||
bookingsRepositoryFixture = new BookingsRepositoryFixture(moduleRef);
|
||||
eventTypesRepositoryFixture = new EventTypesRepositoryFixture(moduleRef);
|
||||
schedulesService = moduleRef.get<SchedulesService_2024_04_15>(SchedulesService_2024_04_15);
|
||||
billingService = moduleRef.get<BillingService>(BillingService);
|
||||
|
||||
// Spy on the billing service methods
|
||||
increaseUsageSpy = jest.spyOn(billingService, "increaseUsageByUserId");
|
||||
cancelUsageSpy = jest.spyOn(billingService, "cancelUsageByBookingUid");
|
||||
|
||||
// Create a regular user (not platform-managed)
|
||||
user = await userRepositoryFixture.create({
|
||||
email: userEmail,
|
||||
username: userEmail,
|
||||
isPlatformManaged: false,
|
||||
});
|
||||
|
||||
const userSchedule: CreateScheduleInput_2024_04_15 = {
|
||||
name: `billing-test-schedule-2024-08-13-${randomString()}`,
|
||||
timeZone: "Europe/Rome",
|
||||
isDefault: true,
|
||||
};
|
||||
await schedulesService.createUserSchedule(user.id, userSchedule);
|
||||
|
||||
const event = await eventTypesRepositoryFixture.create(
|
||||
{
|
||||
title: `billing-test-event-type-2024-08-13-${randomString()}`,
|
||||
slug: `billing-test-event-type-2024-08-13-${randomString()}`,
|
||||
length: 60,
|
||||
},
|
||||
user.id
|
||||
);
|
||||
eventTypeId = event.id;
|
||||
|
||||
app = moduleRef.createNestApplication();
|
||||
bootstrap(app as NestExpressApplication);
|
||||
await app.init();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await bookingsRepositoryFixture.deleteAllBookings(user.id, user.email);
|
||||
await userRepositoryFixture.deleteByEmail(user.email);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("should NOT call billing service when creating a booking for a regular user", async () => {
|
||||
increaseUsageSpy.mockClear();
|
||||
|
||||
const body: CreateBookingInput_2024_08_13 = {
|
||||
start: new Date(Date.UTC(2040, 4, 21, 9, 30, 0)).toISOString(),
|
||||
eventTypeId: eventTypeId,
|
||||
attendee: {
|
||||
name: "Test Attendee",
|
||||
email: "[email protected]",
|
||||
timeZone: "Europe/London",
|
||||
language: "en",
|
||||
},
|
||||
location: "https://meet.google.com/abc-def-ghi",
|
||||
};
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post("/v2/bookings")
|
||||
.send(body)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.expect(201);
|
||||
|
||||
const responseBody: CreateBookingOutput_2024_08_13 = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data).toBeDefined();
|
||||
|
||||
// Verify billing service was NOT called for regular user
|
||||
expect(increaseUsageSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should NOT call billing cancel service when cancelling a booking for a regular user", async () => {
|
||||
// First create a booking
|
||||
const createBody: CreateBookingInput_2024_08_13 = {
|
||||
start: new Date(Date.UTC(2040, 4, 22, 9, 30, 0)).toISOString(),
|
||||
eventTypeId: eventTypeId,
|
||||
attendee: {
|
||||
name: "Test Attendee Cancel",
|
||||
email: "[email protected]",
|
||||
timeZone: "Europe/London",
|
||||
language: "en",
|
||||
},
|
||||
location: "https://meet.google.com/abc-def-ghi",
|
||||
};
|
||||
|
||||
const createResponse = await request(app.getHttpServer())
|
||||
.post("/v2/bookings")
|
||||
.send(createBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.expect(201);
|
||||
|
||||
const createResponseBody: CreateBookingOutput_2024_08_13 = createResponse.body;
|
||||
const data = createResponseBody.data as BookingOutput_2024_08_13;
|
||||
const bookingUid = data.uid;
|
||||
|
||||
// Clear the spy before cancelling
|
||||
cancelUsageSpy.mockClear();
|
||||
|
||||
// Cancel the booking
|
||||
await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${bookingUid}/cancel`)
|
||||
.send({})
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.expect(200);
|
||||
|
||||
// Verify billing cancel service was NOT called for regular user
|
||||
expect(cancelUsageSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Platform-managed user", () => {
|
||||
jest.setTimeout(30000);
|
||||
let app: INestApplication;
|
||||
let userRepositoryFixture: UserRepositoryFixture;
|
||||
let bookingsRepositoryFixture: BookingsRepositoryFixture;
|
||||
let schedulesService: SchedulesService_2024_04_15;
|
||||
let eventTypesRepositoryFixture: EventTypesRepositoryFixture;
|
||||
let oauthClientRepositoryFixture: OAuthClientRepositoryFixture;
|
||||
let teamRepositoryFixture: TeamRepositoryFixture;
|
||||
let profilesRepositoryFixture: ProfileRepositoryFixture;
|
||||
let membershipsRepositoryFixture: MembershipRepositoryFixture;
|
||||
let billingService: BillingService;
|
||||
let increaseUsageSpy: jest.SpyInstance;
|
||||
let cancelUsageSpy: jest.SpyInstance;
|
||||
|
||||
const platformAdminEmail = `billing-platform-admin-2024-08-13-${randomString()}@api.com`;
|
||||
const managedUserEmail = `billing-managed-user-2024-08-13-${randomString()}@api.com`;
|
||||
let platformAdmin: User;
|
||||
let managedUser: User;
|
||||
let organization: Team;
|
||||
let oAuthClient: PlatformOAuthClient;
|
||||
let eventTypeId: number;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await withApiAuth(
|
||||
managedUserEmail,
|
||||
Test.createTestingModule({
|
||||
imports: [AppModule, PrismaModule, UsersModule, SchedulesModule_2024_04_15],
|
||||
})
|
||||
)
|
||||
.overrideGuard(PermissionsGuard)
|
||||
.useValue({
|
||||
canActivate: () => true,
|
||||
})
|
||||
.compile();
|
||||
|
||||
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
|
||||
bookingsRepositoryFixture = new BookingsRepositoryFixture(moduleRef);
|
||||
eventTypesRepositoryFixture = new EventTypesRepositoryFixture(moduleRef);
|
||||
schedulesService = moduleRef.get<SchedulesService_2024_04_15>(SchedulesService_2024_04_15);
|
||||
oauthClientRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef);
|
||||
teamRepositoryFixture = new TeamRepositoryFixture(moduleRef);
|
||||
profilesRepositoryFixture = new ProfileRepositoryFixture(moduleRef);
|
||||
membershipsRepositoryFixture = new MembershipRepositoryFixture(moduleRef);
|
||||
billingService = moduleRef.get<BillingService>(BillingService);
|
||||
|
||||
// Spy on the billing service methods
|
||||
increaseUsageSpy = jest.spyOn(billingService, "increaseUsageByUserId");
|
||||
cancelUsageSpy = jest.spyOn(billingService, "cancelUsageByBookingUid");
|
||||
|
||||
// Create platform admin
|
||||
platformAdmin = await userRepositoryFixture.create({ email: platformAdminEmail });
|
||||
|
||||
// Create organization
|
||||
organization = await teamRepositoryFixture.create({
|
||||
name: `billing-test-organization-2024-08-13-${randomString()}`,
|
||||
isPlatform: true,
|
||||
isOrganization: true,
|
||||
});
|
||||
|
||||
// Create OAuth client
|
||||
oAuthClient = await oauthClientRepositoryFixture.create(
|
||||
organization.id,
|
||||
{
|
||||
logo: "logo-url",
|
||||
name: "billing-test-oauth-client-2024-08-13",
|
||||
redirectUris: [CLIENT_REDIRECT_URI],
|
||||
permissions: 1023,
|
||||
},
|
||||
"secret"
|
||||
);
|
||||
|
||||
// Create profile for platform admin
|
||||
await profilesRepositoryFixture.create({
|
||||
uid: `billing-test-profile-2024-08-13-${randomString()}`,
|
||||
username: platformAdminEmail,
|
||||
organization: { connect: { id: organization.id } },
|
||||
user: { connect: { id: platformAdmin.id } },
|
||||
});
|
||||
|
||||
// Create membership for platform admin
|
||||
await membershipsRepositoryFixture.create({
|
||||
role: "OWNER",
|
||||
user: { connect: { id: platformAdmin.id } },
|
||||
team: { connect: { id: organization.id } },
|
||||
accepted: true,
|
||||
});
|
||||
|
||||
// Create a platform-managed user
|
||||
managedUser = await userRepositoryFixture.create({
|
||||
email: managedUserEmail,
|
||||
username: managedUserEmail,
|
||||
isPlatformManaged: true,
|
||||
platformOAuthClients: {
|
||||
connect: { id: oAuthClient.id },
|
||||
},
|
||||
});
|
||||
|
||||
// Create profile for managed user
|
||||
await profilesRepositoryFixture.create({
|
||||
uid: `billing-managed-user-profile-2024-08-13-${randomString()}`,
|
||||
username: managedUserEmail,
|
||||
organization: { connect: { id: organization.id } },
|
||||
user: { connect: { id: managedUser.id } },
|
||||
});
|
||||
|
||||
// Create membership for managed user
|
||||
await membershipsRepositoryFixture.create({
|
||||
role: "MEMBER",
|
||||
user: { connect: { id: managedUser.id } },
|
||||
team: { connect: { id: organization.id } },
|
||||
accepted: true,
|
||||
});
|
||||
|
||||
const userSchedule: CreateScheduleInput_2024_04_15 = {
|
||||
name: `billing-managed-user-schedule-2024-08-13-${randomString()}`,
|
||||
timeZone: "Europe/Rome",
|
||||
isDefault: true,
|
||||
};
|
||||
await schedulesService.createUserSchedule(managedUser.id, userSchedule);
|
||||
|
||||
const event = await eventTypesRepositoryFixture.create(
|
||||
{
|
||||
title: `billing-managed-user-event-type-2024-08-13-${randomString()}`,
|
||||
slug: `billing-managed-user-event-type-2024-08-13-${randomString()}`,
|
||||
length: 60,
|
||||
},
|
||||
managedUser.id
|
||||
);
|
||||
eventTypeId = event.id;
|
||||
|
||||
app = moduleRef.createNestApplication();
|
||||
bootstrap(app as NestExpressApplication);
|
||||
await app.init();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await bookingsRepositoryFixture.deleteAllBookings(managedUser.id, managedUser.email);
|
||||
await userRepositoryFixture.deleteByEmail(managedUser.email);
|
||||
await userRepositoryFixture.deleteByEmail(platformAdmin.email);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("should call billing service when creating a booking for a platform-managed user", async () => {
|
||||
increaseUsageSpy.mockClear();
|
||||
|
||||
const body: CreateBookingInput_2024_08_13 = {
|
||||
start: new Date(Date.UTC(2040, 4, 21, 9, 30, 0)).toISOString(),
|
||||
eventTypeId: eventTypeId,
|
||||
attendee: {
|
||||
name: "Test Attendee",
|
||||
email: "[email protected]",
|
||||
timeZone: "Europe/London",
|
||||
language: "en",
|
||||
},
|
||||
location: "https://meet.google.com/abc-def-ghi",
|
||||
};
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post("/v2/bookings")
|
||||
.send(body)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.expect(201);
|
||||
|
||||
const responseBody: CreateBookingOutput_2024_08_13 = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data).toBeDefined();
|
||||
|
||||
const data = responseBody.data as BookingOutput_2024_08_13;
|
||||
|
||||
// Verify billing service WAS called for platform-managed user
|
||||
expect(increaseUsageSpy).toHaveBeenCalledTimes(1);
|
||||
expect(increaseUsageSpy).toHaveBeenCalledWith(
|
||||
managedUser.id,
|
||||
expect.objectContaining({
|
||||
uid: data.uid,
|
||||
startTime: expect.any(Date),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should call billing cancel service when cancelling a booking for a platform-managed user", async () => {
|
||||
// First create a booking
|
||||
const createBody: CreateBookingInput_2024_08_13 = {
|
||||
start: new Date(Date.UTC(2040, 4, 22, 9, 30, 0)).toISOString(),
|
||||
eventTypeId: eventTypeId,
|
||||
attendee: {
|
||||
name: "Test Attendee Cancel",
|
||||
email: "[email protected]",
|
||||
timeZone: "Europe/London",
|
||||
language: "en",
|
||||
},
|
||||
location: "https://meet.google.com/abc-def-ghi",
|
||||
};
|
||||
|
||||
const createResponse = await request(app.getHttpServer())
|
||||
.post("/v2/bookings")
|
||||
.send(createBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.expect(201);
|
||||
|
||||
const createResponseBody: CreateBookingOutput_2024_08_13 = createResponse.body;
|
||||
const data = createResponseBody.data as BookingOutput_2024_08_13;
|
||||
const bookingUid = data.uid;
|
||||
|
||||
// Clear the spy before cancelling
|
||||
cancelUsageSpy.mockClear();
|
||||
|
||||
// Cancel the booking
|
||||
await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${bookingUid}/cancel`)
|
||||
.send({})
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.expect(200);
|
||||
|
||||
// Verify billing cancel service WAS called for platform-managed user
|
||||
expect(cancelUsageSpy).toHaveBeenCalledTimes(1);
|
||||
expect(cancelUsageSpy).toHaveBeenCalledWith(bookingUid);
|
||||
});
|
||||
});
|
||||
});
|
||||
-533
@@ -1,533 +0,0 @@
|
||||
import { CAL_API_VERSION_HEADER, SUCCESS_STATUS, VERSION_2024_08_13 } from "@calcom/platform-constants";
|
||||
import {
|
||||
AttendeeCancelledEmail,
|
||||
AttendeeRescheduledEmail,
|
||||
AttendeeScheduledEmail,
|
||||
AttendeeUpdatedEmail,
|
||||
OrganizerCancelledEmail,
|
||||
OrganizerReassignedEmail,
|
||||
OrganizerRescheduledEmail,
|
||||
OrganizerScheduledEmail,
|
||||
} from "@calcom/platform-libraries/emails";
|
||||
import type {
|
||||
BookingOutput_2024_08_13,
|
||||
CancelBookingInput_2024_08_13,
|
||||
CreateBookingInput_2024_08_13,
|
||||
RescheduleBookingInput_2024_08_13,
|
||||
} from "@calcom/platform-types";
|
||||
import type { Team, User } from "@calcom/prisma/client";
|
||||
import { INestApplication } from "@nestjs/common";
|
||||
import { NestExpressApplication } from "@nestjs/platform-express";
|
||||
import { Test } from "@nestjs/testing";
|
||||
import request from "supertest";
|
||||
import { ApiKeysRepositoryFixture } from "test/fixtures/repository/api-keys.repository.fixture";
|
||||
import { EventTypesRepositoryFixture } from "test/fixtures/repository/event-types.repository.fixture";
|
||||
import { HostsRepositoryFixture } from "test/fixtures/repository/hosts.repository.fixture";
|
||||
import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture";
|
||||
import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.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 { randomString } from "test/utils/randomString";
|
||||
import { AppModule } from "@/app.module";
|
||||
import { bootstrap } from "@/bootstrap";
|
||||
import { CreateBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/create-booking.output";
|
||||
import { RescheduleBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/reschedule-booking.output";
|
||||
import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input";
|
||||
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
|
||||
import { SchedulesService_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/services/schedules.service";
|
||||
import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard";
|
||||
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||
import { UsersModule } from "@/modules/users/users.module";
|
||||
|
||||
// Mock all email sending prototypes
|
||||
jest
|
||||
.spyOn(AttendeeScheduledEmail.prototype, "getHtml")
|
||||
.mockImplementation(() => Promise.resolve("<p>email</p>"));
|
||||
jest
|
||||
.spyOn(OrganizerScheduledEmail.prototype, "getHtml")
|
||||
.mockImplementation(() => Promise.resolve("<p>email</p>"));
|
||||
jest
|
||||
.spyOn(AttendeeRescheduledEmail.prototype, "getHtml")
|
||||
.mockImplementation(() => Promise.resolve("<p>email</p>"));
|
||||
jest
|
||||
.spyOn(OrganizerRescheduledEmail.prototype, "getHtml")
|
||||
.mockImplementation(() => Promise.resolve("<p>email</p>"));
|
||||
jest
|
||||
.spyOn(AttendeeCancelledEmail.prototype, "getHtml")
|
||||
.mockImplementation(() => Promise.resolve("<p>email</p>"));
|
||||
jest
|
||||
.spyOn(OrganizerCancelledEmail.prototype, "getHtml")
|
||||
.mockImplementation(() => Promise.resolve("<p>email</p>"));
|
||||
jest
|
||||
.spyOn(OrganizerReassignedEmail.prototype, "getHtml")
|
||||
.mockImplementation(() => Promise.resolve("<p>email</p>"));
|
||||
jest
|
||||
.spyOn(AttendeeUpdatedEmail.prototype, "getHtml")
|
||||
.mockImplementation(() => Promise.resolve("<p>email</p>"));
|
||||
|
||||
// Type definitions for test setup data
|
||||
type EmailSetup = {
|
||||
team: Team;
|
||||
member1: User;
|
||||
member2: User;
|
||||
member1ApiKey: string;
|
||||
collectiveEventType: { id: number };
|
||||
roundRobinEventType: { id: number };
|
||||
};
|
||||
|
||||
describe("Bookings Endpoints 2024-08-13 team emails", () => {
|
||||
let app: INestApplication;
|
||||
let organization: Team;
|
||||
|
||||
// Fixtures for database interactions
|
||||
let userRepositoryFixture: UserRepositoryFixture;
|
||||
let schedulesService: SchedulesService_2024_04_15;
|
||||
let eventTypesRepositoryFixture: EventTypesRepositoryFixture;
|
||||
let oauthClientRepositoryFixture: OAuthClientRepositoryFixture;
|
||||
let teamRepositoryFixture: TeamRepositoryFixture;
|
||||
let profileRepositoryFixture: ProfileRepositoryFixture;
|
||||
let membershipsRepositoryFixture: MembershipRepositoryFixture;
|
||||
let hostsRepositoryFixture: HostsRepositoryFixture;
|
||||
let apiKeysRepositoryFixture: ApiKeysRepositoryFixture;
|
||||
|
||||
// Setup data for tests
|
||||
let emailsEnabledSetup: EmailSetup;
|
||||
let emailsDisabledSetup: EmailSetup;
|
||||
|
||||
// Utility function to check response data type
|
||||
const responseDataIsBooking = (data: unknown): data is BookingOutput_2024_08_13 => {
|
||||
return !Array.isArray(data) && data !== null && typeof data === "object" && data && "id" in data;
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [AppModule, PrismaModule, UsersModule, SchedulesModule_2024_04_15],
|
||||
})
|
||||
.overrideGuard(PermissionsGuard)
|
||||
.useValue({
|
||||
canActivate: () => true,
|
||||
})
|
||||
.compile();
|
||||
|
||||
// Initialize fixtures and services
|
||||
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
|
||||
eventTypesRepositoryFixture = new EventTypesRepositoryFixture(moduleRef);
|
||||
oauthClientRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef);
|
||||
teamRepositoryFixture = new TeamRepositoryFixture(moduleRef);
|
||||
profileRepositoryFixture = new ProfileRepositoryFixture(moduleRef);
|
||||
membershipsRepositoryFixture = new MembershipRepositoryFixture(moduleRef);
|
||||
hostsRepositoryFixture = new HostsRepositoryFixture(moduleRef);
|
||||
apiKeysRepositoryFixture = new ApiKeysRepositoryFixture(moduleRef);
|
||||
schedulesService = moduleRef.get<SchedulesService_2024_04_15>(SchedulesService_2024_04_15);
|
||||
|
||||
// Create a base organization for all tests
|
||||
organization = await teamRepositoryFixture.create({ name: `team-emails-organization-${randomString()}` });
|
||||
|
||||
// Set up two distinct environments: one with emails enabled, one disabled
|
||||
emailsEnabledSetup = await setupTestEnvironment(true);
|
||||
emailsDisabledSetup = await setupTestEnvironment(false);
|
||||
|
||||
app = moduleRef.createNestApplication();
|
||||
bootstrap(app as NestExpressApplication);
|
||||
await app.init();
|
||||
});
|
||||
|
||||
// Helper function to create a complete test environment
|
||||
async function setupTestEnvironment(emailsEnabled: boolean): Promise<EmailSetup> {
|
||||
const oAuthClient = await createOAuthClient(organization.id, emailsEnabled);
|
||||
const team = await teamRepositoryFixture.create({
|
||||
name: `team-emails-team-${randomString()}`,
|
||||
parent: { connect: { id: organization.id } },
|
||||
createdByOAuthClient: { connect: { id: oAuthClient.id } },
|
||||
});
|
||||
|
||||
const [member1, member2] = await Promise.all([
|
||||
createTeamMember(oAuthClient.id),
|
||||
createTeamMember(oAuthClient.id),
|
||||
]);
|
||||
|
||||
await Promise.all([
|
||||
membershipsRepositoryFixture.create({
|
||||
role: "MEMBER",
|
||||
user: { connect: { id: member1.id } },
|
||||
team: { connect: { id: team.id } },
|
||||
accepted: true,
|
||||
}),
|
||||
membershipsRepositoryFixture.create({
|
||||
role: "MEMBER",
|
||||
user: { connect: { id: member2.id } },
|
||||
team: { connect: { id: team.id } },
|
||||
accepted: true,
|
||||
}),
|
||||
]);
|
||||
|
||||
const collectiveEvent = await createEventType("COLLECTIVE", team.id, [member1.id, member2.id]);
|
||||
const roundRobinEvent = await createEventType("ROUND_ROBIN", team.id, [member1.id, member2.id]);
|
||||
|
||||
// Create API key for member1 to use in authorized tests
|
||||
const { keyString } = await apiKeysRepositoryFixture.createApiKey(member1.id, null);
|
||||
const member1ApiKey = `cal_test_${keyString}`;
|
||||
|
||||
return {
|
||||
team,
|
||||
member1,
|
||||
member2,
|
||||
member1ApiKey,
|
||||
collectiveEventType: { id: collectiveEvent.id },
|
||||
roundRobinEventType: { id: roundRobinEvent.id },
|
||||
};
|
||||
}
|
||||
|
||||
// Helper to create a user and their profile/schedule
|
||||
async function createTeamMember(oauthClientId: string) {
|
||||
const member = await userRepositoryFixture.create({
|
||||
email: `team-emails-member-${randomString()}@api.com`,
|
||||
platformOAuthClients: { connect: { id: oauthClientId } },
|
||||
});
|
||||
const userSchedule: CreateScheduleInput_2024_04_15 = {
|
||||
name: `schedule-${randomString()}`,
|
||||
timeZone: "Europe/Rome",
|
||||
isDefault: true,
|
||||
};
|
||||
await schedulesService.createUserSchedule(member.id, userSchedule);
|
||||
await profileRepositoryFixture.create({
|
||||
uid: `usr-${member.id}`,
|
||||
username: member.email,
|
||||
organization: { connect: { id: organization.id } },
|
||||
user: { connect: { id: member.id } },
|
||||
});
|
||||
return member;
|
||||
}
|
||||
|
||||
// Helper to create an event type and assign hosts
|
||||
async function createEventType(type: "COLLECTIVE" | "ROUND_ROBIN", teamId: number, hostIds: number[]) {
|
||||
const eventType = await eventTypesRepositoryFixture.createTeamEventType({
|
||||
schedulingType: type,
|
||||
team: { connect: { id: teamId } },
|
||||
title: `event-type-${randomString()}`,
|
||||
slug: `event-type-${randomString()}`,
|
||||
length: 60,
|
||||
assignAllTeamMembers: type === "COLLECTIVE",
|
||||
locations: [{ type: "inPerson", address: "via 10, rome, italy" }],
|
||||
});
|
||||
await Promise.all(
|
||||
hostIds.map((userId) =>
|
||||
hostsRepositoryFixture.create({
|
||||
isFixed: type === "COLLECTIVE",
|
||||
user: { connect: { id: userId } },
|
||||
eventType: { connect: { id: eventType.id } },
|
||||
})
|
||||
)
|
||||
);
|
||||
return eventType;
|
||||
}
|
||||
|
||||
// Helper to create an OAuth client
|
||||
async function createOAuthClient(organizationId: number, emailsEnabled: boolean) {
|
||||
return oauthClientRepositoryFixture.create(
|
||||
organizationId,
|
||||
{
|
||||
logo: "logo-url",
|
||||
name: "name",
|
||||
redirectUris: ["http://localhost:5555"],
|
||||
permissions: 32,
|
||||
areEmailsEnabled: emailsEnabled,
|
||||
},
|
||||
"secret"
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("OAuth client team bookings - emails disabled", () => {
|
||||
it("should handle the full booking lifecycle for a collective event without sending emails", async () => {
|
||||
// --- 1. Book Event ---
|
||||
const createBody: CreateBookingInput_2024_08_13 = {
|
||||
start: new Date(Date.UTC(2030, 0, 8, 9, 0, 0)).toISOString(),
|
||||
eventTypeId: emailsDisabledSetup.collectiveEventType.id,
|
||||
attendee: {
|
||||
name: "Mr Proper",
|
||||
email: "[email protected]",
|
||||
timeZone: "Europe/Rome",
|
||||
language: "it",
|
||||
},
|
||||
};
|
||||
const createResponse = await request(app.getHttpServer())
|
||||
.post("/v2/bookings")
|
||||
.send(createBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13);
|
||||
|
||||
expect(createResponse.status).toBe(201);
|
||||
const createResponseBody: CreateBookingOutput_2024_08_13 = createResponse.body;
|
||||
expect(createResponseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseDataIsBooking(createResponseBody.data)).toBe(true);
|
||||
const bookingUid = (createResponseBody.data as BookingOutput_2024_08_13).uid;
|
||||
|
||||
expect(AttendeeScheduledEmail.prototype.getHtml).not.toHaveBeenCalled();
|
||||
expect(OrganizerScheduledEmail.prototype.getHtml).not.toHaveBeenCalled();
|
||||
|
||||
// --- 2. Reschedule Event ---
|
||||
const rescheduleBody: RescheduleBookingInput_2024_08_13 = {
|
||||
start: new Date(Date.UTC(2035, 0, 8, 11, 0, 0)).toISOString(),
|
||||
reschedulingReason: "Flying to mars that day",
|
||||
};
|
||||
const rescheduleResponse = await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${bookingUid}/reschedule`)
|
||||
.send(rescheduleBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13);
|
||||
|
||||
expect(rescheduleResponse.status).toBe(201);
|
||||
const rescheduleResponseBody: RescheduleBookingOutput_2024_08_13 = rescheduleResponse.body;
|
||||
expect(rescheduleResponseBody.status).toEqual(SUCCESS_STATUS);
|
||||
const rescheduledBookingUid = rescheduleResponseBody.data.uid;
|
||||
|
||||
expect(AttendeeRescheduledEmail.prototype.getHtml).not.toHaveBeenCalled();
|
||||
expect(OrganizerRescheduledEmail.prototype.getHtml).not.toHaveBeenCalled();
|
||||
|
||||
// --- 3. Cancel Event ---
|
||||
const cancelBody: CancelBookingInput_2024_08_13 = { cancellationReason: "Going on a vacation" };
|
||||
const cancelResponse = await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${rescheduledBookingUid}/cancel`)
|
||||
.send(cancelBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13);
|
||||
|
||||
expect(cancelResponse.status).toBe(200);
|
||||
expect(cancelResponse.body.status).toEqual(SUCCESS_STATUS);
|
||||
expect(AttendeeCancelledEmail.prototype.getHtml).not.toHaveBeenCalled();
|
||||
expect(OrganizerCancelledEmail.prototype.getHtml).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle the full booking lifecycle for a round-robin event without sending emails", async () => {
|
||||
// --- 1. Book Event ---
|
||||
const createBody: CreateBookingInput_2024_08_13 = {
|
||||
start: new Date(Date.UTC(2030, 0, 8, 10, 0, 0)).toISOString(),
|
||||
eventTypeId: emailsDisabledSetup.roundRobinEventType.id,
|
||||
attendee: {
|
||||
name: "Mr Proper",
|
||||
email: "[email protected]",
|
||||
timeZone: "Europe/Rome",
|
||||
language: "it",
|
||||
},
|
||||
};
|
||||
const createResponse = await request(app.getHttpServer())
|
||||
.post("/v2/bookings")
|
||||
.send(createBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13);
|
||||
|
||||
expect(createResponse.status).toBe(201);
|
||||
const createResponseBody: CreateBookingOutput_2024_08_13 = createResponse.body;
|
||||
expect(responseDataIsBooking(createResponseBody.data)).toBe(true);
|
||||
const bookingUid = (createResponseBody.data as BookingOutput_2024_08_13).uid;
|
||||
let currentHostId = (createResponseBody.data as BookingOutput_2024_08_13).hosts[0].id;
|
||||
expect(AttendeeScheduledEmail.prototype.getHtml).not.toHaveBeenCalled();
|
||||
expect(OrganizerScheduledEmail.prototype.getHtml).not.toHaveBeenCalled();
|
||||
|
||||
// --- 2. Reschedule Event ---
|
||||
const rescheduleBody: RescheduleBookingInput_2024_08_13 = {
|
||||
start: new Date(Date.UTC(2035, 0, 8, 12, 0, 0)).toISOString(),
|
||||
};
|
||||
const rescheduleResponse = await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${bookingUid}/reschedule`)
|
||||
.send(rescheduleBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13);
|
||||
|
||||
expect(rescheduleResponse.status).toBe(201);
|
||||
const rescheduleResponseBody: RescheduleBookingOutput_2024_08_13 = rescheduleResponse.body;
|
||||
const rescheduledBookingUid = rescheduleResponseBody.data.uid;
|
||||
currentHostId = rescheduleResponseBody.data.hosts[0].id;
|
||||
expect(AttendeeRescheduledEmail.prototype.getHtml).not.toHaveBeenCalled();
|
||||
expect(OrganizerRescheduledEmail.prototype.getHtml).not.toHaveBeenCalled();
|
||||
|
||||
// --- 3. Manual Reassign ---
|
||||
const reassignToId =
|
||||
currentHostId === emailsDisabledSetup.member1.id
|
||||
? emailsDisabledSetup.member2.id
|
||||
: emailsDisabledSetup.member1.id;
|
||||
const manualReassignResponse = await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${rescheduledBookingUid}/reassign/${reassignToId}`)
|
||||
.set("Authorization", `Bearer ${emailsDisabledSetup.member1ApiKey}`)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13);
|
||||
|
||||
expect(manualReassignResponse.status).toBe(200);
|
||||
expect(AttendeeUpdatedEmail.prototype.getHtml).not.toHaveBeenCalled();
|
||||
|
||||
// --- 4. Automatic Reassign ---
|
||||
const autoReassignResponse = await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${rescheduledBookingUid}/reassign`)
|
||||
.set("Authorization", `Bearer ${emailsDisabledSetup.member1ApiKey}`)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13);
|
||||
|
||||
expect(autoReassignResponse.status).toBe(200);
|
||||
expect(OrganizerReassignedEmail.prototype.getHtml).not.toHaveBeenCalled();
|
||||
expect(AttendeeUpdatedEmail.prototype.getHtml).not.toHaveBeenCalled();
|
||||
|
||||
// --- 5. Cancel Event ---
|
||||
const cancelBody: CancelBookingInput_2024_08_13 = { cancellationReason: "Vacation" };
|
||||
const cancelResponse = await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${rescheduledBookingUid}/cancel`)
|
||||
.send(cancelBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13);
|
||||
|
||||
expect(cancelResponse.status).toBe(200);
|
||||
expect(AttendeeCancelledEmail.prototype.getHtml).not.toHaveBeenCalled();
|
||||
expect(OrganizerCancelledEmail.prototype.getHtml).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("OAuth client team bookings - emails enabled", () => {
|
||||
it("should handle the full booking lifecycle for a collective event and send emails", async () => {
|
||||
// --- 1. Book Event ---
|
||||
const createBody: CreateBookingInput_2024_08_13 = {
|
||||
start: new Date(Date.UTC(2030, 0, 8, 9, 0, 0)).toISOString(),
|
||||
eventTypeId: emailsEnabledSetup.collectiveEventType.id,
|
||||
attendee: {
|
||||
name: "Mr Proper",
|
||||
email: "[email protected]",
|
||||
timeZone: "Europe/Rome",
|
||||
language: "it",
|
||||
},
|
||||
};
|
||||
const createResponse = await request(app.getHttpServer())
|
||||
.post("/v2/bookings")
|
||||
.send(createBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13);
|
||||
|
||||
expect(createResponse.status).toBe(201);
|
||||
const createResponseBody: CreateBookingOutput_2024_08_13 = createResponse.body;
|
||||
expect(responseDataIsBooking(createResponseBody.data)).toBe(true);
|
||||
const bookingUid = (createResponseBody.data as BookingOutput_2024_08_13).uid;
|
||||
|
||||
expect(AttendeeScheduledEmail.prototype.getHtml).toHaveBeenCalled();
|
||||
expect(OrganizerScheduledEmail.prototype.getHtml).toHaveBeenCalled();
|
||||
|
||||
// --- 2. Reschedule Event ---
|
||||
const rescheduleBody: RescheduleBookingInput_2024_08_13 = {
|
||||
start: new Date(Date.UTC(2035, 0, 8, 11, 0, 0)).toISOString(),
|
||||
};
|
||||
const rescheduleResponse = await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${bookingUid}/reschedule`)
|
||||
.send(rescheduleBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13);
|
||||
|
||||
expect(rescheduleResponse.status).toBe(201);
|
||||
const rescheduledBookingUid = (rescheduleResponse.body as RescheduleBookingOutput_2024_08_13).data.uid;
|
||||
expect(AttendeeRescheduledEmail.prototype.getHtml).toHaveBeenCalled();
|
||||
expect(OrganizerRescheduledEmail.prototype.getHtml).toHaveBeenCalled();
|
||||
|
||||
// --- 3. Cancel Event ---
|
||||
const cancelBody: CancelBookingInput_2024_08_13 = { cancellationReason: "Vacation" };
|
||||
const cancelResponse = await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${rescheduledBookingUid}/cancel`)
|
||||
.send(cancelBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13);
|
||||
|
||||
expect(cancelResponse.status).toBe(200);
|
||||
expect(AttendeeCancelledEmail.prototype.getHtml).toHaveBeenCalled();
|
||||
expect(OrganizerCancelledEmail.prototype.getHtml).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle the full booking lifecycle for a round-robin event and send emails", async () => {
|
||||
// --- 1. Book Event ---
|
||||
const createBody: CreateBookingInput_2024_08_13 = {
|
||||
start: new Date(Date.UTC(2030, 0, 8, 10, 0, 0)).toISOString(),
|
||||
eventTypeId: emailsEnabledSetup.roundRobinEventType.id,
|
||||
attendee: {
|
||||
name: "Mr Proper",
|
||||
email: "[email protected]",
|
||||
timeZone: "Europe/Rome",
|
||||
language: "it",
|
||||
},
|
||||
};
|
||||
const createResponse = await request(app.getHttpServer())
|
||||
.post("/v2/bookings")
|
||||
.send(createBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13);
|
||||
|
||||
expect(createResponse.status).toBe(201);
|
||||
const createResponseBody: CreateBookingOutput_2024_08_13 = createResponse.body;
|
||||
expect(responseDataIsBooking(createResponseBody.data)).toBe(true);
|
||||
const bookingUid = (createResponseBody.data as BookingOutput_2024_08_13).uid;
|
||||
let currentHostId = (createResponseBody.data as BookingOutput_2024_08_13).hosts[0].id;
|
||||
expect(AttendeeScheduledEmail.prototype.getHtml).toHaveBeenCalled();
|
||||
expect(OrganizerScheduledEmail.prototype.getHtml).toHaveBeenCalled();
|
||||
|
||||
// --- 2. Reschedule Event ---
|
||||
jest.clearAllMocks();
|
||||
const rescheduleBody: RescheduleBookingInput_2024_08_13 = {
|
||||
start: new Date(Date.UTC(2035, 0, 8, 12, 0, 0)).toISOString(),
|
||||
};
|
||||
const rescheduleResponse = await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${bookingUid}/reschedule`)
|
||||
.send(rescheduleBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13);
|
||||
|
||||
expect(rescheduleResponse.status).toBe(201);
|
||||
const rescheduleResponseBody: RescheduleBookingOutput_2024_08_13 = rescheduleResponse.body;
|
||||
const rescheduledBookingUid = rescheduleResponseBody.data.uid;
|
||||
currentHostId = rescheduleResponseBody.data.hosts[0].id;
|
||||
expect(AttendeeRescheduledEmail.prototype.getHtml).toHaveBeenCalled();
|
||||
expect(OrganizerCancelledEmail.prototype.getHtml).toHaveBeenCalled(); // Old host gets cancellation
|
||||
expect(OrganizerScheduledEmail.prototype.getHtml).toHaveBeenCalled(); // New host gets scheduled
|
||||
|
||||
// --- 3. Manual Reassign ---
|
||||
jest.clearAllMocks();
|
||||
const originalHostId = currentHostId;
|
||||
const reassignToId =
|
||||
currentHostId === emailsEnabledSetup.member1.id
|
||||
? emailsEnabledSetup.member2.id
|
||||
: emailsEnabledSetup.member1.id;
|
||||
const hasOrganizerChanged = reassignToId !== originalHostId;
|
||||
|
||||
const manualReassignResponse = await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${rescheduledBookingUid}/reassign/${reassignToId}`)
|
||||
.set("Authorization", `Bearer ${emailsEnabledSetup.member1ApiKey}`)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13);
|
||||
|
||||
expect(manualReassignResponse.status).toBe(200);
|
||||
expect(OrganizerScheduledEmail.prototype.getHtml).toHaveBeenCalled();
|
||||
expect(AttendeeCancelledEmail.prototype.getHtml).not.toHaveBeenCalled();
|
||||
if (hasOrganizerChanged) {
|
||||
expect(AttendeeUpdatedEmail.prototype.getHtml).toHaveBeenCalled();
|
||||
} else {
|
||||
expect(AttendeeUpdatedEmail.prototype.getHtml).not.toHaveBeenCalled();
|
||||
}
|
||||
|
||||
// --- 4. Automatic Reassign ---
|
||||
jest.clearAllMocks();
|
||||
const autoReassignResponse = await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${rescheduledBookingUid}/reassign`)
|
||||
.set("Authorization", `Bearer ${emailsEnabledSetup.member1ApiKey}`)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13);
|
||||
|
||||
expect(autoReassignResponse.status).toBe(200);
|
||||
expect(OrganizerScheduledEmail.prototype.getHtml).toHaveBeenCalled();
|
||||
expect(OrganizerReassignedEmail.prototype.getHtml).toHaveBeenCalled();
|
||||
expect(AttendeeUpdatedEmail.prototype.getHtml).toHaveBeenCalled();
|
||||
|
||||
// --- 5. Cancel Event ---
|
||||
jest.clearAllMocks();
|
||||
const cancelBody: CancelBookingInput_2024_08_13 = { cancellationReason: "Vacation" };
|
||||
const cancelResponse = await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${rescheduledBookingUid}/cancel`)
|
||||
.send(cancelBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13);
|
||||
|
||||
expect(cancelResponse.status).toBe(200);
|
||||
expect(AttendeeCancelledEmail.prototype.getHtml).toHaveBeenCalled();
|
||||
expect(OrganizerCancelledEmail.prototype.getHtml).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
// Clean up database records
|
||||
await teamRepositoryFixture.delete(organization.id);
|
||||
await userRepositoryFixture.deleteByEmail(emailsEnabledSetup.member1.email);
|
||||
await userRepositoryFixture.deleteByEmail(emailsEnabledSetup.member2.email);
|
||||
await userRepositoryFixture.deleteByEmail(emailsDisabledSetup.member1.email);
|
||||
await userRepositoryFixture.deleteByEmail(emailsDisabledSetup.member2.email);
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
-1057
File diff suppressed because it is too large.
Load diff
@@ -1,809 +0,0 @@
|
||||
import { CAL_API_VERSION_HEADER, SUCCESS_STATUS, VERSION_2024_08_13 } from "@calcom/platform-constants";
|
||||
import type { CreateBookingInput_2024_08_13 } from "@calcom/platform-types";
|
||||
import type { Booking, PlatformOAuthClient, Team, User } from "@calcom/prisma/client";
|
||||
import { INestApplication } from "@nestjs/common";
|
||||
import { NestExpressApplication } from "@nestjs/platform-express";
|
||||
import { Test } from "@nestjs/testing";
|
||||
import request from "supertest";
|
||||
import { ApiKeysRepositoryFixture } from "test/fixtures/repository/api-keys.repository.fixture";
|
||||
import { BookingsRepositoryFixture } from "test/fixtures/repository/bookings.repository.fixture";
|
||||
import { EventTypesRepositoryFixture } from "test/fixtures/repository/event-types.repository.fixture";
|
||||
import { HostsRepositoryFixture } from "test/fixtures/repository/hosts.repository.fixture";
|
||||
import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture";
|
||||
import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.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 { randomString } from "test/utils/randomString";
|
||||
import { AppModule } from "@/app.module";
|
||||
import { bootstrap } from "@/bootstrap";
|
||||
import { ReassignBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/reassign-booking.output";
|
||||
import { BOOKING_REASSIGN_PERMISSION_ERROR } from "@/ee/bookings/2024-08-13/services/bookings.service";
|
||||
import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input";
|
||||
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
|
||||
import { SchedulesService_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/services/schedules.service";
|
||||
import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard";
|
||||
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||
import { UsersModule } from "@/modules/users/users.module";
|
||||
|
||||
describe("Bookings Endpoints 2024-08-13", () => {
|
||||
describe("Reassign bookings", () => {
|
||||
let app: INestApplication;
|
||||
let organization: Team;
|
||||
let team: Team;
|
||||
|
||||
let userRepositoryFixture: UserRepositoryFixture;
|
||||
let bookingsRepositoryFixture: BookingsRepositoryFixture;
|
||||
let schedulesService: SchedulesService_2024_04_15;
|
||||
let eventTypesRepositoryFixture: EventTypesRepositoryFixture;
|
||||
let oauthClientRepositoryFixture: OAuthClientRepositoryFixture;
|
||||
let oAuthClient: PlatformOAuthClient;
|
||||
let teamRepositoryFixture: TeamRepositoryFixture;
|
||||
let membershipsRepositoryFixture: MembershipRepositoryFixture;
|
||||
let hostsRepositoryFixture: HostsRepositoryFixture;
|
||||
let organizationsRepositoryFixture: OrganizationRepositoryFixture;
|
||||
let profileRepositoryFixture: ProfileRepositoryFixture;
|
||||
let apiKeysRepositoryFixture: ApiKeysRepositoryFixture;
|
||||
|
||||
const teamUserEmail = `reassign-bookings-2024-08-13-user1-${randomString()}@api.com`;
|
||||
const teamUserEmail2 = `reassign-bookings-2024-08-13-user2-${randomString()}@api.com`;
|
||||
const teamUserEmail3 = `reassign-bookings-2024-08-13-user3-${randomString()}@api.com`;
|
||||
let teamUser1: User;
|
||||
let teamUser2: User;
|
||||
let teamUser3: User;
|
||||
let teamUser1ApiKey: string;
|
||||
let teamUser2ApiKey: string;
|
||||
|
||||
let teamRoundRobinEventTypeId: number;
|
||||
let teamRoundRobinFixedHostEventTypeId: number;
|
||||
let teamRoundRobinNonFixedEventTypeId: number;
|
||||
let teamRoundRobinWithRescheduleReasonEventTypeId: number;
|
||||
|
||||
let teamRoundRobinNonFixedEventTypeTitle: string;
|
||||
let teamRoundRobinFixedHostEventTypeTitle: string;
|
||||
let teamRoundRobinWithRescheduleReasonEventTypeTitle: string;
|
||||
|
||||
let roundRobinBooking: Booking;
|
||||
let rescheduleReasonBookingUid: string;
|
||||
let rescheduleReasonBookingInitialHostId: number;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [AppModule, PrismaModule, UsersModule, SchedulesModule_2024_04_15],
|
||||
})
|
||||
.overrideGuard(PermissionsGuard)
|
||||
.useValue({
|
||||
canActivate: () => true,
|
||||
})
|
||||
.compile();
|
||||
|
||||
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
|
||||
bookingsRepositoryFixture = new BookingsRepositoryFixture(moduleRef);
|
||||
eventTypesRepositoryFixture = new EventTypesRepositoryFixture(moduleRef);
|
||||
oauthClientRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef);
|
||||
teamRepositoryFixture = new TeamRepositoryFixture(moduleRef);
|
||||
organizationsRepositoryFixture = new OrganizationRepositoryFixture(moduleRef);
|
||||
profileRepositoryFixture = new ProfileRepositoryFixture(moduleRef);
|
||||
membershipsRepositoryFixture = new MembershipRepositoryFixture(moduleRef);
|
||||
hostsRepositoryFixture = new HostsRepositoryFixture(moduleRef);
|
||||
apiKeysRepositoryFixture = new ApiKeysRepositoryFixture(moduleRef);
|
||||
schedulesService = moduleRef.get<SchedulesService_2024_04_15>(SchedulesService_2024_04_15);
|
||||
|
||||
organization = await organizationsRepositoryFixture.create({
|
||||
name: `reassign-bookings-2024-08-13-organization-${randomString()}`,
|
||||
});
|
||||
oAuthClient = await createOAuthClient(organization.id);
|
||||
|
||||
team = await teamRepositoryFixture.create({
|
||||
name: `reassign-bookings-2024-08-13-team-${randomString()}`,
|
||||
isOrganization: false,
|
||||
parent: { connect: { id: organization.id } },
|
||||
createdByOAuthClient: {
|
||||
connect: {
|
||||
id: oAuthClient.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
teamUser1 = await userRepositoryFixture.create({
|
||||
email: teamUserEmail,
|
||||
locale: "en",
|
||||
name: `reassign-bookings-2024-08-13-user1-${randomString()}`,
|
||||
});
|
||||
|
||||
teamUser2 = await userRepositoryFixture.create({
|
||||
email: teamUserEmail2,
|
||||
locale: "en",
|
||||
name: `reassign-bookings-2024-08-13-user2-${randomString()}`,
|
||||
});
|
||||
|
||||
teamUser3 = await userRepositoryFixture.create({
|
||||
email: teamUserEmail3,
|
||||
locale: "en",
|
||||
name: `reassign-bookings-2024-08-13-user3-${randomString()}`,
|
||||
});
|
||||
|
||||
const { keyString } = await apiKeysRepositoryFixture.createApiKey(teamUser1.id, null);
|
||||
teamUser1ApiKey = `cal_test_${keyString}`;
|
||||
|
||||
const { keyString: keyString2 } = await apiKeysRepositoryFixture.createApiKey(teamUser2.id, null);
|
||||
teamUser2ApiKey = `cal_test_${keyString2}`;
|
||||
|
||||
const userSchedule: CreateScheduleInput_2024_04_15 = {
|
||||
name: `reassign-bookings-2024-08-13-schedule-${randomString()}`,
|
||||
timeZone: "Europe/Rome",
|
||||
isDefault: true,
|
||||
availabilities: [
|
||||
{
|
||||
days: [0, 1, 2, 3, 4, 5, 6], // All days of the week
|
||||
startTime: new Date(Date.UTC(2024, 0, 1, 0, 0, 0)), // 00:00 UTC
|
||||
endTime: new Date(Date.UTC(2024, 0, 1, 23, 59, 0)), // 23:59 UTC
|
||||
},
|
||||
],
|
||||
};
|
||||
await schedulesService.createUserSchedule(teamUser1.id, userSchedule);
|
||||
await schedulesService.createUserSchedule(teamUser2.id, userSchedule);
|
||||
await schedulesService.createUserSchedule(teamUser3.id, userSchedule);
|
||||
|
||||
await profileRepositoryFixture.create({
|
||||
uid: `usr-${teamUser1.id}`,
|
||||
username: teamUserEmail,
|
||||
organization: {
|
||||
connect: {
|
||||
id: organization.id,
|
||||
},
|
||||
},
|
||||
user: {
|
||||
connect: {
|
||||
id: teamUser1.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await profileRepositoryFixture.create({
|
||||
uid: `usr-${teamUser2.id}`,
|
||||
username: teamUserEmail2,
|
||||
organization: {
|
||||
connect: {
|
||||
id: organization.id,
|
||||
},
|
||||
},
|
||||
user: {
|
||||
connect: {
|
||||
id: teamUser2.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await profileRepositoryFixture.create({
|
||||
uid: `usr-${teamUser3.id}`,
|
||||
username: teamUserEmail3,
|
||||
organization: {
|
||||
connect: {
|
||||
id: organization.id,
|
||||
},
|
||||
},
|
||||
user: {
|
||||
connect: {
|
||||
id: teamUser3.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await membershipsRepositoryFixture.create({
|
||||
role: "MEMBER",
|
||||
team: { connect: { id: team.id } },
|
||||
user: { connect: { id: teamUser1.id } },
|
||||
accepted: true,
|
||||
});
|
||||
|
||||
await membershipsRepositoryFixture.create({
|
||||
role: "MEMBER",
|
||||
team: { connect: { id: team.id } },
|
||||
user: { connect: { id: teamUser2.id } },
|
||||
accepted: true,
|
||||
});
|
||||
|
||||
await membershipsRepositoryFixture.create({
|
||||
role: "MEMBER",
|
||||
team: { connect: { id: team.id } },
|
||||
user: { connect: { id: teamUser3.id } },
|
||||
accepted: true,
|
||||
});
|
||||
|
||||
const team1EventType = await eventTypesRepositoryFixture.createTeamEventType({
|
||||
schedulingType: "ROUND_ROBIN",
|
||||
team: {
|
||||
connect: { id: team.id },
|
||||
},
|
||||
users: {
|
||||
connect: [{ id: teamUser1.id }, { id: teamUser2.id }],
|
||||
},
|
||||
title: `reassign-bookings-2024-08-13-event-type-${randomString()}`,
|
||||
slug: `reassign-bookings-2024-08-13-event-type-${randomString()}`,
|
||||
length: 60,
|
||||
assignAllTeamMembers: false,
|
||||
bookingFields: [],
|
||||
locations: [{ type: "inPerson", address: "via 10, rome, italy" }],
|
||||
});
|
||||
|
||||
teamRoundRobinEventTypeId = team1EventType.id;
|
||||
|
||||
await hostsRepositoryFixture.create({
|
||||
isFixed: false,
|
||||
user: {
|
||||
connect: {
|
||||
id: teamUser1.id,
|
||||
},
|
||||
},
|
||||
eventType: {
|
||||
connect: {
|
||||
id: team1EventType.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await hostsRepositoryFixture.create({
|
||||
isFixed: false,
|
||||
user: {
|
||||
connect: {
|
||||
id: teamUser2.id,
|
||||
},
|
||||
},
|
||||
eventType: {
|
||||
connect: {
|
||||
id: team1EventType.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
roundRobinBooking = await bookingsRepositoryFixture.create({
|
||||
user: {
|
||||
connect: {
|
||||
id: teamUser1.id,
|
||||
},
|
||||
},
|
||||
startTime: new Date(Date.UTC(2050, 0, 7, 13, 0, 0)),
|
||||
endTime: new Date(Date.UTC(2050, 0, 7, 14, 0, 0)),
|
||||
title: "round robin coding lets goo",
|
||||
uid: "round-robin-coding",
|
||||
eventType: {
|
||||
connect: {
|
||||
id: teamRoundRobinEventTypeId,
|
||||
},
|
||||
},
|
||||
location: "via 10, rome, italy",
|
||||
customInputs: {},
|
||||
metadata: {},
|
||||
responses: {
|
||||
name: "Bob",
|
||||
email: "[email protected]",
|
||||
},
|
||||
attendees: {
|
||||
create: {
|
||||
email: "[email protected]",
|
||||
name: "Bob",
|
||||
locale: "en",
|
||||
timeZone: "Europe/Rome",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const teamNonFixedEventType = await eventTypesRepositoryFixture.createTeamEventType({
|
||||
schedulingType: "ROUND_ROBIN",
|
||||
team: {
|
||||
connect: { id: team.id },
|
||||
},
|
||||
users: {
|
||||
connect: [{ id: teamUser2.id }, { id: teamUser3.id }],
|
||||
},
|
||||
title: `reassign-bookings-2024-08-13-non-fixed-event-type-${randomString()}`,
|
||||
slug: `reassign-bookings-2024-08-13-non-fixed-event-type-${randomString()}`,
|
||||
length: 60,
|
||||
assignAllTeamMembers: false,
|
||||
bookingFields: [],
|
||||
locations: [{ type: "inPerson", address: "via 10, rome, italy" }],
|
||||
});
|
||||
|
||||
teamRoundRobinNonFixedEventTypeId = teamNonFixedEventType.id;
|
||||
teamRoundRobinNonFixedEventTypeTitle = teamNonFixedEventType.title;
|
||||
|
||||
await hostsRepositoryFixture.create({
|
||||
isFixed: false,
|
||||
user: {
|
||||
connect: {
|
||||
id: teamUser2.id,
|
||||
},
|
||||
},
|
||||
eventType: {
|
||||
connect: {
|
||||
id: teamNonFixedEventType.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await hostsRepositoryFixture.create({
|
||||
isFixed: false,
|
||||
user: {
|
||||
connect: {
|
||||
id: teamUser3.id,
|
||||
},
|
||||
},
|
||||
eventType: {
|
||||
connect: {
|
||||
id: teamNonFixedEventType.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
const team2EventType = await eventTypesRepositoryFixture.createTeamEventType({
|
||||
schedulingType: "ROUND_ROBIN",
|
||||
team: {
|
||||
connect: { id: team.id },
|
||||
},
|
||||
users: {
|
||||
connect: [{ id: teamUser1.id }, { id: teamUser2.id }, { id: teamUser3.id }],
|
||||
},
|
||||
title: `reassign-bookings-2024-08-13-fixed-event-type-${randomString()}`,
|
||||
slug: `reassign-bookings-2024-08-13-fixed-event-type-${randomString()}`,
|
||||
length: 60,
|
||||
assignAllTeamMembers: false,
|
||||
bookingFields: [],
|
||||
locations: [{ type: "inPerson", address: "via 10, rome, italy" }],
|
||||
});
|
||||
|
||||
teamRoundRobinFixedHostEventTypeId = team2EventType.id;
|
||||
teamRoundRobinFixedHostEventTypeTitle = team2EventType.title;
|
||||
|
||||
await hostsRepositoryFixture.create({
|
||||
isFixed: true,
|
||||
user: {
|
||||
connect: {
|
||||
id: teamUser1.id,
|
||||
},
|
||||
},
|
||||
eventType: {
|
||||
connect: {
|
||||
id: team2EventType.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await hostsRepositoryFixture.create({
|
||||
isFixed: false,
|
||||
user: {
|
||||
connect: {
|
||||
id: teamUser2.id,
|
||||
},
|
||||
},
|
||||
eventType: {
|
||||
connect: {
|
||||
id: team2EventType.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await hostsRepositoryFixture.create({
|
||||
isFixed: false,
|
||||
user: {
|
||||
connect: {
|
||||
id: teamUser3.id,
|
||||
},
|
||||
},
|
||||
eventType: {
|
||||
connect: {
|
||||
id: team2EventType.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const teamEventTypeWithRescheduleReason = await eventTypesRepositoryFixture.createTeamEventType({
|
||||
schedulingType: "ROUND_ROBIN",
|
||||
team: {
|
||||
connect: { id: team.id },
|
||||
},
|
||||
users: {
|
||||
connect: [{ id: teamUser1.id }, { id: teamUser2.id }],
|
||||
},
|
||||
title: `reassign-bookings-2024-08-13-reschedule-reason-event-type-${randomString()}`,
|
||||
slug: `reassign-bookings-2024-08-13-reschedule-reason-event-type-${randomString()}`,
|
||||
length: 60,
|
||||
assignAllTeamMembers: false,
|
||||
bookingFields: [
|
||||
{
|
||||
name: "rescheduleReason",
|
||||
type: "textarea",
|
||||
defaultLabel: "Reason for rescheduling",
|
||||
required: true,
|
||||
sources: [
|
||||
{
|
||||
id: "default",
|
||||
type: "default",
|
||||
label: "Default",
|
||||
},
|
||||
],
|
||||
editable: "system",
|
||||
views: [
|
||||
{
|
||||
id: "reschedule",
|
||||
label: "Reschedule View",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
locations: [{ type: "inPerson", address: "via 10, rome, italy" }],
|
||||
});
|
||||
|
||||
teamRoundRobinWithRescheduleReasonEventTypeId = teamEventTypeWithRescheduleReason.id;
|
||||
teamRoundRobinWithRescheduleReasonEventTypeTitle = teamEventTypeWithRescheduleReason.title;
|
||||
|
||||
await hostsRepositoryFixture.create({
|
||||
isFixed: false,
|
||||
user: {
|
||||
connect: {
|
||||
id: teamUser1.id,
|
||||
},
|
||||
},
|
||||
eventType: {
|
||||
connect: {
|
||||
id: teamEventTypeWithRescheduleReason.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await hostsRepositoryFixture.create({
|
||||
isFixed: false,
|
||||
user: {
|
||||
connect: {
|
||||
id: teamUser2.id,
|
||||
},
|
||||
},
|
||||
eventType: {
|
||||
connect: {
|
||||
id: teamEventTypeWithRescheduleReason.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
app = moduleRef.createNestApplication();
|
||||
bootstrap(app as NestExpressApplication);
|
||||
|
||||
await app.init();
|
||||
});
|
||||
|
||||
it("should reassign round robin booking", async () => {
|
||||
const booking = await bookingsRepositoryFixture.getByUid(roundRobinBooking.uid);
|
||||
expect(booking?.userId).toEqual(teamUser1.id);
|
||||
|
||||
return request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${roundRobinBooking.uid}/reassign`)
|
||||
.set("Authorization", `Bearer ${teamUser1ApiKey}`)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.expect(200)
|
||||
.then(async (response) => {
|
||||
const responseBody: ReassignBookingOutput_2024_08_13 = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data).toBeDefined();
|
||||
|
||||
const data: ReassignBookingOutput_2024_08_13["data"] = responseBody.data;
|
||||
expect(data.bookingUid).toEqual(roundRobinBooking.uid);
|
||||
expect(data.reassignedTo).toEqual({
|
||||
id: teamUser2.id,
|
||||
name: teamUser2.name,
|
||||
email: teamUser2.email,
|
||||
displayEmail: teamUser2.email,
|
||||
});
|
||||
|
||||
const reassigned = await bookingsRepositoryFixture.getByUid(roundRobinBooking.uid);
|
||||
expect(reassigned?.userId).toEqual(teamUser2.id);
|
||||
});
|
||||
});
|
||||
|
||||
it("should reassign round robin booking to a specific user", async () => {
|
||||
const booking = await bookingsRepositoryFixture.getByUid(roundRobinBooking.uid);
|
||||
expect(booking?.userId).toEqual(teamUser2.id);
|
||||
|
||||
const body: CreateBookingInput_2024_08_13 = {
|
||||
start: new Date(Date.UTC(2030, 0, 8, 13, 0, 0)).toISOString(),
|
||||
eventTypeId: teamRoundRobinEventTypeId,
|
||||
attendee: {
|
||||
name: "alice",
|
||||
email: "[email protected]",
|
||||
timeZone: "Europe/Madrid",
|
||||
language: "es",
|
||||
},
|
||||
meetingUrl: "https://meet.google.com/abc-def-ghi",
|
||||
};
|
||||
|
||||
return request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${roundRobinBooking.uid}/reassign/${teamUser1.id}`)
|
||||
.send(body)
|
||||
.set("Authorization", `Bearer ${teamUser1ApiKey}`)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.expect(200)
|
||||
.then(async (response) => {
|
||||
const responseBody: ReassignBookingOutput_2024_08_13 = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data).toBeDefined();
|
||||
|
||||
const data: ReassignBookingOutput_2024_08_13["data"] = responseBody.data;
|
||||
expect(data.bookingUid).toEqual(roundRobinBooking.uid);
|
||||
expect(data.reassignedTo).toEqual({
|
||||
id: teamUser1.id,
|
||||
name: teamUser1.name,
|
||||
email: teamUser1.email,
|
||||
displayEmail: teamUser1.email,
|
||||
});
|
||||
|
||||
const reassigned = await bookingsRepositoryFixture.getByUid(roundRobinBooking.uid);
|
||||
expect(reassigned?.userId).toEqual(teamUser1.id);
|
||||
});
|
||||
});
|
||||
|
||||
it("should have correct title when reassigning round robin booking with non-fixed host", async () => {
|
||||
const nonFixedHostBookingBody: CreateBookingInput_2024_08_13 = {
|
||||
start: new Date(Date.UTC(2050, 0, 9, 13, 0, 0)).toISOString(),
|
||||
eventTypeId: teamRoundRobinNonFixedEventTypeId,
|
||||
attendee: {
|
||||
name: "Charlie",
|
||||
email: "[email protected]",
|
||||
timeZone: "Europe/Rome",
|
||||
language: "en",
|
||||
},
|
||||
meetingUrl: "https://meet.google.com/abc-def-ghi",
|
||||
};
|
||||
|
||||
const createResponse = await request(app.getHttpServer())
|
||||
.post("/v2/bookings")
|
||||
.send(nonFixedHostBookingBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.expect(201);
|
||||
|
||||
const bookingUid = createResponse.body.data.uid;
|
||||
const booking = await bookingsRepositoryFixture.getByUid(bookingUid);
|
||||
|
||||
expect(booking).toBeDefined();
|
||||
expect(booking?.userId).toEqual(teamUser2.id);
|
||||
|
||||
const expectedInitialTitle = `${teamRoundRobinNonFixedEventTypeTitle} between ${teamUser2.name} and Charlie`;
|
||||
expect(booking?.title).toEqual(expectedInitialTitle);
|
||||
|
||||
return request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${bookingUid}/reassign`)
|
||||
.set("Authorization", `Bearer ${teamUser2ApiKey}`)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.expect(200)
|
||||
.then(async (response) => {
|
||||
const responseBody: ReassignBookingOutput_2024_08_13 = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data).toBeDefined();
|
||||
|
||||
const data: ReassignBookingOutput_2024_08_13["data"] = responseBody.data;
|
||||
expect(data.bookingUid).toEqual(bookingUid);
|
||||
expect(data.reassignedTo.id).toEqual(teamUser3.id);
|
||||
|
||||
const reassigned = await bookingsRepositoryFixture.getByUid(bookingUid);
|
||||
expect(reassigned?.userId).toEqual(teamUser3.id);
|
||||
|
||||
const expectedReassignedTitle = `${teamRoundRobinNonFixedEventTypeTitle} between ${teamUser3.name} and Charlie`;
|
||||
expect(reassigned?.title).toEqual(expectedReassignedTitle);
|
||||
});
|
||||
});
|
||||
|
||||
it("should have correct title when reassigning round robin booking with fixed host", async () => {
|
||||
const fixedHostBookingBody: CreateBookingInput_2024_08_13 = {
|
||||
start: new Date(Date.UTC(2050, 0, 8, 13, 0, 0)).toISOString(),
|
||||
eventTypeId: teamRoundRobinFixedHostEventTypeId,
|
||||
attendee: {
|
||||
name: "Alice",
|
||||
email: "[email protected]",
|
||||
timeZone: "Europe/Rome",
|
||||
language: "en",
|
||||
},
|
||||
meetingUrl: "https://meet.google.com/abc-def-ghi",
|
||||
};
|
||||
|
||||
const createResponse = await request(app.getHttpServer())
|
||||
.post("/v2/bookings")
|
||||
.send(fixedHostBookingBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.expect(201);
|
||||
|
||||
const bookingUid = createResponse.body.data.uid;
|
||||
const booking = await bookingsRepositoryFixture.getByUid(bookingUid);
|
||||
|
||||
expect(booking).toBeDefined();
|
||||
expect(booking?.userId).toEqual(teamUser1.id);
|
||||
|
||||
const expectedInitialTitle = `${teamRoundRobinFixedHostEventTypeTitle} between ${team.name} and Alice`;
|
||||
expect(booking?.title).toEqual(expectedInitialTitle);
|
||||
|
||||
return request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${bookingUid}/reassign/${teamUser3.id}`)
|
||||
.set("Authorization", `Bearer ${teamUser1ApiKey}`)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.expect(200)
|
||||
.then(async (response) => {
|
||||
const responseBody: ReassignBookingOutput_2024_08_13 = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data).toBeDefined();
|
||||
|
||||
const data: ReassignBookingOutput_2024_08_13["data"] = responseBody.data;
|
||||
expect(data.bookingUid).toEqual(bookingUid);
|
||||
expect(data.reassignedTo.id).toEqual(teamUser1.id);
|
||||
|
||||
const reassigned = await bookingsRepositoryFixture.getByUid(bookingUid);
|
||||
expect(reassigned?.userId).toEqual(teamUser1.id);
|
||||
|
||||
const expectedReassignedTitle = `${teamRoundRobinFixedHostEventTypeTitle} between ${team.name} and Alice`;
|
||||
expect(reassigned?.title).toEqual(expectedReassignedTitle);
|
||||
});
|
||||
});
|
||||
|
||||
it("should preserve attendee name when reassigning round robin host manually with rescheduleReason required", async () => {
|
||||
const bookingBody: CreateBookingInput_2024_08_13 = {
|
||||
start: new Date(Date.UTC(2050, 0, 10, 13, 0, 0)).toISOString(),
|
||||
eventTypeId: teamRoundRobinWithRescheduleReasonEventTypeId,
|
||||
attendee: {
|
||||
name: "David",
|
||||
email: "[email protected]",
|
||||
timeZone: "Europe/Rome",
|
||||
language: "en",
|
||||
},
|
||||
meetingUrl: "https://meet.google.com/abc-def-ghi",
|
||||
};
|
||||
|
||||
const createResponse = await request(app.getHttpServer())
|
||||
.post("/v2/bookings")
|
||||
.send(bookingBody)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.expect(201);
|
||||
|
||||
const bookingUid = createResponse.body.data.uid;
|
||||
rescheduleReasonBookingUid = bookingUid;
|
||||
const booking = await bookingsRepositoryFixture.getByUid(bookingUid);
|
||||
|
||||
expect(booking).toBeDefined();
|
||||
expect(booking?.userId).toBeDefined();
|
||||
const initialHostId = booking?.userId!;
|
||||
rescheduleReasonBookingInitialHostId = initialHostId;
|
||||
|
||||
const expectedInitialTitle = `${teamRoundRobinWithRescheduleReasonEventTypeTitle} between ${
|
||||
booking?.userId === teamUser1.id ? teamUser1.name : teamUser2.name
|
||||
} and David`;
|
||||
expect(booking?.title).toEqual(expectedInitialTitle);
|
||||
expect(booking?.title).not.toContain("Nameless");
|
||||
|
||||
const reassignToHostId = initialHostId === teamUser1.id ? teamUser2.id : teamUser1.id;
|
||||
const reassignToHostName = reassignToHostId === teamUser1.id ? teamUser1.name : teamUser2.name;
|
||||
|
||||
return request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${bookingUid}/reassign/${reassignToHostId}`)
|
||||
.set("Authorization", `Bearer ${teamUser1ApiKey}`)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.expect(200)
|
||||
.then(async (response) => {
|
||||
const responseBody: ReassignBookingOutput_2024_08_13 = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data).toBeDefined();
|
||||
|
||||
const data: ReassignBookingOutput_2024_08_13["data"] = responseBody.data;
|
||||
expect(data.bookingUid).toEqual(bookingUid);
|
||||
expect(data.reassignedTo.id).toEqual(reassignToHostId);
|
||||
|
||||
const reassigned = await bookingsRepositoryFixture.getByUid(bookingUid);
|
||||
expect(reassigned?.userId).toEqual(reassignToHostId);
|
||||
|
||||
const expectedReassignedTitle = `${teamRoundRobinWithRescheduleReasonEventTypeTitle} between ${reassignToHostName} and David`;
|
||||
expect(reassigned?.title).toEqual(expectedReassignedTitle);
|
||||
expect(reassigned?.title).not.toContain("Nameless");
|
||||
});
|
||||
});
|
||||
|
||||
it("should preserve attendee name when reassigning round robin host automatically with rescheduleReason required", async () => {
|
||||
const bookingUid = rescheduleReasonBookingUid;
|
||||
const booking = await bookingsRepositoryFixture.getByUid(bookingUid);
|
||||
|
||||
expect(booking).toBeDefined();
|
||||
expect(booking?.userId).toBeDefined();
|
||||
|
||||
const currentHostId = booking?.userId!;
|
||||
const initialHostId = rescheduleReasonBookingInitialHostId;
|
||||
const initialHostName = initialHostId === teamUser1.id ? teamUser1.name : teamUser2.name;
|
||||
|
||||
expect(currentHostId).not.toEqual(initialHostId);
|
||||
|
||||
return request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${bookingUid}/reassign`)
|
||||
.set("Authorization", `Bearer ${teamUser1ApiKey}`)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.expect(200)
|
||||
.then(async (response) => {
|
||||
const responseBody: ReassignBookingOutput_2024_08_13 = response.body;
|
||||
expect(responseBody.status).toEqual(SUCCESS_STATUS);
|
||||
expect(responseBody.data).toBeDefined();
|
||||
|
||||
const data: ReassignBookingOutput_2024_08_13["data"] = responseBody.data;
|
||||
expect(data.bookingUid).toEqual(bookingUid);
|
||||
expect(data.reassignedTo.id).toEqual(initialHostId);
|
||||
|
||||
const autoReassigned = await bookingsRepositoryFixture.getByUid(bookingUid);
|
||||
expect(autoReassigned?.userId).toEqual(initialHostId);
|
||||
|
||||
const expectedAutoReassignedTitle = `${teamRoundRobinWithRescheduleReasonEventTypeTitle} between ${initialHostName} and David`;
|
||||
expect(autoReassigned?.title).toEqual(expectedAutoReassignedTitle);
|
||||
expect(autoReassigned?.title).not.toContain("Nameless");
|
||||
});
|
||||
});
|
||||
|
||||
it("should return 403 when unauthorized user tries to reassign booking", async () => {
|
||||
const unauthorizedUserEmail = `fake-user-${randomString()}@api.com`;
|
||||
const unauthorizedUser = await userRepositoryFixture.create({
|
||||
email: unauthorizedUserEmail,
|
||||
locale: "en",
|
||||
name: `fake-user-${randomString()}`,
|
||||
});
|
||||
|
||||
const { keyString } = await apiKeysRepositoryFixture.createApiKey(unauthorizedUser.id, null);
|
||||
const unauthorizedApiKeyString = `cal_test_${keyString}`;
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${roundRobinBooking.uid}/reassign`)
|
||||
.set("Authorization", `Bearer ${unauthorizedApiKeyString}`)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.expect(403);
|
||||
|
||||
expect(response.body.error.message).toBe(BOOKING_REASSIGN_PERMISSION_ERROR);
|
||||
|
||||
await userRepositoryFixture.deleteByEmail(unauthorizedUserEmail);
|
||||
});
|
||||
|
||||
it("should return 403 when unauthorized user tries to reassign booking to specific user", async () => {
|
||||
const unauthorizedUserEmail = `fake-user-${randomString()}@api.com`;
|
||||
const unauthorizedUser = await userRepositoryFixture.create({
|
||||
email: unauthorizedUserEmail,
|
||||
locale: "en",
|
||||
name: `fake-user-${randomString()}`,
|
||||
});
|
||||
|
||||
const { keyString } = await apiKeysRepositoryFixture.createApiKey(unauthorizedUser.id, null);
|
||||
const unauthorizedApiKeyString = `cal_test_${keyString}`;
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post(`/v2/bookings/${roundRobinBooking.uid}/reassign/${teamUser2.id}`)
|
||||
.send({ reason: "Testing unauthorized access" })
|
||||
.set("Authorization", `Bearer ${unauthorizedApiKeyString}`)
|
||||
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
|
||||
.expect(403);
|
||||
|
||||
expect(response.body.error.message).toBe(BOOKING_REASSIGN_PERMISSION_ERROR);
|
||||
|
||||
await userRepositoryFixture.deleteByEmail(unauthorizedUserEmail);
|
||||
});
|
||||
|
||||
async function createOAuthClient(organizationId: number) {
|
||||
const data = {
|
||||
logo: "logo-url",
|
||||
name: "name",
|
||||
redirectUris: ["http://localhost:5555"],
|
||||
permissions: 32,
|
||||
};
|
||||
const secret = "secret";
|
||||
|
||||
const client = await oauthClientRepositoryFixture.create(organizationId, data, secret);
|
||||
return client;
|
||||
}
|
||||
|
||||
afterAll(async () => {
|
||||
await oauthClientRepositoryFixture.delete(oAuthClient.id);
|
||||
await teamRepositoryFixture.delete(organization.id);
|
||||
await userRepositoryFixture.deleteByEmail(teamUser1.email);
|
||||
await userRepositoryFixture.deleteByEmail(teamUserEmail2);
|
||||
await userRepositoryFixture.deleteByEmail(teamUserEmail3);
|
||||
await bookingsRepositoryFixture.deleteAllBookings(teamUser1.id, teamUser1.email);
|
||||
await bookingsRepositoryFixture.deleteAllBookings(teamUser2.id, teamUser2.email);
|
||||
await bookingsRepositoryFixture.deleteAllBookings(teamUser3.id, teamUser3.email);
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
-122
@@ -1,122 +0,0 @@
|
||||
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 { 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 { TeamsEventTypesService } from "@/modules/teams/event-types/services/teams-event-types.service";
|
||||
import { Body, Controller, Delete, Get, Param, ParseIntPipe, Patch, Post, UseGuards } from "@nestjs/common";
|
||||
import { ApiHeader, ApiOperation, ApiParam, ApiTags as DocsTags } from "@nestjs/swagger";
|
||||
|
||||
import { SUCCESS_STATUS } from "@calcom/platform-constants";
|
||||
import {
|
||||
CreatePrivateLinkInput,
|
||||
CreatePrivateLinkOutput,
|
||||
DeletePrivateLinkOutput,
|
||||
GetPrivateLinksOutput,
|
||||
UpdatePrivateLinkInput,
|
||||
UpdatePrivateLinkOutput,
|
||||
} from "@calcom/platform-types";
|
||||
|
||||
import { PrivateLinksService } from "../services/private-links.service";
|
||||
|
||||
@Controller({
|
||||
path: "/v2/organizations/:orgId/teams/:teamId/event-types/:eventTypeId/private-links",
|
||||
version: API_VERSIONS_VALUES,
|
||||
})
|
||||
@DocsTags("Orgs / Teams / Event Types / Private Links")
|
||||
@ApiHeader(OPTIONAL_X_CAL_CLIENT_ID_HEADER)
|
||||
@ApiHeader(OPTIONAL_X_CAL_SECRET_KEY_HEADER)
|
||||
@ApiHeader(OPTIONAL_API_KEY_HEADER)
|
||||
@ApiParam({ name: "orgId", type: Number, required: true })
|
||||
export class OrganizationsEventTypesPrivateLinksController {
|
||||
constructor(
|
||||
private readonly privateLinksService: PrivateLinksService,
|
||||
private readonly teamsEventTypesService: TeamsEventTypesService
|
||||
) {}
|
||||
|
||||
@Post("/")
|
||||
@Roles("TEAM_ADMIN")
|
||||
@PlatformPlan("ESSENTIALS")
|
||||
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, IsTeamInOrg, PlatformPlanGuard, IsAdminAPIEnabledGuard)
|
||||
@ApiOperation({ summary: "Create a private link for a team event type" })
|
||||
async createPrivateLink(
|
||||
@Param("teamId", ParseIntPipe) teamId: number,
|
||||
@Param("eventTypeId", ParseIntPipe) eventTypeId: number,
|
||||
@Body() body: CreatePrivateLinkInput
|
||||
): Promise<CreatePrivateLinkOutput> {
|
||||
await this.teamsEventTypesService.validateEventTypeExists(teamId, eventTypeId);
|
||||
// Use teamId as the seed for link generation in org/team context
|
||||
const privateLink = await this.privateLinksService.createPrivateLink(eventTypeId, teamId, body);
|
||||
return {
|
||||
status: SUCCESS_STATUS,
|
||||
data: privateLink,
|
||||
};
|
||||
}
|
||||
|
||||
@Get("/")
|
||||
@Roles("TEAM_ADMIN")
|
||||
@PlatformPlan("ESSENTIALS")
|
||||
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, IsTeamInOrg, PlatformPlanGuard, IsAdminAPIEnabledGuard)
|
||||
@ApiOperation({ summary: "Get all private links for a team event type" })
|
||||
async getPrivateLinks(
|
||||
@Param("teamId", ParseIntPipe) teamId: number,
|
||||
@Param("eventTypeId", ParseIntPipe) eventTypeId: number
|
||||
): Promise<GetPrivateLinksOutput> {
|
||||
await this.teamsEventTypesService.validateEventTypeExists(teamId, eventTypeId);
|
||||
const privateLinks = await this.privateLinksService.getPrivateLinks(eventTypeId);
|
||||
return {
|
||||
status: SUCCESS_STATUS,
|
||||
data: privateLinks,
|
||||
};
|
||||
}
|
||||
|
||||
@Patch("/:linkId")
|
||||
@Roles("TEAM_ADMIN")
|
||||
@PlatformPlan("ESSENTIALS")
|
||||
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, IsTeamInOrg, PlatformPlanGuard, IsAdminAPIEnabledGuard)
|
||||
@ApiOperation({ summary: "Update a private link for a team event type" })
|
||||
async updatePrivateLink(
|
||||
@Param("teamId", ParseIntPipe) teamId: number,
|
||||
@Param("eventTypeId", ParseIntPipe) eventTypeId: number,
|
||||
@Param("linkId") linkId: string,
|
||||
@Body() body: Omit<UpdatePrivateLinkInput, "linkId">
|
||||
): Promise<UpdatePrivateLinkOutput> {
|
||||
await this.teamsEventTypesService.validateEventTypeExists(teamId, eventTypeId);
|
||||
const updateInput: UpdatePrivateLinkInput = { ...body, linkId };
|
||||
const privateLink = await this.privateLinksService.updatePrivateLink(eventTypeId, updateInput);
|
||||
return {
|
||||
status: SUCCESS_STATUS,
|
||||
data: privateLink,
|
||||
};
|
||||
}
|
||||
|
||||
@Delete("/:linkId")
|
||||
@Roles("TEAM_ADMIN")
|
||||
@PlatformPlan("ESSENTIALS")
|
||||
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, IsTeamInOrg, PlatformPlanGuard, IsAdminAPIEnabledGuard)
|
||||
@ApiOperation({ summary: "Delete a private link for a team event type" })
|
||||
async deletePrivateLink(
|
||||
@Param("teamId", ParseIntPipe) teamId: number,
|
||||
@Param("eventTypeId", ParseIntPipe) eventTypeId: number,
|
||||
@Param("linkId") linkId: string
|
||||
): Promise<DeletePrivateLinkOutput> {
|
||||
await this.teamsEventTypesService.validateEventTypeExists(teamId, eventTypeId);
|
||||
await this.privateLinksService.deletePrivateLink(eventTypeId, linkId);
|
||||
return {
|
||||
status: SUCCESS_STATUS,
|
||||
data: {
|
||||
linkId,
|
||||
message: "Private link deleted successfully",
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
import { BookingsModule_2024_04_15 } from "@/ee/bookings/2024-04-15/bookings.module";
|
||||
import { BookingsModule_2024_08_13 } from "@/ee/bookings/2024-08-13/bookings.module";
|
||||
import { CalendarsModule } from "@/ee/calendars/calendars.module";
|
||||
import { EventTypesPrivateLinksModule } from "@/ee/event-types-private-links/event-types-private-links.module";
|
||||
import { EventTypesModule_2024_04_15 } from "@/ee/event-types/event-types_2024_04_15/event-types.module";
|
||||
import { EventTypesModule_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.module";
|
||||
import { GcalModule } from "@/ee/gcal/gcal.module";
|
||||
import { MeModule } from "@/ee/me/me.module";
|
||||
import { ProviderModule } from "@/ee/provider/provider.module";
|
||||
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
|
||||
import { SchedulesModule_2024_06_11 } from "@/ee/schedules/schedules_2024_06_11/schedules.module";
|
||||
import { RoutingFormsModule } from "@/modules/routing-forms/routing-forms.module";
|
||||
import { SlotsModule_2024_04_15 } from "@/modules/slots/slots-2024-04-15/slots.module";
|
||||
import { SlotsModule_2024_09_04 } from "@/modules/slots/slots-2024-09-04/slots.module";
|
||||
import { TeamsEventTypesModule } from "@/modules/teams/event-types/teams-event-types.module";
|
||||
import { TeamsInviteModule } from "@/modules/teams/invite/teams-invite.module";
|
||||
import { TeamsMembershipsModule } from "@/modules/teams/memberships/teams-memberships.module";
|
||||
import { TeamsModule } from "@/modules/teams/teams/teams.module";
|
||||
import type { MiddlewareConsumer, NestModule } from "@nestjs/common";
|
||||
import { Module } from "@nestjs/common";
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
GcalModule,
|
||||
ProviderModule,
|
||||
SchedulesModule_2024_04_15,
|
||||
SchedulesModule_2024_06_11,
|
||||
TeamsEventTypesModule,
|
||||
MeModule,
|
||||
EventTypesModule_2024_04_15,
|
||||
EventTypesModule_2024_06_14,
|
||||
CalendarsModule,
|
||||
BookingsModule_2024_04_15,
|
||||
BookingsModule_2024_08_13,
|
||||
TeamsMembershipsModule,
|
||||
TeamsInviteModule,
|
||||
SlotsModule_2024_04_15,
|
||||
SlotsModule_2024_09_04,
|
||||
TeamsModule,
|
||||
RoutingFormsModule,
|
||||
EventTypesPrivateLinksModule,
|
||||
],
|
||||
})
|
||||
export class PlatformEndpointsModule implements NestModule {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
configure(_consumer: MiddlewareConsumer) {
|
||||
// TODO: apply ratelimits
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import { EventTypesModule_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.module";
|
||||
import { SchedulesController_2024_06_11 } from "@/ee/schedules/schedules_2024_06_11/controllers/schedules.controller";
|
||||
import { SchedulesRepository_2024_06_11 } from "@/ee/schedules/schedules_2024_06_11/schedules.repository";
|
||||
import { InputSchedulesService_2024_06_11 } from "@/ee/schedules/schedules_2024_06_11/services/input-schedules.service";
|
||||
import { OutputSchedulesService_2024_06_11 } from "@/ee/schedules/schedules_2024_06_11/services/output-schedules.service";
|
||||
import { SchedulesService_2024_06_11 } from "@/ee/schedules/schedules_2024_06_11/services/schedules.service";
|
||||
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||
import { TokensModule } from "@/modules/tokens/tokens.module";
|
||||
import { UsersModule } from "@/modules/users/users.module";
|
||||
import { Module } from "@nestjs/common";
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, UsersModule, TokensModule, EventTypesModule_2024_06_14],
|
||||
providers: [
|
||||
SchedulesRepository_2024_06_11,
|
||||
SchedulesService_2024_06_11,
|
||||
InputSchedulesService_2024_06_11,
|
||||
OutputSchedulesService_2024_06_11,
|
||||
],
|
||||
controllers: [SchedulesController_2024_06_11],
|
||||
exports: [SchedulesService_2024_06_11, SchedulesRepository_2024_06_11, OutputSchedulesService_2024_06_11],
|
||||
})
|
||||
export class SchedulesModule_2024_06_11 {}
|
||||
@@ -1,25 +1,21 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { PrismaBookingRepository } from "@/lib/repositories/prisma-booking.repository";
|
||||
import { PrismaEventTypeRepository } from "@/lib/repositories/prisma-event-type.repository";
|
||||
import { PrismaFeaturesRepository } from "@/lib/repositories/prisma-features.repository";
|
||||
import { PrismaHolidayRepository } from "@/lib/repositories/prisma-holiday.repository";
|
||||
import { PrismaMembershipRepository } from "@/lib/repositories/prisma-membership.repository";
|
||||
import { PrismaOOORepository } from "@/lib/repositories/prisma-ooo.repository";
|
||||
import { PrismaRoutingFormResponseRepository } from "@/lib/repositories/prisma-routing-form-response.repository";
|
||||
import { PrismaScheduleRepository } from "@/lib/repositories/prisma-schedule.repository";
|
||||
import { PrismaSelectedSlotRepository } from "@/lib/repositories/prisma-selected-slot.repository";
|
||||
import { PrismaTeamRepository } from "@/lib/repositories/prisma-team.repository";
|
||||
import { PrismaUserRepository } from "@/lib/repositories/prisma-user.repository";
|
||||
import { AvailableSlotsService } from "@/lib/services/available-slots.service";
|
||||
import { BusyTimesService } from "@/lib/services/busy-times.service";
|
||||
import { CheckBookingLimitsService } from "@/lib/services/check-booking-limits.service";
|
||||
import { FilterHostsService } from "@/lib/services/filter-hosts.service";
|
||||
import { NoSlotsNotificationService } from "@/lib/services/no-slots-notification.service";
|
||||
import { OrgMembershipLookupService } from "@/lib/services/org-membership-lookup.service";
|
||||
import { QualifiedHostsService } from "@/lib/services/qualified-hosts.service";
|
||||
import { UserAvailabilityService } from "@/lib/services/user-availability.service";
|
||||
import { PrismaWorkerModule } from "@/modules/prisma/prisma-worker.module";
|
||||
import { RedisService } from "@/modules/redis/redis.service";
|
||||
import { Module } from "@nestjs/common";
|
||||
|
||||
@Module({
|
||||
imports: [PrismaWorkerModule],
|
||||
@@ -31,19 +27,15 @@ import { Module } from "@nestjs/common";
|
||||
PrismaSelectedSlotRepository,
|
||||
PrismaUserRepository,
|
||||
PrismaEventTypeRepository,
|
||||
PrismaRoutingFormResponseRepository,
|
||||
PrismaTeamRepository,
|
||||
RedisService,
|
||||
PrismaFeaturesRepository,
|
||||
PrismaMembershipRepository,
|
||||
CheckBookingLimitsService,
|
||||
QualifiedHostsService,
|
||||
AvailableSlotsService,
|
||||
UserAvailabilityService,
|
||||
BusyTimesService,
|
||||
FilterHostsService,
|
||||
QualifiedHostsService,
|
||||
NoSlotsNotificationService,
|
||||
OrgMembershipLookupService,
|
||||
],
|
||||
exports: [AvailableSlotsService],
|
||||
})
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
import { BookingEventHandlerModule } from "@/lib/modules/booking-event-handler.module";
|
||||
import { PrismaBookingAttendeeRepository } from "@/lib/repositories/prisma-booking-attendee.repository";
|
||||
import { PrismaBookingRepository } from "@/lib/repositories/prisma-booking.repository";
|
||||
import { PrismaFeaturesRepository } from "@/lib/repositories/prisma-features.repository";
|
||||
import { BookingAttendeesRemoveService } from "@/lib/services/booking-attendees-remove.service";
|
||||
import { BookingAttendeesService } from "@/lib/services/booking-attendees.service";
|
||||
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||
import { Module } from "@nestjs/common";
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, BookingEventHandlerModule],
|
||||
imports: [PrismaModule],
|
||||
providers: [
|
||||
PrismaBookingRepository,
|
||||
PrismaBookingAttendeeRepository,
|
||||
PrismaFeaturesRepository,
|
||||
BookingAttendeesRemoveService,
|
||||
BookingAttendeesService,
|
||||
],
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { Module, Scope } from "@nestjs/common";
|
||||
import { Logger } from "@/lib/logger.bridge";
|
||||
import { BookingAuditProducerService } from "@/lib/services/booking-audit-producer.service";
|
||||
import { BookingEventHandlerService } from "@/lib/services/booking-event-handler.service";
|
||||
import { HashedLinkService } from "@/lib/services/hashed-link.service";
|
||||
import { TaskerService } from "@/lib/services/tasker.service";
|
||||
import { Module, Scope } from "@nestjs/common";
|
||||
|
||||
@Module({
|
||||
providers: [
|
||||
@@ -16,7 +15,6 @@ import { Module, Scope } from "@nestjs/common";
|
||||
},
|
||||
TaskerService,
|
||||
HashedLinkService,
|
||||
BookingAuditProducerService,
|
||||
BookingEventHandlerService,
|
||||
],
|
||||
exports: [BookingEventHandlerService],
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
import { InstantBookingCreateService } from "@/lib/services/instant-booking-create.service";
|
||||
import { Module } from "@nestjs/common";
|
||||
|
||||
@Module({
|
||||
providers: [InstantBookingCreateService],
|
||||
exports: [InstantBookingCreateService],
|
||||
})
|
||||
export class InstantBookingModule {}
|
||||
@@ -1,13 +1,12 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { PrismaAccessCodeRepository } from "@/lib/repositories/prisma-access-code.repository";
|
||||
import { PrismaOAuthClientRepository } from "@/lib/repositories/prisma-oauth-client.repository";
|
||||
import { PrismaTeamRepository } from "@/lib/repositories/prisma-team.repository";
|
||||
import { OAuthService } from "@/lib/services/oauth.service";
|
||||
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||
import { Module } from "@nestjs/common";
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
providers: [PrismaAccessCodeRepository, PrismaOAuthClientRepository, PrismaTeamRepository, OAuthService],
|
||||
providers: [PrismaAccessCodeRepository, PrismaOAuthClientRepository, OAuthService],
|
||||
exports: [OAuthService],
|
||||
})
|
||||
export class oAuthServiceModule {}
|
||||
@@ -1,32 +0,0 @@
|
||||
import { Module, Scope } from "@nestjs/common";
|
||||
import { Logger } from "@/lib/logger.bridge";
|
||||
import { PrismaPlatformBillingRepository } from "@/lib/repositories/prisma-platform-billing.repository";
|
||||
import { StripeBillingProviderService } from "@/lib/services/stripe-billing-provider.service";
|
||||
import { PlatformBillingSyncTaskerService } from "@/lib/services/tasker/platform-billing-sync-tasker.service";
|
||||
import { PlatformBillingTaskService } from "@/lib/services/tasker/platform-billing-task.service";
|
||||
import { PlatformBillingTasker } from "@/lib/services/tasker/platform-billing-tasker.service";
|
||||
import { PlatformBillingTriggerTaskerService } from "@/lib/services/tasker/platform-billing-trigger-tasker.service";
|
||||
import { OrganizationsModule } from "@/modules/organizations/organizations.module";
|
||||
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||
import { StripeModule } from "@/modules/stripe/stripe.module";
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, StripeModule, OrganizationsModule],
|
||||
providers: [
|
||||
PrismaPlatformBillingRepository,
|
||||
StripeBillingProviderService,
|
||||
{
|
||||
provide: Logger,
|
||||
useFactory: () => {
|
||||
return new Logger();
|
||||
},
|
||||
scope: Scope.TRANSIENT,
|
||||
},
|
||||
PlatformBillingTaskService,
|
||||
PlatformBillingSyncTaskerService,
|
||||
PlatformBillingTriggerTaskerService,
|
||||
PlatformBillingTasker,
|
||||
],
|
||||
exports: [PlatformBillingTasker],
|
||||
})
|
||||
export class PlatformBillingTaskerModule {}
|
||||
@@ -1,13 +1,11 @@
|
||||
import { RegularBookingModule } from "@/lib/modules/regular-booking.module";
|
||||
import { RecurringBookingService } from "@/lib/services/recurring-booking.service";
|
||||
import { Module } from "@nestjs/common";
|
||||
import { BookingEventHandlerService } from "@/lib/services/booking-event-handler.service";
|
||||
import { Module, Scope } from "@nestjs/common";
|
||||
import { Logger } from "@/lib/logger.bridge";
|
||||
import { Scope } from "@nestjs/common";
|
||||
import { BookingAuditProducerService } from "@/lib/services/booking-audit-producer.service";
|
||||
import { HashedLinkService } from "@/lib/services/hashed-link.service";
|
||||
import { TaskerService } from "@/lib/services/tasker.service";
|
||||
import { RegularBookingModule } from "@/lib/modules/regular-booking.module";
|
||||
import { PrismaFeaturesRepository } from "@/lib/repositories/prisma-features.repository";
|
||||
import { BookingEventHandlerService } from "@/lib/services/booking-event-handler.service";
|
||||
import { HashedLinkService } from "@/lib/services/hashed-link.service";
|
||||
import { RecurringBookingService } from "@/lib/services/recurring-booking.service";
|
||||
import { TaskerService } from "@/lib/services/tasker.service";
|
||||
import { PrismaWorkerModule } from "@/modules/prisma/prisma-worker.module";
|
||||
@Module({
|
||||
imports: [RegularBookingModule, PrismaWorkerModule],
|
||||
@@ -23,7 +21,6 @@ import { PrismaWorkerModule } from "@/modules/prisma/prisma-worker.module";
|
||||
},
|
||||
scope: Scope.TRANSIENT,
|
||||
},
|
||||
BookingAuditProducerService,
|
||||
TaskerService,
|
||||
/** Required by BookingEventHandlerService - Ends **/
|
||||
/** Required by RecurringBookingService **/
|
||||
@@ -31,4 +28,4 @@ import { PrismaWorkerModule } from "@/modules/prisma/prisma-worker.module";
|
||||
],
|
||||
exports: [RecurringBookingService],
|
||||
})
|
||||
export class RecurringBookingModule { }
|
||||
export class RecurringBookingModule {}
|
||||
@@ -1,11 +1,12 @@
|
||||
import { getWebhookProducer } from "@calcom/platform-libraries/bookings";
|
||||
import { Module, Scope } from "@nestjs/common";
|
||||
import { WEBHOOK_PRODUCER } from "./regular-booking.tokens";
|
||||
import { Logger } from "@/lib/logger.bridge";
|
||||
import { PrismaAttributeRepository } from "@/lib/repositories/prisma-attribute.repository";
|
||||
import { PrismaBookingRepository } from "@/lib/repositories/prisma-booking.repository";
|
||||
import { PrismaFeaturesRepository } from "@/lib/repositories/prisma-features.repository";
|
||||
import { PrismaHostRepository } from "@/lib/repositories/prisma-host.repository";
|
||||
import { PrismaOOORepository } from "@/lib/repositories/prisma-ooo.repository";
|
||||
import { PrismaUserRepository } from "@/lib/repositories/prisma-user.repository";
|
||||
import { BookingAuditProducerService } from "@/lib/services/booking-audit-producer.service";
|
||||
import { BookingEmailSmsService } from "@/lib/services/booking-emails-sms-service";
|
||||
import { BookingEventHandlerService } from "@/lib/services/booking-event-handler.service";
|
||||
import { CheckBookingAndDurationLimitsService } from "@/lib/services/check-booking-and-duration-limits.service";
|
||||
@@ -19,16 +20,10 @@ import { BookingEmailAndSmsTasker } from "@/lib/services/tasker/booking-emails-s
|
||||
import { BookingEmailAndSmsTriggerTaskerService } from "@/lib/services/tasker/booking-emails-sms-trigger-tasker.service";
|
||||
import { TaskerService } from "@/lib/services/tasker.service";
|
||||
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||
import { Module, Scope } from "@nestjs/common";
|
||||
|
||||
import { getWebhookProducer } from "@calcom/platform-libraries/bookings";
|
||||
|
||||
import { WEBHOOK_PRODUCER } from "./regular-booking.tokens";
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
providers: [
|
||||
PrismaAttributeRepository,
|
||||
PrismaBookingRepository,
|
||||
PrismaFeaturesRepository,
|
||||
PrismaHostRepository,
|
||||
@@ -45,7 +40,6 @@ import { WEBHOOK_PRODUCER } from "./regular-booking.tokens";
|
||||
provide: WEBHOOK_PRODUCER,
|
||||
useFactory: () => getWebhookProducer(),
|
||||
},
|
||||
BookingAuditProducerService,
|
||||
BookingEventHandlerService,
|
||||
CheckBookingAndDurationLimitsService,
|
||||
CheckBookingLimitsService,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Injection token for IWebhookProducerService.
|
||||
* Used to bridge the Cal.com DI container into NestJS.
|
||||
* Used to bridge the Cal.diy DI container into NestJS.
|
||||
*
|
||||
* Defined in a separate file to avoid a circular import between
|
||||
* regular-booking.module.ts and regular-booking.service.ts.
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { PrismaAttributeRepository as PrismaAttributeRepositoryLib } from "@calcom/platform-libraries/repositories";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
|
||||
@Injectable()
|
||||
export class PrismaAttributeRepository extends PrismaAttributeRepositoryLib {
|
||||
constructor(private readonly dbWrite: PrismaWriteService) {
|
||||
super(dbWrite.prisma as unknown as PrismaClient);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { PlatformBillingRepository } from "@calcom/platform-libraries/organizations";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
|
||||
@Injectable()
|
||||
export class PrismaPlatformBillingRepository extends PlatformBillingRepository {
|
||||
constructor(dbWrite: PrismaWriteService) {
|
||||
super(dbWrite.prisma as unknown as PrismaClient);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { PrismaRoutingFormResponseRepository as PrismaRoutingFormResponseRepositoryLib } from "@calcom/platform-libraries/repositories";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
|
||||
@Injectable()
|
||||
export class PrismaRoutingFormResponseRepository extends PrismaRoutingFormResponseRepositoryLib {
|
||||
constructor(private readonly dbWrite: PrismaWriteService) {
|
||||
super(dbWrite.prisma as unknown as PrismaClient);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,37 @@
|
||||
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { PrismaTeamRepository as PrismaTeamRepositoryLib } from "@calcom/platform-libraries/repositories";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
|
||||
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
|
||||
|
||||
@Injectable()
|
||||
export class PrismaTeamRepository extends PrismaTeamRepositoryLib {
|
||||
constructor(private readonly dbWrite: PrismaWriteService) {
|
||||
super(dbWrite.prisma as unknown as PrismaClient);
|
||||
export class PrismaTeamRepository {
|
||||
constructor(
|
||||
private readonly dbWrite: PrismaWriteService,
|
||||
private readonly dbRead: PrismaReadService
|
||||
) {}
|
||||
|
||||
async findTeamById(teamId: number) {
|
||||
return this.dbRead.prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
});
|
||||
}
|
||||
|
||||
async findTeamsByIds(teamIds: number[]) {
|
||||
return this.dbRead.prisma.team.findMany({
|
||||
where: { id: { in: teamIds } },
|
||||
});
|
||||
}
|
||||
|
||||
async getTeamByIdIfUserIsAdmin(args: { userId: number; teamId: number }) {
|
||||
return this.dbRead.prisma.team.findFirst({
|
||||
where: {
|
||||
id: args.teamId,
|
||||
members: {
|
||||
some: {
|
||||
userId: args.userId,
|
||||
role: { in: ["ADMIN", "OWNER"] },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,19 @@
|
||||
import { AvailableSlotsService as BaseAvailableSlotsService } from "@calcom/platform-libraries/slots";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { PrismaBookingRepository } from "@/lib/repositories/prisma-booking.repository";
|
||||
import { PrismaEventTypeRepository } from "@/lib/repositories/prisma-event-type.repository";
|
||||
import { PrismaFeaturesRepository } from "@/lib/repositories/prisma-features.repository";
|
||||
import { PrismaOOORepository } from "@/lib/repositories/prisma-ooo.repository";
|
||||
import { PrismaRoutingFormResponseRepository } from "@/lib/repositories/prisma-routing-form-response.repository";
|
||||
import { PrismaScheduleRepository } from "@/lib/repositories/prisma-schedule.repository";
|
||||
import { PrismaSelectedSlotRepository } from "@/lib/repositories/prisma-selected-slot.repository";
|
||||
import { PrismaTeamRepository } from "@/lib/repositories/prisma-team.repository";
|
||||
import { PrismaUserRepository } from "@/lib/repositories/prisma-user.repository";
|
||||
import { BusyTimesService } from "@/lib/services/busy-times.service";
|
||||
import { CheckBookingLimitsService } from "@/lib/services/check-booking-limits.service";
|
||||
import { NoSlotsNotificationService } from "@/lib/services/no-slots-notification.service";
|
||||
import { OrgMembershipLookupService } from "@/lib/services/org-membership-lookup.service";
|
||||
import { QualifiedHostsService } from "@/lib/services/qualified-hosts.service";
|
||||
import { RedisService } from "@/modules/redis/redis.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { AvailableSlotsService as BaseAvailableSlotsService } from "@calcom/platform-libraries/slots";
|
||||
type BaseAvailableSlotsDeps = ConstructorParameters<typeof BaseAvailableSlotsService>[0];
|
||||
|
||||
import { UserAvailabilityService } from "./user-availability.service";
|
||||
|
||||
@@ -24,8 +22,6 @@ export class AvailableSlotsService extends BaseAvailableSlotsService {
|
||||
constructor(
|
||||
oooRepoDependency: PrismaOOORepository,
|
||||
scheduleRepoDependency: PrismaScheduleRepository,
|
||||
teamRepository: PrismaTeamRepository,
|
||||
routingFormResponseRepository: PrismaRoutingFormResponseRepository,
|
||||
bookingRepository: PrismaBookingRepository,
|
||||
selectedSlotRepository: PrismaSelectedSlotRepository,
|
||||
eventTypeRepository: PrismaEventTypeRepository,
|
||||
@@ -36,14 +32,11 @@ export class AvailableSlotsService extends BaseAvailableSlotsService {
|
||||
checkBookingLimitsService: CheckBookingLimitsService,
|
||||
userAvailabilityService: UserAvailabilityService,
|
||||
busyTimesService: BusyTimesService,
|
||||
noSlotsNotificationService: NoSlotsNotificationService,
|
||||
orgMembershipLookupService: OrgMembershipLookupService
|
||||
noSlotsNotificationService: NoSlotsNotificationService
|
||||
) {
|
||||
super({
|
||||
oooRepo: oooRepoDependency,
|
||||
scheduleRepo: scheduleRepoDependency,
|
||||
teamRepo: teamRepository,
|
||||
routingFormResponseRepo: routingFormResponseRepository,
|
||||
bookingRepo: bookingRepository,
|
||||
selectedSlotRepo: selectedSlotRepository,
|
||||
eventTypeRepo: eventTypeRepository,
|
||||
@@ -52,10 +45,9 @@ export class AvailableSlotsService extends BaseAvailableSlotsService {
|
||||
checkBookingLimitsService,
|
||||
userAvailabilityService,
|
||||
busyTimesService,
|
||||
qualifiedHostsService,
|
||||
featuresRepo: featuresRepository,
|
||||
qualifiedHostsService:
|
||||
qualifiedHostsService as unknown as BaseAvailableSlotsDeps["qualifiedHostsService"],
|
||||
noSlotsNotificationService,
|
||||
orgMembershipLookup: orgMembershipLookupService,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,11 @@
|
||||
import { PrismaBookingAttendeeRepository } from "@/lib/repositories/prisma-booking-attendee.repository";
|
||||
import { PrismaFeaturesRepository } from "@/lib/repositories/prisma-features.repository";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { BookingAttendeesRemoveService as BaseBookingAttendeesRemoveService } from "@calcom/platform-libraries/bookings";
|
||||
|
||||
import { BookingEventHandlerService } from "./booking-event-handler.service";
|
||||
|
||||
@Injectable()
|
||||
export class BookingAttendeesRemoveService extends BaseBookingAttendeesRemoveService {
|
||||
constructor(
|
||||
bookingEventHandlerService: BookingEventHandlerService,
|
||||
featuresRepository: PrismaFeaturesRepository,
|
||||
bookingAttendeeRepository: PrismaBookingAttendeeRepository
|
||||
) {
|
||||
super({ bookingEventHandlerService, featuresRepository, bookingAttendeeRepository });
|
||||
constructor(bookingAttendeeRepository: PrismaBookingAttendeeRepository) {
|
||||
super({ bookingAttendeeRepository });
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,16 @@
|
||||
import { PrismaBookingRepository } from "@/lib/repositories/prisma-booking.repository";
|
||||
import { PrismaFeaturesRepository } from "@/lib/repositories/prisma-features.repository";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { BookingAttendeesService as BaseBookingAttendeesService } from "@calcom/platform-libraries/bookings";
|
||||
|
||||
import { BookingAttendeesRemoveService } from "./booking-attendees-remove.service";
|
||||
import { BookingEventHandlerService } from "./booking-event-handler.service";
|
||||
|
||||
@Injectable()
|
||||
export class BookingAttendeesService extends BaseBookingAttendeesService {
|
||||
constructor(
|
||||
bookingEventHandlerService: BookingEventHandlerService,
|
||||
featuresRepository: PrismaFeaturesRepository,
|
||||
bookingRepository: PrismaBookingRepository,
|
||||
bookingAttendeesRemoveService: BookingAttendeesRemoveService
|
||||
) {
|
||||
super({ bookingEventHandlerService, featuresRepository, bookingRepository, bookingAttendeesRemoveService });
|
||||
super({ bookingRepository, bookingAttendeesRemoveService });
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
import { TaskerService } from "@/lib/services/tasker.service";
|
||||
import { Logger } from "@/lib/logger.bridge";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { BookingAuditTaskerProducerService, getAuditActorRepository } from "@calcom/platform-libraries/bookings";
|
||||
|
||||
@Injectable()
|
||||
export class BookingAuditProducerService extends BookingAuditTaskerProducerService {
|
||||
constructor(taskerService: TaskerService, bridgeLogger: Logger) {
|
||||
super({
|
||||
tasker: taskerService.getTasker(),
|
||||
log: bridgeLogger,
|
||||
auditActorRepository: getAuditActorRepository(),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,14 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { BookingEventHandlerService as BaseBookingEventHandlerService } from "@calcom/platform-libraries/bookings";
|
||||
|
||||
import { Logger } from "@/lib/logger.bridge";
|
||||
|
||||
import { BookingAuditProducerService } from "./booking-audit-producer.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { HashedLinkService } from "./hashed-link.service";
|
||||
import { Logger } from "@/lib/logger.bridge";
|
||||
|
||||
@Injectable()
|
||||
export class BookingEventHandlerService extends BaseBookingEventHandlerService {
|
||||
constructor(
|
||||
hashedLinkService: HashedLinkService,
|
||||
bridgeLogger: Logger,
|
||||
bookingAuditProducerService: BookingAuditProducerService
|
||||
) {
|
||||
constructor(hashedLinkService: HashedLinkService, bridgeLogger: Logger) {
|
||||
super({
|
||||
log: bridgeLogger,
|
||||
hashedLinkService,
|
||||
bookingAuditProducerService,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
import { PrismaBookingRepository } from "@/lib/repositories/prisma-booking.repository";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { FilterHostsService as BaseFilterHostsService } from "@calcom/platform-libraries/slots";
|
||||
|
||||
@Injectable()
|
||||
export class FilterHostsService extends BaseFilterHostsService {
|
||||
constructor(bookingRepository: PrismaBookingRepository) {
|
||||
super({
|
||||
bookingRepo: bookingRepository,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { InstantBookingCreateService as BaseInstantBookingCreateService } from "@calcom/platform-libraries/bookings";
|
||||
|
||||
@Injectable()
|
||||
export class InstantBookingCreateService extends BaseInstantBookingCreateService {}
|
||||
@@ -1,11 +1,9 @@
|
||||
import { PrismaAttributeRepository } from "@/lib/repositories/prisma-attribute.repository";
|
||||
import { LuckyUserService as BaseLuckyUserService } from "@calcom/platform-libraries/bookings";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { PrismaBookingRepository } from "@/lib/repositories/prisma-booking.repository";
|
||||
import { PrismaHostRepository } from "@/lib/repositories/prisma-host.repository";
|
||||
import { PrismaOOORepository } from "@/lib/repositories/prisma-ooo.repository";
|
||||
import { PrismaUserRepository } from "@/lib/repositories/prisma-user.repository";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { LuckyUserService as BaseLuckyUserService } from "@calcom/platform-libraries/bookings";
|
||||
|
||||
@Injectable()
|
||||
export class LuckyUserService extends BaseLuckyUserService {
|
||||
@@ -13,15 +11,13 @@ export class LuckyUserService extends BaseLuckyUserService {
|
||||
bookingRepository: PrismaBookingRepository,
|
||||
hostRepository: PrismaHostRepository,
|
||||
oooRepository: PrismaOOORepository,
|
||||
userRepository: PrismaUserRepository,
|
||||
attributeRepository: PrismaAttributeRepository
|
||||
userRepository: PrismaUserRepository
|
||||
) {
|
||||
super({
|
||||
bookingRepository: bookingRepository,
|
||||
hostRepository: hostRepository,
|
||||
oooRepository: oooRepository,
|
||||
userRepository: userRepository,
|
||||
attributeRepository: attributeRepository,
|
||||
bookingRepository,
|
||||
hostRepository,
|
||||
oooRepository,
|
||||
userRepository,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import { PrismaMembershipRepository } from "@/lib/repositories/prisma-membership.repository";
|
||||
import { PrismaTeamRepository } from "@/lib/repositories/prisma-team.repository";
|
||||
import { RedisService } from "@/modules/redis/redis.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
@@ -7,13 +6,8 @@ import { NoSlotsNotificationService as BaseNoSlotsNotificationService } from "@c
|
||||
|
||||
@Injectable()
|
||||
export class NoSlotsNotificationService extends BaseNoSlotsNotificationService {
|
||||
constructor(
|
||||
teamRepository: PrismaTeamRepository,
|
||||
membershipRepository: PrismaMembershipRepository,
|
||||
redisService: RedisService
|
||||
) {
|
||||
constructor(membershipRepository: PrismaMembershipRepository, redisService: RedisService) {
|
||||
super({
|
||||
teamRepo: teamRepository,
|
||||
membershipRepo: membershipRepository,
|
||||
redisClient: redisService,
|
||||
});
|
||||
|
||||
@@ -3,7 +3,6 @@ import { OAuthService as BaseOAuthService } from "@calcom/platform-libraries";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { PrismaAccessCodeRepository } from "@/lib/repositories/prisma-access-code.repository";
|
||||
import { PrismaOAuthClientRepository } from "@/lib/repositories/prisma-oauth-client.repository";
|
||||
import { PrismaTeamRepository } from "@/lib/repositories/prisma-team.repository";
|
||||
import type { OAuth2ExchangeInput } from "@/modules/auth/oauth2/inputs/exchange.input";
|
||||
import { OAuth2ExchangeConfidentialInput } from "@/modules/auth/oauth2/inputs/exchange.input";
|
||||
import type { OAuth2RefreshInput } from "@/modules/auth/oauth2/inputs/refresh.input";
|
||||
@@ -14,13 +13,11 @@ import type { OAuth2TokenInput } from "@/modules/auth/oauth2/inputs/token.input.
|
||||
export class OAuthService extends BaseOAuthService {
|
||||
constructor(
|
||||
accessCodeRepository: PrismaAccessCodeRepository,
|
||||
oAuthClientRepository: PrismaOAuthClientRepository,
|
||||
teamsRepository: PrismaTeamRepository
|
||||
oAuthClientRepository: PrismaOAuthClientRepository
|
||||
) {
|
||||
super({
|
||||
accessCodeRepository: accessCodeRepository,
|
||||
oAuthClientRepository: oAuthClientRepository,
|
||||
teamsRepository: teamsRepository,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import {
|
||||
type OrgMembershipLookup,
|
||||
ProfileRepository,
|
||||
} from "@calcom/platform-libraries";
|
||||
|
||||
/**
|
||||
* NestJS service that implements OrgMembershipLookup interface.
|
||||
* Wraps ProfileRepository's static method for DI compatibility.
|
||||
*/
|
||||
@Injectable()
|
||||
export class OrgMembershipLookupService implements OrgMembershipLookup {
|
||||
async findFirstOrganizationIdForUser({
|
||||
userId,
|
||||
}: {
|
||||
userId: number;
|
||||
}): Promise<number | null> {
|
||||
return ProfileRepository.findFirstOrganizationIdForUser({ userId });
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { OrganizationMembershipService as BaseOrganizationMembershipService } from "@calcom/platform-libraries/organizations";
|
||||
|
||||
@Injectable()
|
||||
export class OrganizationMembershipService extends BaseOrganizationMembershipService {
|
||||
constructor(organizationsRepository: OrganizationsRepository) {
|
||||
super({ organizationRepository: organizationsRepository });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,86 @@
|
||||
import { PrismaBookingRepository } from "@/lib/repositories/prisma-booking.repository";
|
||||
import { FilterHostsService } from "@/lib/services/filter-hosts.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { QualifiedHostsService as BaseQualifiedHostsService } from "@calcom/platform-libraries/slots";
|
||||
type Host = {
|
||||
isFixed: boolean;
|
||||
user: Record<string, unknown>;
|
||||
groupId?: string | null;
|
||||
};
|
||||
|
||||
type User = Record<string, unknown>;
|
||||
|
||||
type QualifiedHost = { user: Record<string, unknown>; isFixed?: boolean; groupId?: string | null };
|
||||
|
||||
@Injectable()
|
||||
export class QualifiedHostsService extends BaseQualifiedHostsService {
|
||||
constructor(bookingRepository: PrismaBookingRepository, filterHostsService: FilterHostsService) {
|
||||
super({
|
||||
bookingRepo: bookingRepository,
|
||||
filterHostsService,
|
||||
});
|
||||
export class QualifiedHostsService {
|
||||
async getQualifiedUsers(
|
||||
_hosts: { userId: number; isFixed: boolean }[],
|
||||
_input: { eventTypeId: number; startTime: string; endTime: string }
|
||||
): Promise<{ userId: number; isFixed: boolean; priority: number }[]> {
|
||||
// In community edition, all hosts qualify
|
||||
return _hosts.map((host) => ({ ...host, priority: 0 }));
|
||||
}
|
||||
|
||||
async findQualifiedHostsWithDelegationCredentials(...args: unknown[]): Promise<{
|
||||
qualifiedRRHosts: QualifiedHost[];
|
||||
allFallbackRRHosts: QualifiedHost[];
|
||||
fixedHosts: QualifiedHost[];
|
||||
}> {
|
||||
const input = (args[0] ?? {}) as Record<string, unknown>;
|
||||
const eventType = (input.eventType ?? {}) as Record<string, unknown>;
|
||||
const contactOwnerEmail = input.contactOwnerEmail as string | null | undefined;
|
||||
const routedTeamMemberIds = (input.routedTeamMemberIds ?? []) as number[];
|
||||
|
||||
const hosts = (eventType.hosts ?? []) as Host[];
|
||||
const users = (eventType.users ?? []) as User[];
|
||||
const schedulingType = eventType.schedulingType as string | null | undefined;
|
||||
|
||||
if (hosts.length > 0) {
|
||||
const fixedHosts: QualifiedHost[] = [];
|
||||
const allRRHosts: QualifiedHost[] = [];
|
||||
|
||||
for (const host of hosts) {
|
||||
const qualifiedHost: QualifiedHost = {
|
||||
user: host.user,
|
||||
isFixed: host.isFixed,
|
||||
groupId: host.groupId ?? null,
|
||||
};
|
||||
|
||||
if (host.isFixed || schedulingType !== "ROUND_ROBIN") {
|
||||
fixedHosts.push(qualifiedHost);
|
||||
} else {
|
||||
allRRHosts.push(qualifiedHost);
|
||||
}
|
||||
}
|
||||
|
||||
let qualifiedRRHosts = allRRHosts;
|
||||
|
||||
if (contactOwnerEmail) {
|
||||
const contactOwnerHost = allRRHosts.filter(
|
||||
(h) => (h.user as { email?: string }).email === contactOwnerEmail
|
||||
);
|
||||
if (contactOwnerHost.length > 0) {
|
||||
qualifiedRRHosts = contactOwnerHost;
|
||||
}
|
||||
} else if (routedTeamMemberIds.length > 0) {
|
||||
const routedMemberIdSet = new Set(routedTeamMemberIds);
|
||||
const routedHosts = allRRHosts.filter((h) => routedMemberIdSet.has((h.user as { id: number }).id));
|
||||
if (routedHosts.length > 0) {
|
||||
qualifiedRRHosts = routedHosts;
|
||||
}
|
||||
}
|
||||
|
||||
return { qualifiedRRHosts, allFallbackRRHosts: allRRHosts, fixedHosts };
|
||||
}
|
||||
|
||||
if (users.length > 0) {
|
||||
const fixedHosts = users.map((user) => ({
|
||||
user,
|
||||
isFixed: true as const,
|
||||
groupId: null,
|
||||
}));
|
||||
return { qualifiedRRHosts: [], allFallbackRRHosts: [], fixedHosts };
|
||||
}
|
||||
|
||||
return { qualifiedRRHosts: [], allFallbackRRHosts: [], fixedHosts: [] };
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,12 @@
|
||||
import { RegularBookingService } from "@/lib/services/regular-booking.service";
|
||||
import { BookingEventHandlerService } from "@/lib/services/booking-event-handler.service";
|
||||
import { PrismaFeaturesRepository } from "@/lib/repositories/prisma-features.repository";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { RecurringBookingService as BaseRecurringBookingService } from "@calcom/platform-libraries/bookings";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { RegularBookingService } from "@/lib/services/regular-booking.service";
|
||||
|
||||
@Injectable()
|
||||
export class RecurringBookingService extends BaseRecurringBookingService {
|
||||
constructor(
|
||||
regularBookingService: RegularBookingService,
|
||||
bookingEventHandler: BookingEventHandlerService,
|
||||
featuresRepository: PrismaFeaturesRepository
|
||||
) {
|
||||
constructor(regularBookingService: RegularBookingService) {
|
||||
super({
|
||||
regularBookingService,
|
||||
bookingEventHandler,
|
||||
featuresRepository,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import type { PrismaClient } from "@calcom/prisma";
|
||||
import { Inject, Injectable } from "@nestjs/common";
|
||||
import { WEBHOOK_PRODUCER } from "@/lib/modules/regular-booking.tokens";
|
||||
import { PrismaBookingRepository } from "@/lib/repositories/prisma-booking.repository";
|
||||
import { PrismaFeaturesRepository } from "@/lib/repositories/prisma-features.repository";
|
||||
import { PrismaUserRepository } from "@/lib/repositories/prisma-user.repository";
|
||||
import { BookingEventHandlerService } from "@/lib/services/booking-event-handler.service";
|
||||
import { CheckBookingAndDurationLimitsService } from "@/lib/services/check-booking-and-duration-limits.service";
|
||||
@@ -25,7 +24,6 @@ export class RegularBookingService extends BaseRegularBookingService {
|
||||
luckyUserService: LuckyUserService,
|
||||
userRepository: PrismaUserRepository,
|
||||
bookingEmailAndSmsTasker: BookingEmailAndSmsTasker,
|
||||
featuresRepository: PrismaFeaturesRepository,
|
||||
bookingEventHandler: BookingEventHandlerService,
|
||||
@Inject(WEBHOOK_PRODUCER) webhookProducer: IWebhookProducerService
|
||||
) {
|
||||
@@ -37,7 +35,6 @@ export class RegularBookingService extends BaseRegularBookingService {
|
||||
luckyUserService,
|
||||
userRepository,
|
||||
bookingEmailAndSmsTasker,
|
||||
featuresRepository,
|
||||
bookingEventHandler,
|
||||
webhookProducer,
|
||||
});
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
import { StripeBillingService } from "@calcom/platform-libraries";
|
||||
import type { IBillingProviderService } from "@calcom/platform-libraries/organizations";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { StripeService } from "@/modules/stripe/stripe.service";
|
||||
|
||||
@Injectable()
|
||||
export class StripeBillingProviderService
|
||||
extends StripeBillingService
|
||||
implements Pick<IBillingProviderService, "createSubscriptionUsageRecord">
|
||||
{
|
||||
constructor(readonly stripeService: StripeService) {
|
||||
super(stripeService.getStripe());
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
import { Logger } from "@/lib/logger.bridge";
|
||||
import { PlatformBillingTaskService } from "@/lib/services/tasker/platform-billing-task.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { PlatformOrganizationBillingSyncTasker as BasePlatformOrganizationBillingSyncTasker } from "@calcom/platform-libraries/organizations";
|
||||
|
||||
@Injectable()
|
||||
export class PlatformBillingSyncTaskerService extends BasePlatformOrganizationBillingSyncTasker {
|
||||
constructor(billingTaskService: PlatformBillingTaskService, logger: Logger) {
|
||||
super({
|
||||
logger,
|
||||
billingTaskService,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import { Logger } from "@/lib/logger.bridge";
|
||||
import { PrismaPlatformBillingRepository } from "@/lib/repositories/prisma-platform-billing.repository";
|
||||
import { StripeBillingProviderService } from "@/lib/services/stripe-billing-provider.service";
|
||||
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { PlatformOrganizationBillingTaskService as BasePlatformOrganizationBillingTaskService } from "@calcom/platform-libraries/organizations";
|
||||
|
||||
@Injectable()
|
||||
export class PlatformBillingTaskService extends BasePlatformOrganizationBillingTaskService {
|
||||
constructor(
|
||||
organizationRepository: OrganizationsRepository,
|
||||
platformBillingRepository: PrismaPlatformBillingRepository,
|
||||
billingProviderService: StripeBillingProviderService,
|
||||
logger: Logger
|
||||
) {
|
||||
super({
|
||||
logger,
|
||||
organizationRepository,
|
||||
platformBillingRepository,
|
||||
billingProviderService,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
import { PlatformOrganizationBillingTasker as BasePlatformOrganizationBillingTasker } from "@calcom/platform-libraries/organizations";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { Logger } from "@/lib/logger.bridge";
|
||||
import { PlatformBillingSyncTaskerService } from "@/lib/services/tasker/platform-billing-sync-tasker.service";
|
||||
import { PlatformBillingTriggerTaskerService } from "@/lib/services/tasker/platform-billing-trigger-tasker.service";
|
||||
|
||||
@Injectable()
|
||||
export class PlatformBillingTasker extends BasePlatformOrganizationBillingTasker {
|
||||
constructor(
|
||||
syncTasker: PlatformBillingSyncTaskerService,
|
||||
asyncTasker: PlatformBillingTriggerTaskerService,
|
||||
logger: Logger
|
||||
) {
|
||||
super({
|
||||
logger,
|
||||
asyncTasker: asyncTasker,
|
||||
syncTasker: syncTasker,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import { Logger } from "@/lib/logger.bridge";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { PlatformOrganizationBillingTriggerTasker as BasePlatformOrganizationBillingTriggerTasker } from "@calcom/platform-libraries/organizations";
|
||||
|
||||
@Injectable()
|
||||
export class PlatformBillingTriggerTaskerService extends BasePlatformOrganizationBillingTriggerTasker {
|
||||
constructor(logger: Logger) {
|
||||
super({
|
||||
logger,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,35 +1,27 @@
|
||||
import { EventTypesModule_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.module";
|
||||
import { EventTypesModule_2024_06_14 } from "@/platform/event-types/event-types_2024_06_14/event-types.module";
|
||||
import { AtomsSecondaryEmailsRepository } from "@/modules/atoms/atoms-secondary-emails.repository";
|
||||
import { AtomsRepository } from "@/modules/atoms/atoms.repository";
|
||||
import { AtomsConferencingAppsController } from "@/modules/atoms/controllers/atoms.conferencing-apps.controller";
|
||||
import { AtomsController } from "@/modules/atoms/controllers/atoms.controller";
|
||||
import { AtomsEventTypesController } from "@/modules/atoms/controllers/atoms.event-types.controller";
|
||||
import { AtomsSchedulesController } from "@/modules/atoms/controllers/atoms.schedules.controller";
|
||||
import { AtomsVerificationController } from "@/modules/atoms/controllers/atoms.verification.controller";
|
||||
import { AttributesAtomsService } from "@/modules/atoms/services/attributes-atom.service";
|
||||
import { ConferencingAtomsService } from "@/modules/atoms/services/conferencing-atom.service";
|
||||
import { EventTypesAtomService } from "@/modules/atoms/services/event-types-atom.service";
|
||||
import { SchedulesAtomsService } from "@/modules/atoms/services/schedules-atom.service";
|
||||
import { VerificationAtomsService } from "@/modules/atoms/services/verification-atom.service";
|
||||
import { CredentialsRepository } from "@/modules/credentials/credentials.repository";
|
||||
import { MembershipsRepository } from "@/modules/memberships/memberships.repository";
|
||||
import { OrganizationsModule } from "@/modules/organizations/organizations.module";
|
||||
import { OrganizationsTeamsRepository } from "@/modules/organizations/teams/index/organizations-teams.repository";
|
||||
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||
import { RedisService } from "@/modules/redis/redis.service";
|
||||
import { TeamsEventTypesModule } from "@/modules/teams/event-types/teams-event-types.module";
|
||||
import { TeamsRepository } from "@/modules/teams/teams/teams.repository";
|
||||
import { UsersService } from "@/modules/users/services/users.service";
|
||||
import { UsersRepository } from "@/modules/users/users.repository";
|
||||
import { Module } from "@nestjs/common";
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, EventTypesModule_2024_06_14, OrganizationsModule, TeamsEventTypesModule],
|
||||
imports: [PrismaModule, EventTypesModule_2024_06_14],
|
||||
providers: [
|
||||
OrganizationsTeamsRepository,
|
||||
EventTypesAtomService,
|
||||
ConferencingAtomsService,
|
||||
AttributesAtomsService,
|
||||
MembershipsRepository,
|
||||
CredentialsRepository,
|
||||
UsersRepository,
|
||||
@@ -39,11 +31,9 @@ import { Module } from "@nestjs/common";
|
||||
SchedulesAtomsService,
|
||||
VerificationAtomsService,
|
||||
RedisService,
|
||||
TeamsRepository,
|
||||
],
|
||||
exports: [EventTypesAtomService],
|
||||
controllers: [
|
||||
AtomsController,
|
||||
AtomsEventTypesController,
|
||||
AtomsConferencingAppsController,
|
||||
AtomsSchedulesController,
|
||||
|
||||
@@ -1,16 +1,9 @@
|
||||
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
|
||||
import { ConferencingAtomsService } from "@/modules/atoms/services/conferencing-atom.service";
|
||||
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 { UserWithProfile } from "@/modules/users/users.repository";
|
||||
import { Controller, Get, Param, ParseIntPipe, UseGuards, Version, VERSION_NEUTRAL } from "@nestjs/common";
|
||||
import { Controller, Get, UseGuards, Version, VERSION_NEUTRAL } from "@nestjs/common";
|
||||
import { ApiTags as DocsTags, ApiExcludeController as DocsExcludeController } from "@nestjs/swagger";
|
||||
|
||||
import { SUCCESS_STATUS } from "@calcom/platform-constants";
|
||||
@@ -31,22 +24,6 @@ These endpoints should not be recommended for use by third party and are exclude
|
||||
export class AtomsConferencingAppsController {
|
||||
constructor(private readonly conferencingService: ConferencingAtomsService) {}
|
||||
|
||||
@Get("/organizations/:orgId/teams/:teamId/conferencing")
|
||||
@Roles("TEAM_ADMIN")
|
||||
@PlatformPlan("ESSENTIALS")
|
||||
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, IsTeamInOrg, PlatformPlanGuard, IsAdminAPIEnabledGuard)
|
||||
@Version(VERSION_NEUTRAL)
|
||||
async listTeamInstalledConferencingApps(
|
||||
@GetUser() user: UserWithProfile,
|
||||
@Param("teamId", ParseIntPipe) teamId: number
|
||||
): Promise<ApiResponse<ConnectedApps>> {
|
||||
const conferencingApps = await this.conferencingService.getTeamConferencingApps(user, teamId);
|
||||
return {
|
||||
status: SUCCESS_STATUS,
|
||||
data: conferencingApps,
|
||||
};
|
||||
}
|
||||
|
||||
@Get("/conferencing")
|
||||
@Version(VERSION_NEUTRAL)
|
||||
@UseGuards(ApiAuthGuard)
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
|
||||
import { FindTeamMembersMatchingAttributeQueryDto } from "@/modules/atoms/inputs/find-team-members-matching-attribute.input";
|
||||
import { AttributesAtomsService } from "@/modules/atoms/services/attributes-atom.service";
|
||||
import { ConferencingAtomsService } from "@/modules/atoms/services/conferencing-atom.service";
|
||||
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
|
||||
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
|
||||
import { UserWithProfile } from "@/modules/users/users.repository";
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
ParseIntPipe,
|
||||
UseGuards,
|
||||
Version,
|
||||
VERSION_NEUTRAL,
|
||||
Query,
|
||||
} from "@nestjs/common";
|
||||
import { ApiTags as DocsTags, ApiExcludeController as DocsExcludeController } from "@nestjs/swagger";
|
||||
|
||||
import { SUCCESS_STATUS } from "@calcom/platform-constants";
|
||||
|
||||
import { FindTeamMembersMatchingAttributeResponseDto } from "../outputs/find-team-members-matching-attribute.output";
|
||||
|
||||
/*
|
||||
Endpoints used only by platform atoms, reusing code from other modules, data is already formatted and ready to be used by frontend atoms
|
||||
these endpoints should not be recommended for use by third party and are excluded from docs
|
||||
*/
|
||||
|
||||
@Controller({
|
||||
path: "/v2/atoms",
|
||||
version: API_VERSIONS_VALUES,
|
||||
})
|
||||
@DocsTags("Atoms - endpoints for atoms")
|
||||
@DocsExcludeController(true)
|
||||
export class AtomsController {
|
||||
constructor(
|
||||
private readonly conferencingService: ConferencingAtomsService,
|
||||
private readonly attributesService: AttributesAtomsService
|
||||
) {}
|
||||
|
||||
@Get("/organizations/:orgId/teams/:teamId/members-matching-attribute")
|
||||
@Version(VERSION_NEUTRAL)
|
||||
@UseGuards(ApiAuthGuard)
|
||||
async findTeamMembersMatchingAttributes(
|
||||
@GetUser() user: UserWithProfile,
|
||||
@Param("teamId", ParseIntPipe) teamId: number,
|
||||
@Param("orgId", ParseIntPipe) orgId: number,
|
||||
@Query() query: FindTeamMembersMatchingAttributeQueryDto
|
||||
): Promise<FindTeamMembersMatchingAttributeResponseDto> {
|
||||
const result = await this.attributesService.findTeamMembersMatchingAttribute(teamId, orgId, {
|
||||
attributesQueryValue: query.attributesQueryValue,
|
||||
isPreview: query.isPreview,
|
||||
enablePerf: query.enablePerf,
|
||||
concurrency: query.concurrency,
|
||||
});
|
||||
|
||||
return {
|
||||
status: SUCCESS_STATUS,
|
||||
data: result,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
Version,
|
||||
} from "@nestjs/common";
|
||||
import { ApiExcludeController as DocsExcludeController, ApiTags as DocsTags } from "@nestjs/swagger";
|
||||
import { GetEventTypePublicOutput } from "@/ee/event-types/event-types_2024_04_15/outputs/get-event-type-public.output";
|
||||
import { GetEventTypePublicOutput } from "@/platform/event-types/event-types_2024_04_15/outputs/get-event-type-public.output";
|
||||
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
|
||||
import {
|
||||
BulkUpdateEventTypeToDefaultLocationDto,
|
||||
@@ -23,15 +23,8 @@ import {
|
||||
} from "@/modules/atoms/inputs/event-types-app.input";
|
||||
import { GetAtomPublicEventTypeQueryParams } from "@/modules/atoms/inputs/get-atom-public-event-type-query-params.input";
|
||||
import { EventTypesAtomService } from "@/modules/atoms/services/event-types-atom.service";
|
||||
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 { UserWithProfile } from "@/modules/users/users.repository";
|
||||
|
||||
/*
|
||||
@@ -94,19 +87,6 @@ export class AtomsEventTypesController {
|
||||
};
|
||||
}
|
||||
|
||||
@Get("/organizations/:orgId/teams/:teamId/event-types")
|
||||
@Roles("TEAM_ADMIN")
|
||||
@PlatformPlan("ESSENTIALS")
|
||||
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, IsTeamInOrg, PlatformPlanGuard, IsAdminAPIEnabledGuard)
|
||||
@Version(VERSION_NEUTRAL)
|
||||
async listTeamEventTypes(@Param("teamId", ParseIntPipe) teamId: number): Promise<ApiResponse<unknown>> {
|
||||
const eventTypes = await this.eventTypesService.getTeamEventTypes(teamId);
|
||||
return {
|
||||
status: SUCCESS_STATUS,
|
||||
data: eventTypes,
|
||||
};
|
||||
}
|
||||
|
||||
@Get("/event-types")
|
||||
@Version(VERSION_NEUTRAL)
|
||||
@UseGuards(ApiAuthGuard)
|
||||
@@ -160,22 +140,6 @@ export class AtomsEventTypesController {
|
||||
};
|
||||
}
|
||||
|
||||
@Patch("/organizations/:orgId/teams/:teamId/event-types/bulk-update-to-default-location")
|
||||
@Version(VERSION_NEUTRAL)
|
||||
@Roles("TEAM_ADMIN")
|
||||
@PlatformPlan("ESSENTIALS")
|
||||
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, IsTeamInOrg, PlatformPlanGuard, IsAdminAPIEnabledGuard)
|
||||
async bulkUpdateAtomTeamEventTypes(
|
||||
@GetUser() user: UserWithProfile,
|
||||
@Body() body: BulkUpdateEventTypeToDefaultLocationDto,
|
||||
@Param("teamId", ParseIntPipe) teamId: number
|
||||
): Promise<{ status: typeof SUCCESS_STATUS | typeof ERROR_STATUS }> {
|
||||
await this.eventTypesService.bulkUpdateTeamEventTypesDefaultLocation(body.eventTypeIds, teamId);
|
||||
return {
|
||||
status: SUCCESS_STATUS,
|
||||
};
|
||||
}
|
||||
|
||||
@Patch("event-types/:eventTypeId")
|
||||
@Version(VERSION_NEUTRAL)
|
||||
@UseGuards(ApiAuthGuard)
|
||||
@@ -195,26 +159,4 @@ export class AtomsEventTypesController {
|
||||
};
|
||||
}
|
||||
|
||||
@Patch("/organizations/:orgId/teams/:teamId/event-types/:eventTypeId")
|
||||
@Version(VERSION_NEUTRAL)
|
||||
@Roles("TEAM_ADMIN")
|
||||
@PlatformPlan("ESSENTIALS")
|
||||
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, IsTeamInOrg, PlatformPlanGuard, IsAdminAPIEnabledGuard)
|
||||
async updateAtomTeamEventType(
|
||||
@GetUser() user: UserWithProfile,
|
||||
@Param("eventTypeId", ParseIntPipe) eventTypeId: number,
|
||||
@Param("teamId", ParseIntPipe) teamId: number,
|
||||
@Body() body: UpdateEventTypeReturn
|
||||
): Promise<ApiResponse<UpdateEventTypeReturn>> {
|
||||
const eventType = await this.eventTypesService.updateTeamEventType(
|
||||
eventTypeId,
|
||||
{ ...body, id: eventTypeId },
|
||||
user,
|
||||
teamId
|
||||
);
|
||||
return {
|
||||
status: SUCCESS_STATUS,
|
||||
data: eventType,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
|
||||
import type { TFindTeamMembersMatchingAttributeLogicInputSchema } from "@calcom/platform-libraries";
|
||||
|
||||
export class FindTeamMembersMatchingAttributeQueryDto {
|
||||
@ApiProperty({
|
||||
nullable: true,
|
||||
})
|
||||
attributesQueryValue!: TFindTeamMembersMatchingAttributeLogicInputSchema["attributesQueryValue"] | null;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
type: Boolean,
|
||||
})
|
||||
isPreview?: boolean;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
type: Boolean,
|
||||
})
|
||||
enablePerf?: boolean;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
type: Number,
|
||||
})
|
||||
concurrency?: number;
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { Expose, Type } from "class-transformer";
|
||||
import { IsString, ValidateNested } from "class-validator";
|
||||
|
||||
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
|
||||
import { FindTeamMembersMatchingAttributeOutputDto } from "@calcom/platform-types";
|
||||
|
||||
export class FindTeamMembersMatchingAttributeResponseDto {
|
||||
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
|
||||
@IsString()
|
||||
@Expose()
|
||||
readonly status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
|
||||
|
||||
@ValidateNested()
|
||||
@Type(() => FindTeamMembersMatchingAttributeOutputDto)
|
||||
@Expose()
|
||||
@ApiProperty({ type: FindTeamMembersMatchingAttributeOutputDto })
|
||||
readonly data!: FindTeamMembersMatchingAttributeOutputDto;
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
import { UsersRepository } from "@/modules/users/users.repository";
|
||||
import { Logger } from "@nestjs/common";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { findTeamMembersMatchingAttributeLogic } from "@calcom/platform-libraries";
|
||||
|
||||
import { FindTeamMembersMatchingAttributeQueryDto } from "../inputs/find-team-members-matching-attribute.input";
|
||||
|
||||
@Injectable()
|
||||
export class AttributesAtomsService {
|
||||
private logger = new Logger("AttributesAtomService");
|
||||
|
||||
constructor(private readonly usersRepository: UsersRepository) {}
|
||||
|
||||
async findTeamMembersMatchingAttribute(
|
||||
teamId: number,
|
||||
orgId: number,
|
||||
input: FindTeamMembersMatchingAttributeQueryDto
|
||||
) {
|
||||
const {
|
||||
teamMembersMatchingAttributeLogic: matchingTeamMembersWithResult,
|
||||
mainAttributeLogicBuildingWarnings: mainWarnings,
|
||||
fallbackAttributeLogicBuildingWarnings: fallbackWarnings,
|
||||
troubleshooter,
|
||||
} = await findTeamMembersMatchingAttributeLogic(
|
||||
{
|
||||
teamId,
|
||||
orgId,
|
||||
attributesQueryValue: input.attributesQueryValue,
|
||||
},
|
||||
{
|
||||
enablePerf: input.enablePerf,
|
||||
concurrency: input.concurrency,
|
||||
enableTroubleshooter: input.enablePerf,
|
||||
}
|
||||
);
|
||||
|
||||
if (!matchingTeamMembersWithResult) {
|
||||
return {
|
||||
troubleshooter,
|
||||
mainWarnings,
|
||||
fallbackWarnings,
|
||||
result: null,
|
||||
};
|
||||
}
|
||||
|
||||
const matchingTeamMembersIds = matchingTeamMembersWithResult.map(
|
||||
(member: { userId: number }) => member.userId
|
||||
);
|
||||
|
||||
const matchingTeamMembers = await this.usersRepository.findByIds(matchingTeamMembersIds);
|
||||
|
||||
return {
|
||||
mainWarnings,
|
||||
fallbackWarnings,
|
||||
troubleshooter: troubleshooter,
|
||||
result: matchingTeamMembers.map((user) => ({
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
})),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -23,16 +23,4 @@ export class ConferencingAtomsService {
|
||||
});
|
||||
}
|
||||
|
||||
async getTeamConferencingApps(user: UserWithProfile, teamId: number): Promise<ConnectedApps> {
|
||||
return getConnectedApps({
|
||||
user,
|
||||
input: {
|
||||
variant: "conferencing",
|
||||
onlyInstalled: true,
|
||||
teamId,
|
||||
includeTeamInstalledApps: true,
|
||||
},
|
||||
prisma: this.dbWrite.prisma as unknown as PrismaClient,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -15,9 +15,7 @@ import {
|
||||
} from "@calcom/platform-libraries/app-store";
|
||||
import {
|
||||
bulkUpdateEventsToDefaultLocation,
|
||||
bulkUpdateTeamEventsToDefaultLocation,
|
||||
EventTypeMetaDataSchema,
|
||||
getBulkTeamEventTypes,
|
||||
getBulkUserEventTypes,
|
||||
getEventTypeById,
|
||||
getPublicEvent,
|
||||
@@ -27,18 +25,15 @@ import {
|
||||
} from "@calcom/platform-libraries/event-types";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { EventTypesService_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/services/event-types.service";
|
||||
import { systemBeforeFieldEmail } from "@/ee/event-types/event-types_2024_06_14/transformers";
|
||||
import { EventTypesService_2024_06_14 } from "@/platform/event-types/event-types_2024_06_14/services/event-types.service";
|
||||
import { systemBeforeFieldEmail } from "@/platform/event-types/event-types_2024_06_14/transformers";
|
||||
import { AtomsRepository } from "@/modules/atoms/atoms.repository";
|
||||
import { CredentialsRepository } from "@/modules/credentials/credentials.repository";
|
||||
import { MembershipsRepository } from "@/modules/memberships/memberships.repository";
|
||||
import { OrganizationsTeamsRepository } from "@/modules/organizations/teams/index/organizations-teams.repository";
|
||||
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
|
||||
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
|
||||
import { TeamsEventTypesService } from "@/modules/teams/event-types/services/teams-event-types.service";
|
||||
import { UsersService } from "@/modules/users/services/users.service";
|
||||
import { UserWithProfile } from "@/modules/users/users.repository";
|
||||
import { UsersRepository } from "@/modules/users/users.repository";
|
||||
import { UsersRepository, UserWithProfile } from "@/modules/users/users.repository";
|
||||
|
||||
type EnabledAppType = App & {
|
||||
credential: CredentialDataWithTeamName;
|
||||
@@ -75,9 +70,7 @@ export class EventTypesAtomService {
|
||||
private readonly dbWrite: PrismaWriteService,
|
||||
private readonly dbRead: PrismaReadService,
|
||||
private readonly eventTypeService: EventTypesService_2024_06_14,
|
||||
private readonly teamEventTypeService: TeamsEventTypesService,
|
||||
private readonly organizationsTeamsRepository: OrganizationsTeamsRepository,
|
||||
private readonly usersRepository: UsersRepository,
|
||||
private readonly usersRepository: UsersRepository
|
||||
) {}
|
||||
|
||||
private async getTeamSlug(teamId: number): Promise<string> {
|
||||
@@ -132,57 +125,6 @@ export class EventTypesAtomService {
|
||||
return getBulkUserEventTypes(userId);
|
||||
}
|
||||
|
||||
async getTeamEventTypes(teamId: number) {
|
||||
return getBulkTeamEventTypes(teamId);
|
||||
}
|
||||
|
||||
async updateTeamEventType(
|
||||
eventTypeId: number,
|
||||
body: TUpdateEventTypeInputSchema,
|
||||
user: UserWithProfile,
|
||||
teamId: number
|
||||
) {
|
||||
await this.checkCanUpdateTeamEventType(user, eventTypeId, teamId, body.scheduleId);
|
||||
|
||||
const eventTypeUser = await this.eventTypeService.getUserToUpdateEvent(user);
|
||||
const bookingFields = body.bookingFields ? [...body.bookingFields] : undefined;
|
||||
|
||||
if (
|
||||
bookingFields?.length &&
|
||||
!bookingFields.find((field) => field.type === "email") &&
|
||||
!bookingFields.find((field) => field.type === "phone")
|
||||
) {
|
||||
bookingFields.push(systemBeforeFieldEmail);
|
||||
}
|
||||
|
||||
// Normalize period dates to UTC midnight (only if provided)
|
||||
const periodDates =
|
||||
body.periodStartDate !== undefined || body.periodEndDate !== undefined
|
||||
? {
|
||||
...(body.periodStartDate !== undefined
|
||||
? { periodStartDate: normalizePeriodDate(body.periodStartDate) }
|
||||
: {}),
|
||||
...(body.periodEndDate !== undefined
|
||||
? { periodEndDate: normalizePeriodDate(body.periodEndDate) }
|
||||
: {}),
|
||||
}
|
||||
: {};
|
||||
|
||||
const eventType = await updateEventType({
|
||||
input: { ...body, id: eventTypeId, bookingFields, ...periodDates },
|
||||
ctx: {
|
||||
user: eventTypeUser,
|
||||
prisma: this.dbWrite.prisma,
|
||||
},
|
||||
});
|
||||
|
||||
if (!eventType) {
|
||||
throw new NotFoundException(`Event type with id ${eventTypeId} not found`);
|
||||
}
|
||||
|
||||
return eventType;
|
||||
}
|
||||
|
||||
async updateEventType(eventTypeId: number, body: TUpdateEventTypeInputSchema, user: UserWithProfile) {
|
||||
await this.eventTypeService.checkCanUpdateEventType(user.id, eventTypeId, body.scheduleId);
|
||||
const eventTypeUser = await this.eventTypeService.getUserToUpdateEvent(user);
|
||||
@@ -224,34 +166,6 @@ export class EventTypesAtomService {
|
||||
return eventType;
|
||||
}
|
||||
|
||||
async checkCanUpdateTeamEventType(
|
||||
user: UserWithProfile,
|
||||
eventTypeId: number,
|
||||
teamId: number,
|
||||
scheduleId: number | null | undefined
|
||||
) {
|
||||
const organizationId = this.usersService.getUserMainOrgId(user);
|
||||
|
||||
if (organizationId) {
|
||||
const isUserOrganizationAdmin = await this.membershipsRepository.isUserOrganizationAdmin(
|
||||
user.id,
|
||||
organizationId
|
||||
);
|
||||
|
||||
if (isUserOrganizationAdmin) {
|
||||
const orgTeam = await this.organizationsTeamsRepository.findOrgTeam(organizationId, teamId);
|
||||
if (orgTeam) {
|
||||
await this.teamEventTypeService.validateEventTypeExists(teamId, eventTypeId);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await this.checkTeamOwnsEventType(user.id, eventTypeId, teamId);
|
||||
await this.teamEventTypeService.validateEventTypeExists(teamId, eventTypeId);
|
||||
await this.eventTypeService.checkUserOwnsSchedule(user.id, scheduleId);
|
||||
}
|
||||
|
||||
async checkTeamOwnsEventType(userId: number, eventTypeId: number, teamId: number) {
|
||||
const membership = await this.dbRead.prisma.membership.findFirst({
|
||||
where: {
|
||||
@@ -316,7 +230,7 @@ export class EventTypesAtomService {
|
||||
credentials,
|
||||
},
|
||||
});
|
||||
credentials = allCredentials;
|
||||
credentials = allCredentials as typeof credentials;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -443,13 +357,6 @@ export class EventTypesAtomService {
|
||||
});
|
||||
}
|
||||
|
||||
async bulkUpdateTeamEventTypesDefaultLocation(eventTypeIds: number[], teamId: number) {
|
||||
return bulkUpdateTeamEventsToDefaultLocation({
|
||||
eventTypeIds,
|
||||
prisma: this.dbWrite.prisma as unknown as PrismaClient,
|
||||
teamId,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Returns the public event type for atoms, handling both team and user events.
|
||||
*/
|
||||
|
||||
@@ -7,7 +7,6 @@ import { DeploymentsModule } from "@/modules/deployments/deployments.module";
|
||||
import { MembershipsModule } from "@/modules/memberships/memberships.module";
|
||||
import { OAuthFlowService } from "@/modules/oauth-clients/services/oauth-flow.service";
|
||||
import { RedisModule } from "@/modules/redis/redis.module";
|
||||
import { RolesModule } from "@/modules/roles/roles.module";
|
||||
import { TokensModule } from "@/modules/tokens/tokens.module";
|
||||
import { UsersModule } from "@/modules/users/users.module";
|
||||
import { Module } from "@nestjs/common";
|
||||
@@ -22,7 +21,6 @@ import { PassportModule } from "@nestjs/passport";
|
||||
MembershipsModule,
|
||||
TokensModule,
|
||||
DeploymentsModule,
|
||||
RolesModule,
|
||||
],
|
||||
providers: [NextAuthGuard, NextAuthStrategy, ApiAuthGuard, ApiAuthStrategy, OAuthFlowService],
|
||||
exports: [NextAuthGuard, ApiAuthGuard],
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
import type { PlatformPlanType } from "@/modules/billing/types";
|
||||
import { Reflector } from "@nestjs/core";
|
||||
|
||||
export const PlatformPlan = Reflector.createDecorator<PlatformPlanType>();
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Reflector } from "@nestjs/core";
|
||||
|
||||
import type { PermissionString } from "@calcom/platform-libraries/pbac";
|
||||
// PBAC (Permission-Based Access Control) is not available in community edition
|
||||
// PermissionString is defined locally since the platform-libraries/pbac module was removed
|
||||
type PermissionString = string;
|
||||
|
||||
export const Pbac = Reflector.createDecorator<PermissionString[]>();
|
||||
@@ -1,117 +0,0 @@
|
||||
import { PlatformPlanGuard } from "@/modules/auth/guards/billing/platform-plan.guard";
|
||||
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
|
||||
import { RedisService } from "@/modules/redis/redis.service";
|
||||
import { createMock } from "@golevelup/ts-jest";
|
||||
import { ForbiddenException } from "@nestjs/common";
|
||||
import { ExecutionContext } from "@nestjs/common";
|
||||
import { Reflector } from "@nestjs/core";
|
||||
|
||||
describe("PlatformPlanGuard", () => {
|
||||
let guard: PlatformPlanGuard;
|
||||
let reflector: Reflector;
|
||||
let organizationsRepository: OrganizationsRepository;
|
||||
let redisService: RedisService;
|
||||
|
||||
const mockContext = createMockExecutionContext({
|
||||
params: { teamId: "1", orgId: "1" },
|
||||
user: { id: "1" },
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
reflector = new Reflector();
|
||||
organizationsRepository = createMock<OrganizationsRepository>();
|
||||
redisService = createMock<RedisService>({
|
||||
redis: {
|
||||
get: jest.fn().mockResolvedValue(null),
|
||||
set: jest.fn().mockResolvedValue(null),
|
||||
},
|
||||
});
|
||||
guard = new PlatformPlanGuard(reflector, organizationsRepository, redisService);
|
||||
});
|
||||
|
||||
it("should be defined", () => {
|
||||
expect(guard).toBeDefined();
|
||||
});
|
||||
|
||||
it("should return true", async () => {
|
||||
jest.spyOn(reflector, "get").mockReturnValue("ESSENTIALS");
|
||||
jest.spyOn(organizationsRepository, "findByIdIncludeBilling").mockResolvedValue({
|
||||
isPlatform: true,
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
platformBilling: {
|
||||
subscriptionId: "sub_123",
|
||||
plan: "SCALE",
|
||||
},
|
||||
});
|
||||
|
||||
await expect(guard.canActivate(mockContext)).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it("should throw ForbiddenException if the organization does not exist", async () => {
|
||||
jest.spyOn(reflector, "get").mockReturnValue("ESSENTIALS");
|
||||
jest.spyOn(organizationsRepository, "findByIdIncludeBilling").mockResolvedValue(null);
|
||||
|
||||
await expect(guard.canActivate(mockContext)).rejects.toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("should return true if the organization is not platform", async () => {
|
||||
jest.spyOn(reflector, "get").mockReturnValue("ESSENTIALS");
|
||||
jest.spyOn(organizationsRepository, "findByIdIncludeBilling").mockResolvedValue({
|
||||
isPlatform: false,
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
platformBilling: undefined,
|
||||
});
|
||||
|
||||
await expect(guard.canActivate(mockContext)).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it("should throw ForbiddenException if the organization has no subscription", async () => {
|
||||
jest.spyOn(reflector, "get").mockReturnValue("ESSENTIALS");
|
||||
jest.spyOn(organizationsRepository, "findByIdIncludeBilling").mockResolvedValue({
|
||||
isPlatform: true,
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
platformBilling: {
|
||||
subscriptionId: null,
|
||||
plan: "STARTER",
|
||||
},
|
||||
});
|
||||
|
||||
await expect(guard.canActivate(mockContext)).rejects.toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("should throw ForbiddenException if the user has a lower plan than required", async () => {
|
||||
jest.spyOn(reflector, "get").mockReturnValue("ESSENTIALS");
|
||||
jest.spyOn(organizationsRepository, "findByIdIncludeBilling").mockResolvedValue({
|
||||
isPlatform: true,
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
platformBilling: {
|
||||
subscriptionId: "sub_123",
|
||||
plan: "STARTER",
|
||||
},
|
||||
});
|
||||
|
||||
await expect(guard.canActivate(mockContext)).rejects.toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("should return true if the result is cached in Redis", async () => {
|
||||
jest.spyOn(reflector, "get").mockReturnValue("ESSENTIALS");
|
||||
jest.spyOn(redisService.redis, "get").mockResolvedValue(JSON.stringify(true));
|
||||
|
||||
await expect(guard.canActivate(mockContext)).resolves.toBe(true);
|
||||
});
|
||||
|
||||
function createMockExecutionContext(context: Record<string, string | object>): ExecutionContext {
|
||||
return createMock<ExecutionContext>({
|
||||
switchToHttp: () => ({
|
||||
getRequest: () => ({
|
||||
params: context.params,
|
||||
user: context.user,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -1,96 +0,0 @@
|
||||
import { PlatformPlan } from "@/modules/auth/decorators/billing/platform-plan.decorator";
|
||||
import { ApiAuthGuardUser } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
|
||||
import { PlatformPlanType, orderedPlans } from "@/modules/billing/types";
|
||||
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
|
||||
import { RedisService } from "@/modules/redis/redis.service";
|
||||
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";
|
||||
import { Reflector } from "@nestjs/core";
|
||||
import { Request } from "express";
|
||||
|
||||
@Injectable()
|
||||
export class PlatformPlanGuard implements CanActivate {
|
||||
constructor(
|
||||
private reflector: Reflector,
|
||||
private readonly organizationsRepository: OrganizationsRepository,
|
||||
private readonly redisService: RedisService
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const minimumPlan = this.reflector.get(PlatformPlan, context.getHandler()) as PlatformPlanType;
|
||||
if (!minimumPlan) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
const orgId = request.params.orgId;
|
||||
const user = request.user as ApiAuthGuardUser;
|
||||
if (!user) {
|
||||
throw new ForbiddenException("PlatformPlanGuard - No user associated with the request.");
|
||||
}
|
||||
if (!orgId) {
|
||||
throw new ForbiddenException("PlatformPlanGuard - No organization associated with the request.");
|
||||
}
|
||||
|
||||
return await this.checkPlatformPlanAccess(orgId, minimumPlan);
|
||||
}
|
||||
|
||||
async checkPlatformPlanAccess(orgId: string, minimumPlan: PlatformPlanType) {
|
||||
const REDIS_CACHE_KEY = `apiv2:org:${orgId}:guard:platformbilling:${minimumPlan}`;
|
||||
const cachedValue = await this.redisService.redis.get(REDIS_CACHE_KEY);
|
||||
if (cachedValue !== null) {
|
||||
return cachedValue === "true";
|
||||
}
|
||||
|
||||
const organization = await this.organizationsRepository.findByIdIncludeBilling(Number(orgId));
|
||||
const isPlatform = organization?.isPlatform;
|
||||
const hasSubscription = organization?.platformBilling?.subscriptionId;
|
||||
|
||||
if (!organization) {
|
||||
throw new ForbiddenException(`PlatformPlanGuard - No organization found with id=${orgId}.`);
|
||||
}
|
||||
if (!isPlatform) {
|
||||
await this.redisService.redis.set(REDIS_CACHE_KEY, "true", "EX", 300);
|
||||
return true;
|
||||
}
|
||||
if (!hasSubscription) {
|
||||
throw new ForbiddenException(
|
||||
`PlatformPlanGuard - No platform subscription found for organization with id=${orgId}.`
|
||||
);
|
||||
}
|
||||
if (
|
||||
!hasMinimumPlan({
|
||||
currentPlan: organization.platformBilling?.plan as PlatformPlanType,
|
||||
minimumPlan: minimumPlan,
|
||||
plans: orderedPlans,
|
||||
})
|
||||
) {
|
||||
throw new ForbiddenException(
|
||||
`PlatformPlanGuard - organization with id=${orgId} does not have required plan for this operation. Minimum plan is ${minimumPlan} while the organization has ${
|
||||
organization.platformBilling?.plan || "undefined"
|
||||
}.`
|
||||
);
|
||||
}
|
||||
|
||||
await this.redisService.redis.set(REDIS_CACHE_KEY, "true", "EX", 300);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
type HasMinimumPlanProp = {
|
||||
currentPlan: PlatformPlanType;
|
||||
minimumPlan: PlatformPlanType;
|
||||
plans: readonly PlatformPlanType[];
|
||||
};
|
||||
|
||||
export function hasMinimumPlan(props: HasMinimumPlanProp): boolean {
|
||||
const currentPlanIndex = props.plans.indexOf(props.currentPlan);
|
||||
const minimumPlanIndex = props.plans.indexOf(props.minimumPlan);
|
||||
|
||||
if (currentPlanIndex === -1 || minimumPlanIndex === -1) {
|
||||
throw new ForbiddenException(
|
||||
`PlatformPlanGuard - Invalid platform billing plan provided. Current plan: ${props.currentPlan}, Minimum plan: ${props.minimumPlan}`
|
||||
);
|
||||
}
|
||||
|
||||
return currentPlanIndex >= minimumPlanIndex;
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
import { OrganizationsMembershipRepository } from "@/modules/organizations/memberships/organizations-membership.repository";
|
||||
import {
|
||||
Injectable,
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
NotFoundException,
|
||||
} from "@nestjs/common";
|
||||
import { Request } from "express";
|
||||
|
||||
import type { Membership } from "@calcom/prisma/client";
|
||||
|
||||
@Injectable()
|
||||
export class IsMembershipInOrg implements CanActivate {
|
||||
constructor(private organizationsMembershipRepository: OrganizationsMembershipRepository) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request & { membership: Membership }>();
|
||||
const membershipId: string = request.params.membershipId;
|
||||
const orgId: string = request.params.orgId;
|
||||
|
||||
if (!orgId) {
|
||||
throw new ForbiddenException("IsMembershipInOrg - No org id found in request params.");
|
||||
}
|
||||
|
||||
if (!membershipId) {
|
||||
throw new ForbiddenException("IsMembershipInOrg - No membership id found in request params.");
|
||||
}
|
||||
|
||||
const membership = await this.organizationsMembershipRepository.findOrgMembership(
|
||||
Number(orgId),
|
||||
Number(membershipId)
|
||||
);
|
||||
|
||||
if (!membership) {
|
||||
throw new NotFoundException(`IsMembershipInOrg - Membership (${membershipId}) not found.`);
|
||||
}
|
||||
|
||||
request.membership = membership;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
import { MembershipRoles } from "@/modules/auth/decorators/roles/membership-roles.decorator";
|
||||
import { MembershipsRepository } from "@/modules/memberships/memberships.repository";
|
||||
import { OrganizationsService } from "@/modules/organizations/index/organizations.service";
|
||||
import { UsersService } from "@/modules/users/services/users.service";
|
||||
import { UserWithProfile } from "@/modules/users/users.repository";
|
||||
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";
|
||||
import { Reflector } from "@nestjs/core";
|
||||
|
||||
import { MembershipRole } from "@calcom/platform-libraries";
|
||||
|
||||
@Injectable()
|
||||
export class OrganizationRolesGuard implements CanActivate {
|
||||
constructor(
|
||||
private reflector: Reflector,
|
||||
private organizationsService: OrganizationsService,
|
||||
private membershipRepository: MembershipsRepository,
|
||||
private usersService: UsersService
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const user: UserWithProfile = request.user;
|
||||
const organizationId = this.getOrganizationId(context);
|
||||
|
||||
if (!user || !organizationId) {
|
||||
throw new ForbiddenException("OrganizationRolesGuard - No organization associated with the user.");
|
||||
}
|
||||
|
||||
await this.isPlatform(organizationId);
|
||||
|
||||
const membership = await this.membershipRepository.findOrgUserMembership(organizationId, user.id);
|
||||
const allowedRoles = this.reflector.get(MembershipRoles, context.getHandler());
|
||||
|
||||
this.isMembershipAccepted(membership.accepted);
|
||||
this.isRoleAllowed(membership.role, allowedRoles);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
async isPlatform(organizationId: number) {
|
||||
const isPlatform = await this.organizationsService.isPlatform(organizationId);
|
||||
if (!isPlatform) {
|
||||
throw new ForbiddenException("OrganizationRolesGuard - Organization is not a platform (SHP).");
|
||||
}
|
||||
}
|
||||
|
||||
getOrganizationId(context: ExecutionContext) {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const user: UserWithProfile = request.user;
|
||||
const authMethodOrganizationId = request.organizationId;
|
||||
if (authMethodOrganizationId) return authMethodOrganizationId;
|
||||
|
||||
const userOrganizationId = user ? this.usersService.getUserMainOrgId(user) : null;
|
||||
return userOrganizationId;
|
||||
}
|
||||
|
||||
isMembershipAccepted(accepted: boolean) {
|
||||
if (!accepted) {
|
||||
throw new ForbiddenException(
|
||||
`OrganizationRolesGuard - User has not accepted membership in the organization.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
isRoleAllowed(membershipRole: MembershipRole, allowedRoles: MembershipRole[]) {
|
||||
if (!allowedRoles?.length || !Object.keys(allowedRoles)?.length) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const hasRequiredRole = allowedRoles.includes(membershipRole);
|
||||
if (!hasRequiredRole) {
|
||||
throw new ForbiddenException(
|
||||
`OrganizationRolesGuard - User must have one of the roles: ${allowedRoles.join(", ")}.`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
|
||||
import { RedisService } from "@/modules/redis/redis.service";
|
||||
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";
|
||||
import { Request } from "express";
|
||||
|
||||
import type { Team } from "@calcom/prisma/client";
|
||||
|
||||
type CachedData = {
|
||||
org?: Team;
|
||||
canAccess?: boolean;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class IsAdminAPIEnabledGuard implements CanActivate {
|
||||
constructor(
|
||||
private organizationsRepository: OrganizationsRepository,
|
||||
private readonly redisService: RedisService
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request & { organization?: Team }>();
|
||||
const organizationId: string = request.params.orgId;
|
||||
|
||||
if (!organizationId) {
|
||||
throw new ForbiddenException("IsAdminAPIEnabledGuard - No organization id found in request params.");
|
||||
}
|
||||
|
||||
const { canAccess, organization } = await this.checkAdminAPIEnabled(organizationId);
|
||||
if (organization) {
|
||||
request.organization = organization;
|
||||
}
|
||||
if (!canAccess) {
|
||||
throw new ForbiddenException(
|
||||
`IsAdminAPIEnabledGuard - Organization with id=${organizationId} does not have Admin API access. Please contact https://cal.com/sales to upgrade.`
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async checkAdminAPIEnabled(
|
||||
organizationId: string
|
||||
): Promise<{ canAccess: boolean; organization?: Team | null }> {
|
||||
let canAccess = false;
|
||||
const REDIS_CACHE_KEY = `apiv2:org:${organizationId}:guard:isAdminAccess`;
|
||||
const cachedData = await this.redisService.redis.get(REDIS_CACHE_KEY);
|
||||
|
||||
if (cachedData) {
|
||||
const { org: cachedOrg, canAccess: cachedCanAccess } = JSON.parse(cachedData) as CachedData;
|
||||
if (cachedOrg?.id === Number(organizationId) && cachedCanAccess !== undefined) {
|
||||
return {
|
||||
canAccess: cachedCanAccess,
|
||||
organization: cachedOrg,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const org = await this.organizationsRepository.findById({ id: Number(organizationId) });
|
||||
|
||||
if (org?.isOrganization && !org?.isPlatform) {
|
||||
const adminAPIAccessIsEnabledInOrg = await this.organizationsRepository.fetchOrgAdminApiStatus(
|
||||
Number(organizationId)
|
||||
);
|
||||
if (!adminAPIAccessIsEnabledInOrg) {
|
||||
throw new ForbiddenException(
|
||||
`IsAdminAPIEnabledGuard - Organization does not have Admin API access, please contact https://cal.com/sales to upgrade`
|
||||
);
|
||||
}
|
||||
}
|
||||
canAccess = true;
|
||||
|
||||
if (org && canAccess) {
|
||||
await this.redisService.redis.set(
|
||||
REDIS_CACHE_KEY,
|
||||
JSON.stringify({ org: org, canAccess } satisfies CachedData),
|
||||
"EX",
|
||||
300
|
||||
);
|
||||
}
|
||||
|
||||
return { canAccess, organization: org };
|
||||
}
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
import { ManagedOrganizationsRepository } from "@/modules/organizations/organizations/managed-organizations.repository";
|
||||
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";
|
||||
import { Request } from "express";
|
||||
|
||||
import type { Team } from "@calcom/prisma/client";
|
||||
|
||||
@Injectable()
|
||||
export class IsManagedOrgInManagerOrg implements CanActivate {
|
||||
constructor(private managedOrganizationsRepository: ManagedOrganizationsRepository) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request & { managedOrganization: Team }>();
|
||||
const managedOrgId: string = request.params.managedOrganizationId;
|
||||
const managerOrgId: string = request.params.orgId;
|
||||
|
||||
if (!managerOrgId) {
|
||||
throw new ForbiddenException("IsManagedOrgInManagerOrg - No manager org id found in request params.");
|
||||
}
|
||||
|
||||
if (!managedOrgId) {
|
||||
throw new ForbiddenException("IsManagedOrgInManagerOrg - No managed org id found in request params.");
|
||||
}
|
||||
|
||||
const managedOrganization = await this.managedOrganizationsRepository.getByManagerManagedIds(
|
||||
Number(managerOrgId),
|
||||
Number(managedOrgId)
|
||||
);
|
||||
|
||||
if (!managedOrganization) {
|
||||
throw new ForbiddenException(
|
||||
`IsManagedOrgInManagerOrg - Managed organization with id=${managedOrgId} is not owned by manager organization with id=${managerOrgId}.`
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
|
||||
import { RedisService } from "@/modules/redis/redis.service";
|
||||
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";
|
||||
import { Request } from "express";
|
||||
|
||||
import type { Team } from "@calcom/prisma/client";
|
||||
|
||||
type CachedData = {
|
||||
org?: Team;
|
||||
canAccess?: boolean;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class IsOrgGuard implements CanActivate {
|
||||
constructor(
|
||||
private organizationsRepository: OrganizationsRepository,
|
||||
private readonly redisService: RedisService
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request & { organization: Team }>();
|
||||
const organizationId: string = request.params.orgId;
|
||||
|
||||
if (!organizationId) {
|
||||
throw new ForbiddenException("IsOrgGuard - No organization id found in request params.");
|
||||
}
|
||||
|
||||
const { canAccess, org } = await this.checkOrgAccess(organizationId);
|
||||
|
||||
if (canAccess && org) {
|
||||
request.organization = org;
|
||||
}
|
||||
|
||||
if (!canAccess) {
|
||||
throw new ForbiddenException(
|
||||
`IsOrgGuard - provided organization id=${organizationId} does not represent any existing organization.`
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
async checkOrgAccess(organizationId: string): Promise<{ canAccess: boolean; org?: Team | null }> {
|
||||
const REDIS_CACHE_KEY = `apiv2:org:${organizationId}:guard:isOrg`;
|
||||
let canAccess = false;
|
||||
const cachedData = await this.redisService.redis.get(REDIS_CACHE_KEY);
|
||||
|
||||
if (cachedData) {
|
||||
const { org: cachedOrg, canAccess: cachedCanAccess } = JSON.parse(cachedData) as CachedData;
|
||||
if (cachedOrg?.id === Number(organizationId) && cachedCanAccess !== undefined) {
|
||||
return {
|
||||
org: cachedOrg,
|
||||
canAccess: cachedCanAccess,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const org = await this.organizationsRepository.findById({ id: Number(organizationId) });
|
||||
|
||||
if (org?.isOrganization) {
|
||||
canAccess = true;
|
||||
}
|
||||
|
||||
if (org && canAccess) {
|
||||
await this.redisService.redis.set(
|
||||
REDIS_CACHE_KEY,
|
||||
JSON.stringify({ org, canAccess } satisfies CachedData),
|
||||
"EX",
|
||||
300
|
||||
);
|
||||
}
|
||||
|
||||
return { canAccess, org };
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
import { ApiAuthGuardUser } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
|
||||
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
|
||||
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";
|
||||
import { Request } from "express";
|
||||
|
||||
import type { Team } from "@calcom/prisma/client";
|
||||
|
||||
@Injectable()
|
||||
export class IsUserRoutingForm implements CanActivate {
|
||||
constructor(private readonly dbRead: PrismaReadService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request & { organization: Team }>();
|
||||
const routingFormId: string = request.params.routingFormId;
|
||||
const user = request.user as ApiAuthGuardUser;
|
||||
if (!routingFormId) {
|
||||
throw new ForbiddenException("IsUserRoutingForm - No routing form id found in request params.");
|
||||
}
|
||||
|
||||
const userRoutingForm = await this.dbRead.prisma.app_RoutingForms_Form.findFirst({
|
||||
where: {
|
||||
id: routingFormId,
|
||||
userId: Number(user.id),
|
||||
teamId: null,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!userRoutingForm) {
|
||||
throw new ForbiddenException(
|
||||
`Routing Form with id=${routingFormId} is not a user Routing Form owned by user with id=${user.id}.`
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
|
||||
import { OrganizationsWebhooksRepository } from "@/modules/organizations/webhooks/organizations-webhooks.repository";
|
||||
import { RedisService } from "@/modules/redis/redis.service";
|
||||
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";
|
||||
import { Request } from "express";
|
||||
|
||||
import type { Team } from "@calcom/prisma/client";
|
||||
|
||||
type CachedData = {
|
||||
org?: Team;
|
||||
canAccess?: boolean;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class IsWebhookInOrg implements CanActivate {
|
||||
constructor(
|
||||
private organizationsRepository: OrganizationsRepository,
|
||||
private organizationsWebhooksRepository: OrganizationsWebhooksRepository,
|
||||
private readonly redisService: RedisService
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
let canAccess = false;
|
||||
const request = context.switchToHttp().getRequest<Request & { organization: Team }>();
|
||||
const webhookId: string = request.params.webhookId;
|
||||
const organizationId: string = request.params.orgId;
|
||||
|
||||
if (!organizationId) {
|
||||
throw new ForbiddenException("IsWebhookInOrg - No organization id found in request params.");
|
||||
}
|
||||
if (!webhookId) {
|
||||
throw new ForbiddenException("IsWebhookInOrg - No webhook id found in request params.");
|
||||
}
|
||||
|
||||
const REDIS_CACHE_KEY = `apiv2:org:${webhookId}:guard:isWebhookInOrg`;
|
||||
const cachedData = await this.redisService.redis.get(REDIS_CACHE_KEY);
|
||||
|
||||
if (cachedData) {
|
||||
const { org: cachedOrg, canAccess: cachedCanAccess } = JSON.parse(cachedData) as CachedData;
|
||||
if (cachedOrg?.id === Number(organizationId) && cachedCanAccess !== undefined) {
|
||||
request.organization = cachedOrg;
|
||||
return cachedCanAccess;
|
||||
}
|
||||
}
|
||||
|
||||
const org = await this.organizationsRepository.findById({ id: Number(organizationId) });
|
||||
|
||||
if (org?.isOrganization) {
|
||||
const isWebhookInOrg = await this.organizationsWebhooksRepository.findWebhook(
|
||||
Number(organizationId),
|
||||
webhookId
|
||||
);
|
||||
if (isWebhookInOrg) canAccess = true;
|
||||
}
|
||||
|
||||
if (org && canAccess) {
|
||||
await this.redisService.redis.set(
|
||||
REDIS_CACHE_KEY,
|
||||
JSON.stringify({ org: org, canAccess } satisfies CachedData),
|
||||
"EX",
|
||||
300
|
||||
);
|
||||
}
|
||||
|
||||
if (!canAccess) {
|
||||
throw new ForbiddenException(
|
||||
`IsWebhookInOrg - webhook with id=${webhookId} is not part of the organization with id=${organizationId}.`
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,177 +1,17 @@
|
||||
import { Pbac } from "@/modules/auth/decorators/pbac/pbac.decorator";
|
||||
import { ApiAuthGuardUser } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
|
||||
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
|
||||
import { RedisService } from "@/modules/redis/redis.service";
|
||||
import {
|
||||
Injectable,
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
UnauthorizedException,
|
||||
BadRequestException,
|
||||
} from "@nestjs/common";
|
||||
import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
|
||||
import { Reflector } from "@nestjs/core";
|
||||
import { Request } from "express";
|
||||
import { Pbac } from "@/modules/auth/decorators/pbac/pbac.decorator";
|
||||
|
||||
import type { PermissionString } from "@calcom/platform-libraries/pbac";
|
||||
import { PermissionCheckService, FeaturesRepository } from "@calcom/platform-libraries/pbac";
|
||||
|
||||
export const REDIS_PBAC_CACHE_KEY = (teamId: number) => `apiv2:team:${teamId}:has:pbac:guard:pbac`;
|
||||
export const REDIS_REQUIRED_PERMISSIONS_CACHE_KEY = (
|
||||
userId: number,
|
||||
teamId: number,
|
||||
requiredPermissions: PermissionString[]
|
||||
) =>
|
||||
`apiv2:user:${userId}:team:${teamId}:requiredPermissions:${requiredPermissions
|
||||
.sort()
|
||||
.join(",")}:guard:pbac`;
|
||||
// PBAC (Permission-Based Access Control) is not available in community edition.
|
||||
// This guard always allows access since there is no permission check service.
|
||||
|
||||
@Injectable()
|
||||
export class PbacGuard implements CanActivate {
|
||||
constructor(
|
||||
private reflector: Reflector,
|
||||
private prismaReadService: PrismaReadService,
|
||||
private readonly redisService: RedisService
|
||||
) {}
|
||||
constructor(private reflector: Reflector) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request & { pbacAuthorizedRequest?: boolean }>();
|
||||
const user = request.user as ApiAuthGuardUser;
|
||||
const teamId = request.params.teamId;
|
||||
const orgId = request.params.orgId;
|
||||
const requiredPermissions = this.reflector.get(Pbac, context.getHandler());
|
||||
|
||||
const effectiveTeamId = teamId || orgId;
|
||||
if (!user) {
|
||||
throw new UnauthorizedException("PbacGuard - the request does not have an authorized user provided");
|
||||
}
|
||||
if (!effectiveTeamId) {
|
||||
throw new BadRequestException(
|
||||
"PbacGuard - can't check pbac because no teamId or orgId provided within the request url"
|
||||
);
|
||||
}
|
||||
|
||||
if (!requiredPermissions || requiredPermissions.length === 0) {
|
||||
request.pbacAuthorizedRequest = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
const hasPbacEnabled = await this.hasPbacEnabled(Number(effectiveTeamId));
|
||||
if (!hasPbacEnabled) {
|
||||
request.pbacAuthorizedRequest = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
const hasRequiredPermissions = await this.checkUserHasRequiredPermissions(
|
||||
user.id,
|
||||
Number(effectiveTeamId),
|
||||
requiredPermissions
|
||||
);
|
||||
|
||||
if (!hasRequiredPermissions) {
|
||||
request.pbacAuthorizedRequest = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
request.pbacAuthorizedRequest = true;
|
||||
const request = context.switchToHttp().getRequest<{ pbacAuthorizedRequest?: boolean }>();
|
||||
request.pbacAuthorizedRequest = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
async hasPbacEnabled(teamId: number) {
|
||||
const cachedHasPbacEnabled = await this.getCachePbacEnabled(teamId);
|
||||
|
||||
if (cachedHasPbacEnabled) {
|
||||
return cachedHasPbacEnabled;
|
||||
}
|
||||
|
||||
const pbacFeatureFlag = "pbac";
|
||||
const featuresRepository = new FeaturesRepository(this.prismaReadService.prisma);
|
||||
const hasPbacEnabled = await featuresRepository.checkIfTeamHasFeature(teamId, pbacFeatureFlag);
|
||||
|
||||
if (hasPbacEnabled) {
|
||||
await this.setCachePbacEnabled(teamId, hasPbacEnabled);
|
||||
}
|
||||
|
||||
return hasPbacEnabled;
|
||||
}
|
||||
|
||||
async checkUserHasRequiredPermissions(
|
||||
userId: number,
|
||||
teamId: number,
|
||||
requiredPermissions: PermissionString[]
|
||||
) {
|
||||
const cachedAccess = await this.getCacheRequiredPermissions(userId, teamId, requiredPermissions);
|
||||
|
||||
if (cachedAccess) {
|
||||
return cachedAccess;
|
||||
}
|
||||
|
||||
const permissionCheckService = new PermissionCheckService();
|
||||
const hasRequiredPermissions = await permissionCheckService.checkPermissions({
|
||||
userId,
|
||||
teamId,
|
||||
permissions: requiredPermissions,
|
||||
fallbackRoles: [],
|
||||
});
|
||||
|
||||
if (hasRequiredPermissions) {
|
||||
await this.setCacheRequiredPermissions(userId, teamId, requiredPermissions, hasRequiredPermissions);
|
||||
}
|
||||
|
||||
return hasRequiredPermissions;
|
||||
}
|
||||
|
||||
private async getCacheRequiredPermissions(
|
||||
userId: number,
|
||||
teamId: number,
|
||||
requiredPermissions: PermissionString[]
|
||||
): Promise<boolean | null> {
|
||||
return this.redisService.get<boolean>(
|
||||
REDIS_REQUIRED_PERMISSIONS_CACHE_KEY(userId, teamId, requiredPermissions)
|
||||
);
|
||||
}
|
||||
|
||||
private async setCacheRequiredPermissions(
|
||||
userId: number,
|
||||
teamId: number,
|
||||
requiredPermissions: PermissionString[],
|
||||
hasRequired: boolean
|
||||
): Promise<void> {
|
||||
await this.redisService.set<boolean>(
|
||||
REDIS_REQUIRED_PERMISSIONS_CACHE_KEY(userId, teamId, requiredPermissions),
|
||||
hasRequired,
|
||||
{ ttl: 300_000 }
|
||||
);
|
||||
}
|
||||
|
||||
private async getCachePbacEnabled(teamId: number) {
|
||||
const cachedResult = await this.redisService.get<boolean>(REDIS_PBAC_CACHE_KEY(teamId));
|
||||
return cachedResult;
|
||||
}
|
||||
|
||||
private async setCachePbacEnabled(teamId: number, pbacEnabled: boolean) {
|
||||
await this.redisService.set<boolean>(REDIS_PBAC_CACHE_KEY(teamId), pbacEnabled, {
|
||||
ttl: 300_000,
|
||||
});
|
||||
}
|
||||
|
||||
throwForbiddenError(
|
||||
userId: number,
|
||||
teamId: string,
|
||||
orgId: string,
|
||||
requiredPermissions: PermissionString[]
|
||||
) {
|
||||
let errorMessage = `PbacGuard - user with id=${userId} does not have the minimum required permissions=${requiredPermissions.join(
|
||||
","
|
||||
)} `;
|
||||
if (teamId) {
|
||||
errorMessage += `within team with id=${teamId}`;
|
||||
}
|
||||
if (orgId) {
|
||||
errorMessage += `within organization with id=${orgId}`;
|
||||
}
|
||||
errorMessage += `.`;
|
||||
|
||||
throw new ForbiddenException(errorMessage);
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import { RoutingFormsRepository } from "@/modules/routing-forms/routing-forms.repository";
|
||||
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";
|
||||
import { Request } from "express";
|
||||
|
||||
import type { Team } from "@calcom/prisma/client";
|
||||
|
||||
@Injectable()
|
||||
export class IsRoutingFormInTeam implements CanActivate {
|
||||
constructor(private routingFormsRepository: RoutingFormsRepository) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request & { team: Team }>();
|
||||
const teamId: string = request.params.teamId;
|
||||
const routingFormId: string = request.params.routingFormId;
|
||||
|
||||
if (!routingFormId) {
|
||||
throw new ForbiddenException("IsRoutingFormInTeam - No routing form id found in request params.");
|
||||
}
|
||||
|
||||
if (!teamId) {
|
||||
throw new ForbiddenException("IsRoutingFormInTeam - No team id found in request params.");
|
||||
}
|
||||
|
||||
const routingForm = await this.routingFormsRepository.getTeamRoutingForm(Number(teamId), routingFormId);
|
||||
|
||||
if (!routingForm) {
|
||||
throw new ForbiddenException(
|
||||
`IsRoutingFormInTeam - team with id=(${teamId}) does not own routing form with id=(${routingFormId}).`
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
import { OrganizationsTeamsRepository } from "@/modules/organizations/teams/index/organizations-teams.repository";
|
||||
import {
|
||||
Injectable,
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
NotFoundException,
|
||||
} from "@nestjs/common";
|
||||
import { Request } from "express";
|
||||
|
||||
import type { Team } from "@calcom/prisma/client";
|
||||
|
||||
@Injectable()
|
||||
export class IsTeamInOrg implements CanActivate {
|
||||
constructor(private organizationsTeamsRepository: OrganizationsTeamsRepository) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request & { team?: Team }>();
|
||||
const teamId: string = request.params.teamId;
|
||||
const orgId: string = request.params.orgId;
|
||||
|
||||
if (!orgId) {
|
||||
throw new ForbiddenException("IsTeamInOrg - No org id found in request params.");
|
||||
}
|
||||
|
||||
if (!teamId) {
|
||||
throw new ForbiddenException("IsTeamInOrg - No team id found in request params.");
|
||||
}
|
||||
|
||||
const { canAccess, team } = await this.checkIfTeamIsInOrg(orgId, teamId);
|
||||
|
||||
if (!canAccess) {
|
||||
throw new ForbiddenException(
|
||||
`IsTeamInOrg - Team with id=${teamId} is not part of the organization with id=${orgId}.`
|
||||
);
|
||||
}
|
||||
|
||||
request.team = team;
|
||||
return true;
|
||||
}
|
||||
|
||||
async checkIfTeamIsInOrg(orgId: string, teamId: string): Promise<{ canAccess: boolean; team?: Team }> {
|
||||
const team = await this.organizationsTeamsRepository.findOrgTeam(Number(orgId), Number(teamId));
|
||||
|
||||
if (!team) {
|
||||
throw new NotFoundException(`IsTeamInOrg - Team (${teamId}) not found.`);
|
||||
}
|
||||
|
||||
if (!team.isOrganization && team.parentId === Number(orgId)) {
|
||||
return { canAccess: true, team };
|
||||
}
|
||||
|
||||
return { canAccess: false };
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
|
||||
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";
|
||||
import { Request } from "express";
|
||||
|
||||
import type { Team } from "@calcom/prisma/client";
|
||||
|
||||
@Injectable()
|
||||
export class IsUserInOrgTeam implements CanActivate {
|
||||
constructor(private organizationsRepository: OrganizationsRepository) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request & { team: Team }>();
|
||||
const teamId: string = request.params.teamId;
|
||||
const orgId: string = request.params.orgId;
|
||||
const userId: string = request.params.userId;
|
||||
|
||||
if (!userId) {
|
||||
throw new ForbiddenException("IsUserInOrgTeam - No user id found in request params.");
|
||||
}
|
||||
|
||||
if (!orgId) {
|
||||
throw new ForbiddenException("IsUserInOrgTeam - No org id found in request params.");
|
||||
}
|
||||
|
||||
if (!teamId) {
|
||||
throw new ForbiddenException("IsUserInOrgTeam - No team id found in request params.");
|
||||
}
|
||||
|
||||
const user = await this.organizationsRepository.findOrgTeamUser(
|
||||
Number(orgId),
|
||||
Number(teamId),
|
||||
Number(userId)
|
||||
);
|
||||
|
||||
if (user) {
|
||||
request.user = user;
|
||||
return true;
|
||||
}
|
||||
|
||||
throw new ForbiddenException(
|
||||
`IsUserInOrgTeam - user with id=(${userId}) is not part of the team with id=(${teamId}) in the organization with id=(${orgId})`
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
|
||||
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";
|
||||
import { Request } from "express";
|
||||
|
||||
import type { Team } from "@calcom/prisma/client";
|
||||
|
||||
@Injectable()
|
||||
export class IsUserInOrg implements CanActivate {
|
||||
constructor(private organizationsRepository: OrganizationsRepository) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request & { team: Team }>();
|
||||
const orgId: string = request.params.orgId;
|
||||
const userId: string = request.params.userId;
|
||||
|
||||
if (!userId) {
|
||||
throw new ForbiddenException("IsUserInOrg - No user id found in request params.");
|
||||
}
|
||||
|
||||
if (!orgId) {
|
||||
throw new ForbiddenException("IsUserInOrg - No org id found in request params.");
|
||||
}
|
||||
|
||||
const user = await this.organizationsRepository.findOrgUser(Number(orgId), Number(userId));
|
||||
|
||||
if (!user) {
|
||||
throw new ForbiddenException(
|
||||
`IsUserInOrg - user with id=${userId} is not part of the organization with id=${orgId}.`
|
||||
);
|
||||
}
|
||||
|
||||
request.user = user;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
import { WorkflowsRepository, WorkflowType } from "@/modules/workflows/workflows.repository";
|
||||
import {
|
||||
Injectable,
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
NotFoundException,
|
||||
} from "@nestjs/common";
|
||||
import { Request } from "express";
|
||||
|
||||
@Injectable()
|
||||
export class IsEventTypeWorkflowInTeam implements CanActivate {
|
||||
constructor(private workflowsRepository: WorkflowsRepository) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request & { workflow?: WorkflowType }>();
|
||||
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.getEventTypeTeamWorkflowById(
|
||||
Number(teamId),
|
||||
Number(workflowId)
|
||||
);
|
||||
|
||||
if (!workflow) {
|
||||
throw new NotFoundException(`IsWorkflowInTeam - event-type workflow (${workflowId}) not found.`);
|
||||
}
|
||||
|
||||
if (workflow.teamId === Number(teamId)) {
|
||||
return { canAccess: true, workflow };
|
||||
}
|
||||
|
||||
return { canAccess: false };
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
import { WorkflowsRepository, WorkflowType } from "@/modules/workflows/workflows.repository";
|
||||
import {
|
||||
Injectable,
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
NotFoundException,
|
||||
} from "@nestjs/common";
|
||||
import { Request } from "express";
|
||||
|
||||
@Injectable()
|
||||
export class IsRoutingFormWorkflowInTeam implements CanActivate {
|
||||
constructor(private workflowsRepository: WorkflowsRepository) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request & { workflow?: WorkflowType }>();
|
||||
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.getRoutingFormTeamWorkflowById(
|
||||
Number(teamId),
|
||||
Number(workflowId)
|
||||
);
|
||||
|
||||
if (!workflow) {
|
||||
throw new NotFoundException(`IsWorkflowInTeam - routing form workflow (${workflowId}) not found.`);
|
||||
}
|
||||
|
||||
if (workflow.teamId === Number(teamId)) {
|
||||
return { canAccess: true, workflow };
|
||||
}
|
||||
|
||||
return { canAccess: false };
|
||||
}
|
||||
}
|
||||
@@ -100,7 +100,7 @@ describe("OAuth2 Controller Endpoints", () => {
|
||||
testRedirectUri,
|
||||
scopes,
|
||||
undefined,
|
||||
teamSlug ?? team.slug
|
||||
teamSlug ?? team.slug ?? undefined
|
||||
);
|
||||
const redirectUrl = new URL(result.redirectUrl);
|
||||
return redirectUrl.searchParams.get("code") as string;
|
||||
|
||||
@@ -1,8 +1,16 @@
|
||||
import { ERROR_STATUS, SUCCESS_STATUS } from "@calcom/platform-constants";
|
||||
import { OAuthClientType } from "@calcom/prisma/enums";
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { ApiHideProperty, ApiProperty } from "@nestjs/swagger";
|
||||
import { Expose, Type } from "class-transformer";
|
||||
import { IsBoolean, IsEnum, IsNotEmptyObject, IsOptional, IsString, ValidateNested } from "class-validator";
|
||||
import {
|
||||
IsArray,
|
||||
IsBoolean,
|
||||
IsEnum,
|
||||
IsNotEmptyObject,
|
||||
IsOptional,
|
||||
IsString,
|
||||
ValidateNested,
|
||||
} from "class-validator";
|
||||
|
||||
export class OAuth2ClientDto {
|
||||
@ApiProperty({
|
||||
@@ -14,9 +22,16 @@ export class OAuth2ClientDto {
|
||||
client_id!: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: "The redirect URI for the OAuth client",
|
||||
example: "https://example.com/callback",
|
||||
description: "The redirect URIs for the OAuth client",
|
||||
example: ["https://example.com/callback"],
|
||||
type: [String],
|
||||
})
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
@Expose({ name: "redirectUris" })
|
||||
redirect_uris!: string[];
|
||||
|
||||
@ApiHideProperty()
|
||||
@IsString()
|
||||
@Expose({ name: "redirectUri" })
|
||||
redirect_uri!: string;
|
||||
|
||||
@@ -7,6 +7,7 @@ import { OAuth2RedirectException } from "@/modules/auth/oauth2/filters/oauth2-re
|
||||
const NON_REDIRECTABLE_REASONS = new Set([
|
||||
"client_not_found",
|
||||
"client_not_approved",
|
||||
"client_rejected",
|
||||
"redirect_uri_mismatch",
|
||||
]);
|
||||
|
||||
|
||||
@@ -1,3 +1,25 @@
|
||||
import { X_CAL_CLIENT_ID, X_CAL_SECRET_KEY } from "@calcom/platform-constants";
|
||||
import type { PlatformOAuthClient, Team, User } from "@calcom/prisma/client";
|
||||
import { ExecutionContext, HttpException } from "@nestjs/common";
|
||||
import { ConfigModule, ConfigService } from "@nestjs/config";
|
||||
import { JwtService as NestJwtService } from "@nestjs/jwt";
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { createRequest } from "node-mocks-http";
|
||||
import { ApiKeysRepositoryFixture } from "test/fixtures/repository/api-keys.repository.fixture";
|
||||
import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture";
|
||||
import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.repository.fixture";
|
||||
import { ProfileRepositoryFixture } from "test/fixtures/repository/profiles.repository.fixture";
|
||||
import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture";
|
||||
import { TokensRepositoryFixture } from "test/fixtures/repository/tokens.repository.fixture";
|
||||
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
|
||||
import { MockedRedisService } from "test/mocks/mock-redis-service";
|
||||
import { randomString } from "test/utils/randomString";
|
||||
import {
|
||||
ApiAuthGuardRequest,
|
||||
ApiAuthStrategy,
|
||||
ONLY_CLIENT_ID_PROVIDED_MESSAGE,
|
||||
ONLY_CLIENT_SECRET_PROVIDED_MESSAGE,
|
||||
} from "./api-auth.strategy";
|
||||
import appConfig from "@/config/app";
|
||||
import { AuthMethods } from "@/lib/enums/auth-methods";
|
||||
import { ApiKeysRepository } from "@/modules/api-keys/api-keys-repository";
|
||||
@@ -13,31 +35,6 @@ import { ProfilesModule } from "@/modules/profiles/profiles.module";
|
||||
import { TokensModule } from "@/modules/tokens/tokens.module";
|
||||
import { UsersService } from "@/modules/users/services/users.service";
|
||||
import { UsersRepository } from "@/modules/users/users.repository";
|
||||
import { ExecutionContext, HttpException } from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { ConfigModule } from "@nestjs/config";
|
||||
import { JwtService as NestJwtService } from "@nestjs/jwt";
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { createRequest } from "node-mocks-http";
|
||||
import { ApiKeysRepositoryFixture } from "test/fixtures/repository/api-keys.repository.fixture";
|
||||
import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture";
|
||||
import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.repository.fixture";
|
||||
import { ProfileRepositoryFixture } from "test/fixtures/repository/profiles.repository.fixture";
|
||||
import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture";
|
||||
import { TokensRepositoryFixture } from "test/fixtures/repository/tokens.repository.fixture";
|
||||
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
|
||||
import { MockedRedisService } from "test/mocks/mock-redis-service";
|
||||
import { randomString } from "test/utils/randomString";
|
||||
|
||||
import { X_CAL_CLIENT_ID, X_CAL_SECRET_KEY } from "@calcom/platform-constants";
|
||||
import type { PlatformOAuthClient, Team, User } from "@calcom/prisma/client";
|
||||
|
||||
import {
|
||||
ApiAuthGuardRequest,
|
||||
ONLY_CLIENT_ID_PROVIDED_MESSAGE,
|
||||
ONLY_CLIENT_SECRET_PROVIDED_MESSAGE,
|
||||
} from "./api-auth.strategy";
|
||||
import { ApiAuthStrategy } from "./api-auth.strategy";
|
||||
|
||||
describe("ApiAuthStrategy", () => {
|
||||
let strategy: ApiAuthStrategy;
|
||||
@@ -233,7 +230,7 @@ describe("ApiAuthStrategy", () => {
|
||||
authorization: `Bearer cal_test_}`,
|
||||
},
|
||||
get: (key: string) =>
|
||||
({ Authorization: `Bearer cal_test_badkey1234`, origin: "http://localhost:3000" }[key]),
|
||||
({ Authorization: `Bearer cal_test_badkey1234`, origin: "http://localhost:3000" })[key],
|
||||
}),
|
||||
}),
|
||||
} as ExecutionContext;
|
||||
@@ -255,7 +252,7 @@ describe("ApiAuthStrategy", () => {
|
||||
headers: {
|
||||
[X_CAL_CLIENT_ID]: `${oAuthClient.id}gibberish`,
|
||||
},
|
||||
get: (key: string) => ({ origin: "http://localhost:3000" }[key]),
|
||||
get: (key: string) => ({ origin: "http://localhost:3000" })[key],
|
||||
}),
|
||||
}),
|
||||
} as ExecutionContext;
|
||||
@@ -278,7 +275,7 @@ describe("ApiAuthStrategy", () => {
|
||||
headers: {
|
||||
[X_CAL_SECRET_KEY]: `${oAuthClient.secret}gibberish`,
|
||||
},
|
||||
get: (key: string) => ({ origin: "http://localhost:3000" }[key]),
|
||||
get: (key: string) => ({ origin: "http://localhost:3000" })[key],
|
||||
}),
|
||||
}),
|
||||
} as ExecutionContext;
|
||||
@@ -303,7 +300,7 @@ describe("ApiAuthStrategy", () => {
|
||||
[X_CAL_SECRET_KEY]: `secret`,
|
||||
},
|
||||
get: (key: string) =>
|
||||
({ Authorization: `Bearer cal_test_badkey1234`, origin: "http://localhost:3000" }[key]),
|
||||
({ Authorization: `Bearer cal_test_badkey1234`, origin: "http://localhost:3000" })[key],
|
||||
}),
|
||||
}),
|
||||
} as ExecutionContext;
|
||||
@@ -327,7 +324,7 @@ describe("ApiAuthStrategy", () => {
|
||||
[X_CAL_SECRET_KEY]: `gibberish`,
|
||||
},
|
||||
get: (key: string) =>
|
||||
({ Authorization: `Bearer cal_test_badkey1234`, origin: "http://localhost:3000" }[key]),
|
||||
({ Authorization: `Bearer cal_test_badkey1234`, origin: "http://localhost:3000" })[key],
|
||||
}),
|
||||
}),
|
||||
} as ExecutionContext;
|
||||
@@ -346,7 +343,7 @@ describe("ApiAuthStrategy", () => {
|
||||
const context: ExecutionContext = {
|
||||
switchToHttp: () => ({
|
||||
getRequest: () => ({
|
||||
get: (key: string) => ({ Authorization: ``, origin: "http://localhost:3000" }[key]),
|
||||
get: (key: string) => ({ Authorization: ``, origin: "http://localhost:3000" })[key],
|
||||
}),
|
||||
}),
|
||||
} as ExecutionContext;
|
||||
|
||||
@@ -3,7 +3,6 @@ import { AuthMethods } from "@/lib/enums/auth-methods";
|
||||
import { isOriginAllowed } from "@/lib/is-origin-allowed/is-origin-allowed";
|
||||
import { BaseStrategy } from "@/lib/passport/strategies/types";
|
||||
import { ApiKeysRepository } from "@/modules/api-keys/api-keys-repository";
|
||||
import { DeploymentsService } from "@/modules/deployments/deployments.service";
|
||||
import { MembershipsRepository } from "@/modules/memberships/memberships.repository";
|
||||
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
|
||||
import { OAuthFlowService } from "@/modules/oauth-clients/services/oauth-flow.service";
|
||||
@@ -40,7 +39,6 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
|
||||
private readonly logger = new Logger("ApiAuthStrategy");
|
||||
|
||||
constructor(
|
||||
private readonly deploymentsService: DeploymentsService,
|
||||
private readonly config: ConfigService,
|
||||
private readonly oauthFlowService: OAuthFlowService,
|
||||
private readonly tokensRepository: TokensRepository,
|
||||
@@ -236,12 +234,6 @@ export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth")
|
||||
}
|
||||
|
||||
async apiKeyStrategy(apiKey: string, request: ApiAuthGuardRequest) {
|
||||
const isLicenseValid = await this.deploymentsService.checkLicense();
|
||||
if (!isLicenseValid) {
|
||||
throw new UnauthorizedException(
|
||||
"ApiAuthStrategy - api key - Invalid or missing CALCOM_LICENSE_KEY environment variable"
|
||||
);
|
||||
}
|
||||
const strippedApiKey = stripApiKey(apiKey, this.config.get<string>("api.keyPrefix"));
|
||||
const apiKeyHash = sha256Hash(strippedApiKey);
|
||||
const keyData = await this.apiKeyRepository.getApiKeyFromHash(apiKeyHash);
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
import { BullModule } from "@nestjs/bull";
|
||||
import { Module } from "@nestjs/common";
|
||||
import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/bookings.repository";
|
||||
import { PlatformBillingTaskerModule } from "@/lib/modules/platform-billing-tasker.module";
|
||||
import { BillingProcessor } from "@/modules/billing/billing.processor";
|
||||
import { BillingRepository } from "@/modules/billing/billing.repository";
|
||||
import { BillingController } from "@/modules/billing/controllers/billing.controller";
|
||||
import { IsUserInBillingOrg } from "@/modules/billing/guards/is-user-in-billing-org";
|
||||
import { BillingConfigService } from "@/modules/billing/services/billing.config.service";
|
||||
import { BillingService } from "@/modules/billing/services/billing.service";
|
||||
import { BillingServiceCachingProxy } from "@/modules/billing/services/billing-service-caching-proxy";
|
||||
import { ManagedOrganizationsBillingService } from "@/modules/billing/services/managed-organizations.billing.service";
|
||||
import { MembershipsModule } from "@/modules/memberships/memberships.module";
|
||||
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
|
||||
import { OrganizationsModule } from "@/modules/organizations/organizations.module";
|
||||
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||
import { RedisModule } from "@/modules/redis/redis.module";
|
||||
import { StripeModule } from "@/modules/stripe/stripe.module";
|
||||
import { UsersModule } from "@/modules/users/users.module";
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
PrismaModule,
|
||||
StripeModule,
|
||||
RedisModule,
|
||||
MembershipsModule,
|
||||
OrganizationsModule,
|
||||
BullModule.registerQueue({
|
||||
name: "billing",
|
||||
limiter: {
|
||||
max: 1,
|
||||
duration: 1000,
|
||||
},
|
||||
}),
|
||||
UsersModule,
|
||||
PlatformBillingTaskerModule,
|
||||
],
|
||||
providers: [
|
||||
BillingConfigService,
|
||||
BillingService,
|
||||
{
|
||||
provide: "IBillingService",
|
||||
useClass: BillingServiceCachingProxy,
|
||||
},
|
||||
BillingRepository,
|
||||
BillingProcessor,
|
||||
ManagedOrganizationsBillingService,
|
||||
OAuthClientRepository,
|
||||
BookingsRepository_2024_08_13,
|
||||
IsUserInBillingOrg,
|
||||
],
|
||||
exports: [BillingService, BillingRepository, ManagedOrganizationsBillingService],
|
||||
controllers: [BillingController],
|
||||
})
|
||||
export class BillingModule {}
|
||||
@@ -1,91 +0,0 @@
|
||||
import { BillingRepository } from "@/modules/billing/billing.repository";
|
||||
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
|
||||
import { StripeService } from "@/modules/stripe/stripe.service";
|
||||
import { Process, Processor } from "@nestjs/bull";
|
||||
import { Logger } from "@nestjs/common";
|
||||
import { Job } from "bull";
|
||||
|
||||
export const INCREMENT_JOB = "increment";
|
||||
export const BILLING_QUEUE = "billing";
|
||||
export type IncrementJobDataType = {
|
||||
userId: number;
|
||||
};
|
||||
|
||||
export type DecrementJobDataType = IncrementJobDataType;
|
||||
|
||||
@Processor(BILLING_QUEUE)
|
||||
export class BillingProcessor {
|
||||
private readonly logger = new Logger(BillingProcessor.name);
|
||||
|
||||
constructor(
|
||||
public readonly stripeService: StripeService,
|
||||
private readonly billingRepository: BillingRepository,
|
||||
private readonly teamsRepository: OrganizationsRepository
|
||||
) {}
|
||||
|
||||
@Process(INCREMENT_JOB)
|
||||
async handleIncrement(job: Job<IncrementJobDataType>) {
|
||||
const { userId } = job.data;
|
||||
try {
|
||||
// get the platform organization of the managed user
|
||||
const team = await this.teamsRepository.findPlatformOrgFromUserId(userId);
|
||||
const teamId = team.id;
|
||||
if (!team.id) {
|
||||
this.logger.error(`User (${userId}) is not part of the platform organization (${teamId}) `, {
|
||||
teamId,
|
||||
userId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const billingSubscription = await this.billingRepository.getBillingForTeam(teamId);
|
||||
if (!billingSubscription || !billingSubscription?.subscriptionId) {
|
||||
this.logger.error(`Team ${teamId} did not have stripe subscription associated to it`, {
|
||||
teamId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const stripeSubscription = await this.stripeService
|
||||
.getStripe()
|
||||
.subscriptions.retrieve(billingSubscription.subscriptionId);
|
||||
if (!stripeSubscription?.id) {
|
||||
this.logger.error(`Failed to retrieve stripe subscription (${billingSubscription.subscriptionId})`, {
|
||||
teamId,
|
||||
subscriptionId: billingSubscription.subscriptionId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const meteredItem = stripeSubscription.items.data.find(
|
||||
(item) => item.price?.recurring?.usage_type === "metered"
|
||||
);
|
||||
// no metered item found to increase usage, return early
|
||||
if (!meteredItem) {
|
||||
this.logger.error(`Stripe subscription (${stripeSubscription.id} is not usage based`, {
|
||||
teamId,
|
||||
subscriptionId: stripeSubscription.id,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await this.stripeService.getStripe().subscriptionItems.createUsageRecord(meteredItem.id, {
|
||||
action: "increment",
|
||||
quantity: 1,
|
||||
timestamp: "now",
|
||||
});
|
||||
this.logger.log("Increased organization usage for subscription", {
|
||||
subscriptionId: billingSubscription.subscriptionId,
|
||||
teamId,
|
||||
userId,
|
||||
itemId: meteredItem.id,
|
||||
});
|
||||
} catch (err) {
|
||||
this.logger.error("Failed to increase usage for Organization", {
|
||||
userId,
|
||||
err,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
import { PlatformPlan } from "@/modules/billing/types";
|
||||
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
|
||||
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
|
||||
import { Injectable, Logger } from "@nestjs/common";
|
||||
|
||||
@Injectable()
|
||||
export class BillingRepository {
|
||||
private readonly logger = new Logger("BillingRepository");
|
||||
constructor(private readonly dbRead: PrismaReadService, private readonly dbWrite: PrismaWriteService) {}
|
||||
|
||||
getBillingForTeam = (teamId: number) =>
|
||||
this.dbRead.prisma.platformBilling.findUnique({
|
||||
where: {
|
||||
id: teamId,
|
||||
},
|
||||
});
|
||||
|
||||
async getBillingForTeamBySubscriptionId(subscriptionId: string) {
|
||||
return this.dbRead.prisma.platformBilling.findFirst({
|
||||
where: {
|
||||
subscriptionId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async updateTeamBilling(
|
||||
teamId: number,
|
||||
billingStart: number,
|
||||
billingEnd: number,
|
||||
plan: PlatformPlan,
|
||||
subscriptionId?: string,
|
||||
priceId?: string
|
||||
) {
|
||||
return this.dbWrite.prisma.platformBilling.update({
|
||||
where: {
|
||||
id: teamId,
|
||||
},
|
||||
data: {
|
||||
billingCycleStart: billingStart,
|
||||
billingCycleEnd: billingEnd,
|
||||
subscriptionId,
|
||||
plan: plan.toString(),
|
||||
overdue: false,
|
||||
priceId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async updateBillingOverdue(subId: string, cusId: string, overdue: boolean) {
|
||||
try {
|
||||
return this.dbWrite.prisma.platformBilling.updateMany({
|
||||
where: {
|
||||
subscriptionId: subId,
|
||||
customerId: cusId,
|
||||
},
|
||||
data: {
|
||||
overdue,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
this.logger.error("Could not update billing overdue", {
|
||||
subId,
|
||||
cusId,
|
||||
err,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async deleteBilling(id: number) {
|
||||
return this.dbWrite.prisma.platformBilling.delete({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,246 +0,0 @@
|
||||
import type { PlatformBilling, Team } from "@calcom/prisma/client";
|
||||
import { INestApplication } from "@nestjs/common";
|
||||
import { NestExpressApplication } from "@nestjs/platform-express";
|
||||
import { Test } from "@nestjs/testing";
|
||||
import Stripe from "stripe";
|
||||
import request from "supertest";
|
||||
import { PlatformBillingRepositoryFixture } from "test/fixtures/repository/billing.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 { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
|
||||
import { randomString } from "test/utils/randomString";
|
||||
import { withApiAuth } from "test/utils/withApiAuth";
|
||||
import { AppModule } from "@/app.module";
|
||||
import { bootstrap } from "@/bootstrap";
|
||||
import { CheckPlatformBillingResponseDto } from "@/modules/billing/controllers/outputs/CheckPlatformBillingResponse.dto";
|
||||
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||
import { StripeService } from "@/modules/stripe/stripe.service";
|
||||
import { TokensModule } from "@/modules/tokens/tokens.module";
|
||||
import { UsersModule } from "@/modules/users/users.module";
|
||||
import { UserWithProfile } from "@/modules/users/users.repository";
|
||||
|
||||
describe("Platform Billing Controller (e2e)", () => {
|
||||
let app: INestApplication;
|
||||
const userEmail = `billing-user-${randomString()}@api.com`;
|
||||
let user: UserWithProfile;
|
||||
let billing: PlatformBilling;
|
||||
let userRepositoryFixture: UserRepositoryFixture;
|
||||
let organizationsRepositoryFixture: OrganizationRepositoryFixture;
|
||||
let profileRepositoryFixture: ProfileRepositoryFixture;
|
||||
let membershipsRepositoryFixture: MembershipRepositoryFixture;
|
||||
let platformBillingRepositoryFixture: PlatformBillingRepositoryFixture;
|
||||
let organization: Team;
|
||||
let organization2: Team;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await withApiAuth(
|
||||
userEmail,
|
||||
Test.createTestingModule({
|
||||
imports: [AppModule, PrismaModule, UsersModule, TokensModule],
|
||||
})
|
||||
).compile();
|
||||
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
|
||||
organizationsRepositoryFixture = new OrganizationRepositoryFixture(moduleRef);
|
||||
profileRepositoryFixture = new ProfileRepositoryFixture(moduleRef);
|
||||
membershipsRepositoryFixture = new MembershipRepositoryFixture(moduleRef);
|
||||
platformBillingRepositoryFixture = new PlatformBillingRepositoryFixture(moduleRef);
|
||||
|
||||
organization = await organizationsRepositoryFixture.create({
|
||||
name: `billing-organization-${randomString()}`,
|
||||
isPlatform: true,
|
||||
});
|
||||
organization2 = await organizationsRepositoryFixture.create({
|
||||
name: `billing-organization-2-${randomString()}`,
|
||||
isPlatform: true,
|
||||
});
|
||||
|
||||
user = await userRepositoryFixture.create({
|
||||
email: userEmail,
|
||||
username: userEmail,
|
||||
});
|
||||
|
||||
await profileRepositoryFixture.create({
|
||||
uid: `usr-${user.id}`,
|
||||
username: userEmail,
|
||||
organization: {
|
||||
connect: {
|
||||
id: organization.id,
|
||||
},
|
||||
},
|
||||
user: {
|
||||
connect: {
|
||||
id: user.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
await membershipsRepositoryFixture.create({
|
||||
role: "OWNER",
|
||||
team: { connect: { id: organization.id } },
|
||||
user: { connect: { id: user.id } },
|
||||
accepted: true,
|
||||
});
|
||||
|
||||
billing = await platformBillingRepositoryFixture.create(organization.id);
|
||||
|
||||
app = moduleRef.createNestApplication();
|
||||
bootstrap(app as NestExpressApplication);
|
||||
|
||||
await app.init();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
userRepositoryFixture.deleteByEmail(user.email);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("/billing/webhook (GET) should not get billing plan for org since it's not set yet", () => {
|
||||
return request(app.getHttpServer())
|
||||
.get(`/v2/billing/${organization.id}/check`)
|
||||
|
||||
.expect(200)
|
||||
.then(async (res) => {
|
||||
const data = res.body.data as CheckPlatformBillingResponseDto;
|
||||
expect(data?.plan).toEqual("FREE");
|
||||
});
|
||||
});
|
||||
|
||||
it("/billing/webhook (POST) should set billing free plan for org", () => {
|
||||
jest.spyOn(StripeService.prototype, "getStripe").mockImplementation(
|
||||
() =>
|
||||
({
|
||||
webhooks: {
|
||||
constructEventAsync: async () => {
|
||||
return {
|
||||
type: "checkout.session.completed",
|
||||
data: {
|
||||
object: {
|
||||
metadata: {
|
||||
teamId: organization.id,
|
||||
plan: "FREE",
|
||||
},
|
||||
mode: "subscription",
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
}) as unknown as Stripe
|
||||
);
|
||||
|
||||
return request(app.getHttpServer())
|
||||
.post("/v2/billing/webhook")
|
||||
.set("stripe-signature", "t=1234567890,v1=random_signature_for_e2e_test")
|
||||
.expect(200)
|
||||
.then(async (/* res */) => {
|
||||
const billing = await platformBillingRepositoryFixture.get(organization.id);
|
||||
expect(billing?.plan).toEqual("FREE");
|
||||
});
|
||||
});
|
||||
|
||||
it("/billing/:orgId/check (GET) should check billing plan for org", () => {
|
||||
return request(app.getHttpServer())
|
||||
.get(`/v2/billing/${organization.id}/check`)
|
||||
.expect(200)
|
||||
.then(async (res) => {
|
||||
const data = res.body.data as CheckPlatformBillingResponseDto;
|
||||
expect(data?.plan).toEqual("FREE");
|
||||
});
|
||||
});
|
||||
|
||||
it("/billing/:organizationId/check (GET) should not be able to check other org plan", () => {
|
||||
return request(app.getHttpServer()).get(`/v2/billing/${organization2.id}/check`).expect(403);
|
||||
});
|
||||
|
||||
it("/billing/webhook (POST) failed payment should set billing free plan to overdue", () => {
|
||||
jest.spyOn(StripeService.prototype, "getStripe").mockImplementation(
|
||||
() =>
|
||||
({
|
||||
webhooks: {
|
||||
constructEventAsync: async () => {
|
||||
return {
|
||||
type: "invoice.payment_failed",
|
||||
data: {
|
||||
object: {
|
||||
customer: billing?.customerId,
|
||||
subscription: billing?.subscriptionId,
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
}) as unknown as Stripe
|
||||
);
|
||||
return request(app.getHttpServer())
|
||||
.post("/v2/billing/webhook")
|
||||
.set("stripe-signature", "t=1234567890,v1=random_signature_for_e2e_test")
|
||||
.expect(200)
|
||||
.then(async (/* res */) => {
|
||||
const billing = await platformBillingRepositoryFixture.get(organization.id);
|
||||
expect(billing?.overdue).toEqual(true);
|
||||
});
|
||||
});
|
||||
|
||||
it("/billing/webhook (POST) success payment should set billing free plan to not overdue", () => {
|
||||
jest.spyOn(StripeService.prototype, "getStripe").mockImplementation(
|
||||
() =>
|
||||
({
|
||||
webhooks: {
|
||||
constructEventAsync: async () => {
|
||||
return {
|
||||
type: "invoice.payment_succeeded",
|
||||
data: {
|
||||
object: {
|
||||
customer: billing?.customerId,
|
||||
subscription: billing?.subscriptionId,
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
}) as unknown as Stripe
|
||||
);
|
||||
|
||||
return request(app.getHttpServer())
|
||||
.post("/v2/billing/webhook")
|
||||
.set("stripe-signature", "t=1234567890,v1=random_signature_for_e2e_test")
|
||||
.expect(200)
|
||||
.then(async (/* res */) => {
|
||||
const billing = await platformBillingRepositoryFixture.get(organization.id);
|
||||
expect(billing?.overdue).toEqual(false);
|
||||
});
|
||||
});
|
||||
|
||||
it("/billing/webhook (POST) should delete subscription", () => {
|
||||
jest.spyOn(StripeService.prototype, "getStripe").mockImplementation(
|
||||
() =>
|
||||
({
|
||||
webhooks: {
|
||||
constructEventAsync: async () => {
|
||||
return {
|
||||
type: "customer.subscription.deleted",
|
||||
data: {
|
||||
object: {
|
||||
metadata: {
|
||||
teamId: organization.id,
|
||||
plan: "FREE",
|
||||
},
|
||||
id: billing?.subscriptionId,
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
}) as unknown as Stripe
|
||||
);
|
||||
|
||||
return request(app.getHttpServer())
|
||||
.post("/v2/billing/webhook")
|
||||
.set("stripe-signature", "t=1234567890,v1=random_signature_for_e2e_test")
|
||||
.expect(200)
|
||||
.then(async (/* res */) => {
|
||||
const billing = await platformBillingRepositoryFixture.get(organization.id);
|
||||
expect(billing).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,181 +0,0 @@
|
||||
import { AppConfig } from "@/config/type";
|
||||
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
|
||||
import { ApiAuthGuardOnlyAllow } from "@/modules/auth/decorators/api-auth-guard-only-allow.decorator";
|
||||
import { MembershipRoles } from "@/modules/auth/decorators/roles/membership-roles.decorator";
|
||||
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
|
||||
import { OrganizationRolesGuard } from "@/modules/auth/guards/organization-roles/organization-roles.guard";
|
||||
import { SubscribeToPlanInput } from "@/modules/billing/controllers/inputs/subscribe-to-plan.input";
|
||||
import { CheckPlatformBillingResponseDto } from "@/modules/billing/controllers/outputs/CheckPlatformBillingResponse.dto";
|
||||
import { SubscribeTeamToBillingResponseDto } from "@/modules/billing/controllers/outputs/SubscribeTeamToBillingResponse.dto";
|
||||
import { IsUserInBillingOrg } from "@/modules/billing/guards/is-user-in-billing-org";
|
||||
import { IBillingService } from "@/modules/billing/interfaces/billing-service.interface";
|
||||
import { StripeService } from "@/modules/stripe/stripe.service";
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Req,
|
||||
UseGuards,
|
||||
Headers,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
Inject,
|
||||
Logger,
|
||||
Delete,
|
||||
ParseIntPipe,
|
||||
} from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { ApiExcludeController } from "@nestjs/swagger";
|
||||
import { Request } from "express";
|
||||
import Stripe from "stripe";
|
||||
|
||||
import { ApiResponse } from "@calcom/platform-types";
|
||||
|
||||
@Controller({
|
||||
path: "/v2/billing",
|
||||
version: API_VERSIONS_VALUES,
|
||||
})
|
||||
@ApiExcludeController(true)
|
||||
export class BillingController {
|
||||
private readonly stripeWhSecret: string;
|
||||
private logger = new Logger("Billing Controller");
|
||||
|
||||
constructor(
|
||||
@Inject("IBillingService") private readonly billingService: IBillingService,
|
||||
public readonly stripeService: StripeService,
|
||||
private readonly configService: ConfigService<AppConfig>
|
||||
) {
|
||||
this.stripeWhSecret = configService.get("stripe.webhookSecret", { infer: true }) ?? "";
|
||||
}
|
||||
|
||||
@Get("/:teamId/check")
|
||||
@UseGuards(ApiAuthGuard, OrganizationRolesGuard, IsUserInBillingOrg)
|
||||
@MembershipRoles(["OWNER", "ADMIN", "MEMBER"])
|
||||
@ApiAuthGuardOnlyAllow(["NEXT_AUTH"])
|
||||
async checkTeamBilling(
|
||||
@Param("teamId", ParseIntPipe) teamId: number
|
||||
): Promise<ApiResponse<CheckPlatformBillingResponseDto>> {
|
||||
const { status, plan } = await this.billingService.getBillingData(teamId);
|
||||
|
||||
return {
|
||||
status: "success",
|
||||
data: {
|
||||
valid: status === "valid",
|
||||
plan,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@Post("/:teamId/subscribe")
|
||||
@UseGuards(ApiAuthGuard, OrganizationRolesGuard, IsUserInBillingOrg)
|
||||
@MembershipRoles(["OWNER", "ADMIN"])
|
||||
@ApiAuthGuardOnlyAllow(["NEXT_AUTH"])
|
||||
async subscribeTeamToStripe(
|
||||
@Param("teamId") teamId: number,
|
||||
@Body() input: SubscribeToPlanInput
|
||||
): Promise<ApiResponse<SubscribeTeamToBillingResponseDto | undefined>> {
|
||||
const customerId = await this.billingService.createTeamBilling(teamId);
|
||||
const url = await this.billingService.redirectToSubscribeCheckout(teamId, input.plan, customerId);
|
||||
|
||||
return {
|
||||
status: "success",
|
||||
data: {
|
||||
url,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@Post("/:teamId/upgrade")
|
||||
@UseGuards(ApiAuthGuard, OrganizationRolesGuard, IsUserInBillingOrg)
|
||||
@MembershipRoles(["OWNER", "ADMIN"])
|
||||
@ApiAuthGuardOnlyAllow(["NEXT_AUTH"])
|
||||
async upgradeTeamBillingInStripe(
|
||||
@Param("teamId") teamId: number,
|
||||
@Body() input: SubscribeToPlanInput
|
||||
): Promise<ApiResponse<SubscribeTeamToBillingResponseDto | undefined>> {
|
||||
const url = await this.billingService.updateSubscriptionForTeam(teamId, input.plan);
|
||||
|
||||
return {
|
||||
status: "success",
|
||||
data: {
|
||||
url,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@Delete("/:teamId/unsubscribe")
|
||||
@UseGuards(ApiAuthGuard, OrganizationRolesGuard, IsUserInBillingOrg)
|
||||
@MembershipRoles(["OWNER", "ADMIN"])
|
||||
@ApiAuthGuardOnlyAllow(["NEXT_AUTH"])
|
||||
async cancelTeamSubscriptionInStripe(@Param("teamId") teamId: number): Promise<ApiResponse> {
|
||||
await this.billingService.cancelTeamSubscription(teamId);
|
||||
|
||||
return {
|
||||
status: "success",
|
||||
};
|
||||
}
|
||||
|
||||
@Post("/webhook")
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async stripeWebhook(
|
||||
@Req() request: Request,
|
||||
@Headers("stripe-signature") stripeSignature: string
|
||||
): Promise<ApiResponse> {
|
||||
try {
|
||||
if (!stripeSignature) {
|
||||
this.logger.warn("Missing stripe-signature header in webhook request");
|
||||
return {
|
||||
status: "success",
|
||||
};
|
||||
}
|
||||
|
||||
if (!this.stripeWhSecret) {
|
||||
this.logger.error("Missing STRIPE_WEBHOOK_SECRET configuration");
|
||||
return {
|
||||
status: "success",
|
||||
};
|
||||
}
|
||||
|
||||
const event = await this.billingService.stripeService
|
||||
.getStripe()
|
||||
.webhooks.constructEventAsync(request.body, stripeSignature, this.stripeWhSecret);
|
||||
|
||||
switch (event.type) {
|
||||
case "checkout.session.completed":
|
||||
await this.billingService.handleStripeCheckoutEvents(event);
|
||||
break;
|
||||
case "customer.subscription.updated":
|
||||
await this.billingService.handleStripePaymentPastDue(event);
|
||||
break;
|
||||
case "customer.subscription.deleted":
|
||||
await this.billingService.handleStripeSubscriptionDeleted(event);
|
||||
break;
|
||||
case "invoice.created":
|
||||
await this.billingService.handleStripeSubscriptionForActiveManagedUsers(event);
|
||||
break;
|
||||
case "invoice.payment_failed":
|
||||
await this.billingService.handleStripePaymentFailed(event);
|
||||
break;
|
||||
case "invoice.payment_succeeded":
|
||||
await this.billingService.handleStripePaymentSuccess(event);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return {
|
||||
status: "success",
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof Stripe.errors.StripeSignatureVerificationError) {
|
||||
this.logger.error("Webhook signature validation failed", error);
|
||||
return {
|
||||
status: "success",
|
||||
};
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
import { PlatformPlan } from "@/modules/billing/types";
|
||||
import { IsEnum } from "class-validator";
|
||||
|
||||
export class SubscribeToPlanInput {
|
||||
@IsEnum(PlatformPlan)
|
||||
plan!: PlatformPlan;
|
||||
}
|
||||
-5
@@ -1,5 +0,0 @@
|
||||
export class CheckPlatformBillingResponseDto {
|
||||
valid!: boolean;
|
||||
|
||||
plan?: string;
|
||||
}
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
export class SubscribeTeamToBillingResponseDto {
|
||||
url?: string;
|
||||
action?: "redirect";
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
import { ApiAuthGuardUser } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
|
||||
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
|
||||
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";
|
||||
import { Request } from "express";
|
||||
|
||||
import type { Team } from "@calcom/prisma/client";
|
||||
|
||||
@Injectable()
|
||||
export class IsUserInBillingOrg implements CanActivate {
|
||||
constructor(private organizationsRepository: OrganizationsRepository) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request & { team: Team }>();
|
||||
const orgId: string = request.params.teamId;
|
||||
const userId = (request.user as ApiAuthGuardUser).id;
|
||||
|
||||
if (!userId) {
|
||||
throw new ForbiddenException("IsUserInBillingOrg - No user id found.");
|
||||
}
|
||||
|
||||
if (!orgId) {
|
||||
throw new ForbiddenException("IsUserInBillingOrg - No org id found in request params.");
|
||||
}
|
||||
|
||||
const user = await this.organizationsRepository.findOrgUser(Number(orgId), Number(userId));
|
||||
|
||||
if (!user) {
|
||||
throw new ForbiddenException(
|
||||
`IsUserInBillingOrg - user with id=${userId} is not part of the organization with id=${orgId}.`
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
import { PlatformPlan } from "@/modules/billing/types";
|
||||
import type { StripeService } from "@/modules/stripe/stripe.service";
|
||||
import Stripe from "stripe";
|
||||
|
||||
import { PlatformBilling, Team } from "@calcom/prisma/client";
|
||||
|
||||
export type BillingData = {
|
||||
team: (Team & { platformBilling: PlatformBilling | null }) | null;
|
||||
status: "valid" | "no_subscription" | "no_billing";
|
||||
plan: PlatformPlan | "none";
|
||||
};
|
||||
|
||||
export interface IBillingService {
|
||||
getBillingData(teamId: number): Promise<BillingData>;
|
||||
createTeamBilling(teamId: number): Promise<string>;
|
||||
redirectToSubscribeCheckout(teamId: number, plan: PlatformPlan, customerId?: string): Promise<string>;
|
||||
updateSubscriptionForTeam(teamId: number, plan: PlatformPlan): Promise<string>;
|
||||
cancelTeamSubscription(teamId: number): Promise<void>;
|
||||
handleStripeSubscriptionDeleted(event: Stripe.Event): Promise<void>;
|
||||
handleStripePaymentSuccess(event: Stripe.Event): Promise<void>;
|
||||
handleStripePaymentFailed(event: Stripe.Event): Promise<void>;
|
||||
handleStripePaymentPastDue(event: Stripe.Event): Promise<void>;
|
||||
handleStripeCheckoutEvents(event: Stripe.Event): Promise<void>;
|
||||
handleStripeSubscriptionForActiveManagedUsers(event: Stripe.Event): Promise<void>;
|
||||
getSubscriptionIdFromInvoice(invoice: Stripe.Invoice): string | null;
|
||||
getCustomerIdFromInvoice(invoice: Stripe.Invoice): string | null;
|
||||
stripeService: StripeService;
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
import { IBillingService, BillingData } from "@/modules/billing/interfaces/billing-service.interface";
|
||||
import { BillingService } from "@/modules/billing/services/billing.service";
|
||||
import { PlatformPlan } from "@/modules/billing/types";
|
||||
import { RedisService } from "@/modules/redis/redis.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import Stripe from "stripe";
|
||||
|
||||
export const REDIS_BILLING_CACHE_KEY = (teamId: number) => `apiv2:team:${teamId}:billing`;
|
||||
export const BILLING_CACHE_TTL_MS = 3_600_000; // 1 hour
|
||||
|
||||
@Injectable()
|
||||
export class BillingServiceCachingProxy implements IBillingService {
|
||||
constructor(private readonly billingService: BillingService, private readonly redisService: RedisService) {}
|
||||
|
||||
async getBillingData(teamId: number) {
|
||||
const cachedBillingData = await this.getBillingCache(teamId);
|
||||
if (cachedBillingData) {
|
||||
return cachedBillingData;
|
||||
}
|
||||
|
||||
const billingData = await this.billingService.getBillingData(teamId);
|
||||
await this.setBillingCache(teamId, billingData);
|
||||
return billingData;
|
||||
}
|
||||
|
||||
private async deleteBillingCache(teamId: number) {
|
||||
await this.redisService.del(REDIS_BILLING_CACHE_KEY(teamId));
|
||||
}
|
||||
|
||||
private async getBillingCache(teamId: number) {
|
||||
const cachedResult = await this.redisService.get<BillingData>(REDIS_BILLING_CACHE_KEY(teamId));
|
||||
return cachedResult;
|
||||
}
|
||||
|
||||
private async setBillingCache(teamId: number, billingData: BillingData): Promise<void> {
|
||||
await this.redisService.set<BillingData>(REDIS_BILLING_CACHE_KEY(teamId), billingData, {
|
||||
ttl: BILLING_CACHE_TTL_MS,
|
||||
});
|
||||
}
|
||||
|
||||
async createTeamBilling(teamId: number): Promise<string> {
|
||||
return this.billingService.createTeamBilling(teamId);
|
||||
}
|
||||
|
||||
async redirectToSubscribeCheckout(
|
||||
teamId: number,
|
||||
plan: PlatformPlan,
|
||||
customerId?: string
|
||||
): Promise<string> {
|
||||
return this.billingService.redirectToSubscribeCheckout(teamId, plan, customerId);
|
||||
}
|
||||
|
||||
async updateSubscriptionForTeam(teamId: number, plan: PlatformPlan): Promise<string> {
|
||||
return this.billingService.updateSubscriptionForTeam(teamId, plan);
|
||||
}
|
||||
|
||||
async cancelTeamSubscription(teamId: number): Promise<void> {
|
||||
await this.billingService.cancelTeamSubscription(teamId);
|
||||
await this.deleteBillingCache(teamId);
|
||||
}
|
||||
|
||||
async handleStripeSubscriptionDeleted(event: Stripe.Event): Promise<void> {
|
||||
await this.billingService.handleStripeSubscriptionDeleted(event);
|
||||
const subscription = event.data.object as Stripe.Subscription;
|
||||
const teamId = subscription?.metadata?.teamId;
|
||||
if (teamId) {
|
||||
await this.deleteBillingCache(Number.parseInt(teamId));
|
||||
}
|
||||
}
|
||||
|
||||
async handleStripePaymentSuccess(event: Stripe.Event): Promise<void> {
|
||||
await this.billingService.handleStripePaymentSuccess(event);
|
||||
const invoice = event.data.object as Stripe.Invoice;
|
||||
const subscriptionId = this.getSubscriptionIdFromInvoice(invoice);
|
||||
if (subscriptionId) {
|
||||
const teamBilling = await this.billingService.billingRepository.getBillingForTeamBySubscriptionId(
|
||||
subscriptionId
|
||||
);
|
||||
if (teamBilling?.id) {
|
||||
await this.deleteBillingCache(teamBilling.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async handleStripePaymentFailed(event: Stripe.Event): Promise<void> {
|
||||
await this.billingService.handleStripePaymentFailed(event);
|
||||
const invoice = event.data.object as Stripe.Invoice;
|
||||
const subscriptionId = this.getSubscriptionIdFromInvoice(invoice);
|
||||
if (subscriptionId) {
|
||||
const teamBilling = await this.billingService.billingRepository.getBillingForTeamBySubscriptionId(
|
||||
subscriptionId
|
||||
);
|
||||
if (teamBilling?.id) {
|
||||
await this.deleteBillingCache(teamBilling.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async handleStripePaymentPastDue(event: Stripe.Event): Promise<void> {
|
||||
await this.billingService.handleStripePaymentPastDue(event);
|
||||
const subscription = event.data.object as Stripe.Subscription;
|
||||
const subscriptionId = subscription.id;
|
||||
if (subscriptionId) {
|
||||
const teamBilling = await this.billingService.billingRepository.getBillingForTeamBySubscriptionId(
|
||||
subscriptionId
|
||||
);
|
||||
if (teamBilling?.id) {
|
||||
await this.deleteBillingCache(teamBilling.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async handleStripeCheckoutEvents(event: Stripe.Event): Promise<void> {
|
||||
await this.billingService.handleStripeCheckoutEvents(event);
|
||||
const checkoutSession = event.data.object as Stripe.Checkout.Session;
|
||||
const teamId = checkoutSession.metadata?.teamId;
|
||||
if (teamId) {
|
||||
await this.deleteBillingCache(Number.parseInt(teamId));
|
||||
}
|
||||
}
|
||||
|
||||
async handleStripeSubscriptionForActiveManagedUsers(event: Stripe.Event): Promise<void> {
|
||||
return this.billingService.handleStripeSubscriptionForActiveManagedUsers(event);
|
||||
}
|
||||
|
||||
getSubscriptionIdFromInvoice(invoice: Stripe.Invoice): string | null {
|
||||
return this.billingService.getSubscriptionIdFromInvoice(invoice);
|
||||
}
|
||||
|
||||
getCustomerIdFromInvoice(invoice: Stripe.Invoice): string | null {
|
||||
return this.billingService.getCustomerIdFromInvoice(invoice);
|
||||
}
|
||||
|
||||
get stripeService() {
|
||||
return this.billingService.stripeService;
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
import { PlatformPlan } from "@/modules/billing/types";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
@Injectable()
|
||||
export class BillingConfigService {
|
||||
private readonly config: Map<
|
||||
PlatformPlan,
|
||||
{
|
||||
base: string;
|
||||
overage: string;
|
||||
}
|
||||
>;
|
||||
|
||||
constructor() {
|
||||
this.config = new Map<
|
||||
PlatformPlan,
|
||||
{
|
||||
base: string;
|
||||
overage: string;
|
||||
}
|
||||
>();
|
||||
|
||||
const planKeys = Object.keys(PlatformPlan).filter((key) => isNaN(Number(key)));
|
||||
for (const key of planKeys) {
|
||||
this.config.set(PlatformPlan[key.toUpperCase() as keyof typeof PlatformPlan], {
|
||||
base: process.env[`STRIPE_PRICE_ID_${key}`] ?? "",
|
||||
overage: process.env[`STRIPE_PRICE_ID_${key}_OVERAGE`] ?? "",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
get(plan: PlatformPlan):
|
||||
| {
|
||||
base: string;
|
||||
overage: string;
|
||||
}
|
||||
| undefined {
|
||||
return this.config.get(plan);
|
||||
}
|
||||
}
|
||||
@@ -1,513 +0,0 @@
|
||||
import { getActiveUserBillingService } from "@calcom/platform-libraries/organizations";
|
||||
import { getIncrementUsageIdempotencyKey, getIncrementUsageJobTag } from "@calcom/platform-libraries/tasker";
|
||||
import { InjectQueue } from "@nestjs/bull";
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
InternalServerErrorException,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
OnModuleDestroy,
|
||||
} from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { Queue } from "bull";
|
||||
import { DateTime } from "luxon";
|
||||
import Stripe from "stripe";
|
||||
import { AppConfig } from "@/config/type";
|
||||
import { PlatformBillingTasker } from "@/lib/services/tasker/platform-billing-tasker.service";
|
||||
import { BILLING_QUEUE, INCREMENT_JOB, IncrementJobDataType } from "@/modules/billing/billing.processor";
|
||||
import { BillingRepository } from "@/modules/billing/billing.repository";
|
||||
import { BillingData, IBillingService } from "@/modules/billing/interfaces/billing-service.interface";
|
||||
import { BillingConfigService } from "@/modules/billing/services/billing.config.service";
|
||||
import { PlatformPlan } from "@/modules/billing/types";
|
||||
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
|
||||
import { StripeService } from "@/modules/stripe/stripe.service";
|
||||
import { UsersRepository } from "@/modules/users/users.repository";
|
||||
|
||||
@Injectable()
|
||||
export class BillingService implements IBillingService, OnModuleDestroy {
|
||||
private logger = new Logger("BillingService");
|
||||
private readonly webAppUrl: string;
|
||||
|
||||
constructor(
|
||||
private readonly teamsRepository: OrganizationsRepository,
|
||||
public readonly stripeService: StripeService,
|
||||
public readonly billingRepository: BillingRepository,
|
||||
private readonly configService: ConfigService<AppConfig>,
|
||||
private readonly billingConfigService: BillingConfigService,
|
||||
private readonly usersRepository: UsersRepository,
|
||||
private readonly platformBillingTasker: PlatformBillingTasker,
|
||||
@InjectQueue(BILLING_QUEUE) private readonly billingQueue: Queue
|
||||
) {
|
||||
this.webAppUrl = this.configService.get("app.baseUrl", { infer: true }) ?? "https://app.cal.com";
|
||||
}
|
||||
|
||||
async getBillingData(teamId: number): Promise<BillingData> {
|
||||
const teamWithBilling = await this.teamsRepository.findByIdIncludeBilling(teamId);
|
||||
|
||||
if (teamWithBilling?.platformBilling) {
|
||||
if (!teamWithBilling?.platformBilling.subscriptionId) {
|
||||
return { team: teamWithBilling, status: "no_subscription" as const, plan: "none" };
|
||||
} else {
|
||||
return {
|
||||
team: teamWithBilling,
|
||||
status: "valid" as const,
|
||||
plan: teamWithBilling.platformBilling.plan as PlatformPlan,
|
||||
};
|
||||
}
|
||||
} else {
|
||||
return { team: teamWithBilling, status: "no_billing" as const, plan: "none" };
|
||||
}
|
||||
}
|
||||
|
||||
async createTeamBilling(teamId: number): Promise<string> {
|
||||
const teamWithBilling = await this.teamsRepository.findByIdIncludeBilling(teamId);
|
||||
let customerId = teamWithBilling?.platformBilling?.customerId ?? "";
|
||||
|
||||
if (!teamWithBilling?.platformBilling) {
|
||||
customerId = await this.teamsRepository.createNewBillingRelation(teamId);
|
||||
|
||||
this.logger.log("Team had no Stripe Customer ID, created one for them.", {
|
||||
id: teamId,
|
||||
stripeId: customerId,
|
||||
});
|
||||
}
|
||||
|
||||
return customerId;
|
||||
}
|
||||
|
||||
async redirectToSubscribeCheckout(
|
||||
teamId: number,
|
||||
plan: PlatformPlan,
|
||||
customerId?: string
|
||||
): Promise<string> {
|
||||
const { url } = await this.stripeService.getStripe().checkout.sessions.create({
|
||||
customer: customerId,
|
||||
line_items: [
|
||||
{
|
||||
price: this.billingConfigService.get(plan)?.base,
|
||||
quantity: 1,
|
||||
},
|
||||
{
|
||||
price: this.billingConfigService.get(plan)?.overage,
|
||||
},
|
||||
],
|
||||
success_url: `${this.webAppUrl}/settings/platform/`,
|
||||
cancel_url: `${this.webAppUrl}/settings/platform/`,
|
||||
mode: "subscription",
|
||||
metadata: {
|
||||
teamId: teamId.toString(),
|
||||
plan: plan.toString(),
|
||||
},
|
||||
subscription_data: {
|
||||
metadata: {
|
||||
teamId: teamId.toString(),
|
||||
plan: plan.toString(),
|
||||
},
|
||||
},
|
||||
allow_promotion_codes: true,
|
||||
});
|
||||
|
||||
if (!url) throw new InternalServerErrorException("Failed to create Stripe session.");
|
||||
|
||||
return url;
|
||||
}
|
||||
|
||||
async updateSubscriptionForTeam(teamId: number, plan: PlatformPlan): Promise<string> {
|
||||
const teamWithBilling = await this.teamsRepository.findByIdIncludeBilling(teamId);
|
||||
const customerId = teamWithBilling?.platformBilling?.customerId;
|
||||
|
||||
if (!customerId) {
|
||||
throw new NotFoundException("No customer id associated with the team.");
|
||||
}
|
||||
|
||||
const { url } = await this.stripeService.getStripe().checkout.sessions.create({
|
||||
customer: customerId,
|
||||
success_url: `${this.webAppUrl}/settings/platform/`,
|
||||
cancel_url: `${this.webAppUrl}/settings/platform/plans`,
|
||||
mode: "setup",
|
||||
metadata: {
|
||||
teamId: teamId.toString(),
|
||||
plan: plan.toString(),
|
||||
},
|
||||
currency: "usd",
|
||||
});
|
||||
|
||||
if (!url) throw new InternalServerErrorException("Failed to create Stripe session.");
|
||||
|
||||
return url;
|
||||
}
|
||||
|
||||
async setPerBookingSubscriptionForTeam(
|
||||
teamId: number,
|
||||
subscriptionId: string,
|
||||
plan: PlatformPlan
|
||||
): Promise<ReturnType<typeof BillingRepository.prototype.updateTeamBilling>> {
|
||||
const billingCycleStart = DateTime.now().get("day");
|
||||
const billingCycleEnd = DateTime.now().plus({ month: 1 }).get("day");
|
||||
|
||||
return this.billingRepository.updateTeamBilling(
|
||||
teamId,
|
||||
billingCycleStart,
|
||||
billingCycleEnd,
|
||||
plan,
|
||||
subscriptionId
|
||||
);
|
||||
}
|
||||
|
||||
async setPerActiveUserSubscriptionForTeam(
|
||||
teamId: number,
|
||||
subscriptionId: string,
|
||||
plan: PlatformPlan,
|
||||
priceId: string
|
||||
): Promise<ReturnType<typeof BillingRepository.prototype.updateTeamBilling>> {
|
||||
const billingCycleStart = DateTime.now().get("day");
|
||||
const billingCycleEnd = DateTime.now().plus({ month: 1 }).get("day");
|
||||
|
||||
return this.billingRepository.updateTeamBilling(
|
||||
teamId,
|
||||
billingCycleStart,
|
||||
billingCycleEnd,
|
||||
plan,
|
||||
subscriptionId,
|
||||
priceId
|
||||
);
|
||||
}
|
||||
|
||||
async handleStripeSubscriptionDeleted(event: Stripe.Event): Promise<void> {
|
||||
const subscription = event.data.object as Stripe.Subscription;
|
||||
const teamId = subscription?.metadata?.teamId;
|
||||
const plan = PlatformPlan[subscription?.metadata?.plan?.toUpperCase() as keyof typeof PlatformPlan];
|
||||
if (teamId && plan) {
|
||||
const currentBilling = await this.billingRepository.getBillingForTeam(Number.parseInt(teamId, 10));
|
||||
if (currentBilling?.subscriptionId === subscription.id) {
|
||||
await this.billingRepository.deleteBilling(currentBilling.id);
|
||||
this.logger.log(`Stripe Subscription deleted`, {
|
||||
customerId: currentBilling.customerId,
|
||||
subscriptionId: currentBilling.subscriptionId,
|
||||
teamId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
this.logger.log("No platform billing found.");
|
||||
return;
|
||||
}
|
||||
this.logger.log("Webhook received but not pertaining to Platform, discarding.");
|
||||
return;
|
||||
}
|
||||
|
||||
getSubscriptionIdFromInvoice(invoice: Stripe.Invoice): string | null {
|
||||
if (typeof invoice.subscription === "string") {
|
||||
return invoice.subscription;
|
||||
} else if (invoice.subscription && typeof invoice.subscription === "object") {
|
||||
return invoice.subscription.id;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
getCustomerIdFromInvoice(invoice: Stripe.Invoice): string | null {
|
||||
if (typeof invoice.customer === "string") {
|
||||
return invoice.customer;
|
||||
} else if (invoice.customer && typeof invoice.customer === "object") {
|
||||
return invoice.customer.id;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async handleStripePaymentSuccess(event: Stripe.Event): Promise<void> {
|
||||
const invoice = event.data.object as Stripe.Invoice;
|
||||
const subscriptionId = this.getSubscriptionIdFromInvoice(invoice);
|
||||
const customerId = this.getCustomerIdFromInvoice(invoice);
|
||||
if (subscriptionId && customerId) {
|
||||
await this.billingRepository.updateBillingOverdue(subscriptionId, customerId, false);
|
||||
}
|
||||
}
|
||||
|
||||
async handleStripePaymentFailed(event: Stripe.Event): Promise<void> {
|
||||
const invoice = event.data.object as Stripe.Invoice;
|
||||
const subscriptionId = this.getSubscriptionIdFromInvoice(invoice);
|
||||
const customerId = this.getCustomerIdFromInvoice(invoice);
|
||||
if (subscriptionId && customerId) {
|
||||
await this.billingRepository.updateBillingOverdue(subscriptionId, customerId, true);
|
||||
}
|
||||
}
|
||||
|
||||
async handleStripePaymentPastDue(event: Stripe.Event): Promise<void> {
|
||||
const invoice = event.data.object as Stripe.Invoice;
|
||||
const subscriptionId = this.getSubscriptionIdFromInvoice(invoice);
|
||||
const customerId = this.getCustomerIdFromInvoice(invoice);
|
||||
|
||||
if (subscriptionId && customerId) {
|
||||
const existingUserSubscription = await this.stripeService
|
||||
.getStripe()
|
||||
.subscriptions.retrieve(subscriptionId);
|
||||
|
||||
if (existingUserSubscription.status === "past_due") {
|
||||
await this.billingRepository.updateBillingOverdue(subscriptionId, customerId, true);
|
||||
}
|
||||
|
||||
if (existingUserSubscription.status === "active") {
|
||||
await this.billingRepository.updateBillingOverdue(subscriptionId, customerId, false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!subscriptionId || !customerId) {
|
||||
this.logger.log(`SubscriptionId: ${subscriptionId} or customerId: ${customerId} missing`);
|
||||
}
|
||||
}
|
||||
|
||||
async handleStripeCheckoutEvents(event: Stripe.Event): Promise<void> {
|
||||
const checkoutSession = event.data.object as Stripe.Checkout.Session;
|
||||
|
||||
if (!checkoutSession.metadata?.teamId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const teamId = Number.parseInt(checkoutSession.metadata.teamId, 10);
|
||||
const plan = checkoutSession.metadata.plan;
|
||||
if (!plan || !teamId) {
|
||||
this.logger.log("Webhook received but not pertaining to Platform, discarding.");
|
||||
return;
|
||||
}
|
||||
const isPriceIdPresent = Boolean(checkoutSession.metadata?.priceId);
|
||||
|
||||
if (checkoutSession.mode === "subscription" && isPriceIdPresent) {
|
||||
await this.setPerActiveUserSubscriptionForTeam(
|
||||
teamId,
|
||||
checkoutSession.subscription as string,
|
||||
PlatformPlan[plan.toUpperCase() as keyof typeof PlatformPlan],
|
||||
checkoutSession.metadata?.priceId
|
||||
);
|
||||
}
|
||||
|
||||
if (checkoutSession.mode === "subscription" && !isPriceIdPresent) {
|
||||
await this.setPerBookingSubscriptionForTeam(
|
||||
teamId,
|
||||
checkoutSession.subscription as string,
|
||||
PlatformPlan[plan.toUpperCase() as keyof typeof PlatformPlan]
|
||||
);
|
||||
}
|
||||
|
||||
if (checkoutSession.mode === "setup") {
|
||||
await this.updateStripeSubscriptionForTeam(teamId, plan as PlatformPlan);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
async handleStripeSubscriptionForActiveManagedUsers(event: Stripe.Event): Promise<void> {
|
||||
const invoice = event.data.object as Stripe.Invoice;
|
||||
const subscriptionId = this.getSubscriptionIdFromInvoice(invoice);
|
||||
|
||||
if (!subscriptionId) {
|
||||
throw new NotFoundException("No subscription found for team");
|
||||
}
|
||||
|
||||
const teamWithBilling = await this.billingRepository.getBillingForTeamBySubscriptionId(subscriptionId);
|
||||
|
||||
if (teamWithBilling?.plan === "PER_ACTIVE_USER") {
|
||||
let activeManagedUsersCount = await this.getActiveManagedUsersCount(
|
||||
subscriptionId,
|
||||
new Date(invoice.period_start * 1000),
|
||||
new Date(invoice.period_end * 1000)
|
||||
);
|
||||
|
||||
if (activeManagedUsersCount < 0) {
|
||||
activeManagedUsersCount = 1;
|
||||
}
|
||||
|
||||
const existingSubscription = await this.stripeService
|
||||
.getStripe()
|
||||
.subscriptions.retrieve(subscriptionId);
|
||||
|
||||
const perActiveUserPrice = this.billingConfigService.get(PlatformPlan.PER_ACTIVE_USER)?.base;
|
||||
const subscriptionItem = existingSubscription.items.data.find(
|
||||
(item) => item.price?.id === perActiveUserPrice
|
||||
);
|
||||
|
||||
if (!subscriptionItem) {
|
||||
throw new NotFoundException(
|
||||
"No subscription item found for PER_ACTIVE_USER plan with matching price ID"
|
||||
);
|
||||
}
|
||||
|
||||
await this.stripeService.getStripe().subscriptions.update(subscriptionId, {
|
||||
items: [{ id: subscriptionItem.id, quantity: activeManagedUsersCount }],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async getActiveManagedUsersCount(
|
||||
subscriptionId: string,
|
||||
invoiceStart: Date,
|
||||
invoiceEnd: Date
|
||||
): Promise<number> {
|
||||
if (!invoiceStart || !invoiceEnd) {
|
||||
this.logger.log("Invoice period start or end date is null");
|
||||
return 0;
|
||||
}
|
||||
|
||||
const activeUserBillingService = getActiveUserBillingService();
|
||||
return activeUserBillingService.getActiveUserCountForPlatformOrg(subscriptionId, invoiceStart, invoiceEnd);
|
||||
}
|
||||
|
||||
async updateStripeSubscriptionForTeam(teamId: number, plan: PlatformPlan): Promise<void> {
|
||||
const teamWithBilling = await this.teamsRepository.findByIdIncludeBilling(teamId);
|
||||
|
||||
if (!teamWithBilling?.platformBilling || !teamWithBilling?.platformBilling.subscriptionId) {
|
||||
throw new NotFoundException("Team plan not found");
|
||||
}
|
||||
|
||||
const existingUserSubscription = await this.stripeService
|
||||
.getStripe()
|
||||
.subscriptions.retrieve(teamWithBilling?.platformBilling?.subscriptionId);
|
||||
const currentLicensedItem = existingUserSubscription.items.data.find(
|
||||
(item) => item.price?.recurring?.usage_type === "licensed"
|
||||
);
|
||||
const currentOverageItem = existingUserSubscription.items.data.find(
|
||||
(item) => item.price?.recurring?.usage_type === "metered"
|
||||
);
|
||||
|
||||
if (!currentLicensedItem) {
|
||||
throw new NotFoundException("There is no licensed item present in the subscription");
|
||||
}
|
||||
|
||||
if (!currentOverageItem) {
|
||||
throw new NotFoundException("There is no overage item present in the subscription");
|
||||
}
|
||||
|
||||
await this.stripeService
|
||||
.getStripe()
|
||||
.subscriptions.update(teamWithBilling?.platformBilling?.subscriptionId, {
|
||||
items: [
|
||||
{
|
||||
id: currentLicensedItem.id,
|
||||
price: this.billingConfigService.get(plan)?.base,
|
||||
},
|
||||
{
|
||||
id: currentOverageItem.id,
|
||||
price: this.billingConfigService.get(plan)?.overage,
|
||||
clear_usage: false,
|
||||
},
|
||||
],
|
||||
billing_cycle_anchor: "now",
|
||||
proration_behavior: "create_prorations",
|
||||
});
|
||||
|
||||
await this.setPerBookingSubscriptionForTeam(
|
||||
teamId,
|
||||
teamWithBilling?.platformBilling?.subscriptionId,
|
||||
PlatformPlan[plan.toUpperCase() as keyof typeof PlatformPlan]
|
||||
);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* Adds a job to the queue to increment usage of a stripe subscription.
|
||||
* we delay the job until the booking starts.
|
||||
* the delay ensure we can adapt to cancel / reschedule.
|
||||
*/
|
||||
async increaseUsageByUserId(
|
||||
userId: number,
|
||||
booking: {
|
||||
uid: string;
|
||||
startTime: Date;
|
||||
fromReschedule?: string | null;
|
||||
}
|
||||
): Promise<boolean | undefined> {
|
||||
if (this.configService.get("e2e")) {
|
||||
return true;
|
||||
}
|
||||
const { uid, startTime, fromReschedule } = booking;
|
||||
|
||||
if (this.configService.get("enableAsyncTasker")) {
|
||||
if (fromReschedule) {
|
||||
this.platformBillingTasker.rescheduleUsageIncrement({
|
||||
payload: { bookingUid: uid, rescheduledTime: startTime },
|
||||
});
|
||||
return true;
|
||||
}
|
||||
this.platformBillingTasker.incrementUsage({
|
||||
payload: { userId },
|
||||
options: {
|
||||
delay: startTime,
|
||||
tags: [getIncrementUsageJobTag(uid)],
|
||||
idempotencyKey: getIncrementUsageIdempotencyKey(uid, userId),
|
||||
},
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
let delay = startTime.getTime() - Date.now();
|
||||
|
||||
if (delay < 0) {
|
||||
delay = 0;
|
||||
}
|
||||
|
||||
if (fromReschedule) {
|
||||
// cancel the usage increment job for the booking that is being rescheduled
|
||||
await this.cancelUsageByBookingUid(fromReschedule);
|
||||
this.logger.log(`Cancelled usage increment job for rescheduled booking uid: ${fromReschedule}`);
|
||||
}
|
||||
await this.billingQueue.add(
|
||||
INCREMENT_JOB,
|
||||
{
|
||||
userId,
|
||||
} satisfies IncrementJobDataType,
|
||||
{ delay: delay, jobId: `increment-${uid}`, removeOnComplete: true }
|
||||
);
|
||||
this.logger.log(`Added stripe usage increment job for booking ${uid} and user ${userId}`);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Cancels the usage increment job for a booking when it is cancelled.
|
||||
* Removing an attendee from a booking does not cancel the usage increment job.
|
||||
*/
|
||||
async cancelUsageByBookingUid(bookingUid: string): Promise<boolean | undefined> {
|
||||
if (this.configService.get("e2e")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this.configService.get("enableAsyncTasker")) {
|
||||
await this.platformBillingTasker.cancelUsageIncrement({ payload: { bookingUid } });
|
||||
return true;
|
||||
}
|
||||
|
||||
const job = await this.billingQueue.getJob(`increment-${bookingUid}`);
|
||||
if (job) {
|
||||
await job.remove();
|
||||
this.logger.log(`Removed increment job for cancelled booking ${bookingUid}`);
|
||||
}
|
||||
}
|
||||
|
||||
async cancelTeamSubscription(teamId: number): Promise<void> {
|
||||
const teamWithBilling = await this.teamsRepository.findByIdIncludeBilling(teamId);
|
||||
const customerId = teamWithBilling?.platformBilling?.customerId;
|
||||
|
||||
if (!customerId) {
|
||||
throw new NotFoundException("No customer id found for team in Stripe");
|
||||
}
|
||||
|
||||
if (!teamWithBilling?.platformBilling || !teamWithBilling?.platformBilling.subscriptionId) {
|
||||
throw new NotFoundException("Team plan not found");
|
||||
}
|
||||
|
||||
try {
|
||||
await this.stripeService
|
||||
.getStripe()
|
||||
.subscriptions.cancel(teamWithBilling?.platformBilling?.subscriptionId);
|
||||
} catch (error) {
|
||||
this.logger.log(error, "error while cancelling team subscription in stripe");
|
||||
throw new BadRequestException("Failed to cancel team subscription");
|
||||
}
|
||||
}
|
||||
|
||||
async onModuleDestroy(): Promise<void> {
|
||||
try {
|
||||
await this.billingQueue.close();
|
||||
} catch (err) {
|
||||
this.logger.error(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
import { hasMinimumPlan } from "@/modules/auth/guards/billing/platform-plan.guard";
|
||||
import { orderedPlans, PlatformPlan } from "@/modules/billing/types";
|
||||
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
|
||||
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
|
||||
import { ForbiddenException, Injectable, NotFoundException } from "@nestjs/common";
|
||||
|
||||
@Injectable()
|
||||
export class ManagedOrganizationsBillingService {
|
||||
constructor(private readonly dbRead: PrismaReadService, private readonly dbWrite: PrismaWriteService) {}
|
||||
|
||||
async createManagedOrganizationBilling(managerOrgId: number, managedOrgId: number) {
|
||||
const managerOrgBilling = await this.dbRead.prisma.platformBilling.findUnique({
|
||||
where: { id: managerOrgId },
|
||||
});
|
||||
if (!managerOrgBilling) {
|
||||
throw new NotFoundException("Manager organization billing not found.");
|
||||
}
|
||||
if (
|
||||
!hasMinimumPlan({
|
||||
currentPlan: managerOrgBilling.plan as PlatformPlan,
|
||||
minimumPlan: PlatformPlan.SCALE,
|
||||
plans: orderedPlans,
|
||||
})
|
||||
) {
|
||||
throw new ForbiddenException(
|
||||
`organization with id=${managerOrgId} does not have required plan for this operation. Minimum plan is ${
|
||||
PlatformPlan.SCALE
|
||||
} while the organization has ${managerOrgBilling.plan || "undefined"}.`
|
||||
);
|
||||
}
|
||||
|
||||
return this.dbWrite.prisma.platformBilling.create({
|
||||
data: {
|
||||
id: managedOrgId,
|
||||
customerId: managerOrgBilling.customerId,
|
||||
subscriptionId: managerOrgBilling.subscriptionId,
|
||||
plan: managerOrgBilling.plan,
|
||||
billingCycleStart: managerOrgBilling.billingCycleStart,
|
||||
billingCycleEnd: managerOrgBilling.billingCycleEnd,
|
||||
overdue: managerOrgBilling.overdue,
|
||||
managerBillingId: managerOrgBilling.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
export enum PlatformPlan {
|
||||
FREE = "FREE",
|
||||
STARTER = "STARTER",
|
||||
ESSENTIALS = "ESSENTIALS",
|
||||
SCALE = "SCALE",
|
||||
ENTERPRISE = "ENTERPRISE",
|
||||
PER_ACTIVE_USER = "PER_ACTIVE_USER",
|
||||
}
|
||||
|
||||
export const orderedPlans = [
|
||||
"FREE",
|
||||
"STARTER",
|
||||
"ESSENTIALS",
|
||||
"SCALE",
|
||||
"PER_ACTIVE_USER",
|
||||
"ENTERPRISE",
|
||||
] as const;
|
||||
|
||||
export type PlatformPlanType = (typeof orderedPlans)[number];
|
||||
@@ -1,9 +1,9 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { BookingReferencesRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/booking-references.repository";
|
||||
import { CalendarsRepository } from "@/ee/calendars/calendars.repository";
|
||||
import { CalendarsService } from "@/ee/calendars/services/calendars.service";
|
||||
import { CalendarsCacheService } from "@/ee/calendars/services/calendars-cache.service";
|
||||
import { GoogleCalendarService as GCalService } from "@/ee/calendars/services/gcal.service";
|
||||
import { BookingReferencesRepository_2024_08_13 } from "@/platform/bookings/2024-08-13/repositories/booking-references.repository";
|
||||
import { CalendarsRepository } from "@/platform/calendars/calendars.repository";
|
||||
import { CalendarsService } from "@/platform/calendars/services/calendars.service";
|
||||
import { CalendarsCacheService } from "@/platform/calendars/services/calendars-cache.service";
|
||||
import { GoogleCalendarService as GCalService } from "@/platform/calendars/services/gcal.service";
|
||||
import { AppsRepository } from "@/modules/apps/apps.repository";
|
||||
import { CalUnifiedCalendarsController } from "@/modules/cal-unified-calendars/controllers/cal-unified-calendars.controller";
|
||||
import { GoogleCalendarService } from "@/modules/cal-unified-calendars/services/google-calendar.service";
|
||||
|
||||
Loaded 100 of 4080 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user