Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add booking and user creation source #18768

Draft
wants to merge 26 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 24 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
0915a37
migration and init to accept creationSource for new bookings
alishaz-polymath Jan 20, 2025
ee38a81
V1 create booking
alishaz-polymath Jan 20, 2025
8c2136a
V1 user creation
alishaz-polymath Jan 20, 2025
51978a9
webapp booking + V1 user
alishaz-polymath Jan 20, 2025
6a8e9d6
user creation in V1, V2 and webapp
alishaz-polymath Jan 20, 2025
dadd358
booking source V2 and fix for v1 user
alishaz-polymath Jan 20, 2025
e30a97c
Merge branch 'main' into feat/add-booking-and-user-creation-source
alishaz-polymath Jan 21, 2025
6b331bb
fit type
alishaz-polymath Jan 21, 2025
046ee53
--fix type
alishaz-polymath Jan 21, 2025
5a7b42b
add test -- WIP
alishaz-polymath Jan 21, 2025
5d8374d
fix type
alishaz-polymath Jan 21, 2025
0f1e654
fix type
alishaz-polymath Jan 21, 2025
7b798c0
^
alishaz-polymath Jan 21, 2025
696a36b
Need more sleep zzz
alishaz-polymath Jan 21, 2025
8444bfc
-_-
alishaz-polymath Jan 21, 2025
dd1ad20
Merge branch 'main' into feat/add-booking-and-user-creation-source
alishaz-polymath Jan 21, 2025
c96e066
Merge branch 'main' into feat/add-booking-and-user-creation-source
alishaz-polymath Jan 21, 2025
5996653
bump libraries platform
ThyMinimalDev Jan 21, 2025
f263546
adds for v2 recurring booking
alishaz-polymath Jan 21, 2025
4d7ea3a
fix lint
alishaz-polymath Jan 21, 2025
73f17e1
instant meetings
alishaz-polymath Jan 21, 2025
6ec7343
fix: api v2 creation source
ThyMinimalDev Jan 21, 2025
47bc888
fixup! fix: api v2 creation source
ThyMinimalDev Jan 21, 2025
4d122e3
bump libraries
ThyMinimalDev Jan 21, 2025
0c2a90f
add user
alishaz-polymath Jan 21, 2025
10dde4c
fix test
alishaz-polymath Jan 22, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions apps/api/v1/pages/api/bookings/_post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import handleNewBooking from "@calcom/features/bookings/lib/handleNewBooking";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { HttpError } from "@calcom/lib/http-error";
import { defaultResponder } from "@calcom/lib/server";
import { CreationSource } from "@calcom/prisma/enums";

import { getAccessibleUsers } from "~/lib/utils/retrieveScopedAccessibleUsers";

Expand Down Expand Up @@ -213,6 +214,10 @@ import { getAccessibleUsers } from "~/lib/utils/retrieveScopedAccessibleUsers";
*/
async function handler(req: NextApiRequest) {
const { userId, isSystemWideAdmin, isOrganizationOwnerOrAdmin } = req;
req.body = {
...req.body,
creationSource: CreationSource.API_V1,
};
if (isSystemWideAdmin) req.userId = req.body.userId || userId;

if (isOrganizationOwnerOrAdmin) {
Expand Down
3 changes: 2 additions & 1 deletion apps/api/v1/pages/api/users/_post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { NextApiRequest } from "next";
import { HttpError } from "@calcom/lib/http-error";
import { defaultResponder } from "@calcom/lib/server";
import prisma from "@calcom/prisma";
import { CreationSource } from "@calcom/prisma/enums";

import { schemaUserCreateBodyParams } from "~/lib/validations/user";

Expand Down Expand Up @@ -92,7 +93,7 @@ async function postHandler(req: NextApiRequest) {
// If user is not ADMIN, return unauthorized.
if (!isSystemWideAdmin) throw new HttpError({ statusCode: 401, message: "You are not authorized" });
const data = await schemaUserCreateBodyParams.parseAsync(req.body);
const user = await prisma.user.create({ data });
const user = await prisma.user.create({ data: { ...data, creationSource: CreationSource.API_V1 } });
req.statusCode = 201;
return { user };
}
Expand Down
29 changes: 29 additions & 0 deletions apps/api/v1/test/lib/bookings/_post.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { ErrorCode } from "@calcom/lib/errorCodes";
import { buildBooking, buildEventType, buildWebhook } from "@calcom/lib/test/builder";
import prisma from "@calcom/prisma";
import type { Booking } from "@calcom/prisma/client";
import { CreationSource } from "@calcom/prisma/enums";

import handler from "../../../pages/api/bookings/_post";

Expand Down Expand Up @@ -220,6 +221,34 @@ describe.skipIf(true)("POST /api/bookings", () => {
});
expect(previousBooking?.status).toBe("cancelled");
});

test("Creates source as api_v1", async () => {
const { req, res } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({
method: "POST",
body: {
name: "test",
start: dayjs().format(),
end: dayjs().add(1, "day").format(),
eventTypeId: 2,
email: "[email protected]",
location: "Cal.com Video",
timeZone: "America/Montevideo",
language: "en",
customInputs: [],
metadata: {},
userId: 4,
},
prisma,
});

prismaMock.eventType.findUniqueOrThrow.mockResolvedValue(buildEventType());
prismaMock.booking.findMany.mockResolvedValue([]);

await handler(req, res);
createdBooking = JSON.parse(res._getData());
expect(createdBooking.creationSource).toEqual(CreationSource.API_V1);
expect(prismaMock.booking.create).toHaveBeenCalledTimes(1);
});
});

describe("Recurring event-type", () => {
Expand Down
2 changes: 1 addition & 1 deletion apps/api/v2/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"@axiomhq/winston": "^1.2.0",
"@calcom/platform-constants": "*",
"@calcom/platform-enums": "*",
"@calcom/platform-libraries": "npm:@calcom/[email protected].86",
"@calcom/platform-libraries": "npm:@calcom/[email protected].90",
"@calcom/platform-libraries-0.0.2": "npm:@calcom/[email protected]",
"@calcom/platform-types": "*",
"@calcom/platform-utils": "*",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
import { ConfigService } from "@nestjs/config";
import { ApiQuery, ApiExcludeController as DocsExcludeController } from "@nestjs/swagger";
import { User } from "@prisma/client";
import { CreationSource } from "@prisma/client";
import { Request } from "express";
import { NextApiRequest } from "next/types";
import { v4 as uuidv4 } from "uuid";
Expand Down Expand Up @@ -383,7 +384,11 @@ export class BookingsController_2024_04_15 {
...oAuthParams,
});
Object.assign(clone, { userId, ...oAuthParams, platformBookingLocation });
clone.body = { ...clone.body, noEmail: !oAuthParams.arePlatformEmailsEnabled };
clone.body = {
...clone.body,
noEmail: !oAuthParams.arePlatformEmailsEnabled,
creationSource: CreationSource.API_V2,
};
return clone as unknown as NextApiRequest & { userId?: number } & OAuthRequestParams;
}

Expand Down Expand Up @@ -411,6 +416,7 @@ export class BookingsController_2024_04_15 {
...oAuthParams,
platformBookingLocation,
noEmail: !oAuthParams.arePlatformEmailsEnabled,
creationSource: CreationSource.API_V2,
});
return clone as unknown as NextApiRequest & { userId?: number } & OAuthRequestParams;
}
Expand Down
18 changes: 14 additions & 4 deletions apps/api/v2/src/ee/bookings/2024-08-13/services/input.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { OAuthFlowService } from "@/modules/oauth-clients/services/oauth-flow.se
import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common";
import { Logger } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { CreationSource } from "@prisma/client";
import { Request } from "express";
import { DateTime } from "luxon";
import { NextApiRequest } from "next/types";
Expand Down Expand Up @@ -97,10 +98,14 @@ export class InputBookingsService_2024_08_13 {

if (oAuthClientParams) {
Object.assign(newRequest, { userId, ...oAuthClientParams, platformBookingLocation: location });
newRequest.body = { ...bodyTransformed, noEmail: !oAuthClientParams.arePlatformEmailsEnabled };
newRequest.body = {
...bodyTransformed,
noEmail: !oAuthClientParams.arePlatformEmailsEnabled,
creationSource: CreationSource.API_V2,
};
} else {
Object.assign(newRequest, { userId, platformBookingLocation: location });
newRequest.body = { ...bodyTransformed, noEmail: false };
newRequest.body = { ...bodyTransformed, noEmail: false, creationSource: CreationSource.API_V2 };
}

return newRequest as unknown as BookingRequest;
Expand Down Expand Up @@ -220,6 +225,7 @@ export class InputBookingsService_2024_08_13 {

newRequest.body = bodyTransformed.map((event) => ({
...event,
creationSource: CreationSource.API_V2,
}));

return newRequest as unknown as BookingRequest;
Expand Down Expand Up @@ -317,10 +323,14 @@ export class InputBookingsService_2024_08_13 {
const location = await this.getRescheduleBookingLocation(bookingUid);
if (oAuthClientParams) {
Object.assign(newRequest, { userId, ...oAuthClientParams, platformBookingLocation: location });
newRequest.body = { ...bodyTransformed, noEmail: !oAuthClientParams.arePlatformEmailsEnabled };
newRequest.body = {
...bodyTransformed,
noEmail: !oAuthClientParams.arePlatformEmailsEnabled,
creationSource: CreationSource.API_V2,
};
} else {
Object.assign(newRequest, { userId, platformBookingLocation: location });
newRequest.body = { ...bodyTransformed, noEmail: false };
newRequest.body = { ...bodyTransformed, noEmail: false, creationSource: CreationSource.API_V2 };
}

return newRequest as unknown as BookingRequest;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { UpdateOrganizationUserInput } from "@/modules/organizations/inputs/upda
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { CreationSource } from "@prisma/client";

@Injectable()
export class OrganizationsUsersRepository {
Expand Down Expand Up @@ -70,7 +71,7 @@ export class OrganizationsUsersRepository {

async createOrganizationUser(orgId: number, createUserBody: CreateOrganizationUserInput) {
const createdUser = await this.dbWrite.prisma.user.create({
data: createUserBody,
data: { ...createUserBody, creationSource: CreationSource.API_V2 },
});

return createdUser;
Expand Down
2 changes: 2 additions & 0 deletions apps/api/v2/src/modules/users/users.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { CreateManagedUserInput } from "@/modules/users/inputs/create-managed-us
import { UpdateManagedUserInput } from "@/modules/users/inputs/update-managed-user.input";
import { Injectable, NotFoundException } from "@nestjs/common";
import type { Profile, User, Team, Prisma } from "@prisma/client";
import { CreationSource } from "@prisma/client";

export type UserWithProfile = User & {
movedToProfile?: (Profile & { organization: Pick<Team, "isPlatform" | "id" | "slug" | "name"> }) | null;
Expand All @@ -30,6 +31,7 @@ export class UsersRepository {
connect: { id: oAuthClientId },
},
isPlatformManaged,
creationSource: CreationSource.API_V2,
},
});
}
Expand Down
2 changes: 2 additions & 0 deletions apps/web/pages/api/auth/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { defaultHandler, defaultResponder } from "@calcom/lib/server";
import slugify from "@calcom/lib/slugify";
import prisma from "@calcom/prisma";
import { IdentityProvider } from "@calcom/prisma/enums";
import { CreationSource } from "@calcom/prisma/enums";

const querySchema = z.object({
username: z
Expand Down Expand Up @@ -48,6 +49,7 @@ async function handler(req: NextApiRequest) {
emailVerified: new Date(),
locale: "en", // TODO: We should revisit this
identityProvider: IdentityProvider.CAL,
creationSource: CreationSource.WEBAPP,
},
});

Expand Down
5 changes: 5 additions & 0 deletions apps/web/pages/api/book/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowE
import getIP from "@calcom/lib/getIP";
import { defaultResponder } from "@calcom/lib/server";
import { checkCfTurnstileToken } from "@calcom/lib/server/checkCfTurnstileToken";
import { CreationSource } from "@calcom/prisma/enums";

async function handler(req: NextApiRequest & { userId?: number }, res: NextApiResponse) {
const userIp = getIP(req);
Expand All @@ -26,6 +27,10 @@ async function handler(req: NextApiRequest & { userId?: number }, res: NextApiRe
const session = await getServerSession({ req, res });
/* To mimic API behavior and comply with types */
req.userId = session?.user?.id || -1;
req.body = {
...req.body,
creationSource: CreationSource.WEBAPP,
};
const booking = await handleNewBooking(req);
return booking;
}
Expand Down
2 changes: 2 additions & 0 deletions apps/web/pages/api/book/instant-event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import handleInstantMeeting from "@calcom/features/instant-meeting/handleInstant
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import getIP from "@calcom/lib/getIP";
import { defaultResponder } from "@calcom/lib/server";
import { CreationSource } from "@calcom/prisma/enums";

async function handler(req: NextApiRequest & { userId?: number }, res: NextApiResponse) {
const userIp = getIP(req);
Expand All @@ -16,6 +17,7 @@ async function handler(req: NextApiRequest & { userId?: number }, res: NextApiRe

const session = await getServerSession({ req, res });
req.userId = session?.user?.id || -1;
req.body.creationSource = CreationSource.WEBAPP;
const booking = await handleInstantMeeting(req);
return booking;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { getDate } from "@calcom/web/test/utils/bookingScenario/bookingScenario";

import type { SchedulingType } from "@calcom/prisma/client";
import type { CreationSource } from "@calcom/prisma/enums";

export const DEFAULT_TIMEZONE_BOOKER = "Asia/Kolkata";
export function getBasicMockRequestDataForBooking() {
Expand Down Expand Up @@ -40,6 +41,7 @@ export function getMockRequestDataForBooking({
data: Partial<ReturnType<typeof getBasicMockRequestDataForBooking>> & {
eventTypeId: number;
user?: string;
creationSource?: CreationSource;
} & CommonPropsMockRequestData;
}) {
return {
Expand Down
2 changes: 2 additions & 0 deletions packages/features/auth/lib/next-auth-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import { ProfileRepository } from "@calcom/lib/server/repository/profile";
import { UserRepository } from "@calcom/lib/server/repository/user";
import slugify from "@calcom/lib/slugify";
import prisma from "@calcom/prisma";
import { CreationSource } from "@calcom/prisma/enums";
import { IdentityProvider, MembershipRole } from "@calcom/prisma/enums";
import { teamMetadataSchema, userMetadata } from "@calcom/prisma/zod-utils";

Expand Down Expand Up @@ -979,6 +980,7 @@ export const getOptions = ({
create: { role: MembershipRole.MEMBER, accepted: true, team: { connect: { id: orgId } } },
},
}),
creationSource: CreationSource.WEBAPP,
},
});

Expand Down
2 changes: 2 additions & 0 deletions packages/features/auth/signup/handlers/calcomHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import logger from "@calcom/lib/logger";
import { usernameHandler, type RequestWithUsernameStatus } from "@calcom/lib/server/username";
import { validateAndGetCorrectedUsernameAndEmail } from "@calcom/lib/validateUsername";
import { prisma } from "@calcom/prisma";
import { CreationSource } from "@calcom/prisma/enums";
import { IdentityProvider } from "@calcom/prisma/enums";
import { signupSchema } from "@calcom/prisma/zod-utils";

Expand Down Expand Up @@ -199,6 +200,7 @@ async function handler(req: RequestWithUsernameStatus, res: NextApiResponse) {
stripeCustomerId: customer.id,
checkoutSessionId,
},
creationSource: CreationSource.WEBAPP,
},
});
if (process.env.AVATARAPI_USERNAME && process.env.AVATARAPI_PASSWORD) {
Expand Down
3 changes: 3 additions & 0 deletions packages/features/bookings/lib/handleNewBooking.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ import { WorkflowRepository } from "@calcom/lib/server/repository/workflow";
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
import prisma from "@calcom/prisma";
import { BookingStatus, SchedulingType, WebhookTriggerEvents } from "@calcom/prisma/enums";
import { CreationSource } from "@calcom/prisma/enums";
import {
eventTypeAppMetadataOptionalSchema,
eventTypeMetaDataSchemaWithTypedApps,
Expand Down Expand Up @@ -277,6 +278,7 @@ const buildDryRunBooking = ({
ratingFeedback: null,
noShowHost: null,
cancelledBy: null,
creationSource: CreationSource.WEBAPP,
} as CreatedBooking;

/**
Expand Down Expand Up @@ -1195,6 +1197,7 @@ async function handler(
},
evt,
originalRescheduledBooking,
creationSource: req.body.creationSource,
});

if (booking?.userId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import dayjs from "@calcom/dayjs";
import { isPrismaObjOrUndefined } from "@calcom/lib";
import prisma from "@calcom/prisma";
import { BookingStatus } from "@calcom/prisma/enums";
import type { CreationSource } from "@calcom/prisma/enums";
import type { CalendarEvent } from "@calcom/types/Calendar";

import type { TgetBookingDataSchema } from "../getBookingDataSchema";
Expand Down Expand Up @@ -51,6 +52,7 @@ type CreateBookingParams = {
};
evt: CalendarEvent;
originalRescheduledBooking: OriginalRescheduledBooking;
creationSource?: CreationSource;
};

function updateEventDetails(
Expand Down Expand Up @@ -85,6 +87,7 @@ export async function createBooking({
routingFormResponseId,
reroutingFormResponses,
rescheduledBy,
creationSource,
}: CreateBookingParams & { rescheduledBy: string | undefined }) {
updateEventDetails(evt, originalRescheduledBooking, input.changedOrganizer);
const associatedBookingForFormResponse = routingFormResponseId
Expand All @@ -101,6 +104,7 @@ export async function createBooking({
input,
evt,
originalRescheduledBooking,
creationSource,
});

return await saveBooking(
Expand Down Expand Up @@ -211,6 +215,7 @@ function buildNewBookingData(params: CreateBookingParams) {
routingFormResponseId,
reroutingFormResponses,
rescheduledBy,
creationSource,
} = params;

const attendeesData = getAttendeesData(evt);
Expand Down Expand Up @@ -258,6 +263,7 @@ function buildNewBookingData(params: CreateBookingParams) {
routedFromRoutingFormReponse: routingFormResponseId
? { connect: { id: routingFormResponseId } }
: undefined,
creationSource,
};

if (reqBody.recurringEventId) {
Expand Down
Loading
Loading