cal/packages/core/getUserAvailability.ts

272 lines
8.6 KiB
TypeScript
Raw Normal View History

2022-06-10 15:38:46 -03:00
import { Prisma } from "@prisma/client";
import { z } from "zod";
2022-07-07 12:26:22 -03:00
import dayjs, { Dayjs } from "@calcom/dayjs";
Feat Booking Limits (#4759) * Add db relevant stuff * Basic UI there still buggy * This UI is hard - some progress * Fix awful state mangament * Fix re-ordering * Working UI logic! * Partical working minMax function * Fix min max * bookingLImits api + tests * Moved checkBookingLimits to backend only code * Fix httperror import * Return busy times * Remove avaliablity calc * Working for everything but year * Remove redundant + fix async forloop * Add compatible type * Future proof with evenTypeId filter * Fix commonjson * Sorting + validation + tests + passing * Add empty test * Move validation check to backend * Add bookinglimits in trpc * Add test for undefined * Apply suggestions from code review Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> * Update apps/web/components/v2/eventtype/EventLimitsTab.tsx Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> * Rename value for eligiability * Rename keyof type * status code * Fix toggle not toggling off * Update apps/web/pages/v2/event-types/[type]/index.tsx Co-authored-by: Omar López <zomars@me.com> * Update apps/web/pages/v2/event-types/[type]/index.tsx Co-authored-by: Omar López <zomars@me.com> * Change back to undefined as it is working for sean. See if it fails on testapp * Fixing test builder Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: Alex van Andel <me@alexvanandel.com> Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> Co-authored-by: Hariom Balhara <hariombalhara@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: Leo Giovanetti <hello@leog.me>
2022-10-12 02:29:04 -03:00
import { parseBookingLimit } from "@calcom/lib";
2022-06-10 15:38:46 -03:00
import { getWorkingHours } from "@calcom/lib/availability";
import { HttpError } from "@calcom/lib/http-error";
2022-07-07 12:26:22 -03:00
import logger from "@calcom/lib/logger";
Feat Booking Limits (#4759) * Add db relevant stuff * Basic UI there still buggy * This UI is hard - some progress * Fix awful state mangament * Fix re-ordering * Working UI logic! * Partical working minMax function * Fix min max * bookingLImits api + tests * Moved checkBookingLimits to backend only code * Fix httperror import * Return busy times * Remove avaliablity calc * Working for everything but year * Remove redundant + fix async forloop * Add compatible type * Future proof with evenTypeId filter * Fix commonjson * Sorting + validation + tests + passing * Add empty test * Move validation check to backend * Add bookinglimits in trpc * Add test for undefined * Apply suggestions from code review Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> * Update apps/web/components/v2/eventtype/EventLimitsTab.tsx Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> * Rename value for eligiability * Rename keyof type * status code * Fix toggle not toggling off * Update apps/web/pages/v2/event-types/[type]/index.tsx Co-authored-by: Omar López <zomars@me.com> * Update apps/web/pages/v2/event-types/[type]/index.tsx Co-authored-by: Omar López <zomars@me.com> * Change back to undefined as it is working for sean. See if it fails on testapp * Fixing test builder Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: Alex van Andel <me@alexvanandel.com> Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> Co-authored-by: Hariom Balhara <hariombalhara@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: Leo Giovanetti <hello@leog.me>
2022-10-12 02:29:04 -03:00
import { checkLimit } from "@calcom/lib/server";
import { performance } from "@calcom/lib/server/perfObserver";
2022-06-10 15:38:46 -03:00
import prisma, { availabilityUserSelect } from "@calcom/prisma";
import { EventTypeMetaDataSchema, stringToDayjs } from "@calcom/prisma/zod-utils";
Feat Booking Limits (#4759) * Add db relevant stuff * Basic UI there still buggy * This UI is hard - some progress * Fix awful state mangament * Fix re-ordering * Working UI logic! * Partical working minMax function * Fix min max * bookingLImits api + tests * Moved checkBookingLimits to backend only code * Fix httperror import * Return busy times * Remove avaliablity calc * Working for everything but year * Remove redundant + fix async forloop * Add compatible type * Future proof with evenTypeId filter * Fix commonjson * Sorting + validation + tests + passing * Add empty test * Move validation check to backend * Add bookinglimits in trpc * Add test for undefined * Apply suggestions from code review Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> * Update apps/web/components/v2/eventtype/EventLimitsTab.tsx Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> * Rename value for eligiability * Rename keyof type * status code * Fix toggle not toggling off * Update apps/web/pages/v2/event-types/[type]/index.tsx Co-authored-by: Omar López <zomars@me.com> * Update apps/web/pages/v2/event-types/[type]/index.tsx Co-authored-by: Omar López <zomars@me.com> * Change back to undefined as it is working for sean. See if it fails on testapp * Fixing test builder Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: Alex van Andel <me@alexvanandel.com> Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> Co-authored-by: Hariom Balhara <hariombalhara@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: Leo Giovanetti <hello@leog.me>
2022-10-12 02:29:04 -03:00
import { BookingLimit, EventBusyDetails } from "@calcom/types/Calendar";
2022-06-10 15:38:46 -03:00
import { getBusyTimes } from "./getBusyTimes";
const availabilitySchema = z
.object({
dateFrom: stringToDayjs,
dateTo: stringToDayjs,
eventTypeId: z.number().optional(),
username: z.string().optional(),
userId: z.number().optional(),
afterEventBuffer: z.number().optional(),
beforeEventBuffer: z.number().optional(),
withSource: z.boolean().optional(),
2022-06-10 15:38:46 -03:00
})
.refine((data) => !!data.username || !!data.userId, "Either username or userId should be filled in.");
const getEventType = async (id: number) => {
const eventType = await prisma.eventType.findUnique({
2022-06-10 15:38:46 -03:00
where: { id },
select: {
Feature/booking page refactor (#3035) * Extracted UI related logic on the DatePicker, stripped out all logic * wip * fixed small regression due to merge * Fix alignment of the chevrons * Added isToday dot, added onMonthChange so we can fetch this month slots * Added includedDates to inverse excludedDates * removed trpcState * Improvements to the state * All params are now dynamic * This builds the flat map so not all paths block on every new build * Added requiresConfirmation * Correctly take into account getFilteredTimes to make the calendar function * Rewritten team availability, seems to work * Circumvent i18n flicker by showing the loader instead * 'You can remove this code. Its not being used now' - Hariom * Nailed a persistent little bug, new Date() caused the current day to flicker on and off * TS fixes * Fix some eventType details in AvailableTimes * '5 / 6 Seats Available' instead of '6 / Seats Available' * More type fixes * Removed unrelated merge artifact * Use WEBAPP_URL instead of hardcoded * Next round of TS fixes * I believe this was mistyped * Temporarily disabled rescheduling 'this is when you originally scheduled', so removed dep * Sorting some dead code * This page has a lot of red, not all related to this PR * A PR to your PR (#3067) * Cleanup * Cleanup * Uses zod to parse params * Type fixes * Fixes ISR * E2E fixes * Disabled dynamic bookings until post v1.7 * More test fixes * Fixed border position (transparent border) to prevent dot from jumping - and possibly fix spacing * Disabled style nitpicks * Delete useSlots.ts Removed early design artifact * Unlock DatePicker locale * Adds mini spinner to DatePicker Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: zomars <zomars@me.com>
2022-06-15 17:54:31 -03:00
id: true,
2022-06-10 15:38:46 -03:00
seatsPerTimeSlot: true,
Feat Booking Limits (#4759) * Add db relevant stuff * Basic UI there still buggy * This UI is hard - some progress * Fix awful state mangament * Fix re-ordering * Working UI logic! * Partical working minMax function * Fix min max * bookingLImits api + tests * Moved checkBookingLimits to backend only code * Fix httperror import * Return busy times * Remove avaliablity calc * Working for everything but year * Remove redundant + fix async forloop * Add compatible type * Future proof with evenTypeId filter * Fix commonjson * Sorting + validation + tests + passing * Add empty test * Move validation check to backend * Add bookinglimits in trpc * Add test for undefined * Apply suggestions from code review Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> * Update apps/web/components/v2/eventtype/EventLimitsTab.tsx Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> * Rename value for eligiability * Rename keyof type * status code * Fix toggle not toggling off * Update apps/web/pages/v2/event-types/[type]/index.tsx Co-authored-by: Omar López <zomars@me.com> * Update apps/web/pages/v2/event-types/[type]/index.tsx Co-authored-by: Omar López <zomars@me.com> * Change back to undefined as it is working for sean. See if it fails on testapp * Fixing test builder Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: Alex van Andel <me@alexvanandel.com> Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> Co-authored-by: Hariom Balhara <hariombalhara@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: Leo Giovanetti <hello@leog.me>
2022-10-12 02:29:04 -03:00
bookingLimits: true,
2022-06-10 15:38:46 -03:00
timeZone: true,
metadata: true,
2022-06-10 15:38:46 -03:00
schedule: {
select: {
availability: true,
timeZone: true,
},
},
availability: {
select: {
startTime: true,
endTime: true,
days: true,
date: true,
2022-06-10 15:38:46 -03:00
},
},
},
});
if (!eventType) {
return eventType;
}
return {
...eventType,
metadata: EventTypeMetaDataSchema.parse(eventType.metadata),
};
};
2022-06-10 15:38:46 -03:00
type EventType = Awaited<ReturnType<typeof getEventType>>;
const getUser = (where: Prisma.UserWhereUniqueInput) =>
prisma.user.findUnique({
where,
select: availabilityUserSelect,
});
type User = Awaited<ReturnType<typeof getUser>>;
Feature/booking page refactor (#3035) * Extracted UI related logic on the DatePicker, stripped out all logic * wip * fixed small regression due to merge * Fix alignment of the chevrons * Added isToday dot, added onMonthChange so we can fetch this month slots * Added includedDates to inverse excludedDates * removed trpcState * Improvements to the state * All params are now dynamic * This builds the flat map so not all paths block on every new build * Added requiresConfirmation * Correctly take into account getFilteredTimes to make the calendar function * Rewritten team availability, seems to work * Circumvent i18n flicker by showing the loader instead * 'You can remove this code. Its not being used now' - Hariom * Nailed a persistent little bug, new Date() caused the current day to flicker on and off * TS fixes * Fix some eventType details in AvailableTimes * '5 / 6 Seats Available' instead of '6 / Seats Available' * More type fixes * Removed unrelated merge artifact * Use WEBAPP_URL instead of hardcoded * Next round of TS fixes * I believe this was mistyped * Temporarily disabled rescheduling 'this is when you originally scheduled', so removed dep * Sorting some dead code * This page has a lot of red, not all related to this PR * A PR to your PR (#3067) * Cleanup * Cleanup * Uses zod to parse params * Type fixes * Fixes ISR * E2E fixes * Disabled dynamic bookings until post v1.7 * More test fixes * Fixed border position (transparent border) to prevent dot from jumping - and possibly fix spacing * Disabled style nitpicks * Delete useSlots.ts Removed early design artifact * Unlock DatePicker locale * Adds mini spinner to DatePicker Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: zomars <zomars@me.com>
2022-06-15 17:54:31 -03:00
export const getCurrentSeats = (eventTypeId: number, dateFrom: Dayjs, dateTo: Dayjs) =>
prisma.booking.findMany({
where: {
eventTypeId,
startTime: {
gte: dateFrom.format(),
lte: dateTo.format(),
},
},
select: {
uid: true,
startTime: true,
_count: {
select: {
attendees: true,
},
},
},
});
export type CurrentSeats = Awaited<ReturnType<typeof getCurrentSeats>>;
/** This should be called getUsersWorkingHoursAndBusySlots (...and remaining seats, and final timezone) */
2022-06-10 15:38:46 -03:00
export async function getUserAvailability(
query: {
withSource?: boolean;
username?: string;
userId?: number;
2022-06-10 15:38:46 -03:00
dateFrom: string;
dateTo: string;
eventTypeId?: number;
afterEventBuffer?: number;
beforeEventBuffer?: number;
2022-06-10 15:38:46 -03:00
},
initialData?: {
user?: User;
eventType?: EventType;
Feature/booking page refactor (#3035) * Extracted UI related logic on the DatePicker, stripped out all logic * wip * fixed small regression due to merge * Fix alignment of the chevrons * Added isToday dot, added onMonthChange so we can fetch this month slots * Added includedDates to inverse excludedDates * removed trpcState * Improvements to the state * All params are now dynamic * This builds the flat map so not all paths block on every new build * Added requiresConfirmation * Correctly take into account getFilteredTimes to make the calendar function * Rewritten team availability, seems to work * Circumvent i18n flicker by showing the loader instead * 'You can remove this code. Its not being used now' - Hariom * Nailed a persistent little bug, new Date() caused the current day to flicker on and off * TS fixes * Fix some eventType details in AvailableTimes * '5 / 6 Seats Available' instead of '6 / Seats Available' * More type fixes * Removed unrelated merge artifact * Use WEBAPP_URL instead of hardcoded * Next round of TS fixes * I believe this was mistyped * Temporarily disabled rescheduling 'this is when you originally scheduled', so removed dep * Sorting some dead code * This page has a lot of red, not all related to this PR * A PR to your PR (#3067) * Cleanup * Cleanup * Uses zod to parse params * Type fixes * Fixes ISR * E2E fixes * Disabled dynamic bookings until post v1.7 * More test fixes * Fixed border position (transparent border) to prevent dot from jumping - and possibly fix spacing * Disabled style nitpicks * Delete useSlots.ts Removed early design artifact * Unlock DatePicker locale * Adds mini spinner to DatePicker Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: zomars <zomars@me.com>
2022-06-15 17:54:31 -03:00
currentSeats?: CurrentSeats;
2022-06-10 15:38:46 -03:00
}
) {
const { username, userId, dateFrom, dateTo, eventTypeId, afterEventBuffer, beforeEventBuffer } =
availabilitySchema.parse(query);
2022-06-10 15:38:46 -03:00
if (!dateFrom.isValid() || !dateTo.isValid())
throw new HttpError({ statusCode: 400, message: "Invalid time range given." });
const where: Prisma.UserWhereUniqueInput = {};
if (username) where.username = username;
if (userId) where.id = userId;
let user: User | null = initialData?.user || null;
if (!user) user = await getUser(where);
if (!user) throw new HttpError({ statusCode: 404, message: "No user found" });
let eventType: EventType | null = initialData?.eventType || null;
if (!eventType && eventTypeId) eventType = await getEventType(eventTypeId);
Feature/booking page refactor (#3035) * Extracted UI related logic on the DatePicker, stripped out all logic * wip * fixed small regression due to merge * Fix alignment of the chevrons * Added isToday dot, added onMonthChange so we can fetch this month slots * Added includedDates to inverse excludedDates * removed trpcState * Improvements to the state * All params are now dynamic * This builds the flat map so not all paths block on every new build * Added requiresConfirmation * Correctly take into account getFilteredTimes to make the calendar function * Rewritten team availability, seems to work * Circumvent i18n flicker by showing the loader instead * 'You can remove this code. Its not being used now' - Hariom * Nailed a persistent little bug, new Date() caused the current day to flicker on and off * TS fixes * Fix some eventType details in AvailableTimes * '5 / 6 Seats Available' instead of '6 / Seats Available' * More type fixes * Removed unrelated merge artifact * Use WEBAPP_URL instead of hardcoded * Next round of TS fixes * I believe this was mistyped * Temporarily disabled rescheduling 'this is when you originally scheduled', so removed dep * Sorting some dead code * This page has a lot of red, not all related to this PR * A PR to your PR (#3067) * Cleanup * Cleanup * Uses zod to parse params * Type fixes * Fixes ISR * E2E fixes * Disabled dynamic bookings until post v1.7 * More test fixes * Fixed border position (transparent border) to prevent dot from jumping - and possibly fix spacing * Disabled style nitpicks * Delete useSlots.ts Removed early design artifact * Unlock DatePicker locale * Adds mini spinner to DatePicker Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: zomars <zomars@me.com>
2022-06-15 17:54:31 -03:00
/* Current logic is if a booking is in a time slot mark it as busy, but seats can have more than one attendee so grab
current bookings with a seats event type and display them on the calendar, even if they are full */
let currentSeats: CurrentSeats | null = initialData?.currentSeats || null;
Feat Booking Limits (#4759) * Add db relevant stuff * Basic UI there still buggy * This UI is hard - some progress * Fix awful state mangament * Fix re-ordering * Working UI logic! * Partical working minMax function * Fix min max * bookingLImits api + tests * Moved checkBookingLimits to backend only code * Fix httperror import * Return busy times * Remove avaliablity calc * Working for everything but year * Remove redundant + fix async forloop * Add compatible type * Future proof with evenTypeId filter * Fix commonjson * Sorting + validation + tests + passing * Add empty test * Move validation check to backend * Add bookinglimits in trpc * Add test for undefined * Apply suggestions from code review Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> * Update apps/web/components/v2/eventtype/EventLimitsTab.tsx Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> * Rename value for eligiability * Rename keyof type * status code * Fix toggle not toggling off * Update apps/web/pages/v2/event-types/[type]/index.tsx Co-authored-by: Omar López <zomars@me.com> * Update apps/web/pages/v2/event-types/[type]/index.tsx Co-authored-by: Omar López <zomars@me.com> * Change back to undefined as it is working for sean. See if it fails on testapp * Fixing test builder Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: Alex van Andel <me@alexvanandel.com> Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> Co-authored-by: Hariom Balhara <hariombalhara@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: Leo Giovanetti <hello@leog.me>
2022-10-12 02:29:04 -03:00
if (!currentSeats && eventType?.seatsPerTimeSlot) {
Feature/booking page refactor (#3035) * Extracted UI related logic on the DatePicker, stripped out all logic * wip * fixed small regression due to merge * Fix alignment of the chevrons * Added isToday dot, added onMonthChange so we can fetch this month slots * Added includedDates to inverse excludedDates * removed trpcState * Improvements to the state * All params are now dynamic * This builds the flat map so not all paths block on every new build * Added requiresConfirmation * Correctly take into account getFilteredTimes to make the calendar function * Rewritten team availability, seems to work * Circumvent i18n flicker by showing the loader instead * 'You can remove this code. Its not being used now' - Hariom * Nailed a persistent little bug, new Date() caused the current day to flicker on and off * TS fixes * Fix some eventType details in AvailableTimes * '5 / 6 Seats Available' instead of '6 / Seats Available' * More type fixes * Removed unrelated merge artifact * Use WEBAPP_URL instead of hardcoded * Next round of TS fixes * I believe this was mistyped * Temporarily disabled rescheduling 'this is when you originally scheduled', so removed dep * Sorting some dead code * This page has a lot of red, not all related to this PR * A PR to your PR (#3067) * Cleanup * Cleanup * Uses zod to parse params * Type fixes * Fixes ISR * E2E fixes * Disabled dynamic bookings until post v1.7 * More test fixes * Fixed border position (transparent border) to prevent dot from jumping - and possibly fix spacing * Disabled style nitpicks * Delete useSlots.ts Removed early design artifact * Unlock DatePicker locale * Adds mini spinner to DatePicker Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: zomars <zomars@me.com>
2022-06-15 17:54:31 -03:00
currentSeats = await getCurrentSeats(eventType.id, dateFrom, dateTo);
Feat Booking Limits (#4759) * Add db relevant stuff * Basic UI there still buggy * This UI is hard - some progress * Fix awful state mangament * Fix re-ordering * Working UI logic! * Partical working minMax function * Fix min max * bookingLImits api + tests * Moved checkBookingLimits to backend only code * Fix httperror import * Return busy times * Remove avaliablity calc * Working for everything but year * Remove redundant + fix async forloop * Add compatible type * Future proof with evenTypeId filter * Fix commonjson * Sorting + validation + tests + passing * Add empty test * Move validation check to backend * Add bookinglimits in trpc * Add test for undefined * Apply suggestions from code review Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> * Update apps/web/components/v2/eventtype/EventLimitsTab.tsx Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> * Rename value for eligiability * Rename keyof type * status code * Fix toggle not toggling off * Update apps/web/pages/v2/event-types/[type]/index.tsx Co-authored-by: Omar López <zomars@me.com> * Update apps/web/pages/v2/event-types/[type]/index.tsx Co-authored-by: Omar López <zomars@me.com> * Change back to undefined as it is working for sean. See if it fails on testapp * Fixing test builder Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: Alex van Andel <me@alexvanandel.com> Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> Co-authored-by: Hariom Balhara <hariombalhara@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: Leo Giovanetti <hello@leog.me>
2022-10-12 02:29:04 -03:00
}
const bookingLimits = parseBookingLimit(eventType?.bookingLimits);
Feature/booking page refactor (#3035) * Extracted UI related logic on the DatePicker, stripped out all logic * wip * fixed small regression due to merge * Fix alignment of the chevrons * Added isToday dot, added onMonthChange so we can fetch this month slots * Added includedDates to inverse excludedDates * removed trpcState * Improvements to the state * All params are now dynamic * This builds the flat map so not all paths block on every new build * Added requiresConfirmation * Correctly take into account getFilteredTimes to make the calendar function * Rewritten team availability, seems to work * Circumvent i18n flicker by showing the loader instead * 'You can remove this code. Its not being used now' - Hariom * Nailed a persistent little bug, new Date() caused the current day to flicker on and off * TS fixes * Fix some eventType details in AvailableTimes * '5 / 6 Seats Available' instead of '6 / Seats Available' * More type fixes * Removed unrelated merge artifact * Use WEBAPP_URL instead of hardcoded * Next round of TS fixes * I believe this was mistyped * Temporarily disabled rescheduling 'this is when you originally scheduled', so removed dep * Sorting some dead code * This page has a lot of red, not all related to this PR * A PR to your PR (#3067) * Cleanup * Cleanup * Uses zod to parse params * Type fixes * Fixes ISR * E2E fixes * Disabled dynamic bookings until post v1.7 * More test fixes * Fixed border position (transparent border) to prevent dot from jumping - and possibly fix spacing * Disabled style nitpicks * Delete useSlots.ts Removed early design artifact * Unlock DatePicker locale * Adds mini spinner to DatePicker Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: zomars <zomars@me.com>
2022-06-15 17:54:31 -03:00
2022-06-10 15:38:46 -03:00
const { selectedCalendars, ...currentUser } = user;
const busyTimes = await getBusyTimes({
credentials: currentUser.credentials,
startTime: dateFrom.toISOString(),
endTime: dateTo.toISOString(),
eventTypeId,
userId: currentUser.id,
selectedCalendars,
beforeEventBuffer,
afterEventBuffer,
2022-06-10 15:38:46 -03:00
});
Feat Booking Limits (#4759) * Add db relevant stuff * Basic UI there still buggy * This UI is hard - some progress * Fix awful state mangament * Fix re-ordering * Working UI logic! * Partical working minMax function * Fix min max * bookingLImits api + tests * Moved checkBookingLimits to backend only code * Fix httperror import * Return busy times * Remove avaliablity calc * Working for everything but year * Remove redundant + fix async forloop * Add compatible type * Future proof with evenTypeId filter * Fix commonjson * Sorting + validation + tests + passing * Add empty test * Move validation check to backend * Add bookinglimits in trpc * Add test for undefined * Apply suggestions from code review Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> * Update apps/web/components/v2/eventtype/EventLimitsTab.tsx Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> * Rename value for eligiability * Rename keyof type * status code * Fix toggle not toggling off * Update apps/web/pages/v2/event-types/[type]/index.tsx Co-authored-by: Omar López <zomars@me.com> * Update apps/web/pages/v2/event-types/[type]/index.tsx Co-authored-by: Omar López <zomars@me.com> * Change back to undefined as it is working for sean. See if it fails on testapp * Fixing test builder Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: Alex van Andel <me@alexvanandel.com> Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> Co-authored-by: Hariom Balhara <hariombalhara@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: Leo Giovanetti <hello@leog.me>
2022-10-12 02:29:04 -03:00
const bufferedBusyTimes: EventBusyDetails[] = busyTimes.map((a) => ({
...a,
start: dayjs(a.start).toISOString(),
end: dayjs(a.end).toISOString(),
title: a.title,
source: query.withSource ? a.source : undefined,
2022-06-10 15:38:46 -03:00
}));
Feat Booking Limits (#4759) * Add db relevant stuff * Basic UI there still buggy * This UI is hard - some progress * Fix awful state mangament * Fix re-ordering * Working UI logic! * Partical working minMax function * Fix min max * bookingLImits api + tests * Moved checkBookingLimits to backend only code * Fix httperror import * Return busy times * Remove avaliablity calc * Working for everything but year * Remove redundant + fix async forloop * Add compatible type * Future proof with evenTypeId filter * Fix commonjson * Sorting + validation + tests + passing * Add empty test * Move validation check to backend * Add bookinglimits in trpc * Add test for undefined * Apply suggestions from code review Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> * Update apps/web/components/v2/eventtype/EventLimitsTab.tsx Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> * Rename value for eligiability * Rename keyof type * status code * Fix toggle not toggling off * Update apps/web/pages/v2/event-types/[type]/index.tsx Co-authored-by: Omar López <zomars@me.com> * Update apps/web/pages/v2/event-types/[type]/index.tsx Co-authored-by: Omar López <zomars@me.com> * Change back to undefined as it is working for sean. See if it fails on testapp * Fixing test builder Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: Alex van Andel <me@alexvanandel.com> Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> Co-authored-by: Hariom Balhara <hariombalhara@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: Leo Giovanetti <hello@leog.me>
2022-10-12 02:29:04 -03:00
if (bookingLimits) {
// Get all dates between dateFrom and dateTo
const dates = []; // this is as dayjs date
let startDate = dayjs(dateFrom);
const endDate = dayjs(dateTo);
while (startDate.isBefore(endDate)) {
dates.push(startDate);
Feat Booking Limits (#4759) * Add db relevant stuff * Basic UI there still buggy * This UI is hard - some progress * Fix awful state mangament * Fix re-ordering * Working UI logic! * Partical working minMax function * Fix min max * bookingLImits api + tests * Moved checkBookingLimits to backend only code * Fix httperror import * Return busy times * Remove avaliablity calc * Working for everything but year * Remove redundant + fix async forloop * Add compatible type * Future proof with evenTypeId filter * Fix commonjson * Sorting + validation + tests + passing * Add empty test * Move validation check to backend * Add bookinglimits in trpc * Add test for undefined * Apply suggestions from code review Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> * Update apps/web/components/v2/eventtype/EventLimitsTab.tsx Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> * Rename value for eligiability * Rename keyof type * status code * Fix toggle not toggling off * Update apps/web/pages/v2/event-types/[type]/index.tsx Co-authored-by: Omar López <zomars@me.com> * Update apps/web/pages/v2/event-types/[type]/index.tsx Co-authored-by: Omar López <zomars@me.com> * Change back to undefined as it is working for sean. See if it fails on testapp * Fixing test builder Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: Alex van Andel <me@alexvanandel.com> Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> Co-authored-by: Hariom Balhara <hariombalhara@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: Leo Giovanetti <hello@leog.me>
2022-10-12 02:29:04 -03:00
startDate = startDate.add(1, "day");
}
const ourBookings = busyTimes.filter((busyTime) =>
busyTime.source?.startsWith(`eventType-${eventType?.id}`)
);
// Apply booking limit filter against our bookings
for (const [key, limit] of Object.entries(bookingLimits)) {
const limitKey = key as keyof BookingLimit;
if (limitKey === "PER_YEAR") {
const yearlyBusyTime = await checkLimit({
eventStartDate: startDate.toDate(),
limitingNumber: limit,
eventId: eventType?.id as number,
key: "PER_YEAR",
returnBusyTimes: true,
});
if (!yearlyBusyTime) break;
bufferedBusyTimes.push({
start: yearlyBusyTime.start.toISOString(),
end: yearlyBusyTime.end.toISOString(),
});
break;
}
// Take PER_DAY and turn it into day and PER_WEEK into week etc.
const filter = limitKey.split("_")[1].toLowerCase() as "day" | "week" | "month" | "year";
// loop through all dates and check if we have reached the limit
for (const date of dates) {
let total = 0;
const startDate = date.startOf(filter);
Feat Booking Limits (#4759) * Add db relevant stuff * Basic UI there still buggy * This UI is hard - some progress * Fix awful state mangament * Fix re-ordering * Working UI logic! * Partical working minMax function * Fix min max * bookingLImits api + tests * Moved checkBookingLimits to backend only code * Fix httperror import * Return busy times * Remove avaliablity calc * Working for everything but year * Remove redundant + fix async forloop * Add compatible type * Future proof with evenTypeId filter * Fix commonjson * Sorting + validation + tests + passing * Add empty test * Move validation check to backend * Add bookinglimits in trpc * Add test for undefined * Apply suggestions from code review Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> * Update apps/web/components/v2/eventtype/EventLimitsTab.tsx Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> * Rename value for eligiability * Rename keyof type * status code * Fix toggle not toggling off * Update apps/web/pages/v2/event-types/[type]/index.tsx Co-authored-by: Omar López <zomars@me.com> * Update apps/web/pages/v2/event-types/[type]/index.tsx Co-authored-by: Omar López <zomars@me.com> * Change back to undefined as it is working for sean. See if it fails on testapp * Fixing test builder Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: Alex van Andel <me@alexvanandel.com> Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> Co-authored-by: Hariom Balhara <hariombalhara@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: Leo Giovanetti <hello@leog.me>
2022-10-12 02:29:04 -03:00
// this is parsed above with parseBookingLimit so we know it's safe.
const endDate = date.endOf(filter);
for (const booking of ourBookings) {
const bookingEventTypeId = parseInt(booking.source?.split("-")[1] as string, 10);
if (
// Only check OUR booking that matches the current eventTypeId
// we don't care about another event type in this case as we dont need to know their booking limits
!(bookingEventTypeId == eventType?.id && dayjs(booking.start).isBetween(startDate, endDate))
) {
continue;
}
// increment total and check against the limit, adding a busy time if condition is met.
total++;
if (total >= limit) {
bufferedBusyTimes.push({
start: startDate.toISOString(),
end: endDate.toISOString(),
});
break;
}
}
}
Feat Booking Limits (#4759) * Add db relevant stuff * Basic UI there still buggy * This UI is hard - some progress * Fix awful state mangament * Fix re-ordering * Working UI logic! * Partical working minMax function * Fix min max * bookingLImits api + tests * Moved checkBookingLimits to backend only code * Fix httperror import * Return busy times * Remove avaliablity calc * Working for everything but year * Remove redundant + fix async forloop * Add compatible type * Future proof with evenTypeId filter * Fix commonjson * Sorting + validation + tests + passing * Add empty test * Move validation check to backend * Add bookinglimits in trpc * Add test for undefined * Apply suggestions from code review Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> * Update apps/web/components/v2/eventtype/EventLimitsTab.tsx Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> * Rename value for eligiability * Rename keyof type * status code * Fix toggle not toggling off * Update apps/web/pages/v2/event-types/[type]/index.tsx Co-authored-by: Omar López <zomars@me.com> * Update apps/web/pages/v2/event-types/[type]/index.tsx Co-authored-by: Omar López <zomars@me.com> * Change back to undefined as it is working for sean. See if it fails on testapp * Fixing test builder Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: Alex van Andel <me@alexvanandel.com> Co-authored-by: Jeroen Reumkens <hello@jeroenreumkens.nl> Co-authored-by: Hariom Balhara <hariombalhara@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: Leo Giovanetti <hello@leog.me>
2022-10-12 02:29:04 -03:00
}
}
const userSchedule = currentUser.schedules.filter(
(schedule) => !currentUser.defaultScheduleId || schedule.id === currentUser.defaultScheduleId
)[0];
const schedule =
!eventType?.metadata?.config?.useHostSchedulesForTeamEvent && eventType?.schedule
? { ...eventType?.schedule }
: {
...userSchedule,
availability: userSchedule?.availability.map((a) => ({
...a,
userId: currentUser.id,
})),
};
2022-06-10 15:38:46 -03:00
2022-07-07 12:26:22 -03:00
const startGetWorkingHours = performance.now();
const timeZone = schedule.timeZone || eventType?.timeZone || currentUser.timeZone;
const availability =
2022-06-10 15:38:46 -03:00
schedule.availability ||
(eventType?.availability.length ? eventType.availability : currentUser.availability);
const workingHours = getWorkingHours({ timeZone }, availability);
2022-07-07 12:26:22 -03:00
const endGetWorkingHours = performance.now();
logger.debug(`getWorkingHours took ${endGetWorkingHours - startGetWorkingHours}ms for userId ${userId}`);
const dateOverrides = availability
.filter((availability) => !!availability.date)
.map((override) => {
const startTime = dayjs.utc(override.startTime);
const endTime = dayjs.utc(override.endTime);
return {
start: dayjs.utc(override.date).hour(startTime.hour()).minute(startTime.minute()).toDate(),
end: dayjs.utc(override.date).hour(endTime.hour()).minute(endTime.minute()).toDate(),
};
});
2022-06-10 15:38:46 -03:00
return {
busy: bufferedBusyTimes,
timeZone,
workingHours,
dateOverrides,
2022-06-10 15:38:46 -03:00
currentSeats,
};
}