Feature/date overrides (#5991)
* Initial incomplete (but mostly functional) push of date override functions * Fixed date shifting on load * Bring back minDate (automatically disable all dates before current date) * Fix type error * Supply working hours to render available dates * Converted to SSR * moving defaultValues to the backend * Improv. as filter can be achieved within the reduce Co-authored-by: Omar López <[email protected]> * Double inversion -> single, as it is an early return * uniq() exit - not needed anymore * Typefixes * It's overriding dates :D * Fixed duplication DateOverrides in list * Implemented changing the month * Make dateOverrides an optional param * Fixed test (which requires dateOverrides due to auto-typing) * Prevent a full update on set as default from list view * Added some extra keys to keep ts happy * Only allow a single date override per date * Disallow editing excludedDates to the same date * Bring back duplicate key ?.? Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: zomars <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
20 files changed
+707
-202
No files matched your search
@@ -2,14 +2,16 @@ import { Availability as AvailabilityModel, Prisma, Schedule as ScheduleModel, U
|
||||
import { z } from "zod";
|
||||
|
||||
import { getUserAvailability } from "@calcom/core/getUserAvailability";
|
||||
import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "@calcom/lib/availability";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule, getWorkingHours } from "@calcom/lib/availability";
|
||||
import { yyyymmdd } from "@calcom/lib/date-fns";
|
||||
import { PrismaClient } from "@calcom/prisma/client";
|
||||
import { stringOrNumber } from "@calcom/prisma/zod-utils";
|
||||
import { Schedule } from "@calcom/types/schedule";
|
||||
import { Schedule, TimeRange } from "@calcom/types/schedule";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { router, authedProcedure } from "../../trpc";
|
||||
import { authedProcedure, router } from "../../trpc";
|
||||
|
||||
export const availabilityRouter = router({
|
||||
list: authedProcedure.query(async ({ ctx }) => {
|
||||
@@ -52,6 +54,70 @@ export const availabilityRouter = router({
|
||||
.query(({ input }) => {
|
||||
return getUserAvailability(input);
|
||||
}),
|
||||
defaultValues: authedProcedure.input(z.object({ scheduleId: z.number() })).query(async ({ ctx, input }) => {
|
||||
const { prisma, user } = ctx;
|
||||
const schedule = await prisma.schedule.findUnique({
|
||||
where: {
|
||||
id: input.scheduleId || (await getDefaultScheduleId(user.id, prisma)),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
name: true,
|
||||
availability: true,
|
||||
timeZone: true,
|
||||
eventType: {
|
||||
select: {
|
||||
_count: true,
|
||||
id: true,
|
||||
eventName: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!schedule || schedule.userId !== user.id) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
}
|
||||
const availability = convertScheduleToAvailability(schedule);
|
||||
return {
|
||||
name: schedule.name,
|
||||
rawSchedule: schedule,
|
||||
schedule: availability,
|
||||
dateOverrides: schedule.availability.reduce((acc, override) => {
|
||||
// only iff future date override
|
||||
if (!override.date || override.date < new Date()) {
|
||||
return acc;
|
||||
}
|
||||
const newValue = {
|
||||
start: dayjs
|
||||
.utc(override.date)
|
||||
.hour(override.startTime.getUTCHours())
|
||||
.minute(override.startTime.getUTCMinutes())
|
||||
.toDate(),
|
||||
end: dayjs
|
||||
.utc(override.date)
|
||||
.hour(override.endTime.getUTCHours())
|
||||
.minute(override.endTime.getUTCMinutes())
|
||||
.toDate(),
|
||||
};
|
||||
const dayRangeIndex = acc.findIndex(
|
||||
// early return prevents override.date from ever being empty.
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
(item) => yyyymmdd(item.ranges[0].start) === yyyymmdd(override.date!)
|
||||
);
|
||||
if (dayRangeIndex === -1) {
|
||||
acc.push({ ranges: [newValue] });
|
||||
return acc;
|
||||
}
|
||||
acc[dayRangeIndex].ranges.push(newValue);
|
||||
return acc;
|
||||
}, [] as { ranges: TimeRange[] }[]),
|
||||
timeZone: schedule.timeZone || user.timeZone,
|
||||
isDefault: !input.scheduleId || user.defaultScheduleId === schedule.id,
|
||||
};
|
||||
}),
|
||||
schedule: router({
|
||||
get: authedProcedure
|
||||
.input(
|
||||
@@ -88,6 +154,10 @@ export const availabilityRouter = router({
|
||||
const availability = convertScheduleToAvailability(schedule);
|
||||
return {
|
||||
schedule,
|
||||
workingHours: getWorkingHours(
|
||||
{ timeZone: schedule.timeZone || undefined },
|
||||
schedule.availability || []
|
||||
),
|
||||
availability,
|
||||
timeZone: schedule.timeZone || user.timeZone,
|
||||
isDefault: !input.scheduleId || user.defaultScheduleId === schedule.id,
|
||||
@@ -201,25 +271,36 @@ export const availabilityRouter = router({
|
||||
timeZone: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
isDefault: z.boolean().optional(),
|
||||
schedule: z.array(
|
||||
z.array(
|
||||
schedule: z
|
||||
.array(
|
||||
z.array(
|
||||
z.object({
|
||||
start: z.date(),
|
||||
end: z.date(),
|
||||
})
|
||||
)
|
||||
)
|
||||
.optional(),
|
||||
dateOverrides: z
|
||||
.array(
|
||||
z.object({
|
||||
start: z.date(),
|
||||
end: z.date(),
|
||||
})
|
||||
)
|
||||
),
|
||||
.optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const { user, prisma } = ctx;
|
||||
const availability = getAvailabilityFromSchedule(input.schedule);
|
||||
|
||||
let updatedUser;
|
||||
if (input.isDefault) {
|
||||
const setupDefault = await setupDefaultSchedule(user.id, input.scheduleId, prisma);
|
||||
updatedUser = setupDefault;
|
||||
}
|
||||
const availability = input.schedule
|
||||
? getAvailabilityFromSchedule(input.schedule)
|
||||
: (input.dateOverrides || []).map((dateOverride) => ({
|
||||
startTime: dateOverride.start,
|
||||
endTime: dateOverride.end,
|
||||
date: dateOverride.start,
|
||||
days: [],
|
||||
}));
|
||||
|
||||
// Not able to update the schedule with userId where clause, so fetch schedule separately and then validate
|
||||
// Bug: https://github.com/prisma/prisma/issues/7290
|
||||
@@ -229,6 +310,8 @@ export const availabilityRouter = router({
|
||||
},
|
||||
select: {
|
||||
userId: true,
|
||||
name: true,
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -240,6 +323,25 @@ export const availabilityRouter = router({
|
||||
});
|
||||
}
|
||||
|
||||
let updatedUser;
|
||||
if (input.isDefault) {
|
||||
const setupDefault = await setupDefaultSchedule(user.id, input.scheduleId, prisma);
|
||||
updatedUser = setupDefault;
|
||||
}
|
||||
|
||||
if (!input.name) {
|
||||
// TODO: Improve
|
||||
// We don't want to pass the full schedule for just a set as default update
|
||||
// but in the current logic, this wipes the existing availability.
|
||||
// Return early to prevent this from happening.
|
||||
return {
|
||||
schedule: userSchedule,
|
||||
isDefault: updatedUser
|
||||
? updatedUser.defaultScheduleId === input.scheduleId
|
||||
: user.defaultScheduleId === input.scheduleId,
|
||||
};
|
||||
}
|
||||
|
||||
const schedule = await prisma.schedule.update({
|
||||
where: {
|
||||
id: input.scheduleId,
|
||||
@@ -254,11 +356,14 @@ export const availabilityRouter = router({
|
||||
},
|
||||
},
|
||||
createMany: {
|
||||
data: availability.map((schedule) => ({
|
||||
days: schedule.days,
|
||||
startTime: schedule.startTime,
|
||||
endTime: schedule.endTime,
|
||||
})),
|
||||
data: [
|
||||
...availability,
|
||||
...(input.dateOverrides || []).map((override) => ({
|
||||
date: override.start,
|
||||
startTime: override.start,
|
||||
endTime: override.end,
|
||||
})),
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -138,6 +138,7 @@ async function getEventType(ctx: { prisma: typeof prisma }, input: z.infer<typeo
|
||||
},
|
||||
availability: {
|
||||
select: {
|
||||
date: true,
|
||||
startTime: true,
|
||||
endTime: true,
|
||||
days: true,
|
||||
@@ -227,11 +228,12 @@ export async function getSchedule(input: z.infer<typeof getScheduleSchema>, ctx:
|
||||
let currentSeats: CurrentSeats | undefined = undefined;
|
||||
|
||||
/* We get all users working hours and busy slots */
|
||||
const usersWorkingHoursAndBusySlots = await Promise.all(
|
||||
const userAvailability = await Promise.all(
|
||||
eventType.users.map(async (currentUser) => {
|
||||
const {
|
||||
busy,
|
||||
workingHours,
|
||||
dateOverrides,
|
||||
currentSeats: _currentSeats,
|
||||
timeZone,
|
||||
} = await getUserAvailability(
|
||||
@@ -251,11 +253,14 @@ export async function getSchedule(input: z.infer<typeof getScheduleSchema>, ctx:
|
||||
return {
|
||||
timeZone,
|
||||
workingHours,
|
||||
dateOverrides,
|
||||
busy,
|
||||
};
|
||||
})
|
||||
);
|
||||
const workingHours = getAggregateWorkingHours(usersWorkingHoursAndBusySlots, eventType.schedulingType);
|
||||
// flattens availability of multiple users
|
||||
const dateOverrides = userAvailability.flatMap((availability) => availability.dateOverrides);
|
||||
const workingHours = getAggregateWorkingHours(userAvailability, eventType.schedulingType);
|
||||
const computedAvailableSlots: Record<string, Slot[]> = {};
|
||||
const availabilityCheckProps = {
|
||||
eventLength: eventType.length,
|
||||
@@ -284,6 +289,7 @@ export async function getSchedule(input: z.infer<typeof getScheduleSchema>, ctx:
|
||||
inviteeDate: currentCheckedTime,
|
||||
eventLength: input.duration || eventType.length,
|
||||
workingHours,
|
||||
dateOverrides,
|
||||
minimumBookingNotice: eventType.minimumBookingNotice,
|
||||
frequency: eventType.slotInterval || input.duration || eventType.length,
|
||||
});
|
||||
@@ -298,7 +304,7 @@ export async function getSchedule(input: z.infer<typeof getScheduleSchema>, ctx:
|
||||
: ("some" as const);
|
||||
|
||||
const availableTimeSlots = timeSlots.filter(isTimeWithinBounds).filter((time) =>
|
||||
usersWorkingHoursAndBusySlots[filterStrategy]((schedule) => {
|
||||
userAvailability[filterStrategy]((schedule) => {
|
||||
const startCheckForAvailability = performance.now();
|
||||
const isAvailable = checkIfIsAvailable({ time, ...schedule, ...availabilityCheckProps });
|
||||
const endCheckForAvailability = performance.now();
|
||||
|
||||
Reference in new issue
Block a user