Fixes user availability to be contextual to the user timezone (#1166)
* WIP, WIP, WIP, WIP * Adds missing types * Type fixes for useSlots * Type fixes * Fixes periodType 500 error when updating * Adds missing dayjs plugin and type fixes * An attempt was made to fix tests * Save work in progress * Added UTC overflow to days * Update lib/availability.ts Co-authored-by: Alex Johansson <[email protected]> * No more magic numbers * Fixed slots.test & added getWorkingHours.test * Tests pass, simpler logic, profit? * Timezone shifting! * Forgot to unskip tests * Updated the user page * Added American seed user, some fixes * tmp fix so to continue testing availability * Removed timeZone parameter, fix defaultValue auto-scroll Co-authored-by: Omar López <[email protected]> Co-authored-by: Alex Johansson <[email protected]>
This commit is contained in:
23 files changed
+587
-333
No files matched your search
+82
-3
@@ -1,11 +1,18 @@
|
||||
import { Availability } from "@prisma/client";
|
||||
import dayjs, { ConfigType } from "dayjs";
|
||||
import customParseFormat from "dayjs/plugin/customParseFormat";
|
||||
import timezone from "dayjs/plugin/timezone";
|
||||
import utc from "dayjs/plugin/utc";
|
||||
|
||||
import { Schedule, TimeRange } from "./types/schedule";
|
||||
import { Schedule, TimeRange, WorkingHours } from "./types/schedule";
|
||||
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(timezone);
|
||||
dayjs.extend(customParseFormat);
|
||||
// sets the desired time in current date, needs to be current date for proper DST translation
|
||||
export const defaultDayRange: TimeRange = {
|
||||
start: new Date(new Date().setHours(9, 0, 0, 0)),
|
||||
end: new Date(new Date().setHours(17, 0, 0, 0)),
|
||||
start: new Date(new Date().setUTCHours(9, 0, 0, 0)),
|
||||
end: new Date(new Date().setUTCHours(17, 0, 0, 0)),
|
||||
};
|
||||
|
||||
export const DEFAULT_SCHEDULE: Schedule = [
|
||||
@@ -45,3 +52,75 @@ export function getAvailabilityFromSchedule(schedule: Schedule): Availability[]
|
||||
return availability;
|
||||
}, [] as Availability[]);
|
||||
}
|
||||
|
||||
export const MINUTES_IN_DAY = 60 * 24;
|
||||
export const MINUTES_DAY_END = MINUTES_IN_DAY - 1;
|
||||
export const MINUTES_DAY_START = 0;
|
||||
|
||||
/**
|
||||
* Allows "casting" availability (days, startTime, endTime) given in UTC to a timeZone or utcOffset
|
||||
*/
|
||||
export function getWorkingHours(
|
||||
relativeTimeUnit: {
|
||||
timeZone?: string;
|
||||
utcOffset?: number;
|
||||
},
|
||||
availability: { days: number[]; startTime: ConfigType; endTime: ConfigType }[]
|
||||
) {
|
||||
// clearly bail when availability is not set, set everything available.
|
||||
if (!availability.length) {
|
||||
return [
|
||||
{
|
||||
days: [0, 1, 2, 3, 4, 5, 6],
|
||||
// shorthand for: dayjs().startOf("day").tz(timeZone).diff(dayjs.utc().startOf("day"), "minutes")
|
||||
startTime: MINUTES_DAY_START,
|
||||
endTime: MINUTES_DAY_END,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const utcOffset = relativeTimeUnit.utcOffset || dayjs().tz(relativeTimeUnit.timeZone).utcOffset();
|
||||
|
||||
const workingHours = availability.reduce((workingHours: WorkingHours[], schedule) => {
|
||||
// Get times localised to the given utcOffset/timeZone
|
||||
const startTime =
|
||||
dayjs.utc(schedule.startTime).get("hour") * 60 +
|
||||
dayjs.utc(schedule.startTime).get("minute") -
|
||||
utcOffset;
|
||||
const endTime =
|
||||
dayjs.utc(schedule.endTime).get("hour") * 60 + dayjs.utc(schedule.endTime).get("minute") - utcOffset;
|
||||
|
||||
// add to working hours, keeping startTime and endTimes between bounds (0-1439)
|
||||
const sameDayStartTime = Math.max(MINUTES_DAY_START, Math.min(MINUTES_DAY_END, startTime));
|
||||
const sameDayEndTime = Math.max(MINUTES_DAY_START, Math.min(MINUTES_DAY_END, endTime));
|
||||
if (sameDayStartTime !== sameDayEndTime) {
|
||||
workingHours.push({
|
||||
days: schedule.days,
|
||||
startTime: sameDayStartTime,
|
||||
endTime: sameDayEndTime,
|
||||
});
|
||||
}
|
||||
// check for overflow to the previous day
|
||||
if (startTime < MINUTES_DAY_START || endTime < MINUTES_DAY_START) {
|
||||
workingHours.push({
|
||||
days: schedule.days.map((day) => day - 1),
|
||||
startTime: startTime + MINUTES_IN_DAY,
|
||||
endTime: Math.min(endTime + MINUTES_IN_DAY, MINUTES_DAY_END),
|
||||
});
|
||||
}
|
||||
// else, check for overflow in the next day
|
||||
else if (startTime > MINUTES_DAY_END || endTime > MINUTES_DAY_END) {
|
||||
workingHours.push({
|
||||
days: schedule.days.map((day) => day + 1),
|
||||
startTime: Math.max(startTime - MINUTES_IN_DAY, MINUTES_DAY_START),
|
||||
endTime: endTime - MINUTES_IN_DAY,
|
||||
});
|
||||
}
|
||||
|
||||
return workingHours;
|
||||
}, []);
|
||||
|
||||
workingHours.sort((a, b) => a.startTime - b.startTime);
|
||||
|
||||
return workingHours;
|
||||
}
|
||||
+54
-59
@@ -1,4 +1,4 @@
|
||||
import { Availability, SchedulingType } from "@prisma/client";
|
||||
import { SchedulingType } from "@prisma/client";
|
||||
import dayjs, { Dayjs } from "dayjs";
|
||||
import isBetween from "dayjs/plugin/isBetween";
|
||||
import utc from "dayjs/plugin/utc";
|
||||
@@ -6,16 +6,15 @@ import { stringify } from "querystring";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import getSlots from "@lib/slots";
|
||||
|
||||
import { FreeBusyTime } from "@components/ui/Schedule/Schedule";
|
||||
import { TimeRange, WorkingHours } from "@lib/types/schedule";
|
||||
|
||||
dayjs.extend(isBetween);
|
||||
dayjs.extend(utc);
|
||||
|
||||
type AvailabilityUserResponse = {
|
||||
busy: FreeBusyTime;
|
||||
busy: TimeRange[];
|
||||
timeZone: string;
|
||||
workingHours: Availability[];
|
||||
workingHours: WorkingHours[];
|
||||
};
|
||||
|
||||
type Slot = {
|
||||
@@ -28,11 +27,6 @@ type UseSlotsProps = {
|
||||
eventTypeId: number;
|
||||
minimumBookingNotice?: number;
|
||||
date: Dayjs;
|
||||
workingHours: {
|
||||
days: number[];
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
}[];
|
||||
users: { username: string | null }[];
|
||||
schedulingType: SchedulingType | null;
|
||||
};
|
||||
@@ -52,65 +46,66 @@ export const useSlots = (props: UseSlotsProps) => {
|
||||
const dateTo = date.endOf("day").format();
|
||||
const query = stringify({ dateFrom, dateTo, eventTypeId });
|
||||
|
||||
Promise.all(
|
||||
users.map((user) =>
|
||||
fetch(`/api/availability/${user.username}?${query}`)
|
||||
.then(handleAvailableSlots)
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
setError(e);
|
||||
})
|
||||
)
|
||||
).then((results) => {
|
||||
let loadedSlots: Slot[] = results[0];
|
||||
if (results.length === 1) {
|
||||
loadedSlots = loadedSlots?.sort((a, b) => (a.time.isAfter(b.time) ? 1 : -1));
|
||||
Promise.all<Slot[]>(
|
||||
users.map((user) => fetch(`/api/availability/${user.username}?${query}`).then(handleAvailableSlots))
|
||||
)
|
||||
.then((results) => {
|
||||
let loadedSlots: Slot[] = results[0] || [];
|
||||
if (results.length === 1) {
|
||||
loadedSlots = loadedSlots?.sort((a, b) => (a.time.isAfter(b.time) ? 1 : -1));
|
||||
setSlots(loadedSlots);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
let poolingMethod;
|
||||
switch (props.schedulingType) {
|
||||
// intersect by time, does not take into account eventLength (yet)
|
||||
case SchedulingType.COLLECTIVE:
|
||||
poolingMethod = (slots: Slot[], compareWith: Slot[]) =>
|
||||
slots.filter((slot) => compareWith.some((compare) => compare.time.isSame(slot.time)));
|
||||
break;
|
||||
case SchedulingType.ROUND_ROBIN:
|
||||
// TODO: Create a Reservation (lock this slot for X minutes)
|
||||
// this will make the following code redundant
|
||||
poolingMethod = (slots: Slot[], compareWith: Slot[]) => {
|
||||
compareWith.forEach((compare) => {
|
||||
const match = slots.findIndex((slot) => slot.time.isSame(compare.time));
|
||||
if (match !== -1) {
|
||||
slots[match].users?.push(compare.users![0]);
|
||||
} else {
|
||||
slots.push(compare);
|
||||
}
|
||||
});
|
||||
return slots;
|
||||
};
|
||||
break;
|
||||
}
|
||||
|
||||
if (!poolingMethod) {
|
||||
throw Error(`No poolingMethod found for schedulingType: "${props.schedulingType}""`);
|
||||
}
|
||||
|
||||
for (let i = 1; i < results.length; i++) {
|
||||
loadedSlots = poolingMethod(loadedSlots, results[i]);
|
||||
}
|
||||
loadedSlots = loadedSlots.sort((a, b) => (a.time.isAfter(b.time) ? 1 : -1));
|
||||
setSlots(loadedSlots);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
let poolingMethod;
|
||||
switch (props.schedulingType) {
|
||||
// intersect by time, does not take into account eventLength (yet)
|
||||
case SchedulingType.COLLECTIVE:
|
||||
poolingMethod = (slots, compareWith) =>
|
||||
slots.filter((slot) => compareWith.some((compare) => compare.time.isSame(slot.time)));
|
||||
break;
|
||||
case SchedulingType.ROUND_ROBIN:
|
||||
// TODO: Create a Reservation (lock this slot for X minutes)
|
||||
// this will make the following code redundant
|
||||
poolingMethod = (slots, compareWith) => {
|
||||
compareWith.forEach((compare) => {
|
||||
const match = slots.findIndex((slot) => slot.time.isSame(compare.time));
|
||||
if (match !== -1) {
|
||||
slots[match].users.push(compare.users[0]);
|
||||
} else {
|
||||
slots.push(compare);
|
||||
}
|
||||
});
|
||||
return slots;
|
||||
};
|
||||
break;
|
||||
}
|
||||
|
||||
for (let i = 1; i < results.length; i++) {
|
||||
loadedSlots = poolingMethod(loadedSlots, results[i]);
|
||||
}
|
||||
loadedSlots = loadedSlots.sort((a, b) => (a.time.isAfter(b.time) ? 1 : -1));
|
||||
setSlots(loadedSlots);
|
||||
setLoading(false);
|
||||
});
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
setError(e);
|
||||
});
|
||||
}, [date]);
|
||||
|
||||
const handleAvailableSlots = async (res) => {
|
||||
const handleAvailableSlots = async (res: Response) => {
|
||||
const responseBody: AvailabilityUserResponse = await res.json();
|
||||
const times = getSlots({
|
||||
frequency: eventLength,
|
||||
inviteeDate: date,
|
||||
workingHours: responseBody.workingHours,
|
||||
minimumBookingNotice,
|
||||
organizerTimeZone: responseBody.timeZone,
|
||||
});
|
||||
|
||||
// Check for conflicts
|
||||
|
||||
+43
-117
@@ -1,137 +1,63 @@
|
||||
import dayjs, { Dayjs } from "dayjs";
|
||||
import timezone from "dayjs/plugin/timezone";
|
||||
import isBetween from "dayjs/plugin/isBetween";
|
||||
import utc from "dayjs/plugin/utc";
|
||||
|
||||
import { getWorkingHours } from "./availability";
|
||||
import { WorkingHours } from "./types/schedule";
|
||||
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(timezone);
|
||||
dayjs.extend(isBetween);
|
||||
|
||||
type WorkingHour = {
|
||||
days: number[];
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
};
|
||||
|
||||
type GetSlots = {
|
||||
export type GetSlots = {
|
||||
inviteeDate: Dayjs;
|
||||
frequency: number;
|
||||
workingHours: WorkingHour[];
|
||||
minimumBookingNotice?: number;
|
||||
organizerTimeZone: string;
|
||||
workingHours: WorkingHours[];
|
||||
minimumBookingNotice: number;
|
||||
};
|
||||
|
||||
type Boundary = {
|
||||
lowerBound: number;
|
||||
upperBound: number;
|
||||
const getMinuteOffset = (date: Dayjs, step: number) => {
|
||||
// Diffs the current time with the given date and iff same day; (handled by 1440) - return difference; otherwise 0
|
||||
const minuteOffset = Math.min(date.diff(dayjs().startOf("day"), "minutes"), 1440) % 1440;
|
||||
// round down to nearest step
|
||||
return Math.floor(minuteOffset / step) * step;
|
||||
};
|
||||
|
||||
const freqApply = (cb, value: number, frequency: number): number => cb(value / frequency) * frequency;
|
||||
|
||||
const intersectBoundary = (a: Boundary, b: Boundary) => {
|
||||
if (a.upperBound < b.lowerBound || a.lowerBound > b.upperBound) {
|
||||
return;
|
||||
const getSlots = ({ inviteeDate, frequency, minimumBookingNotice, workingHours }: GetSlots) => {
|
||||
// current date in invitee tz
|
||||
const startDate = dayjs(inviteeDate).add(minimumBookingNotice, "minutes"); // + minimum notice period
|
||||
// checks if the start date is in the past
|
||||
if (startDate.isBefore(dayjs(), "day")) {
|
||||
return [];
|
||||
}
|
||||
return {
|
||||
lowerBound: Math.max(b.lowerBound, a.lowerBound),
|
||||
upperBound: Math.min(b.upperBound, a.upperBound),
|
||||
};
|
||||
};
|
||||
|
||||
// say invitee is -60,1380, and boundary is -120,240 - the overlap is -60,240
|
||||
const getOverlaps = (inviteeBoundary: Boundary, boundaries: Boundary[]) =>
|
||||
boundaries.map((boundary) => intersectBoundary(inviteeBoundary, boundary)).filter(Boolean);
|
||||
const localWorkingHours = getWorkingHours(
|
||||
{ utcOffset: -inviteeDate.utcOffset() },
|
||||
workingHours.map((schedule) => ({
|
||||
days: schedule.days,
|
||||
startTime: dayjs.utc().startOf("day").add(schedule.startTime, "minutes"),
|
||||
endTime: dayjs.utc().startOf("day").add(schedule.endTime, "minutes"),
|
||||
}))
|
||||
).filter((hours) => hours.days.includes(inviteeDate.day()));
|
||||
|
||||
const organizerBoundaries = (
|
||||
workingHours: [],
|
||||
inviteeDate: Dayjs,
|
||||
inviteeBounds: Boundary,
|
||||
organizerTimeZone
|
||||
): Boundary[] => {
|
||||
const boundaries: Boundary[] = [];
|
||||
|
||||
const startDay: number = +inviteeDate.startOf("d").add(inviteeBounds.lowerBound, "minutes").format("d");
|
||||
const endDay: number = +inviteeDate.startOf("d").add(inviteeBounds.upperBound, "minutes").format("d");
|
||||
|
||||
workingHours.forEach((item) => {
|
||||
const lowerBound: number = item.startTime - dayjs().tz(organizerTimeZone).utcOffset();
|
||||
const upperBound: number = item.endTime - dayjs().tz(organizerTimeZone).utcOffset();
|
||||
if (startDay !== endDay) {
|
||||
if (inviteeBounds.lowerBound < 0) {
|
||||
// lowerBound edges into the previous day
|
||||
if (item.days.includes(startDay)) {
|
||||
boundaries.push({ lowerBound: lowerBound - 1440, upperBound: upperBound - 1440 });
|
||||
}
|
||||
if (item.days.includes(endDay)) {
|
||||
boundaries.push({ lowerBound, upperBound });
|
||||
}
|
||||
} else {
|
||||
// upperBound edges into the next day
|
||||
if (item.days.includes(endDay)) {
|
||||
boundaries.push({ lowerBound: lowerBound + 1440, upperBound: upperBound + 1440 });
|
||||
}
|
||||
if (item.days.includes(startDay)) {
|
||||
boundaries.push({ lowerBound, upperBound });
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (item.days.includes(startDay)) {
|
||||
boundaries.push({ lowerBound, upperBound });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return boundaries;
|
||||
};
|
||||
|
||||
const inviteeBoundary = (startTime: number, utcOffset: number, frequency: number): Boundary => {
|
||||
const upperBound: number = freqApply(Math.floor, 1440 - utcOffset, frequency);
|
||||
const lowerBound: number = freqApply(Math.ceil, startTime - utcOffset, frequency);
|
||||
return {
|
||||
lowerBound,
|
||||
upperBound,
|
||||
};
|
||||
};
|
||||
|
||||
const getSlotsBetweenBoundary = (frequency: number, { lowerBound, upperBound }: Boundary) => {
|
||||
const slots: Dayjs[] = [];
|
||||
for (let minutes = 0; lowerBound + minutes <= upperBound - frequency; minutes += frequency) {
|
||||
slots.push(
|
||||
dayjs
|
||||
.utc()
|
||||
.startOf("d")
|
||||
.add(lowerBound + minutes, "minutes")
|
||||
);
|
||||
for (let minutes = getMinuteOffset(inviteeDate, frequency); minutes < 1440; minutes += frequency) {
|
||||
const slot = inviteeDate.startOf("day").add(minutes, "minutes");
|
||||
// add slots to available slots if it is found to be between the start and end time of the checked working hours.
|
||||
if (
|
||||
localWorkingHours.some((hours) =>
|
||||
slot.isBetween(
|
||||
inviteeDate.startOf("day").add(hours.startTime, "minutes"),
|
||||
inviteeDate.startOf("day").add(hours.endTime, "minutes"),
|
||||
null,
|
||||
"[)"
|
||||
)
|
||||
)
|
||||
) {
|
||||
slots.push(slot);
|
||||
}
|
||||
}
|
||||
|
||||
return slots;
|
||||
};
|
||||
|
||||
const getSlots = ({
|
||||
inviteeDate,
|
||||
frequency,
|
||||
minimumBookingNotice,
|
||||
workingHours,
|
||||
organizerTimeZone,
|
||||
}: GetSlots): Dayjs[] => {
|
||||
// current date in invitee tz
|
||||
const currentDate = dayjs().utcOffset(inviteeDate.utcOffset());
|
||||
const startDate = currentDate.add(minimumBookingNotice, "minutes"); // + minimum notice period
|
||||
|
||||
const startTime = startDate.isAfter(inviteeDate)
|
||||
? // block out everything when inviteeDate is less than startDate
|
||||
startDate.diff(inviteeDate, "day") > 0
|
||||
? 1440
|
||||
: startDate.hour() * 60 + startDate.minute()
|
||||
: 0;
|
||||
|
||||
const inviteeBounds = inviteeBoundary(startTime, inviteeDate.utcOffset(), frequency);
|
||||
|
||||
return getOverlaps(
|
||||
inviteeBounds,
|
||||
organizerBoundaries(workingHours, inviteeDate, inviteeBounds, organizerTimeZone)
|
||||
)
|
||||
.reduce((slots, boundary: Boundary) => [...slots, ...getSlotsBetweenBoundary(frequency, boundary)], [])
|
||||
.map((slot) =>
|
||||
slot.utcOffset(inviteeDate.utcOffset()).month(inviteeDate.month()).date(inviteeDate.date())
|
||||
);
|
||||
};
|
||||
|
||||
export default getSlots;
|
||||
@@ -1,7 +1,6 @@
|
||||
import { SchedulingType, EventType, Availability } from "@prisma/client";
|
||||
import { EventType, SchedulingType } from "@prisma/client";
|
||||
|
||||
export type OpeningHours = Pick<Availability, "days" | "startTime" | "endTime">;
|
||||
export type DateOverride = Pick<Availability, "date" | "startTime" | "endTime">;
|
||||
import { WorkingHours } from "./schedule";
|
||||
|
||||
export type AdvancedOptions = {
|
||||
eventName?: string;
|
||||
@@ -21,7 +20,7 @@ export type AdvancedOptions = {
|
||||
label: string;
|
||||
avatar: string;
|
||||
}[];
|
||||
availability?: { openingHours: OpeningHours[]; dateOverrides: DateOverride[] };
|
||||
availability?: { openingHours: WorkingHours[]; dateOverrides: WorkingHours[] };
|
||||
customInputs?: EventTypeCustomInput[];
|
||||
timeZone: string;
|
||||
hidden: boolean;
|
||||
@@ -58,5 +57,5 @@ export type EventTypeInput = AdvancedOptions & {
|
||||
locations: unknown;
|
||||
customInputs: EventTypeCustomInput[];
|
||||
timeZone: string;
|
||||
availability?: { openingHours: OpeningHours[]; dateOverrides: DateOverride[] };
|
||||
availability?: { openingHours: WorkingHours[]; dateOverrides: WorkingHours[] };
|
||||
};
|
||||
@@ -4,3 +4,15 @@ export type TimeRange = {
|
||||
};
|
||||
|
||||
export type Schedule = TimeRange[][];
|
||||
|
||||
/**
|
||||
* ```text
|
||||
* Ensure startTime and endTime in minutes since midnight; serialized to UTC by using the organizer timeZone, either by using the schedule timeZone or the user timeZone.
|
||||
* @see lib/availability.ts getWorkingHours(timeZone: string, availability: Availability[])
|
||||
* ```
|
||||
*/
|
||||
export type WorkingHours = {
|
||||
days: number[];
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
};
|
||||
Reference in new issue
Block a user