Skip to content

Scheduling infrastructure for absolutely everyone.

Resolved conflicts

nicolas3c09837104a6
diff --cc components/booking/DatePicker.tsx
index 00000000000,1bea6caf65c..cfcc6a79cc4
mode 000000,100644..100644
--- a/components/booking/DatePicker.tsx
+++ b/components/booking/DatePicker.tsx
@@@ -1,0 -1,134 +1,135 @@@
+ import { ChevronLeftIcon, ChevronRightIcon } from "@heroicons/react/solid";
+ import { useEffect, useState } from "react";
+ import dayjs, { Dayjs } from "dayjs";
+ import utc from "dayjs/plugin/utc";
+ import timezone from "dayjs/plugin/timezone";
+ import getSlots from "@lib/slots";
++
+ dayjs.extend(utc);
+ dayjs.extend(timezone);
+
+ const DatePicker = ({
+ weekStart,
+ onDatePicked,
+ workingHours,
+ organizerTimeZone,
+ inviteeTimeZone,
+ eventLength,
+ }) => {
+ const [calendar, setCalendar] = useState([]);
+ const [selectedMonth, setSelectedMonth]: number = useState();
+ const [selectedDate, setSelectedDate]: Dayjs = useState();
+
+ useEffect(() => {
+ setSelectedMonth(dayjs().tz(inviteeTimeZone).month());
+ }, []);
+
+ useEffect(() => {
+ if (selectedDate) onDatePicked(selectedDate);
+ }, [selectedDate]);
+
+ // Handle month changes
+ const incrementMonth = () => {
+ setSelectedMonth(selectedMonth + 1);
+ };
+
+ const decrementMonth = () => {
+ setSelectedMonth(selectedMonth - 1);
+ };
+
+ useEffect(() => {
+ if (!selectedMonth) {
+ // wish next had a way of dealing with this magically;
+ return;
+ }
+
+ const inviteeDate = dayjs().tz(inviteeTimeZone).month(selectedMonth);
+
+ const isDisabled = (day: number) => {
+ const date: Dayjs = inviteeDate.date(day);
+ return (
+ date.endOf("day").isBefore(dayjs().tz(inviteeTimeZone)) ||
+ !getSlots({
+ inviteeDate: date,
+ frequency: eventLength,
+ workingHours,
+ organizerTimeZone,
+ }).length
+ );
+ };
+
+ // Set up calendar
+ const daysInMonth = inviteeDate.daysInMonth();
+ const days = [];
+ for (let i = 1; i <= daysInMonth; i++) {
+ days.push(i);
+ }
+
+ // Create placeholder elements for empty days in first week
+ let weekdayOfFirst = inviteeDate.date(1).day();
+ if (weekStart === "Monday") {
+ weekdayOfFirst -= 1;
+ if (weekdayOfFirst < 0) weekdayOfFirst = 6;
+ }
+ const emptyDays = Array(weekdayOfFirst)
+ .fill(null)
+ .map((day, i) => (
+ <div key={`e-${i}`} className={"text-center w-10 h-10 rounded-full mx-auto"}>
+ {null}
+ </div>
+ ));
+
+ // Combine placeholder days with actual days
+ setCalendar([
+ ...emptyDays,
+ ...days.map((day) => (
+ <button
+ key={day}
+ onClick={() => setSelectedDate(inviteeDate.date(day))}
+ disabled={isDisabled(day)}
+ className={
+ "text-center w-10 h-10 rounded-full mx-auto" +
+ (isDisabled(day) ? " text-gray-400 font-light" : " text-blue-600 font-medium") +
+ (selectedDate && selectedDate.isSame(inviteeDate.date(day), "day")
+ ? " bg-blue-600 text-white-important"
+ : !isDisabled(day)
+ ? " bg-blue-50"
+ : "")
+ }>
+ {day}
+ </button>
+ )),
+ ]);
+ }, [selectedMonth, inviteeTimeZone, selectedDate]);
+
+ return selectedMonth ? (
+ <div className={"mt-8 sm:mt-0 " + (selectedDate ? "sm:w-1/3 border-r sm:px-4" : "sm:w-1/2 sm:pl-4")}>
+ <div className="flex text-gray-600 font-light text-xl mb-4 ml-2">
+ <span className="w-1/2">{dayjs().month(selectedMonth).format("MMMM YYYY")}</span>
+ <div className="w-1/2 text-right">
+ <button
+ onClick={decrementMonth}
+ className={"mr-4 " + (selectedMonth <= dayjs().tz(inviteeTimeZone).month() && "text-gray-400")}
+ disabled={selectedMonth <= dayjs().tz(inviteeTimeZone).month()}>
+ <ChevronLeftIcon className="w-5 h-5" />
+ </button>
+ <button onClick={incrementMonth}>
+ <ChevronRightIcon className="w-5 h-5" />
+ </button>
+ </div>
+ </div>
+ <div className="grid grid-cols-7 gap-y-4 text-center">
+ {["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
+ .sort((a, b) => (weekStart.startsWith(a) ? -1 : weekStart.startsWith(b) ? 1 : 0))
+ .map((weekDay) => (
+ <div key={weekDay} className="uppercase text-gray-400 text-xs tracking-widest">
+ {weekDay}
+ </div>
+ ))}
+ {calendar}
+ </div>
+ </div>
+ ) : null;
+ };
+
+ export default DatePicker;
diff --cc components/booking/Slots.tsx
index 00000000000,8f92aaeb148..1b4a8bfd21b
mode 000000,100644..100644
--- a/components/booking/Slots.tsx
+++ b/components/booking/Slots.tsx
@@@ -1,0 -1,96 +1,97 @@@
-import { useState, useEffect } from "react";
++import { useEffect, useState } from "react";
+ import { useRouter } from "next/router";
+ import getSlots from "../../lib/slots";
+ import dayjs, { Dayjs } from "dayjs";
+ import isBetween from "dayjs/plugin/isBetween";
+ import utc from "dayjs/plugin/utc";
++
+ dayjs.extend(isBetween);
+ dayjs.extend(utc);
+
+ type Props = {
+ eventLength: number;
+ minimumBookingNotice?: number;
+ date: Dayjs;
+ };
+
+ const Slots = ({ eventLength, minimumBookingNotice, date, workingHours, organizerUtcOffset }: Props) => {
+ minimumBookingNotice = minimumBookingNotice || 0;
+
+ const router = useRouter();
+ const { user } = router.query;
+ const [slots, setSlots] = useState([]);
+ const [isFullyBooked, setIsFullyBooked] = useState(false);
+ const [hasErrors, setHasErrors] = useState(false);
+
+ useEffect(() => {
+ setSlots([]);
+ setIsFullyBooked(false);
+ setHasErrors(false);
+ fetch(
+ `/api/availability/${user}?dateFrom=${date.startOf("day").utc().startOf("day").format()}&dateTo=${date
+ .endOf("day")
+ .utc()
+ .endOf("day")
+ .format()}`
+ )
+ .then((res) => res.json())
+ .then(handleAvailableSlots)
+ .catch((e) => {
+ console.error(e);
+ setHasErrors(true);
+ });
+ }, [date]);
+
+ const handleAvailableSlots = (busyTimes: []) => {
+ const times = getSlots({
+ frequency: eventLength,
+ inviteeDate: date,
+ workingHours,
+ minimumBookingNotice,
+ organizerUtcOffset,
+ });
+
+ const timesLengthBeforeConflicts: number = times.length;
+
+ // Check for conflicts
+ for (let i = times.length - 1; i >= 0; i -= 1) {
+ busyTimes.every((busyTime): boolean => {
+ const startTime = dayjs(busyTime.start).utc();
+ const endTime = dayjs(busyTime.end).utc();
+ // Check if start times are the same
+ if (times[i].utc().isSame(startTime)) {
+ times.splice(i, 1);
+ }
+ // Check if time is between start and end times
+ else if (times[i].utc().isBetween(startTime, endTime)) {
+ times.splice(i, 1);
+ }
+ // Check if slot end time is between start and end time
+ else if (times[i].utc().add(eventLength, "minutes").isBetween(startTime, endTime)) {
+ times.splice(i, 1);
+ }
+ // Check if startTime is between slot
+ else if (startTime.isBetween(times[i].utc(), times[i].utc().add(eventLength, "minutes"))) {
+ times.splice(i, 1);
+ } else {
+ return true;
+ }
+ return false;
+ });
+ }
+
+ if (times.length === 0 && timesLengthBeforeConflicts !== 0) {
+ setIsFullyBooked(true);
+ }
+ // Display available times
+ setSlots(times);
+ };
+
+ return {
+ slots,
+ isFullyBooked,
+ hasErrors,
+ };
+ };
+
+ export default Slots;
diff --cc components/booking/TimeOptions.tsx
index 38aafd8bf52,580e174e4b2..a785789f1ff
--- a/components/booking/TimeOptions.tsx
+++ b/components/booking/TimeOptions.tsx
@@@ -1,10 -1,10 +1,10 @@@
- import {Switch} from "@headlessui/react";
+ import { Switch } from "@headlessui/react";
import TimezoneSelect from "react-timezone-select";
- import {useEffect, useState} from "react";
- import {timeZone, is24h} from '../../lib/clock';
+ import { useEffect, useState } from "react";
-import { timeZone, is24h } from "../../lib/clock";
++import { is24h, timeZone } from "../../lib/clock";
function classNames(...classes) {
- return classes.filter(Boolean).join(' ')
+ return classes.filter(Boolean).join(" ");
}
const TimeOptions = (props) => {
diff --cc components/ui/PoweredByCalendso.tsx
index 00000000000,2e890fa8363..a438189dedc
mode 000000,100644..100644
--- a/components/ui/PoweredByCalendso.tsx
+++ b/components/ui/PoweredByCalendso.tsx
@@@ -1,0 -1,22 +1,19 @@@
+ import Link from "next/link";
+
+ const PoweredByCalendso = () => (
+ <div className="text-xs text-center sm:text-right pt-1">
+ <Link href="https://calendso.com">
- <a
- style={{ color: "#104D86" }}
- className="opacity-50 hover:opacity-100"
- >
++ <a style={{ color: "#104D86" }} className="opacity-50 hover:opacity-100">
+ powered by{" "}
+ <img
+ style={{ top: -2 }}
+ className="w-auto inline h-3 relative"
+ src="/calendso-logo-word.svg"
+ alt="Calendso Logo"
+ />
+ </a>
+ </Link>
+ </div>
+ );
+
-export default PoweredByCalendso;
++export default PoweredByCalendso;
diff --cc components/ui/Scheduler.tsx
index 00000000000,045c726d20b..edec1319bf3
mode 000000,100644..100644
--- a/components/ui/Scheduler.tsx
+++ b/components/ui/Scheduler.tsx
@@@ -1,0 -1,143 +1,144 @@@
+ import React, { useEffect, useState } from "react";
+ import TimezoneSelect from "react-timezone-select";
+ import { TrashIcon } from "@heroicons/react/outline";
+ import { WeekdaySelect } from "./WeekdaySelect";
+ import SetTimesModal from "./modal/SetTimesModal";
+ import dayjs from "dayjs";
+ import utc from "dayjs/plugin/utc";
+ import timezone from "dayjs/plugin/timezone";
+ import { Availability } from "@prisma/client";
++
+ dayjs.extend(utc);
+ dayjs.extend(timezone);
+
+ type Props = {
+ timeZone: string;
+ availability: Availability[];
+ setTimeZone: unknown;
+ };
+
+ export const Scheduler = ({
+ availability,
+ setAvailability,
+ timeZone: selectedTimeZone,
+ setTimeZone,
+ }: Props) => {
+ const [editSchedule, setEditSchedule] = useState(-1);
+ const [dateOverrides, setDateOverrides] = useState([]);
+ const [openingHours, setOpeningHours] = useState([]);
+
+ useEffect(() => {
+ setOpeningHours(
+ availability
+ .filter((item: Availability) => item.days.length !== 0)
+ .map((item) => {
+ item.startDate = dayjs().utc().startOf("day").add(item.startTime, "minutes");
+ item.endDate = dayjs().utc().startOf("day").add(item.endTime, "minutes");
+ return item;
+ })
+ );
+ setDateOverrides(availability.filter((item: Availability) => item.date));
+ }, []);
+
+ // updates availability to how it should be formatted outside this component.
+ useEffect(() => {
+ setAvailability({
+ dateOverrides: dateOverrides,
+ openingHours: openingHours,
+ });
+ }, [dateOverrides, openingHours]);
+
+ const addNewSchedule = () => setEditSchedule(openingHours.length);
+
+ const applyEditSchedule = (changed) => {
+ // new entry
+ if (!changed.days) {
+ changed.days = [1, 2, 3, 4, 5]; // Mon - Fri
+ setOpeningHours(openingHours.concat(changed));
+ } else {
+ // update
+ const replaceWith = { ...openingHours[editSchedule], ...changed };
+ openingHours.splice(editSchedule, 1, replaceWith);
+ setOpeningHours([].concat(openingHours));
+ }
+ };
+
+ const removeScheduleAt = (toRemove: number) => {
+ openingHours.splice(toRemove, 1);
+ setOpeningHours([].concat(openingHours));
+ };
+
+ const OpeningHours = ({ idx, item }) => (
+ <li className="py-2 flex justify-between border-t">
+ <div className="inline-flex ml-2">
+ <WeekdaySelect defaultValue={item.days} onSelect={(selected: number[]) => (item.days = selected)} />
+ <button className="ml-2 text-sm px-2" type="button" onClick={() => setEditSchedule(idx)}>
+ {dayjs()
+ .startOf("day")
+ .add(item.startTime, "minutes")
+ .format(item.startTime % 60 === 0 ? "ha" : "h:mma")}
+ &nbsp;until&nbsp;
+ {dayjs()
+ .startOf("day")
+ .add(item.endTime, "minutes")
+ .format(item.endTime % 60 === 0 ? "ha" : "h:mma")}
+ </button>
+ </div>
+ <button
+ type="button"
+ onClick={() => removeScheduleAt(idx)}
+ className="btn-sm bg-transparent px-2 py-1 ml-1">
+ <TrashIcon className="h-6 w-6 inline text-gray-400 -mt-1" />
+ </button>
+ </li>
+ );
+
+ return (
+ <div>
+ <div className="rounded border flex">
+ <div className="w-3/5">
+ <div className="w-3/4 p-2">
+ <label htmlFor="timeZone" className="block text-sm font-medium text-gray-700">
+ Timezone
+ </label>
+ <div className="mt-1">
+ <TimezoneSelect
+ id="timeZone"
+ value={selectedTimeZone}
+ onChange={(tz) => setTimeZone(tz.value)}
+ className="shadow-sm focus:ring-blue-500 focus:border-blue-500 mt-1 block w-full sm:text-sm border-gray-300 rounded-md"
+ />
+ </div>
+ </div>
+ <ul>
+ {openingHours.map((item, idx) => (
+ <OpeningHours key={idx} idx={idx} item={item} />
+ ))}
+ </ul>
+ <hr />
+ <button type="button" onClick={addNewSchedule} className="btn-white btn-sm m-2">
+ Add another
+ </button>
+ </div>
+ <div className="border-l p-2 w-2/5 text-sm bg-gray-50">
+ {/*<p className="font-bold mb-2">Add date overrides</p>
+ <p className="mb-2">
+ Add dates when your availability changes from your weekly hours
+ </p>
+ <button className="btn-sm btn-white">Add a date override</button>*/}
+ </div>
+ </div>
+ {editSchedule >= 0 && (
+ <SetTimesModal
+ startTime={openingHours[editSchedule] ? openingHours[editSchedule].startTime : 540}
+ endTime={openingHours[editSchedule] ? openingHours[editSchedule].endTime : 1020}
+ onChange={(times) => applyEditSchedule({ ...(openingHours[editSchedule] || {}), ...times })}
+ onExit={() => setEditSchedule(-1)}
+ />
+ )}
+ {/*{showDateOverrideModal &&
+ <DateOverrideModal />
+ }*/}
+ </div>
+ );
+ };
diff --cc lib/calendarClient.ts
index 80b17de2709,d0752699712..364e96baa84
--- a/lib/calendarClient.ts
+++ b/lib/calendarClient.ts
@@@ -122,28 -123,25 +120,25 @@@ export interface CalendarEvent
conferenceData?: ConferenceData;
}
- // eslint-disable-next-line
- interface ConferenceData {
- createRequest: any;
+ export interface ConferenceData {
- createRequest: any;
++ createRequest: unknown;
}
- // eslint-disable-next-line
- interface IntegrationCalendar {
+ export interface IntegrationCalendar {
integration: string;
primary: boolean;
externalId: string;
name: string;
}
- // eslint-disable-next-line
- interface CalendarApiAdapter {
- createEvent(event: CalendarEvent): Promise<any>;
+ export interface CalendarApiAdapter {
- createEvent(event: CalendarEvent): Promise<any>;
++ createEvent(event: CalendarEvent): Promise<unknown>;
updateEvent(uid: string, event: CalendarEvent);
deleteEvent(uid: string);
-- getAvailability(dateFrom, dateTo, selectedCalendars: IntegrationCalendar[]): Promise<any>;
++ getAvailability(dateFrom, dateTo, selectedCalendars: IntegrationCalendar[]): Promise<unknown>;
listCalendars(): Promise<IntegrationCalendar[]>;
}
@@@ -508,15 -507,27 +504,29 @@@ const listCalendars = (withCredentials
results.reduce((acc, calendars) => acc.concat(calendars), [])
);
--const createEvent = async (credential, calEvent: CalendarEvent): Promise<any> => {
- const uid: string = translator.fromUUID(uuidv5(JSON.stringify(calEvent), uuidv5.URL));
++const createEvent = async (credential, calEvent: CalendarEvent): Promise<unknown> => {
+ const parser: CalEventParser = new CalEventParser(calEvent);
+ const uid: string = parser.getUid();
+ const richEvent: CalendarEvent = parser.asRichEvent();
- const creationResult = credential ? await calendars([credential])[0].createEvent(calEvent) : null;
+ const creationResult = credential ? await calendars([credential])[0].createEvent(richEvent) : null;
- const organizerMail = new EventOrganizerMail(calEvent, uid);
- const attendeeMail = new EventAttendeeMail(calEvent, uid);
+ const maybeHangoutLink = creationResult?.hangoutLink;
+ const maybeEntryPoints = creationResult?.entryPoints;
+ const maybeConferenceData = creationResult?.conferenceData;
+
+ const organizerMail = new EventOrganizerMail(calEvent, uid, {
+ hangoutLink: maybeHangoutLink,
+ conferenceData: maybeConferenceData,
+ entryPoints: maybeEntryPoints,
+ });
+
+ const attendeeMail = new EventAttendeeMail(calEvent, uid, {
+ hangoutLink: maybeHangoutLink,
+ conferenceData: maybeConferenceData,
+ entryPoints: maybeEntryPoints,
+ });
+
try {
await organizerMail.sendEmail();
} catch (e) {
@@@ -537,13 -548,11 +547,13 @@@
};
};
--const updateEvent = async (credential, uidToUpdate: string, calEvent: CalendarEvent): Promise<any> => {
- const newUid: string = translator.fromUUID(uuidv5(JSON.stringify(calEvent), uuidv5.URL));
++const updateEvent = async (credential, uidToUpdate: string, calEvent: CalendarEvent): Promise<unknown> => {
+ const parser: CalEventParser = new CalEventParser(calEvent);
+ const newUid: string = parser.getUid();
+ const richEvent: CalendarEvent = parser.asRichEvent();
const updateResult = credential
- ? await calendars([credential])[0].updateEvent(uidToUpdate, calEvent)
+ ? await calendars([credential])[0].updateEvent(uidToUpdate, richEvent)
: null;
const organizerMail = new EventOrganizerRescheduledMail(calEvent, newUid);
@@@ -568,7 -577,7 +578,7 @@@
};
};
--const deleteEvent = (credential, uid: string): Promise<any> => {
++const deleteEvent = (credential, uid: string): Promise<unknown> => {
if (credential) {
return calendars([credential])[0].deleteEvent(uid);
}
diff --cc lib/emails/EventAttendeeMail.ts
index cc4cf4603e5,4a1b3d10c5e..3fd73f17ae2
--- a/lib/emails/EventAttendeeMail.ts
+++ b/lib/emails/EventAttendeeMail.ts
@@@ -4,6 -4,6 +4,7 @@@ import EventMail from "./EventMail"
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
import localizedFormat from "dayjs/plugin/localizedFormat";
++
dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.extend(localizedFormat);
@@@ -22,7 -22,7 +23,7 @@@ export default class EventAttendeeMail
<br />
Your ${this.calEvent.type} with ${this.calEvent.organizer.name} at ${this.getInviteeStart().format(
"h:mma"
-- )}
++ )}
(${this.calEvent.attendees[0].timeZone}) on ${this.getInviteeStart().format(
"dddd, LL"
)} is scheduled.<br />
diff --cc lib/emails/EventMail.ts
index 9ff1cabb951,f7194d12687..90cee0b5e98
--- a/lib/emails/EventMail.ts
+++ b/lib/emails/EventMail.ts
@@@ -1,13 -1,28 +1,31 @@@
- import { CalendarEvent } from "../calendarClient";
- import { serverConfig } from "../serverConfig";
- import nodemailer from "nodemailer";
+import CalEventParser from "../CalEventParser";
+import { stripHtml } from "./helpers";
+ import { CalendarEvent, ConferenceData } from "../calendarClient";
+ import { serverConfig } from "../serverConfig";
+ import nodemailer from "nodemailer";
+
+ interface EntryPoint {
+ entryPointType?: string;
+ uri?: string;
+ label?: string;
+ pin?: string;
+ accessCode?: string;
+ meetingCode?: string;
+ passcode?: string;
+ password?: string;
+ }
+
+ interface AdditionInformation {
+ conferenceData?: ConferenceData;
+ entryPoints?: EntryPoint[];
+ hangoutLink?: string;
+ }
export default abstract class EventMail {
calEvent: CalendarEvent;
+ parser: CalEventParser;
uid: string;
+ additionInformation?: AdditionInformation;
/**
* An EventMail always consists of a CalendarEvent
@@@ -17,10 -32,10 +35,11 @@@
* @param calEvent
* @param uid
*/
- constructor(calEvent: CalendarEvent, uid: string) {
+ constructor(calEvent: CalendarEvent, uid: string, additionInformation: AdditionInformation = null) {
this.calEvent = calEvent;
this.uid = uid;
+ this.parser = new CalEventParser(calEvent);
+ this.additionInformation = additionInformation;
}
/**
diff --cc lib/emails/EventOrganizerMail.ts
index 20409ce2eb5,cc429ed16b0..48b5f078f95
--- a/lib/emails/EventOrganizerMail.ts
+++ b/lib/emails/EventOrganizerMail.ts
@@@ -30,11 -28,11 +30,11 @@@ export default class EventOrganizerMai
title: `${this.calEvent.type} with ${this.calEvent.attendees[0].name}`,
description:
this.calEvent.description +
- this.stripHtml(this.getAdditionalBody()) +
- this.stripHtml(this.getAdditionalFooter()),
+ stripHtml(this.getAdditionalBody()) +
+ stripHtml(this.getAdditionalFooter()),
duration: { minutes: dayjs(this.calEvent.endTime).diff(dayjs(this.calEvent.startTime), "minute") },
organizer: { name: this.calEvent.organizer.name, email: this.calEvent.organizer.email },
-- attendees: this.calEvent.attendees.map((attendee: any) => ({
++ attendees: this.calEvent.attendees.map((attendee: unknown) => ({
name: attendee.name,
email: attendee.email,
})),
@@@ -66,21 -64,15 +66,15 @@@
<a href="mailto:${this.calEvent.attendees[0].email}">${this.calEvent.attendees[0].email}</a><br />
<br />` +
this.getAdditionalBody() +
- (this.calEvent.location
- ? `
- <strong>Location:</strong><br />
- ${this.calEvent.location}<br />
- <br />
- `
- : "") +
+ "<br />" +
`<strong>Invitee Time Zone:</strong><br />
- ${this.calEvent.attendees[0].timeZone}<br />
- <br />
- <strong>Additional notes:</strong><br />
- ${this.calEvent.description}
- ` +
+ ${this.calEvent.attendees[0].timeZone}<br />
+ <br />
+ <strong>Additional notes:</strong><br />
+ ${this.calEvent.description}
+ ` +
this.getAdditionalFooter() +
-- `
++ `
</div>
`
);
diff --cc lib/slots.ts
index 157b56a6925,5beeb9f8af3..3313fbce2fd
--- a/lib/slots.ts
+++ b/lib/slots.ts
@@@ -1,10 -1,6 +1,7 @@@
- const dayjs = require("dayjs");
+ import dayjs, { Dayjs } from "dayjs";
+ import utc from "dayjs/plugin/utc";
+ import timezone from "dayjs/plugin/timezone";
+
- const isToday = require("dayjs/plugin/isToday");
- const utc = require("dayjs/plugin/utc");
- const timezone = require("dayjs/plugin/timezone");
-
- dayjs.extend(isToday);
dayjs.extend(utc);
dayjs.extend(timezone);
diff --cc pages/[user]/[type].tsx
index bf09b987762,7f81af14468..47c40dc5e63
--- a/pages/[user]/[type].tsx
+++ b/pages/[user]/[type].tsx
@@@ -1,23 -1,10 +1,10 @@@
import { useEffect, useState } from "react";
import { GetServerSideProps } from "next";
import Head from "next/head";
- import Link from "next/link";
-import { ClockIcon, GlobeIcon, ChevronDownIcon } from "@heroicons/react/solid";
++import { ChevronDownIcon, ClockIcon, GlobeIcon } from "@heroicons/react/solid";
import prisma from "../../lib/prisma";
import { useRouter } from "next/router";
- import dayjs, { Dayjs } from "dayjs";
- import {
- ClockIcon,
- GlobeIcon,
- ChevronDownIcon,
- ChevronLeftIcon,
- ChevronRightIcon,
- } from "@heroicons/react/solid";
- import isSameOrBefore from "dayjs/plugin/isSameOrBefore";
- import utc from "dayjs/plugin/utc";
- import timezone from "dayjs/plugin/timezone";
- dayjs.extend(isSameOrBefore);
- dayjs.extend(utc);
- dayjs.extend(timezone);
+ import { Dayjs } from "dayjs";
import { collectPageParameters, telemetryEventTypes, useTelemetry } from "../../lib/telemetry";
import AvailableTimes from "../../components/booking/AvailableTimes";
diff --cc pages/_app.tsx
index e2964ddee39,f521f293555..5473bd4188c
--- a/pages/_app.tsx
+++ b/pages/_app.tsx
@@@ -1,14 -1,15 +1,15 @@@
--import '../styles/globals.css';
--import {createTelemetryClient, TelemetryProvider} from '../lib/telemetry';
--import { Provider } from 'next-auth/client';
++import "../styles/globals.css";
++import { createTelemetryClient, TelemetryProvider } from "../lib/telemetry";
++import { Provider } from "next-auth/client";
+ import type { AppProps } from "next/app";
- function MyApp({ Component, pageProps }) {
+ function MyApp({ Component, pageProps }: AppProps) {
return (
-- <TelemetryProvider value={createTelemetryClient()}>
-- <Provider session={pageProps.session}>
-- <Component {...pageProps} />
-- </Provider>
-- </TelemetryProvider>
++ <TelemetryProvider value={createTelemetryClient()}>
++ <Provider session={pageProps.session}>
++ <Component {...pageProps} />
++ </Provider>
++ </TelemetryProvider>
);
}
diff --cc pages/api/availability/week.ts
index 00000000000,d52c55d7b7c..f0cd408e404
mode 000000,100644..100644
--- a/pages/api/availability/week.ts
+++ b/pages/api/availability/week.ts
@@@ -1,0 -1,30 +1,29 @@@
-import type { NextApiRequest, NextApiResponse } from 'next';
-import { getSession } from 'next-auth/client';
-import prisma from '../../../lib/prisma';
++import type { NextApiRequest, NextApiResponse } from "next";
++import { getSession } from "next-auth/client";
++import prisma from "../../../lib/prisma";
+
+ export default async function handler(req: NextApiRequest, res: NextApiResponse) {
- const session = await getSession({req: req});
++ const session = await getSession({ req: req });
+
+ if (!session) {
- res.status(401).json({message: "Not authenticated"});
++ res.status(401).json({ message: "Not authenticated" });
+ return;
+ }
+
+ if (req.method == "PATCH") {
-
+ const startMins = req.body.start;
+ const endMins = req.body.end;
+
- const updateWeek = await prisma.schedule.update({
++ await prisma.schedule.update({
+ where: {
+ id: session.user.id,
+ },
+ data: {
+ startTime: startMins,
- endTime: endMins
++ endTime: endMins,
+ },
+ });
+
- res.status(200).json({message: 'Start and end times updated successfully'});
++ res.status(200).json({ message: "Start and end times updated successfully" });
+ }
-}
++}
diff --cc pages/api/teams.ts
index 1ab69adbc19,1c1254fb054..73a48bd80c6
--- a/pages/api/teams.ts
+++ b/pages/api/teams.ts
@@@ -1,18 -1,18 +1,16 @@@
--import type { NextApiRequest, NextApiResponse } from 'next';
--import prisma from '../../lib/prisma';
--import {getSession} from "next-auth/client";
++import type { NextApiRequest, NextApiResponse } from "next";
++import prisma from "../../lib/prisma";
++import { getSession } from "next-auth/client";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
--
-- const session = await getSession({req: req});
++ const session = await getSession({ req: req });
if (!session) {
-- res.status(401).json({message: "Not authenticated"});
++ res.status(401).json({ message: "Not authenticated" });
return;
}
if (req.method === "POST") {
--
// TODO: Prevent creating a team with identical names?
const createTeam = await prisma.team.create({
@@@ -25,13 -25,13 +23,13 @@@
data: {
teamId: createTeam.id,
userId: session.user.id,
-- role: 'OWNER',
++ role: "OWNER",
accepted: true,
-- }
++ },
});
- return res.status(201).setHeader('Location', process.env.BASE_URL + '/api/teams/1').send(null);
- return res.status(201).json({ message: 'Team created' });
++ return res.status(201).json({ message: "Team created" });
}
- res.status(404).send(null);
- res.status(404).json({ message: 'Team not found' });
++ res.status(404).json({ message: "Team not found" });
}
diff --cc pages/availability/event/[type].tsx
index ff41c7614cb,5e99468f5b7..6302ede032a
--- a/pages/availability/event/[type].tsx
+++ b/pages/availability/event/[type].tsx
@@@ -1,17 -2,65 +2,66 @@@ import { GetServerSideProps } from "nex
import Head from "next/head";
import Link from "next/link";
import { useRouter } from "next/router";
- import { useRef, useState } from "react";
+ import { useEffect, useRef, useState } from "react";
import Select, { OptionBase } from "react-select";
- import prisma from "../../../lib/prisma";
- import { LocationType } from "../../../lib/location";
- import Shell from "../../../components/Shell";
- import { getSession, useSession } from "next-auth/client";
+ import prisma from "@lib/prisma";
+ import { LocationType } from "@lib/location";
+ import Shell from "@components/Shell";
+ import { getSession } from "next-auth/client";
+ import { Scheduler } from "@components/ui/Scheduler";
+
-import { LocationMarkerIcon, PlusCircleIcon, XIcon, PhoneIcon } from "@heroicons/react/outline";
+import { LocationMarkerIcon, PhoneIcon, PlusCircleIcon, XIcon } from "@heroicons/react/outline";
- import { EventTypeCustomInput, EventTypeCustomInputType } from "../../../lib/eventTypeInput";
+ import { EventTypeCustomInput, EventTypeCustomInputType } from "@lib/eventTypeInput";
import { PlusIcon } from "@heroicons/react/solid";
- export default function EventType(props: any): JSX.Element {
+ import dayjs from "dayjs";
+ import utc from "dayjs/plugin/utc";
-dayjs.extend(utc);
+ import timezone from "dayjs/plugin/timezone";
-import { EventType, User, Availability } from "@prisma/client";
++import { Availability, EventType, User } from "@prisma/client";
+ import { validJson } from "@lib/jsonUtils";
++
++dayjs.extend(utc);
+ dayjs.extend(timezone);
+
+ type Props = {
+ user: User;
+ eventType: EventType;
+ locationOptions: OptionBase[];
+ availability: Availability[];
+ };
+
+ type OpeningHours = {
+ days: number[];
+ startTime: number;
+ endTime: number;
+ };
+
+ type DateOverride = {
+ date: string;
+ startTime: number;
+ endTime: number;
+ };
+
+ type EventTypeInput = {
+ id: number;
+ title: string;
+ slug: string;
+ description: string;
+ length: number;
+ hidden: boolean;
+ locations: unknown;
+ eventName: string;
+ customInputs: EventTypeCustomInput[];
+ timeZone: string;
+ availability?: { openingHours: OpeningHours[]; dateOverrides: DateOverride[] };
+ };
+
+ export default function EventTypePage({
+ user,
+ eventType,
+ locationOptions,
+ availability,
+ }: Props): JSX.Element {
const router = useRouter();
const inputOptions: OptionBase[] = [
diff --cc pages/bookings/index.tsx
index 3a7b481f695,eb62b9d4552..adb75ae7439
--- a/pages/bookings/index.tsx
+++ b/pages/bookings/index.tsx
@@@ -2,9 -2,10 +2,9 @@@ import Head from "next/head"
import prisma from "../../lib/prisma";
import { getSession, useSession } from "next-auth/client";
import Shell from "../../components/Shell";
-import dayjs from "dayjs";
export default function Bookings({ bookings }) {
-- const [session, loading] = useSession();
++ const [, loading] = useSession();
if (loading) {
return <p className="text-gray-400">Loading...</p>;
diff --cc pages/settings/teams.tsx
index e4d1dc5f0bb,d74c8ddd740..c129939f3ec
--- a/pages/settings/teams.tsx
+++ b/pages/settings/teams.tsx
@@@ -1,31 -1,43 +1,41 @@@
- import Head from 'next/head';
- import prisma from '../../lib/prisma';
- import Modal from '../../components/Modal';
- import Shell from '../../components/Shell';
- import SettingsShell from '../../components/Settings';
- import { useEffect, useState } from 'react';
- import { useSession, getSession } from 'next-auth/client';
- import {
- UsersIcon,
- } from "@heroicons/react/outline";
+ import { GetServerSideProps } from "next";
-import Head from 'next/head';
-import Shell from '../../components/Shell';
-import SettingsShell from '../../components/Settings';
-import { useEffect, useState } from 'react';
++import Head from "next/head";
++import Shell from "../../components/Shell";
++import SettingsShell from "../../components/Settings";
++import { useEffect, useState } from "react";
+ import type { Session } from "next-auth";
-import { useSession, getSession } from 'next-auth/client';
-import {
- UsersIcon,
-} from "@heroicons/react/outline";
++import { getSession, useSession } from "next-auth/client";
++import { UsersIcon } from "@heroicons/react/outline";
import TeamList from "../../components/team/TeamList";
import TeamListItem from "../../components/team/TeamListItem";
- export default function Teams(props) {
-
- const [session, loading] = useSession();
+ export default function Teams() {
- const [session, loading] = useSession();
++ const [, loading] = useSession();
const [teams, setTeams] = useState([]);
const [invites, setInvites] = useState([]);
const [showCreateTeamModal, setShowCreateTeamModal] = useState(false);
- const loadTeams = () => fetch('/api/user/membership').then((res: any) => res.json()).then(
- (data) => {
- setTeams(data.membership.filter((m) => m.role !== "INVITEE"));
- setInvites(data.membership.filter((m) => m.role === "INVITEE"));
+ const handleErrors = async (resp) => {
+ if (!resp.ok) {
+ const err = await resp.json();
+ throw new Error(err.message);
}
- );
+ return resp.json();
- }
++ };
- useEffect(() => { loadTeams(); }, []);
+ const loadData = () => {
+ fetch("/api/user/membership")
- .then(handleErrors)
- .then((data) => {
- setTeams(data.membership.filter((m) => m.role !== "INVITEE"));
- setInvites(data.membership.filter((m) => m.role === "INVITEE"));
- })
- .catch(console.log);
- }
++ .then(handleErrors)
++ .then((data) => {
++ setTeams(data.membership.filter((m) => m.role !== "INVITEE"));
++ setInvites(data.membership.filter((m) => m.role === "INVITEE"));
++ })
++ .catch(console.log);
++ };
+
+ useEffect(() => {
+ loadData();
+ }, []);
if (loading) {
return <p className="text-gray-400">Loading...</p>;
@@@ -33,17 -45,18 +43,18 @@@
const createTeam = (e) => {
e.preventDefault();
- return fetch('/api/teams', {
- method: 'POST',
- body: JSON.stringify({ name: e.target.elements['name'].value }),
+
- return fetch('/api/teams', {
- method: 'POST',
- body: JSON.stringify({ name: e.target.elements['name'].value }),
++ return fetch("/api/teams", {
++ method: "POST",
++ body: JSON.stringify({ name: e.target.elements["name"].value }),
headers: {
-- 'Content-Type': 'application/json'
-- }
++ "Content-Type": "application/json",
++ },
}).then(() => {
- loadTeams();
+ loadData();
setShowCreateTeamModal(false);
});
-- }
++ };
return (
<Shell heading="Teams">
@@@ -60,10 -73,10 +71,12 @@@
<p className="mt-1 text-sm text-gray-500 mb-4">
View, edit and create teams to organise relationships between users
</p>
-- {!(invites.length || teams.length) &&
++ {!(invites.length || teams.length) && (
<div className="bg-gray-50 sm:rounded-lg">
<div className="px-4 py-5 sm:p-6">
-- <h3 className="text-lg leading-6 font-medium text-gray-900">Create a team to get started</h3>
++ <h3 className="text-lg leading-6 font-medium text-gray-900">
++ Create a team to get started
++ </h3>
<div className="mt-2 max-w-xl text-sm text-gray-500">
<p>Create your first team and invite other users to work together with you.</p>
</div>
@@@ -71,31 -84,31 +84,35 @@@
<button
type="button"
onClick={() => setShowCreateTeamModal(true)}
-- className="btn btn-primary"
-- >
++ className="btn btn-primary">
Create new team
</button>
</div>
</div>
</div>
-- }
++ )}
</div>
-- {!!(invites.length || teams.length) && <div>
-- <button className="btn-sm btn-primary" onClick={() => setShowCreateTeamModal(true)}>Create new team</button>
-- </div>}
++ {!!(invites.length || teams.length) && (
++ <div>
++ <button className="btn-sm btn-primary" onClick={() => setShowCreateTeamModal(true)}>
++ Create new team
++ </button>
++ </div>
++ )}
</div>
<div>
-- {!!teams.length &&
- <TeamList teams={teams} onChange={loadTeams}>
- <TeamList teams={teams} onChange={loadData}>
-- </TeamList>
-- }
++ {!!teams.length && <TeamList teams={teams} onChange={loadData}></TeamList>}
-- {!!invites.length && <div>
-- <h2 className="text-lg leading-6 font-medium text-gray-900">Open Invitations</h2>
-- <ul className="border px-2 rounded mt-2 mb-2 divide-y divide-gray-200">
- {invites.map((team) => <TeamListItem onChange={loadTeams} key={team.id} team={team}></TeamListItem>)}
- {invites.map((team) => <TeamListItem onChange={loadData} key={team.id} team={team}></TeamListItem>)}
-- </ul>
-- </div>}
++ {!!invites.length && (
++ <div>
++ <h2 className="text-lg leading-6 font-medium text-gray-900">Open Invitations</h2>
++ <ul className="border px-2 rounded mt-2 mb-2 divide-y divide-gray-200">
++ {invites.map((team) => (
++ <TeamListItem onChange={loadData} key={team.id} team={team}></TeamListItem>
++ ))}
++ </ul>
++ </div>
++ )}
</div>
{/*{teamsLoaded && <div className="flex justify-between">
<div>
@@@ -111,12 -124,12 +128,20 @@@
</div>}*/}
</div>
</div>
-- {showCreateTeamModal &&
-- <div className="fixed z-10 inset-0 overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
++ {showCreateTeamModal && (
++ <div
++ className="fixed z-10 inset-0 overflow-y-auto"
++ aria-labelledby="modal-title"
++ role="dialog"
++ aria-modal="true">
<div className="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
-- <div className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true"></div>
++ <div
++ className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"
++ aria-hidden="true"></div>
-- <span className="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
++ <span className="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">
++ &#8203;
++ </span>
<div className="inline-block align-bottom bg-white rounded-lg px-4 pt-5 pb-4 text-left shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full sm:p-6">
<div className="sm:flex sm:items-start mb-4">
@@@ -124,33 -137,45 +149,57 @@@
<UsersIcon className="h-6 w-6 text-blue-600" />
</div>
<div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
-- <h3 className="text-lg leading-6 font-medium text-gray-900" id="modal-title">Create a new team</h3>
++ <h3 className="text-lg leading-6 font-medium text-gray-900" id="modal-title">
++ Create a new team
++ </h3>
<div>
-- <p className="text-sm text-gray-400">
-- Create a new team to collaborate with users.
-- </p>
++ <p className="text-sm text-gray-400">Create a new team to collaborate with users.</p>
</div>
</div>
</div>
<form onSubmit={createTeam}>
<div className="mb-4">
-- <label htmlFor="name" className="block text-sm font-medium text-gray-700">Name</label>
-- <input type="text" name="name" id="name" placeholder="Acme Inc." required className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm" />
++ <label htmlFor="name" className="block text-sm font-medium text-gray-700">
++ Name
++ </label>
++ <input
++ type="text"
++ name="name"
++ id="name"
++ placeholder="Acme Inc."
++ required
++ className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
++ />
</div>
<div className="mt-5 sm:mt-4 sm:flex sm:flex-row-reverse">
<button type="submit" className="btn btn-primary">
Create team
-- </button>
-- <button onClick={() => setShowCreateTeamModal(false)} type="button" className="btn btn-white mr-2">
++ </button>
++ <button
++ onClick={() => setShowCreateTeamModal(false)}
++ type="button"
++ className="btn btn-white mr-2">
Cancel
-- </button>
++ </button>
</div>
</form>
</div>
</div>
</div>
-- }
++ )}
</SettingsShell>
</Shell>
);
- }
+ }
+
+ // Export the `session` prop to use sessions with Server Side Rendering
+ export const getServerSideProps: GetServerSideProps<{ session: Session | null }> = async (context) => {
- const session = await getSession(context);
- if (!session) {
- return { redirect: { permanent: false, destination: '/auth/login' } };
- }
++ const session = await getSession(context);
++ if (!session) {
++ return { redirect: { permanent: false, destination: "/auth/login" } };
++ }
+
- return {
- props: { session }
- }
-}
++ return {
++ props: { session },
++ };
++};
diff --cc test/lib/prisma.test.ts
index 00000000000,b2164ffd740..464d6d1aa36
mode 000000,100644..100644
--- a/test/lib/prisma.test.ts
+++ b/test/lib/prisma.test.ts
@@@ -1,0 -1,109 +1,108 @@@
-
-import { it, expect } from '@jest/globals';
++import { expect, it } from "@jest/globals";
+ import { whereAndSelect } from "@lib/prisma";
+
+ it("can decorate using whereAndSelect", async () => {
+ whereAndSelect(
+ (queryObj) => {
+ expect(queryObj).toStrictEqual({ where: { id: 1 }, select: { example: true } });
+ },
+ { id: 1 },
+ [
+ "example",
+ ]
+ );
+ });
+
+ it("can do nested selects using . seperator", async () => {
+
+ whereAndSelect(
+ (queryObj) => {
+ expect(queryObj).toStrictEqual({
+ where: {
+ uid: 1,
+ },
+ select: {
+ description: true,
+ attendees: {
+ select: {
+ email: true,
+ name: true,
+ },
+ },
+ },
+ });
+ },
+ { uid: 1 },
+ [
+ "description",
+ "attendees.email",
+ "attendees.name",
+ ]
+ );
+ });
+
+ it("can handle nesting deeply", async () => {
+ whereAndSelect(
+ (queryObj) => {
+ expect(queryObj).toStrictEqual({
+ where: {
+ uid: 1,
+ },
+ select: {
+ description: true,
+ attendees: {
+ select: {
+ email: {
+ select: {
+ nested: true,
+ }
+ },
+ name: true,
+ },
+ },
+ },
+ });
+ },
+ { uid: 1 },
+ [
+ "description",
+ "attendees.email.nested",
+ "attendees.name",
+ ]
+ );
+ });
+
+ it("can handle nesting multiple", async () => {
+ whereAndSelect(
+ (queryObj) => {
+ expect(queryObj).toStrictEqual({
+ where: {
+ uid: 1,
+ },
+ select: {
+ description: true,
+ attendees: {
+ select: {
+ email: true,
+ name: true,
+ },
+ },
+ bookings: {
+ select: {
+ id: true,
+ name: true,
+ }
+ }
+ }
+ });
+ },
+ { uid: 1 },
+ [
+ "description",
+ "attendees.email",
+ "attendees.name",
+ "bookings.id",
+ "bookings.name",
+ ]
+ );
+ });
diff --cc test/lib/slots.test.ts
index 00000000000,9412b8587f7..580619a486d
mode 000000,100644..100644
--- a/test/lib/slots.test.ts
+++ b/test/lib/slots.test.ts
@@@ -1,0 -1,56 +1,57 @@@
-import getSlots from '@lib/slots';
-import {it, expect} from '@jest/globals';
-import MockDate from 'mockdate';
-import dayjs, {Dayjs} from 'dayjs';
-import utc from 'dayjs/plugin/utc';
-import timezone from 'dayjs/plugin/timezone';
++import getSlots from "@lib/slots";
++import { expect, it } from "@jest/globals";
++import MockDate from "mockdate";
++import dayjs from "dayjs";
++import utc from "dayjs/plugin/utc";
++import timezone from "dayjs/plugin/timezone";
++
+ dayjs.extend(utc);
+ dayjs.extend(timezone);
+
+ MockDate.set('2021-06-20T11:59:59Z');
+
+ it('can fit 24 hourly slots for an empty day', async () => {
+ // 24h in a day.
+ expect(getSlots({
+ inviteeDate: dayjs().add(1, 'day'),
+ frequency: 60,
+ workingHours: [
+ { days: [...Array(7).keys()], startTime: 0, endTime: 1440 }
+ ],
+ organizerTimeZone: 'Europe/London'
+ })).toHaveLength(24);
+ });
+
+ it('only shows future booking slots on the same day', async () => {
+ // The mock date is 1s to midday, so 12 slots should be open given 0 booking notice.
+ expect(getSlots({
+ inviteeDate: dayjs(),
+ frequency: 60,
+ workingHours: [
+ { days: [...Array(7).keys()], startTime: 0, endTime: 1440 }
+ ],
+ organizerTimeZone: 'GMT'
+ })).toHaveLength(12);
+ });
+
+ it('can cut off dates that due to invitee timezone differences fall on the next day', async () => {
+ expect(getSlots({
+ inviteeDate: dayjs().tz('Europe/Amsterdam').startOf('day'), // time translation +01:00
+ frequency: 60,
+ workingHours: [
+ { days: [0], startTime: 1380, endTime: 1440 }
+ ],
+ organizerTimeZone: 'Europe/London'
+ })).toHaveLength(0);
+ });
+
+ it('can cut off dates that due to invitee timezone differences fall on the previous day', async () => {
+ expect(getSlots({
+ inviteeDate: dayjs().startOf('day'), // time translation -01:00
+ frequency: 60,
+ workingHours: [
+ { days: [0], startTime: 0, endTime: 60 }
+ ],
+ organizerTimeZone: 'Europe/London'
+ })).toHaveLength(0);
-});
++});