forked from agentic-review-benchmarks/cal.com
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget.handler.ts
More file actions
1132 lines (1040 loc) · 37.3 KB
/
get.handler.ts
File metadata and controls
1132 lines (1040 loc) · 37.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import dayjs from "@calcom/dayjs";
import getAllUserBookings from "@calcom/features/bookings/lib/getAllUserBookings";
import { isTextFilterValue } from "@calcom/features/data-table/lib/utils";
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
import type { DB } from "@calcom/kysely";
import kysely from "@calcom/kysely";
import { parseEventTypeColor } from "@calcom/lib/isEventTypeColor";
import { parseRecurringEvent } from "@calcom/lib/isRecurringEvent";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import type { PrismaClient } from "@calcom/prisma";
import type { Booking, Prisma as PrismaClientType } from "@calcom/prisma/client";
import { Prisma } from "@calcom/prisma/client";
import { BookingStatus, MembershipRole, SchedulingType } from "@calcom/prisma/enums";
import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import { TRPCError } from "@trpc/server";
import type { Kysely, SelectQueryBuilder } from "kysely";
import { jsonArrayFrom, jsonObjectFrom } from "kysely/helpers/postgres";
import type { TrpcSessionUser } from "../../../types";
import type { TGetInputSchema } from "./get.schema";
type GetOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
prisma: PrismaClient;
};
input: TGetInputSchema;
};
type InputByStatus = "upcoming" | "recurring" | "past" | "cancelled" | "unconfirmed";
const log = logger.getSubLogger({ prefix: ["bookings.get"] });
export const getHandler = async ({ ctx, input }: GetOptions) => {
// Support both offset-based (list) and cursor-based pagination (calendar)
// Cursor is just the offset as a string (fake cursor pagination)
const take = input.limit;
let skip = input.offset;
// If cursor is provided, parse it to get the offset
if (input.cursor) {
const parsedCursor = parseInt(input.cursor, 10);
if (!isNaN(parsedCursor) && parsedCursor >= 0) {
skip = parsedCursor;
}
}
const { prisma, user } = ctx;
const defaultStatus = "upcoming";
const bookingListingByStatus = input.filters.statuses?.length
? input.filters.statuses
: [input.filters.status || defaultStatus];
const { bookings, recurringInfo, totalCount } = await getAllUserBookings({
ctx: {
user: { id: user.id, email: user.email, orgId: user?.profile?.organizationId },
prisma: prisma,
kysely: kysely,
},
bookingListingByStatus: bookingListingByStatus,
take,
skip,
filters: input.filters,
sort: input.sort,
});
// Generate next cursor for infinite query support
const nextOffset = skip + take;
const hasMore = nextOffset < totalCount;
const nextCursor = hasMore ? nextOffset.toString() : undefined;
return {
bookings,
recurringInfo,
totalCount,
nextCursor,
};
};
type BookingsUnionQuery = SelectQueryBuilder<
DB,
"Booking",
Pick<Booking, "id" | "createdAt" | "updatedAt" | "startTime" | "endTime">
>;
export async function getBookings({
user,
prisma,
kysely,
bookingListingByStatus,
sort,
filters,
take,
skip,
}: {
user: { id: number; email: string; orgId?: number | null };
filters: TGetInputSchema["filters"];
prisma: PrismaClient;
kysely: Kysely<DB>;
bookingListingByStatus: InputByStatus[];
sort?: {
sortStart?: "asc" | "desc";
sortEnd?: "asc" | "desc";
sortCreated?: "asc" | "desc";
sortUpdated?: "asc" | "desc";
};
take: number;
skip: number;
}) {
const permissionCheckService = new PermissionCheckService();
const fallbackRoles: MembershipRole[] = [MembershipRole.ADMIN, MembershipRole.OWNER];
const teamIdsWithBookingPermission = await permissionCheckService.getTeamIdsWithPermission({
userId: user.id,
permission: "booking.read",
fallbackRoles,
orgId: user.orgId ?? undefined,
});
const [
eventTypeIdsFromTeamIdsFilter,
attendeeEmailsFromUserIdsFilter,
eventTypeIdsFromEventTypeIdsFilter,
eventTypeIdsWhereUserHasBookingPermission,
userIdsAndEmailsWhereUserHasBookingPermission,
] = await Promise.all([
getEventTypeIdsFromTeamIdsFilter(prisma, filters?.teamIds),
getAttendeeEmailsFromUserIdsFilter(prisma, user.email, filters?.userIds),
getEventTypeIdsFromEventTypeIdsFilter(prisma, filters?.eventTypeIds),
getEventTypeIdsFromTeamIdsFilter(prisma, teamIdsWithBookingPermission),
getUserIdsAndEmailsFromTeamIds(prisma, teamIdsWithBookingPermission),
]);
const bookingQueries: { query: BookingsUnionQuery; tables: (keyof DB)[] }[] = [];
// Get user IDs and emails from teams where user has booking permission
const [allAccessibleUserIds, allAccessibleUserEmails] = userIdsAndEmailsWhereUserHasBookingPermission;
// If userIds filter is provided
if (!!filters?.userIds && filters.userIds.length > 0) {
const areUserIdsWithinUserOrgOrTeam = filters.userIds.every((userId) =>
allAccessibleUserIds.includes(userId)
);
const isCurrentUser = filters.userIds.length === 1 && user.id === filters.userIds[0];
// Scope depends on `user.orgId`:
// - Throw an error if trying to filter by usersIds that are not within your ORG
// - Throw an error if trying to filter by usersIds that are not within your TEAM
if (!areUserIdsWithinUserOrgOrTeam && !isCurrentUser) {
throw new TRPCError({
code: "FORBIDDEN",
message: "You do not have permissions to fetch bookings for specified userIds",
});
}
// 1. Booking created by one of the filtered users
bookingQueries.push({
query: kysely
.selectFrom("Booking")
.select("Booking.id")
.select("Booking.startTime")
.select("Booking.endTime")
.select("Booking.createdAt")
.select("Booking.updatedAt")
.where("userId", "in", filters.userIds),
tables: ["Booking"],
});
// 2. Attendee email matches one of the filtered users' emails
if (attendeeEmailsFromUserIdsFilter?.length) {
bookingQueries.push({
query: 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),
tables: ["Booking", "Attendee"],
});
}
// 3. Seat reference attendee email matches one of the filtered users' emails
if (attendeeEmailsFromUserIdsFilter?.length) {
bookingQueries.push({
query: 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),
tables: ["Booking", "Attendee", "BookingSeat"],
});
}
} else {
// 1. Current user created bookings
bookingQueries.push({
query: kysely
.selectFrom("Booking")
.select("Booking.id")
.select("Booking.startTime")
.select("Booking.endTime")
.select("Booking.createdAt")
.select("Booking.updatedAt")
.where("Booking.userId", "=", user.id),
tables: ["Booking"],
});
// 2. Current user is an attendee
bookingQueries.push({
query: 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),
tables: ["Booking", "Attendee"],
});
// 3. Current user is an attendee via seats reference
bookingQueries.push({
query: 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),
tables: ["Booking", "Attendee", "BookingSeat"],
});
// 4. Scope depends on `user.orgId`:
// - If Current user is ORG_OWNER/ADMIN or has booking.read permission, get bookings where organization/team members are attendees
if (allAccessibleUserEmails?.length) {
bookingQueries.push({
query: 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", allAccessibleUserEmails),
tables: ["Booking", "Attendee"],
});
}
// 5. Scope depends on `user.orgId`:
// - If Current user is ORG_OWNER/ADMIN or has booking.read permission, get bookings where organization/team members are attendees via seatsReference
if (allAccessibleUserEmails?.length) {
bookingQueries.push({
query: 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", allAccessibleUserEmails),
tables: ["Booking", "Attendee", "BookingSeat"],
});
}
// 6. Scope depends on `user.orgId`:
// - If Current user is ORG_OWNER/ADMIN or has booking.read permission, get booking created for an event type within the organization/team
if (eventTypeIdsWhereUserHasBookingPermission?.length) {
bookingQueries.push({
query: 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", eventTypeIdsWhereUserHasBookingPermission),
tables: ["Booking", "EventType"],
});
}
// 7. Scope depends on `user.orgId`:
// - If Current user is ORG_OWNER/ADMIN or has booking.read permission, get bookings created by users within the same organization/team
if (allAccessibleUserIds?.length) {
bookingQueries.push({
query: kysely
.selectFrom("Booking")
.select("Booking.id")
.select("Booking.startTime")
.select("Booking.endTime")
.select("Booking.createdAt")
.select("Booking.updatedAt")
.where("Booking.userId", "in", allAccessibleUserIds),
tables: ["Booking"],
});
}
}
const queriesWithFilters = bookingQueries.map(({ query, tables }) => {
// 1. Apply mandatory status filter
let fullQuery = addStatusesQueryFilters(query, bookingListingByStatus);
// 2. Filter by Event Type IDs derived from Team IDs (if provided)
if (eventTypeIdsFromTeamIdsFilter && eventTypeIdsFromTeamIdsFilter.length > 0) {
fullQuery = fullQuery.where("Booking.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) {
fullQuery = fullQuery.where("Booking.eventTypeId", "in", eventTypeIdsFromEventTypeIdsFilter);
}
// 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,
tables.includes("Attendee")
);
}
}
// 5. Filter by Attendee Email (if provided)
if (filters?.attendeeEmail) {
if (typeof filters.attendeeEmail === "string") {
// Simple string match (exact)
fullQuery = fullQuery
.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,
"email",
filters.attendeeEmail.data.operator,
filters.attendeeEmail.data.operand,
tables.includes("Attendee")
);
}
}
// 6. Filter by Booking Uid (if provided)
if (filters?.bookingUid) {
fullQuery = fullQuery.where("Booking.uid", "=", filters.bookingUid.trim());
}
// 7. 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());
}
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.rescheduledBy",
"Booking.cancelledBy",
"Booking.isRecorded",
"Booking.cancellationReason",
"Booking.rejectionReason",
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.bookingFields",
"EventType.seatsPerTimeSlot",
"EventType.seatsShowAttendees",
"EventType.seatsShowAvailabilityCount",
"EventType.eventTypeColor",
"EventType.customReplyToEmail",
"EventType.allowReschedulingPastBookings",
"EventType.hideOrganizerEmail",
"EventType.disableCancelling",
"EventType.disableRescheduling",
"EventType.minimumRescheduleNotice",
"EventType.teamId",
"EventType.parentId",
eb
.cast<SchedulingType | null>(
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(null)
.end(),
"varchar" // Or 'text' - use the actual SQL data type
)
.as("schedulingType"),
jsonArrayFrom(
eb
.selectFrom("Host")
.select((eb) => [
"Host.userId",
jsonObjectFrom(
eb
.selectFrom("users")
.select(["users.id", "users.email"])
.whereRef("Host.userId", "=", "users.id")
).as("user"),
])
.whereRef("Host.eventTypeId", "=", "EventType.id")
).as("hosts"),
"EventType.length",
jsonObjectFrom(
eb
.selectFrom("Team")
.select(["Team.id", "Team.name", "Team.slug"])
.whereRef("EventType.teamId", "=", "Team.id")
).as("team"),
jsonArrayFrom(
eb
.selectFrom("HostGroup")
.select(["HostGroup.id", "HostGroup.name"])
.whereRef("HostGroup.eventTypeId", "=", "EventType.id")
).as("hostGroups"),
])
.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",
"Payment.appId",
"Payment.refunded",
])
.whereRef("Payment.bookingId", "=", "Booking.id")
).as("payment"),
jsonObjectFrom(
eb
.selectFrom("users")
.select([
"users.id",
"users.name",
"users.email",
"users.avatarUrl",
"users.username",
"users.timeZone",
])
.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")
).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"),
jsonObjectFrom(
eb
.selectFrom("BookingReport")
.select([
"BookingReport.id",
"BookingReport.reportedById",
"BookingReport.reason",
"BookingReport.description",
"BookingReport.createdAt",
])
.whereRef("BookingReport.bookingUid", "=", "Booking.uid")
).as("report"),
])
.orderBy(orderBy.key, orderBy.order)
.execute()
: [];
const [
recurringInfoBasic,
recurringInfoExtended,
// We need all promises to be successful, so we are not using Promise.allSettled
] = await Promise.all([
prisma.booking.groupBy({
by: ["recurringEventId"],
_min: {
startTime: true,
},
_count: {
recurringEventId: true,
},
where: {
recurringEventId: {
not: { equals: null },
},
userId: user.id,
},
}),
prisma.booking.groupBy({
by: ["recurringEventId", "status", "startTime"],
_min: {
startTime: true,
},
where: {
recurringEventId: {
not: { equals: null },
},
userId: user.id,
},
}),
]);
const recurringInfo = recurringInfoBasic.map(
(
info: (typeof recurringInfoBasic)[number]
): {
recurringEventId: string | null;
count: number;
firstDate: Date | null;
bookings: {
[key: string]: Date[];
};
} => {
const bookings = recurringInfoExtended.reduce(
(prev, curr) => {
if (curr.recurringEventId === info.recurringEventId) {
prev[curr.status].push(curr.startTime);
}
return prev;
},
{ ACCEPTED: [], CANCELLED: [], REJECTED: [], PENDING: [], AWAITING_HOST: [] } as {
[key in BookingStatus]: Date[];
}
);
return {
recurringEventId: info.recurringEventId,
count: info._count.recurringEventId,
firstDate: info._min.startTime,
bookings,
};
}
);
// Now enrich bookings with relation data. We could have queried the relation data along with the bookings, but that would cause unnecessary queries to the database.
// Because Prisma is also going to query the select relation data sequentially, we are fine querying it separately here as it would be just 1 query instead of 4
log.info(
`fetching all bookings for ${user.id}`,
safeStringify({
ids: plainBookings.map((booking) => booking.id),
filters,
orderBy,
take,
skip,
})
);
const checkIfUserIsHost = (userId: number, booking: (typeof plainBookings)[number]) => {
if (booking.user?.id === userId) {
return true;
}
if (!booking.eventType?.hosts || booking.eventType.hosts.length === 0) {
return false;
}
const attendeeEmails = new Set(booking.attendees.map((attendee) => attendee.email));
return booking.eventType.hosts.some(({ user: hostUser }) => {
return hostUser?.id === userId && attendeeEmails.has(hostUser.email);
});
};
const bookings = await Promise.all(
plainBookings.map(async (booking) => {
// If seats are enabled, the event is not set to show attendees, and the current user is not the host, filter out attendees who are not the current user
if (
booking.seatsReferences.length &&
!booking.eventType?.seatsShowAttendees &&
!checkIfUserIsHost(user.id, booking)
) {
booking.attendees = booking.attendees.filter((attendee) => attendee.email === user.email);
}
let rescheduler = null;
if (booking.fromReschedule) {
const rescheduledBooking = await prisma.booking.findUnique({
where: {
uid: booking.fromReschedule,
},
select: {
rescheduledBy: true,
},
});
if (rescheduledBooking) {
rescheduler = rescheduledBooking.rescheduledBy;
}
}
return {
...booking,
rescheduler,
eventType: {
...booking.eventType,
recurringEvent: parseRecurringEvent(booking.eventType?.recurringEvent),
eventTypeColor: parseEventTypeColor(booking.eventType?.eventTypeColor),
price: booking.eventType?.price || 0,
currency: booking.eventType?.currency || "usd",
metadata: EventTypeMetaDataSchema.parse(booking.eventType?.metadata || {}),
},
startTime: booking.startTime.toISOString(),
endTime: booking.endTime.toISOString(),
};
})
);
// Enrich attendees with user data
const enrichedBookings = await enrichAttendeesWithUserData(bookings, kysely);
return { bookings: enrichedBookings, recurringInfo, totalCount };
}
type EnrichedUserData = {
name: string | null;
email: string;
avatarUrl: string | null;
username: string | null;
};
/**
* Enriches booking attendees with user data by performing a left outer join
* between attendees and users tables on email addresses.
*
* @param bookings - Array of bookings with attendees to enrich
* @param kysely - Kysely database client instance
* @returns Bookings with attendees enriched with user data (name, email, avatarUrl, username)
*/
async function enrichAttendeesWithUserData<
TBooking extends { attendees: ReadonlyArray<{ id: number; email: string }> },
>(
bookings: TBooking[],
kysely: Kysely<DB>
): Promise<
Array<
Omit<TBooking, "attendees"> & {
attendees: Array<TBooking["attendees"][number] & { user: EnrichedUserData | null }>;
}
>
> {
// Extract all unique attendee emails from bookings
const allAttendees = bookings.flatMap((booking) => booking.attendees);
const uniqueAttendeeIds = Array.from(new Set(allAttendees.map((attendee) => attendee.id)));
// Query attendees with left join to users table
const enrichedAttendees =
uniqueAttendeeIds.length > 0
? await kysely
.selectFrom("Attendee")
.leftJoin("users", "users.email", "Attendee.email")
.select(["Attendee.id", "users.name", "Attendee.email", "users.avatarUrl", "users.username"])
.where("Attendee.id", "in", uniqueAttendeeIds)
.execute()
: [];
// Create a lookup map for O(1) access by attendee ID
const attendeeUserDataMap = new Map<number, EnrichedUserData>(
enrichedAttendees.map((enriched) => [
enriched.id,
{
name: enriched.name,
email: enriched.email,
avatarUrl: enriched.avatarUrl,
username: enriched.username,
},
])
);
// Map over bookings and enrich each attendee with user data
return bookings.map((booking) => ({
...booking,
attendees: booking.attendees.map((attendee) => ({
...attendee,
user: attendeeUserDataMap.get(attendee.id) || null,
})),
}));
}
/**
* Gets event type IDs for the given team IDs using an optimized raw SQL query.
*
* This query uses a UNION to combine:
* 1. Child event types whose parent belongs to the specified teams (managed event types)
* 2. Direct team event types that belong to the specified teams
*
* The subquery structure `WHERE "parent"."id" IN (SELECT "id" FROM "EventType" WHERE "teamId" IN (...)))`
* is intentional - it allows PostgreSQL to use the composite index on EventType(parentId, teamId)
* efficiently via Nested Loop joins, resulting in ~66x faster execution compared to a direct
* WHERE clause on parent.teamId (2.46ms vs 164ms in production benchmarks).
*
* @param prisma The Prisma client
* @param teamIds Array of team IDs to filter by
* @returns Array of event type IDs or undefined if no teamIds provided
*/
async function getEventTypeIdsFromTeamIdsFilter(prisma: PrismaClient, teamIds?: number[]) {
if (!teamIds || teamIds.length === 0) {
return undefined;
}
const result = await prisma.$queryRaw<{ id: number }[]>`
SELECT "child"."id"
FROM "public"."EventType" AS "parent"
LEFT JOIN "public"."EventType" "child" ON ("parent"."id") = ("child"."parentId")
WHERE "parent"."id" IN (SELECT "id" FROM "public"."EventType" WHERE "teamId" IN (${Prisma.join(teamIds)}))
AND "child"."id" IS NOT NULL
UNION
SELECT "parent"."id"
FROM "public"."EventType" AS "parent"
WHERE "parent"."teamId" IN (${Prisma.join(teamIds)})
`;
return result.map((row) => row.id);
}
async function getAttendeeEmailsFromUserIdsFilter(
prisma: PrismaClient,
userEmail: string,
userIds?: number[]
) {
if (!userIds || userIds.length === 0) {
return;
}
const attendeeEmailsFromUserIdsFilter = await prisma.user
.findMany({
where: {
id: {
in: userIds,
},
},
select: {
email: true,
},
})
.then((users) => users.map((user) => user.email));
if (!attendeeEmailsFromUserIdsFilter || attendeeEmailsFromUserIdsFilter?.length === 0) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "The requested users do not exist.",
});
}
return attendeeEmailsFromUserIdsFilter;
}
async function getEventTypeIdsFromEventTypeIdsFilter(prisma: PrismaClient, eventTypeIds?: number[]) {
if (!eventTypeIds || eventTypeIds.length === 0) {
return undefined;
}
const [directEventTypeIds, parentEventTypeIds] = await Promise.all([
prisma.eventType
.findMany({
where: {
id: { in: eventTypeIds },
},
select: {
id: true,
},
})
.then((eventTypes) => eventTypes.map((eventType) => eventType.id)),
prisma.eventType
.findMany({
where: {
parent: {
id: {
in: eventTypeIds,
},
},
},
select: {
id: true,
},
})
.then((eventTypes) => eventTypes.map((eventType) => eventType.id)),
]);
const eventTypeIdsFromDb = Array.from(new Set([...directEventTypeIds, ...parentEventTypeIds]));
if (eventTypeIdsFromDb?.length === 0) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "The requested event-types do not exist.",
});
}
return eventTypeIdsFromDb;
}
/**
* Gets [IDs, Emails] of members from specified team IDs.
* @param prisma The Prisma client.
* @param teamIds Array of team IDs to get members from
* @returns {Promise<[number[], string[]]>} [UserIDs, UserEmails] for members in the specified teams.
*/
async function getUserIdsAndEmailsFromTeamIds(
prisma: PrismaClient,
teamIds: number[]
): Promise<[number[], string[]]> {
if (teamIds.length === 0) {
return [[], []];
}
const users = await prisma.user.findMany({
where: {
teams: {
some: {
teamId: {
in: teamIds,
},
},
},
},
select: {
id: true,
email: true,
},
});
const userIds = Array.from(new Set(users.map((user) => user.id)));
const userEmails = Array.from(new Set(users.map((user) => user.email)));
return [userIds, userEmails];
}
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([