refactor: v2 bookings (#16200)

* chore: version existing bookings as 2024-04-15

* feat: initialize bookings version 2024-08-13

* feat: Create and reschedule booking inputs logic

* feat: create booking

* refactor: create booking response

* feat: reschedule booking

* chore: update language input

* feat: recurring booking

* refactor: add booking status in response

* refactor: recurring bookings

* feat: get booking by uid

* wip: get event types

* feat: fetch by multiple status filters and sort

* feat: fetch by teamId, teamIds, eventTypeId, eventTypeIds

* wip: filter by attendee email

* feat: filter by attendee email

* feat: filter by attendee name

* feat: date range filter

* chore: format get bookings output

* chore: finish main merge

* feat: handle instant bookings

* refactor: separate reschedule endpoint

* feat: cancel endpoint

* feat: mark absent host or attendees

* chore: dont expose metadata for now

* chore: add hostId to response

* fix: metadata

* feat: bill bookings

* feat: cancellationReason

* feat: rescheduling reason

* handle already busy booking error

* test: create new booking

* fix: handleNewRecurringBooking ignoring noEmail

* test: recurring bookings

* test: get individual bookings

* fix: cancel email sent if arePlatformEmailsEnabled=false but platformClientId is undefined

* tests: cancel, reschedule, mark absent

* fix: generateIcsFile null pointer exception

* cancel test

* error msg improve

* tests: team event type creation and teamId, teamIds filters

* test: cancel recurring booking

* refactor: make hosts and attendees an array

* sort by asc start

* simplify

* refactor: absent

* fix: make work with api key

* test

* ts remove any

* feat: BookingUidGuard

* fix: recurring booking no email

* fix: legacy bookings recurring noEmail

* add swagger

* retrigger build

* fix: atom booker work with v2

* docs: exclude old controller from docs

* refactor: make eventTypeIds and teamIds getBookings query params comma separated string

* docs: swagger for get bookings query

* swagger docs

* swagger docs

* docs: document authorization header

* refactor: remove unused attendee variable

* refactor: remove unused check

* refactor: remove unused attendee variable

* refactor: spelling

* use published platform libraries

* fix: ci

* fix: ci

* fix: ci

* fix: ci

* cleanup script platform types

* fix: use libraries from npm

* chore: set test env vapid keys

* fix: event type tests

* fix: remove location from system fields

* fix legacy event types

* Revert "fix legacy event types"

This reverts commit e64b473b73f7ef0fe88942cd87277d29a512b946.

* Revert "fix: remove location from system fields"

This reverts commit bee9a15cb27cd34705f34c427b6b50d51e3b7ee7.

* Revert "fix: event type tests"

This reverts commit fab1cb0f5eeb65e4f542bfbeb83849ceed7ba428.

* update libraries

* fix: increase node space for ci runner

* fix: increase node space for ci runner

* fix: increase node space for ci runner

* readd swagger

* ci

* ci

* refactor: increase idle worker memory jest e2e

* fixup! refactor: increase idle worker memory jest e2e

* fixup! fixup! refactor: increase idle worker memory jest e2e

* refactor: split bookings e2e into smaller e2e files

* fixup! refactor: split bookings e2e into smaller e2e files

* fixup! fixup! refactor: split bookings e2e into smaller e2e files

* fixup! fixup! fixup! refactor: split bookings e2e into smaller e2e files

* fixup! Merge branch 'main' into v2-refactor-bookings

* revert event types service

* fix: remove resetModule, maxWorker 2 jest e2e config

---------

Co-authored-by: Morgan Vernay <[email protected]>
Co-authored-by: Morgan <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-09-23 16:19:25 +03:00
1 parent 3371602e0f
commit 0eabe7f28b
60 files changed
+5021 -857

No files matched your search

@@ -6,7 +6,15 @@ import { SchedulingType } from "@calcom/prisma/client";
import type { AppsStatus } from "@calcom/types/Calendar";
export const handleNewRecurringBooking = async (
req: NextApiRequest & { userId?: number }
req: NextApiRequest & {
userId?: number | undefined;
platformClientId?: string;
platformRescheduleUrl?: string;
platformCancelUrl?: string;
platformBookingUrl?: string;
platformBookingLocation?: string;
noEmail?: boolean;
}
): Promise<BookingResponse[]> => {
const data: RecurringBookingCreateBody[] = req.body;
const createdBookings: BookingResponse[] = [];
@@ -73,7 +81,7 @@ export const handleNewRecurringBooking = async (
thirdPartyRecurringEventId,
numSlotsToCheckForAvailability,
currentRecurringIndex: key,
noEmail: key !== 0,
noEmail: req.noEmail !== undefined ? req.noEmail : key !== 0,
luckyUsers,
};
+47 -17
View File
@@ -4,26 +4,34 @@ import { BookingStatus } from "@calcom/prisma/enums";
import { getBookings } from "@calcom/trpc/server/routers/viewer/bookings/get.handler";
type InputByStatus = "upcoming" | "recurring" | "past" | "cancelled" | "unconfirmed";
type SortOptions = {
sortStart?: "asc" | "desc";
sortEnd?: "asc" | "desc";
sortCreated?: "asc" | "desc";
};
type GetOptions = {
ctx: {
user: { id: number; email: string };
prisma: PrismaClient;
};
bookingListingByStatus: InputByStatus;
bookingListingByStatus: InputByStatus[];
take: number;
skip: number;
filters: {
status: InputByStatus;
status?: InputByStatus;
teamIds?: number[] | undefined;
userIds?: number[] | undefined;
eventTypeIds?: number[] | undefined;
attendeeEmail?: string;
attendeeName?: string;
};
sort?: SortOptions;
};
const getAllUserBookings = async ({ ctx, filters, bookingListingByStatus, take, skip }: GetOptions) => {
const getAllUserBookings = async ({ ctx, filters, bookingListingByStatus, take, skip, sort }: GetOptions) => {
const { prisma, user } = ctx;
const bookingListingFilters: Record<typeof bookingListingByStatus, Prisma.BookingWhereInput> = {
const bookingListingFilters: Record<InputByStatus, Prisma.BookingWhereInput> = {
upcoming: {
endTime: { gte: new Date() },
// These changes are needed to not show confirmed recurring events,
@@ -62,24 +70,17 @@ const getAllUserBookings = async ({ ctx, filters, bookingListingByStatus, take,
status: { equals: BookingStatus.PENDING },
},
};
const bookingListingOrderby: Record<
typeof bookingListingByStatus,
Prisma.BookingOrderByWithAggregationInput
> = {
upcoming: { startTime: "asc" },
recurring: { startTime: "asc" },
past: { startTime: "desc" },
cancelled: { startTime: "desc" },
unconfirmed: { startTime: "asc" },
};
const passedBookingsStatusFilter = bookingListingFilters[bookingListingByStatus];
const orderBy = bookingListingOrderby[bookingListingByStatus];
const orderBy = getOrderBy(bookingListingByStatus, sort);
const combinedFilters = bookingListingByStatus.map((status) => bookingListingFilters[status]);
const { bookings, recurringInfo } = await getBookings({
user,
prisma,
passedBookingsStatusFilter,
passedBookingsStatusFilter: {
OR: combinedFilters,
},
filters: filters,
orderBy,
take,
@@ -101,4 +102,33 @@ const getAllUserBookings = async ({ ctx, filters, bookingListingByStatus, take,
};
};
function getOrderBy(
bookingListingByStatus: InputByStatus[],
sort?: SortOptions
): Prisma.BookingOrderByWithAggregationInput {
const bookingListingOrderby: Record<InputByStatus, Prisma.BookingOrderByWithAggregationInput> = {
upcoming: { startTime: "asc" },
recurring: { startTime: "asc" },
past: { startTime: "desc" },
cancelled: { startTime: "desc" },
unconfirmed: { startTime: "asc" },
};
if (bookingListingByStatus?.length === 1 && !sort) {
return bookingListingOrderby[bookingListingByStatus[0]];
}
if (sort?.sortStart) {
return { startTime: sort.sortStart };
}
if (sort?.sortEnd) {
return { endTime: sort.sortEnd };
}
if (sort?.sortCreated) {
return { createdAt: sort.sortCreated };
}
return { startTime: "asc" };
}
export default getAllUserBookings;
@@ -3,13 +3,13 @@ import { useQuery } from "@tanstack/react-query";
import { SUCCESS_STATUS, V2_ENDPOINTS } from "@calcom/platform-constants";
import type { getAllUserBookings } from "@calcom/platform-libraries";
import type { ApiResponse, ApiSuccessResponse } from "@calcom/platform-types";
import type { GetBookingsInput } from "@calcom/platform-types/bookings";
import type { GetBookingsInput_2024_04_15 } from "@calcom/platform-types/bookings";
import http from "../lib/http";
export const QUERY_KEY = "user-bookings";
export const useGetBookings = (input: GetBookingsInput) => {
export const useGetBookings = (input: GetBookingsInput_2024_04_15) => {
const pathname = `/${V2_ENDPOINTS.bookings}`;
const bookingsQuery = useQuery({
+7 -1
View File
@@ -54,8 +54,14 @@ export const HTTP_CODE_TOKEN_EXPIRED = 498;
export const VERSION_2024_06_14 = "2024-06-14";
export const VERSION_2024_06_11 = "2024-06-11";
export const VERSION_2024_04_15 = "2024-04-15";
export const VERSION_2024_08_13 = "2024-08-13";
export const API_VERSIONS = [VERSION_2024_06_14, VERSION_2024_06_11, VERSION_2024_04_15] as const;
export const API_VERSIONS = [
VERSION_2024_06_14,
VERSION_2024_06_11,
VERSION_2024_04_15,
VERSION_2024_08_13,
] as const;
export type API_VERSIONS_ENUM = (typeof API_VERSIONS)[number];
export type API_VERSIONS_TYPE = typeof API_VERSIONS;
+3
View File
@@ -1,3 +1,6 @@
## 0.0.37
Released to support PR https://github.com/calcom/cal.com/pull/16200
## 0.0.36
Released to support PR https://github.com/calcom/cal.com/pull/16685
@@ -0,0 +1 @@
export * from "./inputs";
@@ -12,7 +12,7 @@ import {
IsString,
} from "class-validator";
export enum Status {
export enum Status_2024_04_15 {
upcoming = "upcoming",
recurring = "recurring",
past = "past",
@@ -20,7 +20,7 @@ export enum Status {
unconfirmed = "unconfirmed",
}
type BookingStatus = `${Status}`;
type BookingStatus = `${Status_2024_04_15}`;
class Filters {
@IsOptional()
@@ -33,7 +33,7 @@ class Filters {
@Type(() => Number)
userIds?: number[];
@IsEnum(Status)
@IsEnum(Status_2024_04_15)
status!: BookingStatus;
@IsOptional()
@@ -42,7 +42,7 @@ class Filters {
eventTypeIds?: number[];
}
export class GetBookingsInput {
export class GetBookingsInput_2024_04_15 {
@ValidateNested({ each: true })
@Type(() => Filters)
filters!: Filters;
@@ -60,7 +60,7 @@ export class GetBookingsInput {
cursor?: number | null;
}
export class CancelBookingInput {
export class CancelBookingInput_2024_04_15 {
@IsNumber()
@IsOptional()
@ApiProperty()
@@ -0,0 +1,2 @@
export * from "./inputs";
export * from "./outputs";
@@ -0,0 +1,9 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsOptional, IsString } from "class-validator";
export class CancelBookingInput_2024_08_13 {
@IsString()
@IsOptional()
@ApiProperty({ example: "User requested cancellation" })
cancellationReason?: string;
}
@@ -0,0 +1,111 @@
import type { PipeTransform } from "@nestjs/common";
import { Injectable, BadRequestException } from "@nestjs/common";
import { plainToClass } from "class-transformer";
import type { ValidationError } from "class-validator";
import { validateSync } from "class-validator";
import { CreateRecurringBookingInput_2024_08_13 } from "./create-booking.input";
import { CreateBookingInput_2024_08_13 } from "./create-booking.input";
import { CreateInstantBookingInput_2024_08_13 } from "./create-booking.input";
export type CreateBookingInput =
| CreateBookingInput_2024_08_13
| CreateRecurringBookingInput_2024_08_13
| CreateInstantBookingInput_2024_08_13;
@Injectable()
export class CreateBookingInputPipe implements PipeTransform {
// note(Lauris): we need empty constructor otherwise v2 can't be started due to error:
// CreateBookingInputPipe is not a constructor
// eslint-disable-next-line @typescript-eslint/no-empty-function
constructor() {}
transform(value: CreateBookingInput): CreateBookingInput {
if (!value) {
throw new BadRequestException("Body is required");
}
if (typeof value !== "object") {
throw new BadRequestException("Body should be an object");
}
if (this.isRecurringBookingInput(value)) {
return this.validateRecurringBooking(value);
}
if (this.isInstantBookingInput(value)) {
return this.validateInstantBooking(value);
}
return this.validateBooking(value);
}
validateBooking(value: CreateBookingInput_2024_08_13) {
const object = plainToClass(CreateBookingInput_2024_08_13, value);
const errors = validateSync(object, {
whitelist: true,
forbidNonWhitelisted: true,
skipMissingProperties: false,
});
if (errors.length > 0) {
throw new BadRequestException(this.formatErrors(errors));
}
return object;
}
validateRecurringBooking(value: CreateRecurringBookingInput_2024_08_13) {
const object = plainToClass(CreateRecurringBookingInput_2024_08_13, value);
const errors = validateSync(object, {
whitelist: true,
forbidNonWhitelisted: true,
skipMissingProperties: false,
});
if (errors.length > 0) {
throw new BadRequestException(this.formatErrors(errors));
}
return object;
}
validateInstantBooking(value: CreateInstantBookingInput_2024_08_13) {
const object = plainToClass(CreateInstantBookingInput_2024_08_13, value);
const errors = validateSync(object, {
whitelist: true,
forbidNonWhitelisted: true,
skipMissingProperties: false,
});
if (errors.length > 0) {
throw new BadRequestException(this.formatErrors(errors));
}
return object;
}
private formatErrors(errors: ValidationError[]): string {
return errors
.map((err) => {
const constraints = err.constraints ? Object.values(err.constraints).join(", ") : "";
const childrenErrors =
err.children && err.children.length > 0 ? `${this.formatErrors(err.children)}` : "";
return `${err.property} property is wrong,${constraints} ${childrenErrors}`;
})
.join(", ");
}
private isRecurringBookingInput(
value: CreateBookingInput
): value is CreateRecurringBookingInput_2024_08_13 {
return value.hasOwnProperty("recurringEventTypeId");
}
private isInstantBookingInput(value: CreateBookingInput): value is CreateRecurringBookingInput_2024_08_13 {
return value.hasOwnProperty("instant") && "instant" in value && value.instant === true;
}
}
@@ -0,0 +1,201 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { Type } from "class-transformer";
import {
IsInt,
IsDateString,
IsTimeZone,
IsEnum,
IsEmail,
ValidateNested,
IsArray,
IsString,
IsOptional,
IsUrl,
IsObject,
IsBoolean,
} from "class-validator";
import type { BookingLanguageType } from "./language";
import { BookingLanguage } from "./language";
class Attendee {
@ApiProperty({
type: String,
description: "The name of the attendee.",
example: "John Doe",
})
@IsString()
name!: string;
@ApiProperty({
type: String,
description: "The email of the attendee.",
example: "[email protected]",
})
@IsEmail()
email!: string;
@ApiProperty({
type: String,
description: "The time zone of the attendee.",
example: "America/New_York",
})
@IsTimeZone()
timeZone!: string;
@ApiPropertyOptional({
enum: BookingLanguage,
description: "The preferred language of the attendee. Used for booking confirmation.",
example: BookingLanguage.it,
default: BookingLanguage.en,
})
@IsEnum(BookingLanguage)
@IsOptional()
language?: BookingLanguageType;
}
export class CreateBookingInput_2024_08_13 {
@ApiProperty({
type: String,
description: "The start time of the booking in ISO 8601 format in UTC timezone.",
example: "2024-08-13T09:00:00Z",
})
@IsDateString()
start!: string;
@ApiProperty({
type: Number,
description: "The ID of the event type that is booked.",
example: 123,
})
@IsInt()
eventTypeId!: number;
@ApiProperty({
type: Attendee,
description: "The attendee's details.",
})
@ValidateNested()
@Type(() => Attendee)
attendee!: Attendee;
@ApiPropertyOptional({
type: [String],
description: "An optional list of guest emails attending the event.",
example: ["[email protected]", "[email protected]"],
})
@IsArray()
@IsString({ each: true })
@IsOptional()
guests?: string[];
@ApiPropertyOptional({
type: String,
description:
"Meeting URL just for this booking. Displayed in email and calendar event. If not provided then cal video link will be generated.",
example: "https://example.com/meeting",
})
@IsUrl()
@IsOptional()
meetingUrl?: string;
// todo(Lauris): expose after refactoring metadata https://app.campsite.co/cal/posts/zysq8w9rwm9c
// @ApiProperty({
// type: Object,
// description: "Optional metadata for the booking.",
// example: { key: "value" },
// required: false,
// })
// @IsObject()
// @IsOptional()
// metadata!: Record<string, unknown>;
@ApiPropertyOptional({
type: Object,
description: "Booking field responses.",
example: { customField: "customValue" },
required: false,
})
@IsObject()
@IsOptional()
bookingFieldsResponses?: Record<string, unknown>;
}
export class CreateInstantBookingInput_2024_08_13 extends CreateBookingInput_2024_08_13 {
@ApiProperty({
type: Boolean,
description: "Flag indicating if the booking is an instant booking. Only available for team events.",
example: true,
})
@IsBoolean()
instant!: boolean;
}
export class CreateRecurringBookingInput_2024_08_13 {
@ApiProperty({
type: String,
description: "The start time of the booking in ISO 8601 format in UTC timezone.",
example: "2024-08-13T09:00:00Z",
})
@IsDateString()
start!: string;
@ApiProperty({
type: Number,
description: "The ID of the event type that is booked.",
example: 123,
})
@IsInt()
eventTypeId!: number;
@ApiProperty({
type: Attendee,
description: "The attendee's details.",
})
@ValidateNested()
@Type(() => Attendee)
attendee!: Attendee;
@ApiProperty({
type: [String],
description: "An optional list of guest emails attending the event.",
example: ["[email protected]", "[email protected]"],
required: false,
})
@IsArray()
@IsString({ each: true })
@IsOptional()
guests?: string[];
@ApiProperty({
type: String,
description:
"Meeting URL just for this booking. Displayed in email and calendar event. If not provided then cal video link will be generated.",
example: "https://example.com/meeting",
required: false,
})
@IsUrl()
@IsOptional()
meetingUrl?: string;
// todo(Lauris): expose after refactoring metadata https://app.campsite.co/cal/posts/zysq8w9rwm9c
// @ApiProperty({
// type: Object,
// description: "Optional metadata for the booking.",
// example: { key: "value" },
// required: false,
// })
// @IsObject()
// @IsOptional()
// metadata!: Record<string, unknown>;
@ApiProperty({
type: Object,
description: "Booking field responses.",
example: { customField: "customValue" },
required: false,
})
@IsObject()
@IsOptional()
bookingFieldsResponses?: Record<string, unknown>;
}
@@ -0,0 +1,208 @@
import { ApiProperty } from "@nestjs/swagger";
import { Transform, Type } from "class-transformer";
import {
ArrayMinSize,
ArrayNotEmpty,
IsArray,
IsEnum,
IsInt,
IsISO8601,
IsNumber,
IsOptional,
IsString,
Max,
Min,
} from "class-validator";
enum Status {
upcoming = "upcoming",
recurring = "recurring",
past = "past",
cancelled = "cancelled",
unconfirmed = "unconfirmed",
}
type StatusType = keyof typeof Status;
enum SortOrder {
asc = "asc",
desc = "desc",
}
type SortOrderType = keyof typeof SortOrder;
export class GetBookingsInput_2024_08_13 {
// note(Lauris): filters
@IsOptional()
@Transform(({ value }) => {
if (typeof value === "string") {
return value.split(",").map((status: string) => status.trim());
}
return value;
})
@ArrayNotEmpty({ message: "status cannot be empty." })
@IsEnum(Status, {
each: true,
message: "Invalid status. Allowed are upcoming, recurring, past, cancelled, unconfirmed",
})
@ApiProperty({
required: false,
description:
"Filter bookings by status. If you want to filter by multiple statuses, separate them with a comma.",
example: "?status=upcoming,past",
enum: Status,
isArray: true,
})
status?: StatusType[];
@IsString()
@IsOptional()
@ApiProperty({
type: String,
required: false,
description: "Filter bookings by the attendee's email address.",
example: "[email protected]",
})
attendeeEmail?: string;
@IsString()
@IsOptional()
@ApiProperty({
type: String,
required: false,
description: "Filter bookings by the attendee's name.",
example: "John Doe",
})
attendeeName?: string;
@IsOptional()
@Transform(({ value }) => {
if (typeof value === "string") {
return value.split(",").map((eventTypeId: string) => parseInt(eventTypeId));
}
return value;
})
@IsArray()
@IsNumber({}, { each: true })
@ArrayMinSize(1, { message: "eventTypeIds must contain at least 1 event type id" })
@ApiProperty({
type: String,
required: false,
description:
"Filter bookings by event type ids belonging to the user. Event type ids must be separated by a comma.",
example: "?eventTypeIds=100,200",
})
eventTypeIds?: number[];
@IsInt()
@IsOptional()
@Type(() => Number)
@ApiProperty({
type: String,
required: false,
description: "Filter bookings by event type id belonging to the user.",
example: "?eventTypeId=100",
})
eventTypeId?: number;
@IsOptional()
@Transform(({ value }) => {
if (typeof value === "string") {
return value.split(",").map((teamId: string) => parseInt(teamId));
}
return value;
})
@IsArray()
@IsNumber({}, { each: true })
@ArrayMinSize(1, { message: "teamIds must contain at least 1 team id" })
@ApiProperty({
type: String,
required: false,
description: "Filter bookings by team ids that user is part of. Team ids must be separated by a comma.",
example: "?teamIds=50,60",
})
teamsIds?: number[];
@IsInt()
@IsOptional()
@Type(() => Number)
@ApiProperty({
type: String,
required: false,
description: "Filter bookings by team id that user is part of",
example: "?teamId=50",
})
teamId?: number;
@IsOptional()
@IsISO8601({ strict: true }, { message: "fromDate must be a valid ISO 8601 date." })
@ApiProperty({
type: String,
required: false,
description: "Filter bookings with start after this date string.",
example: "?afterStart=2025-03-07T10:00:00.000Z",
})
afterStart?: string;
@IsOptional()
@IsISO8601({ strict: true }, { message: "toDate must be a valid ISO 8601 date." })
@ApiProperty({
type: String,
required: false,
description: "Filter bookings with end before this date string.",
example: "?beforeEnd=2025-03-07T11:00:00.000Z",
})
beforeEnd?: string;
// note(Lauris): sort
@IsOptional()
@IsEnum(SortOrder, {
message: 'SortStart must be either "asc" or "desc".',
})
@ApiProperty({
required: false,
description: "Sort results by their start time in ascending or descending order.",
example: "?sortStart=asc OR ?sortStart=desc",
enum: SortOrder,
})
sortStart?: SortOrderType;
@IsOptional()
@IsEnum(SortOrder, {
message: 'SortEnd must be either "asc" or "desc".',
})
@ApiProperty({
required: false,
description: "Sort results by their end time in ascending or descending order.",
example: "?sortEnd=asc OR ?sortEnd=desc",
enum: SortOrder,
})
sortEnd?: SortOrderType;
@IsOptional()
@IsEnum(SortOrder, {
message: 'SortCreated must be either "asc" or "desc".',
})
@ApiProperty({
required: false,
description:
"Sort results by their creation time (when booking was made) in ascending or descending order.",
example: "?sortEnd=asc OR ?sortEnd=desc",
enum: SortOrder,
})
sortCreated?: SortOrderType;
// note(Lauris): pagination
@ApiProperty({ required: false, description: "The number of items to return", example: 10 })
@Transform(({ value }: { value: string }) => value && parseInt(value))
@IsNumber()
@Min(1)
@Max(250)
@IsOptional()
take?: number;
@ApiProperty({ required: false, description: "The number of items to skip", example: 0 })
@Transform(({ value }: { value: string }) => value && parseInt(value))
@IsNumber()
@Min(0)
@IsOptional()
skip?: number;
}
@@ -0,0 +1,6 @@
export * from "./create-booking.input";
export * from "./create-booking-input.pipe";
export * from "./get-bookings.input";
export * from "./reschedule-booking.input";
export * from "./cancel-booking.input";
export * from "./mark-absent.input";
@@ -0,0 +1,46 @@
export enum BookingLanguage {
"ar" = "ar",
"ca" = "ca",
"de" = "de",
"es" = "es",
"eu" = "eu",
"he" = "he",
"id" = "id",
"ja" = "ja",
"lv" = "lv",
"pl" = "pl",
"ro" = "ro",
"sr" = "sr",
"th" = "th",
"vi" = "vi",
"az" = "az",
"cs" = "cs",
"el" = "el",
"es-419" = "es-419",
"fi" = "fi",
"hr" = "hr",
"it" = "it",
"km" = "km",
"nl" = "nl",
"pt" = "pt",
"ru" = "ru",
"sv" = "sv",
"tr" = "tr",
"zh-CN" = "zh-CN",
"bg" = "bg",
"da" = "da",
"en" = "en",
"et" = "et",
"fr" = "fr",
"hu" = "hu",
"iw" = "iw",
"ko" = "ko",
"no" = "no",
"pt-BR" = "pt-BR",
"sk" = "sk",
"ta" = "ta",
"uk" = "uk",
"zh-TW" = "zh-TW",
}
export type BookingLanguageType = keyof typeof BookingLanguage;
@@ -0,0 +1,32 @@
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsOptional, IsBoolean, IsEmail, IsArray, ArrayMinSize, ValidateNested } from "class-validator";
class Attendee {
@IsEmail()
@ApiProperty()
email!: string;
@IsBoolean()
@ApiProperty()
absent!: boolean;
}
export class MarkAbsentBookingInput_2024_08_13 {
@IsBoolean()
@IsOptional()
@ApiProperty({ example: false, required: false, description: "Whether the host was absent" })
host?: boolean;
@ArrayMinSize(1)
@ApiProperty({
type: [String],
description: "Toggle whether an attendee was absent or not.",
example: [{ absent: true, email: "[email protected]" }],
})
@ValidateNested()
@Type(() => Attendee)
@IsArray()
@IsOptional()
attendees?: Attendee[];
}
@@ -0,0 +1,20 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsDateString, IsOptional, IsString } from "class-validator";
export class RescheduleBookingInput_2024_08_13 {
@IsDateString()
@ApiProperty({
description: "Start time in ISO 8601 format for the new booking",
example: "2024-08-13T10:00:00Z",
})
start!: string;
@IsString()
@IsOptional()
@ApiProperty({
example: "User requested reschedule",
description: "Reason for rescheduling the booking",
required: false,
})
reschedulingReason?: string;
}
@@ -0,0 +1,232 @@
import { ApiProperty } from "@nestjs/swagger";
import { Expose, Type } from "class-transformer";
import {
IsArray,
IsBoolean,
IsDateString,
IsEnum,
IsInt,
IsOptional,
IsString,
IsTimeZone,
IsUrl,
ValidateNested,
} from "class-validator";
import type { BookingLanguageType } from "../inputs/language";
import { BookingLanguage } from "../inputs/language";
class Attendee {
@ApiProperty({ type: String, example: "John Doe" })
@IsString()
@Expose()
name!: string;
@ApiProperty({ type: String, example: "America/New_York" })
@IsTimeZone()
@Expose()
timeZone!: string;
@ApiProperty({ enum: BookingLanguage, required: false, example: "en" })
@IsEnum(BookingLanguage)
@Expose()
@IsOptional()
language?: BookingLanguageType;
@ApiProperty({ type: Boolean, example: false })
@IsBoolean()
@Expose()
absent!: boolean;
}
class Host {
@ApiProperty({ type: Number, example: 1 })
@IsInt()
@Expose()
id!: number;
@ApiProperty({ type: String, example: "Jane Doe" })
@IsString()
@Expose()
name!: string;
@ApiProperty({ type: String, example: "America/Los_Angeles" })
@IsTimeZone()
@Expose()
timeZone!: string;
}
export class BookingOutput_2024_08_13 {
@ApiProperty({ type: Number, example: 123 })
@IsInt()
@Expose()
id!: number;
@ApiProperty({ type: String, example: "booking_uid_123" })
@IsString()
@Expose()
uid!: string;
@ApiProperty({ type: [Host] })
@ValidateNested({ each: true })
@Type(() => Host)
@Expose()
hosts!: Host[];
@ApiProperty({ enum: ["cancelled", "accepted", "rejected", "pending", "rescheduled"], example: "accepted" })
@IsEnum(["cancelled", "accepted", "rejected", "pending", "rescheduled"])
@Expose()
status!: "cancelled" | "accepted" | "rejected" | "pending" | "rescheduled";
@ApiProperty({ type: String, required: false, example: "User requested cancellation" })
@IsString()
@IsOptional()
@Expose()
cancellationReason?: string;
@ApiProperty({ type: String, required: false, example: "User rescheduled the event" })
@IsString()
@IsOptional()
@Expose()
reschedulingReason?: string;
@ApiProperty({ type: String, required: false, example: "previous_uid_123" })
@IsString()
@IsOptional()
@Expose()
rescheduledFromUid?: string;
@ApiProperty({ type: String, example: "2024-08-13T15:30:00Z" })
@IsDateString()
@Expose()
start!: string;
@ApiProperty({ type: String, example: "2024-08-13T16:30:00Z" })
@IsDateString()
@Expose()
end!: string;
@ApiProperty({ type: Number, example: 60 })
@IsInt()
@Expose()
duration!: number;
@ApiProperty({ type: Number, example: 45 })
@IsInt()
@Expose()
eventTypeId!: number;
@ApiProperty({ type: [Attendee] })
@ValidateNested({ each: true })
@Type(() => Attendee)
@Expose()
attendees!: Attendee[];
@ApiProperty({ type: [String], required: false, example: ["[email protected]", "[email protected]"] })
@IsArray()
@IsString({ each: true })
@IsOptional()
@Expose()
guests?: string[];
@ApiProperty({ type: String, required: false, example: "https://example.com/meeting" })
@IsUrl()
@IsOptional()
@Expose()
meetingUrl?: string;
@ApiProperty({ type: Boolean, example: true })
@IsBoolean()
@Expose()
absentHost!: boolean;
}
export class RecurringBookingOutput_2024_08_13 {
@ApiProperty({ type: Number, example: 456 })
@IsInt()
@Expose()
id!: number;
@ApiProperty({ type: String, example: "recurring_uid_123" })
@IsString()
@Expose()
uid!: string;
@ApiProperty({ type: [Host] })
@ValidateNested({ each: true })
@Type(() => Host)
@Expose()
hosts!: Host[];
@ApiProperty({ enum: ["cancelled", "accepted", "rejected", "pending"], example: "pending" })
@IsEnum(["cancelled", "accepted", "rejected", "pending"])
@Expose()
status!: "cancelled" | "accepted" | "rejected" | "pending";
@ApiProperty({ type: String, required: false, example: "Event was cancelled" })
@IsString()
@IsOptional()
@Expose()
cancellationReason?: string;
@ApiProperty({ type: String, required: false, example: "Event was rescheduled" })
@IsString()
@IsOptional()
@Expose()
reschedulingReason?: string;
@ApiProperty({ type: String, required: false, example: "previous_recurring_uid_123" })
@IsString()
@IsOptional()
@Expose()
rescheduledFromUid?: string;
@ApiProperty({ type: String, example: "2024-08-13T15:30:00Z" })
@IsDateString()
@Expose()
start!: string;
@ApiProperty({ type: String, example: "2024-08-13T16:30:00Z" })
@IsDateString()
@Expose()
end!: string;
@ApiProperty({ type: Number, example: 30 })
@IsInt()
@Expose()
duration!: number;
@ApiProperty({ type: Number, example: 50 })
@IsInt()
@Expose()
eventTypeId!: number;
@ApiProperty({ type: String, example: "recurring_uid_987" })
@IsString()
@Expose()
recurringBookingUid!: string;
@ApiProperty({ type: [Attendee] })
@ValidateNested({ each: true })
@Type(() => Attendee)
@Expose()
attendees!: Attendee[];
@ApiProperty({ type: [String], required: false, example: ["[email protected]", "[email protected]"] })
@IsArray()
@IsString({ each: true })
@IsOptional()
@Expose()
guests?: string[];
@ApiProperty({ type: String, required: false, example: "https://example.com/recurring-meeting" })
@IsUrl()
@IsOptional()
@Expose()
meetingUrl?: string;
@ApiProperty({ type: Boolean, example: false })
@IsBoolean()
@Expose()
absentHost!: boolean;
}
@@ -0,0 +1 @@
export * from "./booking.output";
@@ -0,0 +1,2 @@
export * from "./2024-04-15";
export * from "./2024-08-13";
+2 -1
View File
@@ -4,7 +4,8 @@
"main": "./dist/index.js",
"types": "./dist/index.js",
"scripts": {
"build": "tsc --build --force tsconfig.json",
"build": "yarn clean && tsc --build --force tsconfig.json",
"clean": "rm -rf ./dist",
"build:watch": "tsc --build --force ./tsconfig.json --watch",
"post-install": "yarn build"
},
@@ -23,7 +23,8 @@ export const getHandler = async ({ ctx, input }: GetOptions) => {
const take = input.limit ?? 10;
const skip = input.cursor ?? 0;
const { prisma, user } = ctx;
const bookingListingByStatus = input.filters.status;
const defaultStatus = "upcoming";
const bookingListingByStatus = [input.filters.status || defaultStatus];
const { bookings, recurringInfo, nextCursor } = await getAllUserBookings({
ctx: { user: { id: user.id, email: user.email }, prisma: prisma },
@@ -68,9 +69,10 @@ export async function getBookings({
take: number;
skip: number;
}) {
// TODO: Fix record typing
const bookingWhereInputFilters: Record<string, Prisma.BookingWhereInput> = {
teamIds: {
const bookingWhereInputFilters: Record<string, Prisma.BookingWhereInput> = {};
if (filters?.teamIds && filters.teamIds.length > 0) {
bookingWhereInputFilters.teamIds = {
AND: [
{
OR: [
@@ -78,7 +80,7 @@ export async function getBookings({
eventType: {
team: {
id: {
in: filters?.teamIds,
in: filters.teamIds,
},
},
},
@@ -88,7 +90,7 @@ export async function getBookings({
parent: {
team: {
id: {
in: filters?.teamIds,
in: filters.teamIds,
},
},
},
@@ -97,8 +99,11 @@ export async function getBookings({
],
},
],
},
userIds: {
};
}
if (filters?.userIds && filters.userIds.length > 0) {
bookingWhereInputFilters.userIds = {
AND: [
{
OR: [
@@ -107,7 +112,7 @@ export async function getBookings({
hosts: {
some: {
userId: {
in: filters?.userIds,
in: filters.userIds,
},
},
},
@@ -115,7 +120,7 @@ export async function getBookings({
},
{
userId: {
in: filters?.userIds,
in: filters.userIds,
},
},
{
@@ -123,7 +128,7 @@ export async function getBookings({
users: {
some: {
id: {
in: filters?.userIds,
in: filters.userIds,
},
},
},
@@ -132,21 +137,24 @@ export async function getBookings({
],
},
],
},
eventTypeIds: {
};
}
if (filters?.eventTypeIds && filters.eventTypeIds.length > 0) {
bookingWhereInputFilters.eventTypeIds = {
AND: [
{
OR: [
{
eventTypeId: {
in: filters?.eventTypeIds,
in: filters.eventTypeIds,
},
},
{
eventType: {
parent: {
id: {
in: filters?.eventTypeIds,
in: filters.eventTypeIds,
},
},
},
@@ -154,8 +162,44 @@ export async function getBookings({
],
},
],
},
};
};
}
if (filters?.attendeeEmail) {
bookingWhereInputFilters.attendeeEmail = {
attendees: {
some: {
email: filters.attendeeEmail.trim(),
},
},
};
}
if (filters?.attendeeName) {
bookingWhereInputFilters.attendeeName = {
attendees: {
some: {
name: filters.attendeeName.trim(),
},
},
};
}
if (filters?.afterStartDate) {
bookingWhereInputFilters.afterStartDate = {
startTime: {
gte: new Date(filters.afterStartDate),
},
};
}
if (filters?.beforeEndDate) {
bookingWhereInputFilters.beforeEndDate = {
endTime: {
lte: new Date(filters.beforeEndDate),
},
};
}
const filtersCombined: Prisma.BookingWhereInput[] = !filters
? []
@@ -192,7 +236,6 @@ export async function getBookings({
},
status: true,
paid: true,
payment: {
select: {
paymentOption: true,
@@ -4,8 +4,12 @@ export const ZGetInputSchema = z.object({
filters: z.object({
teamIds: z.number().array().optional(),
userIds: z.number().array().optional(),
status: z.enum(["upcoming", "recurring", "past", "cancelled", "unconfirmed"]),
status: z.enum(["upcoming", "recurring", "past", "cancelled", "unconfirmed"]).optional(),
eventTypeIds: z.number().array().optional(),
attendeeEmail: z.string().optional(),
attendeeName: z.string().optional(),
afterStartDate: z.string().optional(),
beforeEndDate: z.string().optional(),
}),
limit: z.number().min(1).max(100).nullish(),
cursor: z.number().nullish(), // <-- "cursor" needs to exist when using useInfiniteQuery, but can be any type