chore: get bookings with kysely (#21084)
* chore: get bookings with kysely * fixup! chore: get bookings with kysely * replace left joins with inner joins * add missing filter and count with kysely * main query done * kysely use connection string * fix attendee emails operator * fix immutability and add attendee email filter * chore: everything working but date filters * limit offset * chore: bump platform libraries * fix bookingseat / attendee user email filter * refactor, clean, and subquery updatedAt/createdAt * fix import kysely types path * fix missing references and payments fields * create kysely module in apiv2 * fix before created at filter * fix types * update yarn.lock * update yarn.lock --------- Co-authored-by: Keith Williams <[email protected]>
This commit is contained in:
1 parent
91288b41cd
commit
d4a3894a9e
20 files changed
+1528
-415
No files matched your search
@@ -38,7 +38,7 @@
|
||||
"@axiomhq/winston": "^1.2.0",
|
||||
"@calcom/platform-constants": "*",
|
||||
"@calcom/platform-enums": "*",
|
||||
"@calcom/platform-libraries": "npm:@calcom/[email protected]85",
|
||||
"@calcom/platform-libraries": "npm:@calcom/[email protected]94",
|
||||
"@calcom/platform-libraries-0.0.2": "npm:@calcom/[email protected]",
|
||||
"@calcom/platform-types": "*",
|
||||
"@calcom/platform-utils": "*",
|
||||
|
||||
@@ -9,6 +9,7 @@ import { ApiKeysRepository } from "@/modules/api-keys/api-keys-repository";
|
||||
import { AppsRepository } from "@/modules/apps/apps.repository";
|
||||
import { BillingModule } from "@/modules/billing/billing.module";
|
||||
import { CredentialsRepository } from "@/modules/credentials/credentials.repository";
|
||||
import { KyselyModule } from "@/modules/kysely/kysely.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";
|
||||
@@ -23,6 +24,7 @@ import { Module } from "@nestjs/common";
|
||||
@Module({
|
||||
imports: [
|
||||
PrismaModule,
|
||||
KyselyModule,
|
||||
RedisModule,
|
||||
TokensModule,
|
||||
BillingModule,
|
||||
|
||||
@@ -13,6 +13,7 @@ import { Permissions } from "@/modules/auth/decorators/permissions/permissions.d
|
||||
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
|
||||
import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard";
|
||||
import { BillingService } from "@/modules/billing/services/billing.service";
|
||||
import { KyselyReadService } from "@/modules/kysely/kysely-read.service";
|
||||
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";
|
||||
@@ -99,6 +100,7 @@ export class BookingsController_2024_04_15 {
|
||||
constructor(
|
||||
private readonly oAuthFlowService: OAuthFlowService,
|
||||
private readonly prismaReadService: PrismaReadService,
|
||||
private readonly kyselyReadService: KyselyReadService,
|
||||
private readonly oAuthClientRepository: OAuthClientRepository,
|
||||
private readonly billingService: BillingService,
|
||||
private readonly config: ConfigService,
|
||||
@@ -129,6 +131,7 @@ export class BookingsController_2024_04_15 {
|
||||
ctx: {
|
||||
user: { email: user.email, id: user.id, orgId: profile?.organizationId },
|
||||
prisma: this.prismaReadService.prisma as unknown as PrismaClient,
|
||||
kysely: this.kyselyReadService.kysely,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ 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 { 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";
|
||||
@@ -36,6 +37,7 @@ import { Module } from "@nestjs/common";
|
||||
@Module({
|
||||
imports: [
|
||||
PrismaModule,
|
||||
KyselyModule,
|
||||
RedisModule,
|
||||
TokensModule,
|
||||
BillingModule,
|
||||
|
||||
@@ -7,6 +7,7 @@ import { PlatformBookingsService } from "@/ee/bookings/shared/platform-bookings.
|
||||
import { EventTypesRepository_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.repository";
|
||||
import { BillingService } from "@/modules/billing/services/billing.service";
|
||||
import { BookingSeatRepository } from "@/modules/booking-seat/booking-seat.repository";
|
||||
import { KyselyReadService } from "@/modules/kysely/kysely-read.service";
|
||||
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
|
||||
import { OAuthClientUsersService } from "@/modules/oauth-clients/services/oauth-clients-users.service";
|
||||
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
|
||||
@@ -78,6 +79,7 @@ export class BookingsService_2024_08_13 {
|
||||
private readonly bookingSeatRepository: BookingSeatRepository,
|
||||
private readonly eventTypesRepository: EventTypesRepository_2024_06_14,
|
||||
private readonly prismaReadService: PrismaReadService,
|
||||
private readonly kyselyReadService: KyselyReadService,
|
||||
private readonly billingService: BillingService,
|
||||
private readonly usersService: UsersService,
|
||||
private readonly usersRepository: UsersRepository,
|
||||
@@ -385,6 +387,7 @@ export class BookingsService_2024_08_13 {
|
||||
ctx: {
|
||||
user,
|
||||
prisma: this.prismaReadService.prisma as unknown as PrismaClient,
|
||||
kysely: this.kyselyReadService.kysely,
|
||||
},
|
||||
sort: this.inputService.transformGetBookingsSort(queryParams),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { OnModuleDestroy } from "@nestjs/common";
|
||||
import { Injectable, Logger } from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { DeduplicateJoinsPlugin, Kysely, ParseJSONResultsPlugin, PostgresDialect } from "kysely";
|
||||
import { Pool } from "pg";
|
||||
|
||||
import type { DB } from "@calcom/kysely/types";
|
||||
|
||||
@Injectable()
|
||||
export class KyselyReadService implements OnModuleDestroy {
|
||||
private logger = new Logger("KyselyReadService");
|
||||
|
||||
public kysely: Kysely<DB>;
|
||||
|
||||
constructor(readonly configService: ConfigService) {
|
||||
const dbUrl = configService.get("db.readUrl", { infer: true });
|
||||
const pool = new Pool({ connectionString: dbUrl });
|
||||
|
||||
// 3. Create the Dialect, passing the configured pool instance
|
||||
const dialect = new PostgresDialect({
|
||||
pool: pool, // Use the pool instance created above
|
||||
});
|
||||
this.kysely = new Kysely<DB>({
|
||||
dialect,
|
||||
plugins: [new ParseJSONResultsPlugin(), new DeduplicateJoinsPlugin()],
|
||||
});
|
||||
}
|
||||
|
||||
async onModuleDestroy() {
|
||||
try {
|
||||
await this.kysely.destroy();
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { OnModuleDestroy } from "@nestjs/common";
|
||||
import { Injectable, Logger } from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { Kysely, ParseJSONResultsPlugin, PostgresDialect, DeduplicateJoinsPlugin } from "kysely";
|
||||
import { Pool } from "pg";
|
||||
|
||||
import type { DB } from "@calcom/kysely/types";
|
||||
|
||||
@Injectable()
|
||||
export class KyselyWriteService implements OnModuleDestroy {
|
||||
private logger = new Logger("KyselyWriteService");
|
||||
|
||||
public kysely: Kysely<DB>;
|
||||
|
||||
constructor(readonly configService: ConfigService) {
|
||||
const dbUrl = configService.get("db.writeUrl", { infer: true });
|
||||
const pool = new Pool({ connectionString: dbUrl });
|
||||
|
||||
// 3. Create the Dialect, passing the configured pool instance
|
||||
const dialect = new PostgresDialect({
|
||||
pool: pool, // Use the pool instance created above
|
||||
});
|
||||
this.kysely = new Kysely<DB>({
|
||||
dialect,
|
||||
plugins: [new ParseJSONResultsPlugin(), new DeduplicateJoinsPlugin()],
|
||||
});
|
||||
}
|
||||
|
||||
async onModuleDestroy() {
|
||||
try {
|
||||
await this.kysely.destroy();
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { KyselyReadService } from "@/modules/kysely/kysely-read.service";
|
||||
import { KyselyWriteService } from "@/modules/kysely/kysely-write.service";
|
||||
import { Module } from "@nestjs/common";
|
||||
|
||||
@Module({
|
||||
providers: [KyselyReadService, KyselyWriteService],
|
||||
exports: [KyselyReadService, KyselyWriteService],
|
||||
})
|
||||
export class KyselyModule {}
|
||||
@@ -9563,7 +9563,7 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"/v2/organizations/{orgId}/teams/{teamId}/verified-resources/phone-numbers": {
|
||||
"/v2/organizations/{orgId}/teams/{teamId}/verified-resources/phones": {
|
||||
"get": {
|
||||
"operationId": "OrgTeamsVerifiedResourcesController_getVerifiedPhoneNumbers",
|
||||
"summary": "Get list of verified phone numbers of an org team.",
|
||||
@@ -9671,7 +9671,7 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"/v2/organizations/{orgId}/teams/{teamId}/verified-resources/phone-numbers/{id}": {
|
||||
"/v2/organizations/{orgId}/teams/{teamId}/verified-resources/phones/{id}": {
|
||||
"get": {
|
||||
"operationId": "OrgTeamsVerifiedResourcesController_getVerifiedPhoneById",
|
||||
"summary": "Get verified phone number of an org team by id.",
|
||||
@@ -11855,7 +11855,7 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"/v2/teams/{teamId}/verified-resources/phone-numbers": {
|
||||
"/v2/teams/{teamId}/verified-resources/phones": {
|
||||
"get": {
|
||||
"operationId": "TeamsVerifiedResourcesController_getVerifiedPhoneNumbers",
|
||||
"summary": "Get list of verified phone numbers of a team.",
|
||||
@@ -11963,7 +11963,7 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"/v2/teams/{teamId}/verified-resources/phone-numbers/{id}": {
|
||||
"/v2/teams/{teamId}/verified-resources/phones/{id}": {
|
||||
"get": {
|
||||
"operationId": "TeamsVerifiedResourcesController_getVerifiedPhoneById",
|
||||
"summary": "Get verified phone number of a team by id.",
|
||||
@@ -12235,7 +12235,7 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"/v2/verified-resources/phone-numbers": {
|
||||
"/v2/verified-resources/phones": {
|
||||
"get": {
|
||||
"operationId": "UserVerifiedResourcesController_getVerifiedPhoneNumbers",
|
||||
"summary": "Get list of verified phone numbers.",
|
||||
@@ -12327,7 +12327,7 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"/v2/verified-resources/phone-numbers/{id}": {
|
||||
"/v2/verified-resources/phones/{id}": {
|
||||
"get": {
|
||||
"operationId": "UserVerifiedResourcesController_getVerifiedPhoneById",
|
||||
"summary": "Get verified phone number by id.",
|
||||
|
||||
@@ -9110,7 +9110,7 @@
|
||||
"tags": ["Organization Team Verified Resources"]
|
||||
}
|
||||
},
|
||||
"/v2/organizations/{orgId}/teams/{teamId}/verified-resources/phone-numbers": {
|
||||
"/v2/organizations/{orgId}/teams/{teamId}/verified-resources/phones": {
|
||||
"get": {
|
||||
"operationId": "OrgTeamsVerifiedResourcesController_getVerifiedPhoneNumbers",
|
||||
"summary": "Get list of verified phone numbers of an org team.",
|
||||
@@ -9214,7 +9214,7 @@
|
||||
"tags": ["Organization Team Verified Resources"]
|
||||
}
|
||||
},
|
||||
"/v2/organizations/{orgId}/teams/{teamId}/verified-resources/phone-numbers/{id}": {
|
||||
"/v2/organizations/{orgId}/teams/{teamId}/verified-resources/phones/{id}": {
|
||||
"get": {
|
||||
"operationId": "OrgTeamsVerifiedResourcesController_getVerifiedPhoneById",
|
||||
"summary": "Get verified phone number of an org team by id.",
|
||||
@@ -11311,7 +11311,7 @@
|
||||
"tags": ["Teams Verified Resources"]
|
||||
}
|
||||
},
|
||||
"/v2/teams/{teamId}/verified-resources/phone-numbers": {
|
||||
"/v2/teams/{teamId}/verified-resources/phones": {
|
||||
"get": {
|
||||
"operationId": "TeamsVerifiedResourcesController_getVerifiedPhoneNumbers",
|
||||
"summary": "Get list of verified phone numbers of a team.",
|
||||
@@ -11415,7 +11415,7 @@
|
||||
"tags": ["Teams Verified Resources"]
|
||||
}
|
||||
},
|
||||
"/v2/teams/{teamId}/verified-resources/phone-numbers/{id}": {
|
||||
"/v2/teams/{teamId}/verified-resources/phones/{id}": {
|
||||
"get": {
|
||||
"operationId": "TeamsVerifiedResourcesController_getVerifiedPhoneById",
|
||||
"summary": "Get verified phone number of a team by id.",
|
||||
@@ -11675,7 +11675,7 @@
|
||||
"tags": ["Verified Resources"]
|
||||
}
|
||||
},
|
||||
"/v2/verified-resources/phone-numbers": {
|
||||
"/v2/verified-resources/phones": {
|
||||
"get": {
|
||||
"operationId": "UserVerifiedResourcesController_getVerifiedPhoneNumbers",
|
||||
"summary": "Get list of verified phone numbers.",
|
||||
@@ -11763,7 +11763,7 @@
|
||||
"tags": ["Verified Resources"]
|
||||
}
|
||||
},
|
||||
"/v2/verified-resources/phone-numbers/{id}": {
|
||||
"/v2/verified-resources/phones/{id}": {
|
||||
"get": {
|
||||
"operationId": "UserVerifiedResourcesController_getVerifiedPhoneById",
|
||||
"summary": "Get verified phone number by id.",
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# Generated dynamically based on Prisma schema
|
||||
types.ts
|
||||
@@ -0,0 +1 @@
|
||||
# kysely
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Kysely, ParseJSONResultsPlugin, PostgresDialect, DeduplicateJoinsPlugin } from "kysely";
|
||||
import { Pool } from "pg";
|
||||
|
||||
import type { DB, Booking } from "./types";
|
||||
|
||||
export type { DB, Booking };
|
||||
|
||||
const connectionString = process.env.DATABASE_URL ?? "postgresql://postgres:@localhost:5450/calendso";
|
||||
|
||||
const pool = new Pool({ connectionString });
|
||||
|
||||
// 3. Create the Dialect, passing the configured pool instance
|
||||
const dialect = new PostgresDialect({
|
||||
pool: pool, // Use the pool instance created above
|
||||
});
|
||||
|
||||
// 4. Create the Kysely instance as before
|
||||
const db = new Kysely<DB>({
|
||||
dialect,
|
||||
plugins: [new ParseJSONResultsPlugin(), new DeduplicateJoinsPlugin()],
|
||||
});
|
||||
|
||||
export default db;
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "@calcom/kysely",
|
||||
"private": true,
|
||||
"main": "index.ts",
|
||||
"dependencies": {
|
||||
"kysely": "^0.28.2",
|
||||
"pg": "^8.11.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/pg": "^8.10.7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { ExpressionBuilder, StringReference } from "kysely";
|
||||
import { sql } from "kysely";
|
||||
|
||||
export function traverseJSON<DB, TB extends keyof DB>(
|
||||
eb: ExpressionBuilder<DB, TB>,
|
||||
column: StringReference<DB, TB>,
|
||||
path: string | [string, ...string[]]
|
||||
) {
|
||||
if (!Array.isArray(path)) {
|
||||
path = [path];
|
||||
}
|
||||
|
||||
return sql`${sql.ref(column)}->${sql.raw(path.map((item) => `'${item}'`).join("->"))}`;
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
import type { Kysely } from "kysely";
|
||||
|
||||
import type { TextFilterValue } from "@calcom/features/data-table/lib/types";
|
||||
import type { DB } from "@calcom/kysely";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
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 = {
|
||||
export type SortOptions = {
|
||||
sortStart?: "asc" | "desc";
|
||||
sortEnd?: "asc" | "desc";
|
||||
sortCreated?: "asc" | "desc";
|
||||
@@ -15,6 +16,7 @@ type GetOptions = {
|
||||
ctx: {
|
||||
user: { id: number; email: string; orgId?: number | null };
|
||||
prisma: PrismaClient;
|
||||
kysely: Kysely<DB>;
|
||||
};
|
||||
bookingListingByStatus: InputByStatus[];
|
||||
take: number;
|
||||
@@ -31,59 +33,15 @@ type GetOptions = {
|
||||
};
|
||||
|
||||
const getAllUserBookings = async ({ ctx, filters, bookingListingByStatus, take, skip, sort }: GetOptions) => {
|
||||
const { prisma, user } = ctx;
|
||||
const { prisma, user, kysely } = ctx;
|
||||
|
||||
const bookingListingFilters: Record<InputByStatus, Prisma.BookingWhereInput> = {
|
||||
upcoming: {
|
||||
endTime: { gte: new Date() },
|
||||
// These changes are needed to not show confirmed recurring events,
|
||||
// as rescheduling or cancel for recurring event bookings should be
|
||||
// handled separately for each occurrence
|
||||
OR: [
|
||||
{
|
||||
recurringEventId: { not: null },
|
||||
status: { equals: BookingStatus.ACCEPTED },
|
||||
},
|
||||
{
|
||||
recurringEventId: { equals: null },
|
||||
status: { notIn: [BookingStatus.CANCELLED, BookingStatus.REJECTED] },
|
||||
},
|
||||
],
|
||||
},
|
||||
recurring: {
|
||||
endTime: { gte: new Date() },
|
||||
AND: [
|
||||
{ NOT: { recurringEventId: { equals: null } } },
|
||||
{ status: { notIn: [BookingStatus.CANCELLED, BookingStatus.REJECTED] } },
|
||||
],
|
||||
},
|
||||
past: {
|
||||
endTime: { lte: new Date() },
|
||||
AND: [
|
||||
{ NOT: { status: { equals: BookingStatus.CANCELLED } } },
|
||||
{ NOT: { status: { equals: BookingStatus.REJECTED } } },
|
||||
],
|
||||
},
|
||||
cancelled: {
|
||||
OR: [{ status: { equals: BookingStatus.CANCELLED } }, { status: { equals: BookingStatus.REJECTED } }],
|
||||
},
|
||||
unconfirmed: {
|
||||
endTime: { gte: new Date() },
|
||||
status: { equals: BookingStatus.PENDING },
|
||||
},
|
||||
};
|
||||
|
||||
const orderBy = getOrderBy(bookingListingByStatus, sort);
|
||||
|
||||
const combinedFilters = bookingListingByStatus.map((status) => bookingListingFilters[status]);
|
||||
const { bookings, recurringInfo, totalCount } = await getBookings({
|
||||
user,
|
||||
prisma,
|
||||
passedBookingsStatusFilter: {
|
||||
OR: combinedFilters,
|
||||
},
|
||||
kysely,
|
||||
bookingListingByStatus,
|
||||
filters: filters,
|
||||
orderBy,
|
||||
sort,
|
||||
take,
|
||||
skip,
|
||||
});
|
||||
@@ -95,36 +53,4 @@ 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 };
|
||||
}
|
||||
if (sort?.sortUpdated) {
|
||||
return { updatedAt: sort.sortUpdated };
|
||||
}
|
||||
|
||||
return { startTime: "asc" };
|
||||
}
|
||||
|
||||
export default getAllUserBookings;
|
||||
@@ -30,6 +30,7 @@
|
||||
"@prisma/extension-accelerate": "^0.6.2",
|
||||
"@prisma/generator-helper": "^5.4.2",
|
||||
"prisma": "^5.4.2",
|
||||
"prisma-kysely": "^1.7.1",
|
||||
"ts-node": "^10.9.1",
|
||||
"zod": "^3.22.4",
|
||||
"zod-prisma": "^0.5.4"
|
||||
|
||||
@@ -19,6 +19,12 @@ generator zod {
|
||||
relationModel = "default"
|
||||
}
|
||||
|
||||
generator kysely {
|
||||
provider = "prisma-kysely"
|
||||
output = "../kysely"
|
||||
fileName = "types.ts"
|
||||
}
|
||||
|
||||
generator enums {
|
||||
provider = "ts-node --transpile-only ./enum-generator"
|
||||
}
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
import { Prisma as PrismaClientType } from "@prisma/client";
|
||||
import type { Booking, Prisma, Prisma as PrismaClientType } from "@prisma/client";
|
||||
import type { Kysely } from "kysely";
|
||||
import { DeduplicateJoinsPlugin, type SelectQueryBuilder } from "kysely";
|
||||
import { jsonObjectFrom, jsonArrayFrom } from "kysely/helpers/postgres";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { makeWhereClause } from "@calcom/features/data-table/lib/server";
|
||||
import { isTextFilterValue } from "@calcom/features/data-table/lib/utils";
|
||||
import type { DB } from "@calcom/kysely";
|
||||
import kysely from "@calcom/kysely";
|
||||
import { parseRecurringEvent, parseEventTypeColor } from "@calcom/lib";
|
||||
import getAllUserBookings from "@calcom/lib/bookings/getAllUserBookings";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import { bookingMinimalSelect } from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import { type BookingStatus } from "@calcom/prisma/enums";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
import { BookingStatus } from "@calcom/prisma/enums";
|
||||
import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
@@ -26,6 +29,8 @@ type GetOptions = {
|
||||
input: TGetInputSchema;
|
||||
};
|
||||
|
||||
type InputByStatus = "upcoming" | "recurring" | "past" | "cancelled" | "unconfirmed";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["bookings.get"] });
|
||||
|
||||
export const getHandler = async ({ ctx, input }: GetOptions) => {
|
||||
@@ -41,6 +46,7 @@ export const getHandler = async ({ ctx, input }: GetOptions) => {
|
||||
ctx: {
|
||||
user: { id: user.id, email: user.email, orgId: user?.profile?.organizationId },
|
||||
prisma: prisma,
|
||||
kysely: kysely,
|
||||
},
|
||||
bookingListingByStatus: bookingListingByStatus,
|
||||
take,
|
||||
@@ -55,110 +61,36 @@ export const getHandler = async ({ ctx, input }: GetOptions) => {
|
||||
};
|
||||
};
|
||||
|
||||
type BookingsUnionQuery = SelectQueryBuilder<
|
||||
DB,
|
||||
"Booking",
|
||||
Pick<Booking, "id" | "createdAt" | "updatedAt" | "startTime" | "endTime">
|
||||
>;
|
||||
|
||||
export async function getBookings({
|
||||
user,
|
||||
prisma,
|
||||
passedBookingsStatusFilter,
|
||||
kysely,
|
||||
bookingListingByStatus,
|
||||
sort,
|
||||
filters,
|
||||
orderBy,
|
||||
take,
|
||||
skip,
|
||||
}: {
|
||||
user: { id: number; email: string; orgId?: number | null };
|
||||
filters: TGetInputSchema["filters"];
|
||||
prisma: PrismaClient;
|
||||
passedBookingsStatusFilter: Prisma.BookingWhereInput;
|
||||
orderBy: Prisma.BookingOrderByWithAggregationInput;
|
||||
kysely: Kysely<DB>;
|
||||
bookingListingByStatus: InputByStatus[];
|
||||
sort?: {
|
||||
sortStart?: "asc" | "desc";
|
||||
sortEnd?: "asc" | "desc";
|
||||
sortCreated?: "asc" | "desc";
|
||||
sortUpdated?: "asc" | "desc";
|
||||
};
|
||||
take: number;
|
||||
skip: number;
|
||||
}) {
|
||||
const bookingSelect = {
|
||||
...bookingMinimalSelect,
|
||||
uid: true,
|
||||
responses: true,
|
||||
/**
|
||||
* Who uses it -
|
||||
* 1. We need to be able to decide which booking can have a 'Reroute' action
|
||||
*/
|
||||
routedFromRoutingFormReponse: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
recurringEventId: true,
|
||||
location: true,
|
||||
eventType: {
|
||||
select: {
|
||||
slug: true,
|
||||
id: true,
|
||||
title: true,
|
||||
eventName: true,
|
||||
price: true,
|
||||
recurringEvent: true,
|
||||
currency: true,
|
||||
metadata: true,
|
||||
disableGuests: true,
|
||||
seatsShowAttendees: true,
|
||||
seatsShowAvailabilityCount: true,
|
||||
eventTypeColor: true,
|
||||
customReplyToEmail: true,
|
||||
allowReschedulingPastBookings: true,
|
||||
hideOrganizerEmail: true,
|
||||
disableCancelling: true,
|
||||
disableRescheduling: true,
|
||||
schedulingType: true,
|
||||
length: true,
|
||||
team: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
status: true,
|
||||
paid: true,
|
||||
payment: {
|
||||
select: {
|
||||
paymentOption: true,
|
||||
amount: true,
|
||||
currency: true,
|
||||
success: true,
|
||||
},
|
||||
},
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
fromReschedule: true,
|
||||
rescheduled: true,
|
||||
references: true,
|
||||
isRecorded: true,
|
||||
seatsReferences: {
|
||||
where: {
|
||||
attendee: {
|
||||
email: user.email,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
referenceUid: true,
|
||||
attendee: {
|
||||
select: {
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
assignmentReason: {
|
||||
orderBy: { createdAt: PrismaClientType.SortOrder.desc },
|
||||
take: 1,
|
||||
},
|
||||
};
|
||||
|
||||
const membershipIdsWhereUserIsAdminOwner = (
|
||||
await prisma.membership.findMany({
|
||||
where: {
|
||||
@@ -193,11 +125,12 @@ export async function getBookings({
|
||||
getUserIdsAndEmailsWhereUserIsAdminOrOwner(prisma, membershipConditionWhereUserIsAdminOwner, user.orgId),
|
||||
]);
|
||||
|
||||
const bookingQueries: BookingsUnionQuery[] = [];
|
||||
|
||||
// If user is organization owner/admin, contains organization members emails and ids (organization plan)
|
||||
// If user is only team owner/admin, contain team members emails and ids (teams plan)
|
||||
const [userIdsWhereUserIsAdminOrOwner, userEmailsWhereUserIsAdminOrOwner] =
|
||||
userIdsAndEmailsWhereUserIsAdminOrOwner;
|
||||
const orConditions = [];
|
||||
|
||||
// If userIds filter is provided
|
||||
if (!!filters?.userIds && filters.userIds.length > 0) {
|
||||
@@ -215,165 +148,402 @@ export async function getBookings({
|
||||
});
|
||||
}
|
||||
|
||||
// Filtered view: Booking must match one of the specified users or their attendees
|
||||
const usersFilter = { in: [...filters.userIds] };
|
||||
const attendeesEmailFilter = { in: attendeeEmailsFromUserIdsFilter };
|
||||
|
||||
// 1. Booking created by one of the filtered users
|
||||
orConditions.push({ userId: usersFilter });
|
||||
// 2. Attendee email matches one of the filtered users' emails
|
||||
orConditions.push({ attendees: { some: { email: attendeesEmailFilter } } });
|
||||
// 3. Seat reference attendee email matches one of the filtered users' emails
|
||||
orConditions.push({ seatsReferences: { some: { attendee: { email: attendeesEmailFilter } } } });
|
||||
} else {
|
||||
// Filter by emails for auth user.
|
||||
const userEmailFilter = { equals: user.email };
|
||||
// Auth user is ORG_OWNER/ADMIN or TEAM_OWNER/ADMIN, filter by emails of members of the organization or team
|
||||
const userEmailsFilterWhereUserIsOrgAdminOrOwner = userEmailsWhereUserIsAdminOrOwner?.length
|
||||
? { in: userEmailsWhereUserIsAdminOrOwner }
|
||||
: undefined;
|
||||
bookingQueries.push(
|
||||
kysely
|
||||
.selectFrom("Booking")
|
||||
.select("Booking.id")
|
||||
.select("Booking.startTime")
|
||||
.select("Booking.endTime")
|
||||
.select("Booking.createdAt")
|
||||
.select("Booking.updatedAt")
|
||||
.where("userId", "in", filters.userIds)
|
||||
);
|
||||
|
||||
// 2. Attendee email matches one of the filtered users' emails
|
||||
if (attendeeEmailsFromUserIdsFilter?.length) {
|
||||
bookingQueries.push(
|
||||
kysely
|
||||
.selectFrom("Booking")
|
||||
.select("Booking.id")
|
||||
.select("Booking.startTime")
|
||||
.select("Booking.endTime")
|
||||
.select("Booking.createdAt")
|
||||
.select("Booking.updatedAt")
|
||||
.innerJoin("Attendee", "Attendee.bookingId", "Booking.id")
|
||||
.where("Attendee.email", "in", attendeeEmailsFromUserIdsFilter)
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Seat reference attendee email matches one of the filtered users' emails
|
||||
if (attendeeEmailsFromUserIdsFilter?.length) {
|
||||
bookingQueries.push(
|
||||
kysely
|
||||
.selectFrom("Booking")
|
||||
.select("Booking.id")
|
||||
.select("Booking.startTime")
|
||||
.select("Booking.endTime")
|
||||
.select("Booking.createdAt")
|
||||
.select("Booking.updatedAt")
|
||||
.innerJoin("Attendee", "Attendee.bookingId", "Booking.id")
|
||||
.innerJoin("BookingSeat", "Attendee.id", "BookingSeat.attendeeId")
|
||||
.where("Attendee.email", "in", attendeeEmailsFromUserIdsFilter)
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// 1. Current user created bookings
|
||||
orConditions.push({ userId: { equals: user.id } });
|
||||
bookingQueries.push(
|
||||
kysely
|
||||
.selectFrom("Booking")
|
||||
.select("Booking.id")
|
||||
.select("Booking.startTime")
|
||||
.select("Booking.endTime")
|
||||
.select("Booking.createdAt")
|
||||
.select("Booking.updatedAt")
|
||||
.where("Booking.userId", "=", user.id)
|
||||
);
|
||||
// 2. Current user is an attendee
|
||||
orConditions.push({ attendees: { some: { email: userEmailFilter } } });
|
||||
bookingQueries.push(
|
||||
kysely
|
||||
.selectFrom("Booking")
|
||||
.select("Booking.id")
|
||||
.select("Booking.startTime")
|
||||
.select("Booking.endTime")
|
||||
.select("Booking.createdAt")
|
||||
.select("Booking.updatedAt")
|
||||
.innerJoin("Attendee", "Attendee.bookingId", "Booking.id")
|
||||
.where("Attendee.email", "=", user.email)
|
||||
);
|
||||
// 3. Current user is an attendee via seats reference
|
||||
orConditions.push({ seatsReferences: { some: { attendee: { email: userEmailFilter } } } });
|
||||
bookingQueries.push(
|
||||
kysely
|
||||
.selectFrom("Booking")
|
||||
.select("Booking.id")
|
||||
.select("Booking.startTime")
|
||||
.select("Booking.endTime")
|
||||
.select("Booking.createdAt")
|
||||
.select("Booking.updatedAt")
|
||||
.innerJoin("BookingSeat", "BookingSeat.bookingId", "Booking.id")
|
||||
.innerJoin("Attendee", "Attendee.bookingId", "Booking.id")
|
||||
.where("Attendee.email", "=", user.email)
|
||||
);
|
||||
// 4. Scope depends on `user.orgId`:
|
||||
// - If Current user is ORG_OWNER/ADMIN so we get bookings where organization members are attendees
|
||||
// - If Current user is TEAM_OWNER/ADMIN so we get bookings where team members are attendees
|
||||
userEmailsFilterWhereUserIsOrgAdminOrOwner &&
|
||||
orConditions.push({ attendees: { some: { email: userEmailsFilterWhereUserIsOrgAdminOrOwner } } });
|
||||
userEmailsWhereUserIsAdminOrOwner?.length &&
|
||||
bookingQueries.push(
|
||||
kysely
|
||||
.selectFrom("Booking")
|
||||
.select("Booking.id")
|
||||
.select("Booking.startTime")
|
||||
.select("Booking.endTime")
|
||||
.select("Booking.createdAt")
|
||||
.select("Booking.updatedAt")
|
||||
.innerJoin("Attendee", "Attendee.bookingId", "Booking.id")
|
||||
.where("Attendee.email", "in", userEmailsWhereUserIsAdminOrOwner)
|
||||
);
|
||||
// 5. Scope depends on `user.orgId`:
|
||||
// - If Current user is ORG_OWNER/ADMIN so we get bookings where organization members are attendees via seatsReference
|
||||
// - If Current user is TEAM_OWNER/ADMIN so we get bookings where team members are attendees via seatsReference
|
||||
userEmailsFilterWhereUserIsOrgAdminOrOwner &&
|
||||
orConditions.push({
|
||||
seatsReferences: { some: { attendee: { email: userEmailsFilterWhereUserIsOrgAdminOrOwner } } },
|
||||
});
|
||||
userEmailsWhereUserIsAdminOrOwner?.length &&
|
||||
bookingQueries.push(
|
||||
kysely
|
||||
.selectFrom("Booking")
|
||||
.select("Booking.id")
|
||||
.select("Booking.startTime")
|
||||
.select("Booking.endTime")
|
||||
.select("Booking.createdAt")
|
||||
.select("Booking.updatedAt")
|
||||
.innerJoin("Attendee", "Attendee.bookingId", "Booking.id")
|
||||
.innerJoin("BookingSeat", "Attendee.id", "BookingSeat.attendeeId")
|
||||
.where("Attendee.email", "in", userEmailsWhereUserIsAdminOrOwner)
|
||||
);
|
||||
|
||||
// 6. Scope depends on `user.orgId`:
|
||||
// - If Current user is ORG_OWNER/ADMIN, get booking created for an event type within the organization
|
||||
// - If Current user is TEAM_OWNER/ADMIN, get bookings created for an event type within the team
|
||||
eventTypeIdsWhereUserIsAdminOrOwner?.length &&
|
||||
orConditions.push({ eventTypeId: { in: eventTypeIdsWhereUserIsAdminOrOwner } });
|
||||
bookingQueries.push(
|
||||
kysely
|
||||
.selectFrom("Booking")
|
||||
.select("Booking.id")
|
||||
.select("Booking.startTime")
|
||||
.select("Booking.endTime")
|
||||
.select("Booking.createdAt")
|
||||
.select("Booking.updatedAt")
|
||||
.innerJoin("EventType", "EventType.id", "Booking.eventTypeId")
|
||||
.where("Booking.eventTypeId", "in", eventTypeIdsWhereUserIsAdminOrOwner)
|
||||
);
|
||||
|
||||
// 7. Scope depends on `user.orgId`:
|
||||
// - If Current user is ORG_OWNER/ADMIN, get bookings created by users within the same organization
|
||||
// - If Current user is TEAM_OWNER/ADMIN, get bookings created by users within the same organization
|
||||
userIdsWhereUserIsAdminOrOwner?.length &&
|
||||
orConditions.push({ userId: { in: userIdsWhereUserIsAdminOrOwner } });
|
||||
bookingQueries.push(
|
||||
kysely
|
||||
.selectFrom("Booking")
|
||||
.select("Booking.id")
|
||||
.select("Booking.startTime")
|
||||
.select("Booking.endTime")
|
||||
.select("Booking.createdAt")
|
||||
.select("Booking.updatedAt")
|
||||
.where("Booking.userId", "in", userIdsWhereUserIsAdminOrOwner)
|
||||
);
|
||||
}
|
||||
|
||||
const andConditions = [];
|
||||
const queriesWithFilters = bookingQueries.map((query) => {
|
||||
// 1. Apply mandatory status filter
|
||||
let fullQuery = addStatusesQueryFilters(query, bookingListingByStatus);
|
||||
|
||||
// 1. Apply mandatory status filter
|
||||
andConditions.push(passedBookingsStatusFilter);
|
||||
|
||||
// 2. Filter by Event Type IDs derived from Team IDs (if provided)
|
||||
if (eventTypeIdsFromTeamIdsFilter && eventTypeIdsFromTeamIdsFilter.length > 0) {
|
||||
andConditions.push({ eventTypeId: { in: eventTypeIdsFromTeamIdsFilter } });
|
||||
}
|
||||
|
||||
// 3. Filter by specific Event Type IDs (if provided)
|
||||
// If both teamIds filter and eventTypeIds filter are provided, filter 2. ensures the event-types are within the teams
|
||||
if (eventTypeIdsFromEventTypeIdsFilter && eventTypeIdsFromEventTypeIdsFilter.length > 0) {
|
||||
andConditions.push({ eventTypeId: { in: eventTypeIdsFromEventTypeIdsFilter } });
|
||||
}
|
||||
|
||||
// 4. Filter by Attendee Email (if provided)
|
||||
if (filters?.attendeeEmail) {
|
||||
if (typeof filters.attendeeEmail === "string") {
|
||||
// Simple string match (exact)
|
||||
andConditions.push({ attendees: { some: { email: filters.attendeeEmail.trim() } } });
|
||||
} else if (isTextFilterValue(filters.attendeeEmail)) {
|
||||
// Complex text filter (contains, startsWith, etc.) using makeWhereClause
|
||||
andConditions.push({
|
||||
attendees: {
|
||||
some: makeWhereClause({
|
||||
columnName: "email",
|
||||
filterValue: filters.attendeeEmail,
|
||||
}),
|
||||
},
|
||||
});
|
||||
// 2. Filter by Event Type IDs derived from Team IDs (if provided)
|
||||
if (eventTypeIdsFromTeamIdsFilter && eventTypeIdsFromTeamIdsFilter.length > 0) {
|
||||
fullQuery = fullQuery.where("Booking.eventTypeId", "in", eventTypeIdsFromTeamIdsFilter);
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Filter by Attendee Name (if provided)
|
||||
if (filters?.attendeeName) {
|
||||
if (typeof filters.attendeeName === "string") {
|
||||
// Simple string match (exact)
|
||||
andConditions.push({ attendees: { some: { name: filters.attendeeName.trim() } } });
|
||||
} else if (isTextFilterValue(filters.attendeeName)) {
|
||||
// Complex text filter (contains, startsWith, etc.) using makeWhereClause
|
||||
andConditions.push({
|
||||
attendees: {
|
||||
some: makeWhereClause({
|
||||
columnName: "name",
|
||||
filterValue: filters.attendeeName,
|
||||
}),
|
||||
},
|
||||
});
|
||||
// 3. Filter by specific Event Type IDs (if provided)
|
||||
// If both teamIds filter and eventTypeIds filter are provided, filter 2. ensures the event-types are within the teams
|
||||
if (eventTypeIdsFromEventTypeIdsFilter && eventTypeIdsFromEventTypeIdsFilter.length > 0) {
|
||||
fullQuery = fullQuery.where("Booking.eventTypeId", "in", eventTypeIdsFromEventTypeIdsFilter);
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Date Range Filters
|
||||
if (filters?.afterStartDate) {
|
||||
andConditions.push({ startTime: { gte: dayjs.utc(filters.afterStartDate).toDate() } });
|
||||
}
|
||||
if (filters?.beforeEndDate) {
|
||||
andConditions.push({ endTime: { lte: dayjs.utc(filters.beforeEndDate).toDate() } });
|
||||
}
|
||||
if (filters?.afterUpdatedDate) {
|
||||
andConditions.push({ updatedAt: { gte: dayjs.utc(filters.afterUpdatedDate).toDate() } });
|
||||
}
|
||||
if (filters?.beforeUpdatedDate) {
|
||||
andConditions.push({ updatedAt: { lte: dayjs.utc(filters.beforeUpdatedDate).toDate() } });
|
||||
}
|
||||
if (filters?.afterCreatedDate) {
|
||||
andConditions.push({ createdAt: { gte: dayjs.utc(filters.afterCreatedDate).toDate() } });
|
||||
}
|
||||
if (filters?.beforeCreatedDate) {
|
||||
andConditions.push({ createdAt: { lte: dayjs.utc(filters.beforeCreatedDate).toDate() } });
|
||||
}
|
||||
|
||||
// All the possible date filter keys
|
||||
const dateFilterKeys = [
|
||||
"afterStartDate",
|
||||
"beforeEndDate",
|
||||
"afterUpdatedDate",
|
||||
"beforeUpdatedDate",
|
||||
"afterCreatedDate",
|
||||
"beforeCreatedDate",
|
||||
] as const;
|
||||
|
||||
const hasAnyDateFilter = dateFilterKeys.some((key) => filters?.[key]);
|
||||
|
||||
if (!hasAnyDateFilter) {
|
||||
// is ORG/TEAM admin/owner
|
||||
if (userIdsWhereUserIsAdminOrOwner?.length || userEmailsWhereUserIsAdminOrOwner?.length) {
|
||||
const oneMonthAgo = dayjs.utc().subtract(1, "month").startOf("day").toDate();
|
||||
andConditions.push({ startTime: { gte: oneMonthAgo } });
|
||||
// 4. Filter by Attendee Name (if provided)
|
||||
if (filters?.attendeeName) {
|
||||
if (typeof filters.attendeeName === "string") {
|
||||
// Simple string match (exact)
|
||||
fullQuery = fullQuery
|
||||
.innerJoin("Attendee", "Attendee.bookingId", "Booking.id")
|
||||
.where("Attendee.name", "=", filters.attendeeName.trim());
|
||||
} else if (isTextFilterValue(filters.attendeeName)) {
|
||||
// TODO: write makeWhereClause equivalent for kysely
|
||||
fullQuery = addAdvancedAttendeeWhereClause(
|
||||
fullQuery,
|
||||
"name",
|
||||
filters.attendeeName.data.operator,
|
||||
filters.attendeeName.data.operand
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const whereClause = {
|
||||
OR: orConditions,
|
||||
AND: andConditions,
|
||||
};
|
||||
// 5. Filter by Attendee Email (if provided)
|
||||
if (filters?.attendeeEmail) {
|
||||
if (typeof filters.attendeeEmail === "string") {
|
||||
// Simple string match (exact)
|
||||
fullQuery = fullQuery
|
||||
.withPlugin(new DeduplicateJoinsPlugin())
|
||||
.innerJoin("Attendee", "Attendee.bookingId", "Booking.id")
|
||||
.where("Attendee.email", "=", filters.attendeeEmail.trim());
|
||||
} else if (isTextFilterValue(filters.attendeeEmail)) {
|
||||
// TODO: write makeWhereClause equivalent for kysely
|
||||
fullQuery = addAdvancedAttendeeWhereClause(
|
||||
fullQuery.withPlugin(new DeduplicateJoinsPlugin()),
|
||||
"email",
|
||||
filters.attendeeEmail.data.operator,
|
||||
filters.attendeeEmail.data.operand
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
log.info(`Get bookings where clause for user ${user.id}`, JSON.stringify(whereClause));
|
||||
// 6. Booking Start/End Time Range Filters
|
||||
if (filters?.afterStartDate) {
|
||||
fullQuery = fullQuery.where("Booking.startTime", ">=", dayjs.utc(filters.afterStartDate).toDate());
|
||||
}
|
||||
if (filters?.beforeEndDate) {
|
||||
fullQuery = fullQuery.where("Booking.endTime", "<=", dayjs.utc(filters.beforeEndDate).toDate());
|
||||
}
|
||||
|
||||
const [plainBookings, totalCount] = await Promise.all([
|
||||
prisma.booking.findMany({
|
||||
where: whereClause,
|
||||
select: bookingSelect,
|
||||
orderBy,
|
||||
take,
|
||||
skip,
|
||||
}),
|
||||
prisma.booking.count({
|
||||
where: whereClause,
|
||||
}),
|
||||
]);
|
||||
return fullQuery;
|
||||
});
|
||||
|
||||
const queryUnion = queriesWithFilters.reduce((acc, query) => {
|
||||
return acc.union(query);
|
||||
});
|
||||
|
||||
const orderBy = getOrderBy(bookingListingByStatus, sort);
|
||||
|
||||
const getBookingsUnionCompiled = kysely
|
||||
.selectFrom(queryUnion.as("union_subquery"))
|
||||
.selectAll("union_subquery")
|
||||
.$if(Boolean(filters?.afterUpdatedDate), (eb) =>
|
||||
eb.where("union_subquery.updatedAt", ">=", dayjs.utc(filters.afterUpdatedDate).toDate())
|
||||
)
|
||||
.$if(Boolean(filters?.beforeUpdatedDate), (eb) =>
|
||||
eb.where("union_subquery.updatedAt", "<=", dayjs.utc(filters.beforeUpdatedDate).toDate())
|
||||
)
|
||||
.$if(Boolean(filters?.afterCreatedDate), (eb) =>
|
||||
eb.where("union_subquery.createdAt", ">=", dayjs.utc(filters.afterCreatedDate).toDate())
|
||||
)
|
||||
.$if(Boolean(filters?.beforeCreatedDate), (eb) =>
|
||||
eb.where("union_subquery.createdAt", "<=", dayjs.utc(filters.beforeCreatedDate).toDate())
|
||||
)
|
||||
.orderBy(orderBy.key, orderBy.order)
|
||||
.limit(take)
|
||||
.offset(skip)
|
||||
.compile();
|
||||
|
||||
const bookingsFromUnion = (await kysely.executeQuery(getBookingsUnionCompiled)).rows;
|
||||
|
||||
log.debug(`Get bookings for user ${user.id} SQL:`, getBookingsUnionCompiled.sql);
|
||||
const totalCount = Number(
|
||||
(
|
||||
await kysely
|
||||
.selectFrom(queryUnion.as("union_subquery"))
|
||||
.select(({ fn }) => fn.countAll().as("bookingCount"))
|
||||
.executeTakeFirst()
|
||||
)?.bookingCount ?? 0
|
||||
);
|
||||
|
||||
const plainBookings = !(bookingsFromUnion?.length === 0)
|
||||
? await kysely
|
||||
.selectFrom("Booking")
|
||||
.where(
|
||||
"id",
|
||||
"in",
|
||||
bookingsFromUnion.map((booking) => booking.id)
|
||||
)
|
||||
.select((eb) => [
|
||||
"Booking.id",
|
||||
"Booking.title",
|
||||
"Booking.userPrimaryEmail",
|
||||
"Booking.description",
|
||||
"Booking.customInputs",
|
||||
"Booking.startTime",
|
||||
"Booking.createdAt",
|
||||
"Booking.updatedAt",
|
||||
"Booking.endTime",
|
||||
"Booking.metadata",
|
||||
"Booking.uid",
|
||||
|
||||
eb
|
||||
.cast<Prisma.JsonValue>( // Target TypeScript type
|
||||
eb.ref("Booking.responses"), // Source column
|
||||
"jsonb" // Target SQL type
|
||||
)
|
||||
.as("responses"),
|
||||
"Booking.recurringEventId",
|
||||
"Booking.location",
|
||||
eb
|
||||
.cast<BookingStatus>(
|
||||
eb
|
||||
.case()
|
||||
.when("Booking.status", "=", "cancelled")
|
||||
.then(BookingStatus["CANCELLED"])
|
||||
.when("Booking.status", "=", "accepted")
|
||||
.then(BookingStatus["ACCEPTED"])
|
||||
.when("Booking.status", "=", "rejected")
|
||||
.then(BookingStatus["REJECTED"])
|
||||
.when("Booking.status", "=", "pending")
|
||||
.then(BookingStatus["PENDING"])
|
||||
.when("Booking.status", "=", "awaiting_host")
|
||||
.then(BookingStatus["AWAITING_HOST"])
|
||||
.else(BookingStatus["PENDING"])
|
||||
.end(), // End of CASE expression
|
||||
"varchar"
|
||||
)
|
||||
.as("status"),
|
||||
"Booking.paid",
|
||||
"Booking.fromReschedule",
|
||||
"Booking.rescheduled",
|
||||
"Booking.isRecorded",
|
||||
jsonObjectFrom(
|
||||
eb
|
||||
.selectFrom("App_RoutingForms_FormResponse")
|
||||
.select("id")
|
||||
.whereRef("App_RoutingForms_FormResponse.routedToBookingUid", "=", "Booking.uid")
|
||||
).as("routedFromRoutingFormReponse"),
|
||||
jsonObjectFrom(
|
||||
eb
|
||||
.selectFrom("EventType")
|
||||
.select((eb) => [
|
||||
"EventType.slug",
|
||||
"EventType.id",
|
||||
"EventType.title",
|
||||
"EventType.eventName",
|
||||
"EventType.price",
|
||||
"EventType.recurringEvent",
|
||||
"EventType.currency",
|
||||
"EventType.metadata",
|
||||
"EventType.disableGuests",
|
||||
"EventType.seatsShowAttendees",
|
||||
"EventType.seatsShowAvailabilityCount",
|
||||
"EventType.eventTypeColor",
|
||||
"EventType.customReplyToEmail",
|
||||
"EventType.allowReschedulingPastBookings",
|
||||
"EventType.hideOrganizerEmail",
|
||||
"EventType.disableCancelling",
|
||||
"EventType.disableRescheduling",
|
||||
eb
|
||||
.cast<SchedulingType>(
|
||||
eb
|
||||
.case()
|
||||
.when("EventType.schedulingType", "=", "roundRobin")
|
||||
.then(SchedulingType["ROUND_ROBIN"])
|
||||
.when("EventType.schedulingType", "=", "collective")
|
||||
.then(SchedulingType["COLLECTIVE"])
|
||||
.when("EventType.schedulingType", "=", "managed")
|
||||
.then(SchedulingType["MANAGED"])
|
||||
.else(SchedulingType["ROUND_ROBIN"]) // Ensure ELSE provides a value within SchedulingTypeLiteral for cast safety
|
||||
.end(),
|
||||
"varchar" // Or 'text' - use the actual SQL data type
|
||||
)
|
||||
.as("schedulingType"),
|
||||
"EventType.length",
|
||||
jsonObjectFrom(
|
||||
eb
|
||||
.selectFrom("Team")
|
||||
.select(["Team.id", "Team.name", "Team.slug"])
|
||||
.whereRef("EventType.teamId", "=", "Team.id")
|
||||
).as("team"),
|
||||
])
|
||||
.whereRef("EventType.id", "=", "Booking.eventTypeId")
|
||||
).as("eventType"),
|
||||
jsonArrayFrom(
|
||||
eb
|
||||
.selectFrom("BookingReference")
|
||||
.selectAll()
|
||||
.whereRef("BookingReference.bookingId", "=", "Booking.id")
|
||||
).as("references"),
|
||||
jsonArrayFrom(
|
||||
eb
|
||||
.selectFrom("Payment")
|
||||
.select(["Payment.paymentOption", "Payment.amount", "Payment.currency", "Payment.success"])
|
||||
.whereRef("Payment.bookingId", "=", "Booking.id")
|
||||
).as("payment"),
|
||||
jsonObjectFrom(
|
||||
eb
|
||||
.selectFrom("users")
|
||||
.select(["users.id", "users.name", "users.email"])
|
||||
.whereRef("Booking.userId", "=", "users.id")
|
||||
).as("user"),
|
||||
jsonArrayFrom(
|
||||
eb.selectFrom("Attendee").selectAll().whereRef("Attendee.bookingId", "=", "Booking.id")
|
||||
).as("attendees"),
|
||||
jsonArrayFrom(
|
||||
eb
|
||||
.selectFrom("BookingSeat")
|
||||
.select((eb) => [
|
||||
"BookingSeat.referenceUid",
|
||||
jsonObjectFrom(
|
||||
eb
|
||||
.selectFrom("Attendee")
|
||||
.select(["Attendee.email"])
|
||||
.whereRef("BookingSeat.attendeeId", "=", "Attendee.id")
|
||||
.where("Attendee.email", "=", user.email)
|
||||
).as("attendee"),
|
||||
])
|
||||
.whereRef("BookingSeat.bookingId", "=", "Booking.id")
|
||||
).as("seatsReferences"),
|
||||
jsonArrayFrom(
|
||||
eb
|
||||
.selectFrom("AssignmentReason")
|
||||
.selectAll()
|
||||
.whereRef("AssignmentReason.bookingId", "=", "Booking.id")
|
||||
.orderBy("AssignmentReason.createdAt", "desc")
|
||||
.limit(1)
|
||||
).as("assignmentReason"),
|
||||
])
|
||||
.orderBy(orderBy.key, orderBy.order)
|
||||
.execute()
|
||||
: [];
|
||||
|
||||
const [
|
||||
recurringInfoBasic,
|
||||
@@ -680,3 +850,150 @@ async function getUserIdsAndEmailsWhereUserIsAdminOrOwner(
|
||||
});
|
||||
return [users.map((user) => user.id), users.map((user) => user.email)];
|
||||
}
|
||||
|
||||
function addStatusesQueryFilters(query: BookingsUnionQuery, statuses: InputByStatus[]) {
|
||||
if (statuses?.length) {
|
||||
return query.where(({ eb, or, and }) =>
|
||||
or(
|
||||
statuses.map((status) => {
|
||||
if (status === "upcoming") {
|
||||
return and([
|
||||
eb("Booking.endTime", ">=", new Date()),
|
||||
or([
|
||||
and([eb("Booking.recurringEventId", "is not", null), eb("Booking.status", "=", "accepted")]),
|
||||
and([
|
||||
eb("Booking.recurringEventId", "is", null),
|
||||
eb("Booking.status", "not in", ["cancelled", "rejected"]),
|
||||
]),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
if (status === "recurring") {
|
||||
return and([
|
||||
eb("Booking.endTime", ">=", new Date()),
|
||||
eb("Booking.recurringEventId", "is not", null),
|
||||
eb("Booking.status", "not in", ["cancelled", "rejected"]),
|
||||
]);
|
||||
}
|
||||
|
||||
if (status === "past") {
|
||||
return and([
|
||||
eb("Booking.endTime", "<=", new Date()),
|
||||
eb("Booking.status", "not in", ["cancelled", "rejected"]),
|
||||
]);
|
||||
}
|
||||
|
||||
if (status === "cancelled") {
|
||||
return eb("Booking.status", "in", ["cancelled", "rejected"]);
|
||||
}
|
||||
|
||||
if (status === "unconfirmed") {
|
||||
return and([eb("Booking.endTime", ">=", new Date()), eb("Booking.status", "=", "pending")]);
|
||||
}
|
||||
return and([]);
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
function addAdvancedAttendeeWhereClause(
|
||||
query: BookingsUnionQuery,
|
||||
key: "name" | "email",
|
||||
operator:
|
||||
| "endsWith"
|
||||
| "startsWith"
|
||||
| "equals"
|
||||
| "notEquals"
|
||||
| "contains"
|
||||
| "notContains"
|
||||
| "isEmpty"
|
||||
| "isNotEmpty",
|
||||
operand: string
|
||||
) {
|
||||
switch (operator) {
|
||||
case "endsWith":
|
||||
query
|
||||
.innerJoin("Attendee", "Attendee.id", "Booking.id")
|
||||
.where(`Attendee.${key}`, "like", `%${operand}`);
|
||||
break;
|
||||
case "startsWith":
|
||||
query
|
||||
.innerJoin("Attendee", "Attendee.id", "Booking.id")
|
||||
.where(`Attendee.${key}`, "like", `${operand}%`);
|
||||
break;
|
||||
|
||||
case "equals":
|
||||
query.innerJoin("Attendee", "Attendee.id", "Booking.id").where(`Attendee.${key}`, "=", `${operand}`);
|
||||
break;
|
||||
|
||||
case "notEquals":
|
||||
query.innerJoin("Attendee", "Attendee.id", "Booking.id").where(`Attendee.${key}`, "!=", `${operand}`);
|
||||
break;
|
||||
|
||||
case "contains":
|
||||
query
|
||||
.innerJoin("Attendee", "Attendee.id", "Booking.id")
|
||||
.where(`Attendee.${key}`, "like", `%${operand}%`);
|
||||
break;
|
||||
|
||||
case "notContains":
|
||||
query
|
||||
.innerJoin("Attendee", "Attendee.id", "Booking.id")
|
||||
.where(`Attendee.${key}`, "not like", `%${operand}%`);
|
||||
break;
|
||||
|
||||
case "isEmpty":
|
||||
query.innerJoin("Attendee", "Attendee.id", "Booking.id").where(`Attendee.${key}`, "=", "");
|
||||
break;
|
||||
|
||||
case "isNotEmpty":
|
||||
query.innerJoin("Attendee", "Attendee.id", "Booking.id").where(`Attendee.${key}`, "!=", "");
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
function getOrderBy(
|
||||
bookingListingByStatus: InputByStatus[],
|
||||
sort?: {
|
||||
sortStart?: "asc" | "desc";
|
||||
sortEnd?: "asc" | "desc";
|
||||
sortCreated?: "asc" | "desc";
|
||||
sortUpdated?: "asc" | "desc";
|
||||
}
|
||||
): { key: "startTime" | "endTime" | "createdAt" | "updatedAt"; order: "desc" | "asc" } {
|
||||
const bookingListingOrderby = {
|
||||
upcoming: { startTime: "asc" },
|
||||
recurring: { startTime: "asc" },
|
||||
past: { startTime: "desc" },
|
||||
cancelled: { startTime: "desc" },
|
||||
unconfirmed: { startTime: "asc" },
|
||||
} as const;
|
||||
|
||||
if (bookingListingByStatus?.length === 1 && !sort) {
|
||||
return { key: "startTime", order: bookingListingOrderby[bookingListingByStatus[0]].startTime };
|
||||
}
|
||||
|
||||
if (sort?.sortStart) {
|
||||
return { key: "startTime", order: sort.sortStart };
|
||||
}
|
||||
if (sort?.sortEnd) {
|
||||
return { key: "endTime", order: sort.sortEnd };
|
||||
}
|
||||
if (sort?.sortCreated) {
|
||||
return { key: "createdAt", order: sort.sortCreated };
|
||||
}
|
||||
if (sort?.sortUpdated) {
|
||||
return { key: "updatedAt", order: sort.sortUpdated };
|
||||
}
|
||||
|
||||
return { key: "startTime", order: "asc" };
|
||||
}
|
||||
Reference in new issue
Block a user