fix: Use Google recurring events protocol (#12651)
* working create event --wip-- [skip ci] fix bug related to adding event --wip-- [skip ci] --wip-- [skip ci] add delete all remove console.log remove console.log add patching of instances fix yarn.lock remove comments * fixed typing * use rrule * rollback tsconfig changes * fix comments * fix comments * rename db column * fix delete all booking * Update apps/web/pages/api/book/recurring-event.ts Co-authored-by: Carina Wollendorfer <[email protected]> * remove non-null assertion * attempt to fix type errors * fix recurring event logic * remove skipAvailabilityCheck --------- Co-authored-by: Carina Wollendorfer <[email protected]> Co-authored-by: CarinaWolli <[email protected]> Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: Hariom <[email protected]>
This commit is contained in:
12 files changed
+269
-101
No files matched your search
@@ -59,6 +59,7 @@ async function getBookingToDelete(id: number | undefined, uid: string | undefine
|
||||
type: true,
|
||||
externalCalendarId: true,
|
||||
credentialId: true,
|
||||
thirdPartyRecurringEventId: true,
|
||||
},
|
||||
},
|
||||
payment: true,
|
||||
@@ -458,24 +459,37 @@ async function handler(req: CustomRequest) {
|
||||
bookingToDelete.recurringEventId &&
|
||||
allRemainingBookings
|
||||
) {
|
||||
const promises = bookingToDelete.user.credentials
|
||||
.filter((credential) => credential.type.endsWith("_calendar"))
|
||||
.map(async (credential) => {
|
||||
const calendar = await getCalendar(credential);
|
||||
for (const updBooking of updatedBookings) {
|
||||
const bookingRef = updBooking.references.find((ref) => ref.type.includes("_calendar"));
|
||||
if (bookingRef) {
|
||||
const { uid, externalCalendarId } = bookingRef;
|
||||
const deletedEvent = await calendar?.deleteEvent(uid, evt, externalCalendarId);
|
||||
apiDeletes.push(deletedEvent);
|
||||
let thirdPartyRecurringEventId;
|
||||
for (const reference of bookingToDelete.references) {
|
||||
if (reference.thirdPartyRecurringEventId) {
|
||||
thirdPartyRecurringEventId = reference.thirdPartyRecurringEventId;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (thirdPartyRecurringEventId) {
|
||||
apiDeletes.push(
|
||||
calendar?.deleteEvent(thirdPartyRecurringEventId, evt, externalCalendarId) as Promise<unknown>
|
||||
);
|
||||
} else {
|
||||
const promises = bookingToDelete.user.credentials
|
||||
.filter((credential) => credential.type.endsWith("_calendar"))
|
||||
.map(async (credential) => {
|
||||
const calendar = await getCalendar(credential);
|
||||
for (const updBooking of updatedBookings) {
|
||||
const bookingRef = updBooking.references.find((ref) => ref.type.includes("_calendar"));
|
||||
if (bookingRef) {
|
||||
const { uid, externalCalendarId } = bookingRef;
|
||||
const deletedEvent = await calendar?.deleteEvent(uid, evt, externalCalendarId);
|
||||
apiDeletes.push(deletedEvent);
|
||||
}
|
||||
}
|
||||
});
|
||||
try {
|
||||
await Promise.all(promises);
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
logger.error(error.message);
|
||||
}
|
||||
});
|
||||
try {
|
||||
await Promise.all(promises);
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
logger.error(error.message);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -666,7 +680,8 @@ async function handler(req: CustomRequest) {
|
||||
const prismaPromises: Promise<unknown>[] = [bookingReferenceDeletes];
|
||||
|
||||
try {
|
||||
const settled = await Promise.allSettled(prismaPromises.concat(apiDeletes));
|
||||
const temp = prismaPromises.concat(apiDeletes);
|
||||
const settled = await Promise.allSettled(temp);
|
||||
const rejected = settled.filter(({ status }) => status === "rejected") as PromiseRejectedResult[];
|
||||
if (rejected.length) {
|
||||
throw new Error(`Reasons: ${rejected.map(({ reason }) => reason)}`);
|
||||
|
||||
@@ -985,13 +985,10 @@ async function handler(
|
||||
req: NextApiRequest & { userId?: number | undefined },
|
||||
{
|
||||
isNotAnApiCall = false,
|
||||
skipAvailabilityCheck = false,
|
||||
}: {
|
||||
isNotAnApiCall?: boolean;
|
||||
skipAvailabilityCheck?: boolean;
|
||||
} = {
|
||||
isNotAnApiCall: false,
|
||||
skipAvailabilityCheck: false,
|
||||
}
|
||||
) {
|
||||
const { userId } = req;
|
||||
@@ -1061,7 +1058,6 @@ async function handler(
|
||||
isTeamEventType,
|
||||
eventType: getPiiFreeEventType(eventType),
|
||||
dynamicUserList,
|
||||
skipAvailabilityCheck,
|
||||
paymentAppData: {
|
||||
enabled: paymentAppData.enabled,
|
||||
price: paymentAppData.price,
|
||||
@@ -1230,58 +1226,85 @@ async function handler(
|
||||
}
|
||||
|
||||
//checks what users are available
|
||||
if (!eventType.seatsPerTimeSlot && !skipAvailabilityCheck) {
|
||||
const availableUsers = await ensureAvailableUsers(
|
||||
{
|
||||
...eventType,
|
||||
users: users as IsFixedAwareUser[],
|
||||
...(eventType.recurringEvent && {
|
||||
recurringEvent: {
|
||||
...eventType.recurringEvent,
|
||||
count: recurringCount || eventType.recurringEvent.count,
|
||||
},
|
||||
}),
|
||||
},
|
||||
{
|
||||
dateFrom: dayjs(reqBody.start).tz(reqBody.timeZone).format(),
|
||||
dateTo: dayjs(reqBody.end).tz(reqBody.timeZone).format(),
|
||||
timeZone: reqBody.timeZone,
|
||||
originalRescheduledBooking,
|
||||
},
|
||||
loggerWithEventDetails
|
||||
);
|
||||
|
||||
const luckyUsers: typeof users = [];
|
||||
const luckyUserPool = availableUsers.filter((user) => !user.isFixed);
|
||||
loggerWithEventDetails.debug(
|
||||
"Computed available users",
|
||||
safeStringify({
|
||||
availableUsers: availableUsers.map((user) => user.id),
|
||||
luckyUserPool: luckyUserPool.map((user) => user.id),
|
||||
})
|
||||
);
|
||||
// loop through all non-fixed hosts and get the lucky users
|
||||
while (luckyUserPool.length > 0 && luckyUsers.length < 1 /* TODO: Add variable */) {
|
||||
const newLuckyUser = await getLuckyUser("MAXIMIZE_AVAILABILITY", {
|
||||
// find a lucky user that is not already in the luckyUsers array
|
||||
availableUsers: luckyUserPool.filter(
|
||||
(user) => !luckyUsers.find((existing) => existing.id === user.id)
|
||||
),
|
||||
eventTypeId: eventType.id,
|
||||
});
|
||||
if (!newLuckyUser) {
|
||||
break; // prevent infinite loop
|
||||
if (!eventType.seatsPerTimeSlot) {
|
||||
const eventTypeWithUsers: Awaited<ReturnType<typeof getEventTypesFromDB>> & {
|
||||
users: IsFixedAwareUser[];
|
||||
} = {
|
||||
...eventType,
|
||||
users: users as IsFixedAwareUser[],
|
||||
...(eventType.recurringEvent && {
|
||||
recurringEvent: {
|
||||
...eventType.recurringEvent,
|
||||
count: recurringCount || eventType.recurringEvent.count,
|
||||
},
|
||||
}),
|
||||
};
|
||||
if (req.body.allRecurringDates) {
|
||||
if (req.body.isFirstRecurringSlot) {
|
||||
for (
|
||||
let i = 0;
|
||||
i < req.body.allRecurringDates.length && i < req.body.numSlotsToCheckForAvailability;
|
||||
i++
|
||||
) {
|
||||
const start = req.body.allRecurringDates[i].start;
|
||||
const end = req.body.allRecurringDates[i].end;
|
||||
await ensureAvailableUsers(
|
||||
eventTypeWithUsers,
|
||||
{
|
||||
dateFrom: dayjs(start).tz(reqBody.timeZone).format(),
|
||||
dateTo: dayjs(end).tz(reqBody.timeZone).format(),
|
||||
timeZone: reqBody.timeZone,
|
||||
originalRescheduledBooking,
|
||||
},
|
||||
loggerWithEventDetails
|
||||
);
|
||||
}
|
||||
}
|
||||
luckyUsers.push(newLuckyUser);
|
||||
}
|
||||
// ALL fixed users must be available
|
||||
if (
|
||||
availableUsers.filter((user) => user.isFixed).length !== users.filter((user) => user.isFixed).length
|
||||
) {
|
||||
throw new Error(ErrorCode.HostsUnavailableForBooking);
|
||||
if (!req.body.allRecurringDates || req.body.isFirstRecurringSlot) {
|
||||
const availableUsers = await ensureAvailableUsers(
|
||||
eventTypeWithUsers,
|
||||
{
|
||||
dateFrom: dayjs(reqBody.start).tz(reqBody.timeZone).format(),
|
||||
dateTo: dayjs(reqBody.end).tz(reqBody.timeZone).format(),
|
||||
timeZone: reqBody.timeZone,
|
||||
originalRescheduledBooking,
|
||||
},
|
||||
loggerWithEventDetails
|
||||
);
|
||||
|
||||
const luckyUsers: typeof users = [];
|
||||
const luckyUserPool = availableUsers.filter((user) => !user.isFixed);
|
||||
loggerWithEventDetails.debug(
|
||||
"Computed available users",
|
||||
safeStringify({
|
||||
availableUsers: availableUsers.map((user) => user.id),
|
||||
luckyUserPool: luckyUserPool.map((user) => user.id),
|
||||
})
|
||||
);
|
||||
// loop through all non-fixed hosts and get the lucky users
|
||||
while (luckyUserPool.length > 0 && luckyUsers.length < 1 /* TODO: Add variable */) {
|
||||
const newLuckyUser = await getLuckyUser("MAXIMIZE_AVAILABILITY", {
|
||||
// find a lucky user that is not already in the luckyUsers array
|
||||
availableUsers: luckyUserPool.filter(
|
||||
(user) => !luckyUsers.find((existing) => existing.id === user.id)
|
||||
),
|
||||
eventTypeId: eventType.id,
|
||||
});
|
||||
if (!newLuckyUser) {
|
||||
break; // prevent infinite loop
|
||||
}
|
||||
luckyUsers.push(newLuckyUser);
|
||||
}
|
||||
// ALL fixed users must be available
|
||||
if (
|
||||
availableUsers.filter((user) => user.isFixed).length !== users.filter((user) => user.isFixed).length
|
||||
) {
|
||||
throw new Error(ErrorCode.HostsUnavailableForBooking);
|
||||
}
|
||||
// Pushing fixed user before the luckyUser guarantees the (first) fixed user as the organizer.
|
||||
users = [...availableUsers.filter((user) => user.isFixed), ...luckyUsers];
|
||||
}
|
||||
// Pushing fixed user before the luckyUser guarantees the (first) fixed user as the organizer.
|
||||
users = [...availableUsers.filter((user) => user.isFixed), ...luckyUsers];
|
||||
}
|
||||
|
||||
const [organizerUser] = users;
|
||||
@@ -1459,6 +1482,12 @@ async function handler(
|
||||
iCalSequence,
|
||||
};
|
||||
|
||||
if (req.body.thirdPartyRecurringEventId) {
|
||||
evt.existingRecurringEvent = {
|
||||
recurringEventId: req.body.thirdPartyRecurringEventId,
|
||||
};
|
||||
}
|
||||
|
||||
if (isTeamEventType && eventType.schedulingType === "COLLECTIVE") {
|
||||
evt.destinationCalendar?.push(...teamDestinationCalendars);
|
||||
}
|
||||
@@ -1563,7 +1592,9 @@ async function handler(
|
||||
let results: EventResult<AdditionalInformation & { url?: string; iCalUID?: string }>[] = [];
|
||||
let referencesToCreate: PartialReference[] = [];
|
||||
|
||||
let booking: (Booking & { appsStatus?: AppsStatus[] }) | null = null;
|
||||
let booking: (Booking & { appsStatus?: AppsStatus[]; paymentUid?: string; paymentId?: number }) | null =
|
||||
null;
|
||||
|
||||
loggerWithEventDetails.debug(
|
||||
"Going to create booking in DB now",
|
||||
safeStringify({
|
||||
@@ -2253,6 +2284,7 @@ async function handler(
|
||||
req.statusCode = 201;
|
||||
return {
|
||||
...booking,
|
||||
references: referencesToCreate,
|
||||
seatReferenceUid: evt.attendeeSeatId,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ export type RecurringBookingCreateBody = BookingCreateBody & {
|
||||
noEmail?: boolean;
|
||||
recurringCount?: number;
|
||||
appsStatus?: AppsStatus[] | undefined;
|
||||
allRecurringDates?: string[];
|
||||
allRecurringDates?: Record<string, string>[];
|
||||
currentRecurringIndex?: number;
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user