Skip to content

Scheduling infrastructure for absolutely everyone.

Merge branch 'main' into feature/refresh-tokens-and-error-handling

Malte Delfs917b2c48213c
diff --cc components/booking/AvailableTimes.tsx
index 00000000000,f6f1057414f..d44465d0945
mode 000000,100644..100644
--- a/components/booking/AvailableTimes.tsx
+++ b/components/booking/AvailableTimes.tsx
@@@ -1,0 -1,87 +1,108 @@@
+ import dayjs, {Dayjs} from "dayjs";
+ import isBetween from 'dayjs/plugin/isBetween';
+ dayjs.extend(isBetween);
+ import {useEffect, useMemo, useState} from "react";
+ import getSlots from "../../lib/slots";
+ import Link from "next/link";
+ import {timeZone} from "../../lib/clock";
+ import {useRouter} from "next/router";
++import {ExclamationIcon} from "@heroicons/react/solid";
+
+ const AvailableTimes = (props) => {
+
+ const router = useRouter();
+ const { user, rescheduleUid } = router.query;
+ const [loaded, setLoaded] = useState(false);
++ const [error, setError] = useState(false);
+
+ const times = getSlots({
+ calendarTimeZone: props.user.timeZone,
+ selectedTimeZone: timeZone(),
+ eventLength: props.eventType.length,
+ selectedDate: props.date,
+ dayStartTime: props.user.startTime,
+ dayEndTime: props.user.endTime,
+ });
+
+ const handleAvailableSlots = (busyTimes: []) => {
+ // Check for conflicts
+ for (let i = times.length - 1; i >= 0; i -= 1) {
+ busyTimes.forEach(busyTime => {
+ let startTime = dayjs(busyTime.start);
+ let endTime = dayjs(busyTime.end);
+
+ // Check if start times are the same
+ if (dayjs(times[i]).format('HH:mm') == startTime.format('HH:mm')) {
+ times.splice(i, 1);
+ }
+
+ // Check if time is between start and end times
+ if (dayjs(times[i]).isBetween(startTime, endTime)) {
+ times.splice(i, 1);
+ }
+
+ // Check if slot end time is between start and end time
+ if (dayjs(times[i]).add(props.eventType.length, 'minutes').isBetween(startTime, endTime)) {
+ times.splice(i, 1);
+ }
+
+ // Check if startTime is between slot
+ if (startTime.isBetween(dayjs(times[i]), dayjs(times[i]).add(props.eventType.length, 'minutes'))) {
+ times.splice(i, 1);
+ }
+ });
+ }
+ // Display available times
+ setLoaded(true);
+ };
+
+ // Re-render only when invitee changes date
+ useEffect(() => {
+ setLoaded(false);
++ setError(false);
+ fetch(`/api/availability/${user}?dateFrom=${props.date.startOf('day').utc().format()}&dateTo=${props.date.endOf('day').utc().format()}`)
+ .then( res => res.json())
- .then(handleAvailableSlots);
++ .then(handleAvailableSlots)
++ .catch(e => setError(true))
+ }, [props.date]);
+
+ return (
+ <div className="sm:pl-4 mt-8 sm:mt-0 text-center sm:w-1/3 md:max-h-97 overflow-y-auto">
+ <div className="text-gray-600 font-light text-xl mb-4 text-left">
+ <span className="w-1/2">
+ {props.date.format("dddd DD MMMM YYYY")}
+ </span>
+ </div>
+ {
- loaded ? times.map((time) =>
++ !error && loaded && times.map((time) =>
+ <div key={dayjs(time).utc().format()}>
+ <Link
+ href={`/${props.user.username}/book?date=${dayjs(time).utc().format()}&type=${props.eventType.id}` + (rescheduleUid ? "&rescheduleUid=" + rescheduleUid : "")}>
+ <a key={dayjs(time).format("hh:mma")}
+ className="block font-medium mb-4 text-blue-600 border border-blue-600 rounded hover:text-white hover:bg-blue-600 py-4">{dayjs(time).tz(timeZone()).format(props.timeFormat)}</a>
+ </Link>
+ </div>
- ) : <div className="loader"></div>
++ )
+ }
++ {!error && !loaded && <div className="loader"/>}
++ {error &&
++ <div className="bg-yellow-50 border-l-4 border-yellow-400 p-4">
++ <div className="flex">
++ <div className="flex-shrink-0">
++ <ExclamationIcon className="h-5 w-5 text-yellow-400" aria-hidden="true" />
++ </div>
++ <div className="ml-3">
++ <p className="text-sm text-yellow-700">
++ Could not load the available time slots.{' '}
++ <a href={"mailto:" + props.user.email} className="font-medium underline text-yellow-700 hover:text-yellow-600">
++ Contact {props.user.name} via e-mail
++ </a>
++ </p>
++ </div>
++ </div>
++ </div>}
+ </div>
+ );
+ }
+
-export default AvailableTimes;
++export default AvailableTimes;
diff --cc lib/calendarClient.ts
index 1629beee1e9,791235c5e6f..b830fdfbfe0
--- a/lib/calendarClient.ts
+++ b/lib/calendarClient.ts
@@@ -7,40 -7,13 +7,39 @@@ import EventAttendeeRescheduledMail fro
const translator = short();
+ const { google } = require("googleapis");
+import prisma from "./prisma";
+
- const {google} = require('googleapis');
-
+const googleAuth = (credential) => {
+ const {client_secret, client_id, redirect_uris} = JSON.parse(process.env.GOOGLE_API_CREDENTIALS).web;
+ const myGoogleAuth = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
+ myGoogleAuth.setCredentials(credential.key);
+
+ const isExpired = () => myGoogleAuth.isTokenExpiring();
+
+ const refreshAccessToken = () => myGoogleAuth.refreshToken(credential.key.refresh_token).then(res => {
+ const token = res.res.data;
+ credential.key.access_token = token.access_token;
+ credential.key.expiry_date = token.expiry_date;
+ return prisma.credential.update({
+ where: {
+ id: credential.id
+ },
+ data: {
+ key: credential.key
+ }
+ }).then(() => {
+ myGoogleAuth.setCredentials(credential.key);
+ return myGoogleAuth;
+ });
+ }).catch(err => {
+ console.error("Error refreshing google token", err);
+ return myGoogleAuth;
+ });
-const googleAuth = () => {
- const { client_secret, client_id, redirect_uris } = JSON.parse(
- process.env.GOOGLE_API_CREDENTIALS
- ).web;
- return new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
+ return {
+ getToken: () => !isExpired() ? Promise.resolve(myGoogleAuth) : refreshAccessToken()
+ };
};
function handleErrorsJson(response) {
@@@ -60,38 -33,34 +59,40 @@@ function handleErrorsRaw(response)
}
const o365Auth = (credential) => {
- const isExpired = (expiryDate) => expiryDate < +new Date();
--
- const refreshAccessToken = (refreshToken) =>
- fetch("https://login.microsoftonline.com/common/oauth2/v2.0/token", {
- method: "POST",
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
- body: new URLSearchParams({
- scope: "User.Read Calendars.Read Calendars.ReadWrite",
- client_id: process.env.MS_GRAPH_CLIENT_ID,
- refresh_token: refreshToken,
- grant_type: "refresh_token",
- client_secret: process.env.MS_GRAPH_CLIENT_SECRET,
- }),
- })
- .then(handleErrorsJson)
- .then((responseBody) => {
- credential.key.access_token = responseBody.access_token;
- credential.key.expiry_date = Math.round(
- +new Date() / 1000 + responseBody.expires_in
- );
- return credential.key.access_token;
- });
+ const isExpired = (expiryDate) => expiryDate < Math.round((+(new Date()) / 1000));
+
+ const refreshAccessToken = (refreshToken) => {
+ return fetch('https://login.microsoftonline.com/common/oauth2/v2.0/token', {
+ method: 'POST',
+ headers: {'Content-Type': 'application/x-www-form-urlencoded'},
+ body: new URLSearchParams({
+ 'scope': 'User.Read Calendars.Read Calendars.ReadWrite',
+ 'client_id': process.env.MS_GRAPH_CLIENT_ID,
+ 'refresh_token': refreshToken,
+ 'grant_type': 'refresh_token',
+ 'client_secret': process.env.MS_GRAPH_CLIENT_SECRET,
+ })
+ })
+ .then(handleErrorsJson)
+ .then((responseBody) => {
+ credential.key.access_token = responseBody.access_token;
+ credential.key.expiry_date = Math.round((+(new Date()) / 1000) + responseBody.expires_in);
+ return prisma.credential.update({
+ where: {
+ id: credential.id
+ },
+ data: {
+ key: credential.key
+ }
+ }).then(() => credential.key.access_token)
+ })
+ }
return {
- getToken: () => !isExpired(credential.key.expiry_date) ? Promise.resolve(credential.key.access_token) : refreshAccessToken(credential.key.refresh_token)
+ getToken: () =>
+ !isExpired(credential.key.expiry_date)
+ ? Promise.resolve(credential.key.access_token)
+ : refreshAccessToken(credential.key.refresh_token),
};
};
@@@ -252,158 -267,188 +299,162 @@@ const MicrosoftOffice365Calendar = (cre
};
const GoogleCalendar = (credential): CalendarApiAdapter => {
- const myGoogleAuth = googleAuth();
- myGoogleAuth.setCredentials(credential.key);
- const integrationType = "google_calendar";
+ const auth = googleAuth(credential);
+ const integrationType = "google_calendar";
- return {
- getAvailability: (dateFrom, dateTo, selectedCalendars) =>
- new Promise((resolve, reject) => {
- const calendar = google.calendar({ version: "v3", auth: myGoogleAuth });
- calendar.calendarList
- .list()
- .then((cals) => {
- const filteredItems = cals.data.items.filter(
- (i) =>
- selectedCalendars.findIndex((e) => e.externalId === i.id) > -1
- );
- if (filteredItems.length == 0 && selectedCalendars.length > 0) {
- // Only calendars of other integrations selected
- resolve([]);
+ return {
+ getAvailability: (dateFrom, dateTo, selectedCalendars) => new Promise((resolve, reject) => auth.getToken().then(myGoogleAuth => {
+ const calendar = google.calendar({version: 'v3', auth: myGoogleAuth});
+ const selectedCalendarIds = selectedCalendars.filter(e => e.integration === integrationType).map(e => e.externalId);
+ if (selectedCalendarIds.length == 0 && selectedCalendars.length > 0){
+ // Only calendars of other integrations selected
+ resolve([]);
+ return;
}
- calendar.freebusy.query(
- {
- requestBody: {
- timeMin: dateFrom,
- timeMax: dateTo,
- items:
- filteredItems.length > 0 ? filteredItems : cals.data.items,
- },
- },
- (err, apires) => {
- if (err) {
- reject(err);
- }
- resolve(
- Object.values(apires.data.calendars).flatMap(
- (item) => item["busy"]
- )
- );
- }
- );
- })
- .catch((err) => {
- reject(err);
- });
- }),
- createEvent: (event: CalendarEvent) =>
- new Promise((resolve, reject) => {
- const payload = {
- summary: event.title,
- description: event.description,
- start: {
- dateTime: event.startTime,
- timeZone: event.organizer.timeZone,
- },
- end: {
- dateTime: event.endTime,
- timeZone: event.organizer.timeZone,
- },
- attendees: event.attendees,
- reminders: {
- useDefault: false,
- overrides: [{ method: "email", minutes: 60 }],
- },
- };
+ (selectedCalendarIds.length == 0
+ ? calendar.calendarList.list().then(cals => cals.data.items.map(cal => cal.id))
+ : Promise.resolve(selectedCalendarIds)).then(calsIds => {
+ calendar.freebusy.query({
+ requestBody: {
+ timeMin: dateFrom,
+ timeMax: dateTo,
+ items: calsIds.map(id => ({id: id}))
+ }
+ }, (err, apires) => {
+ if (err) {
+ reject(err);
+ }
+ resolve(
+ Object.values(apires.data.calendars).flatMap(
+ (item) => item["busy"]
+ )
+ )
+ });
+ })
+ .catch((err) => {
+ console.error('There was an error contacting google calendar service: ', err);
+ reject(err);
+ });
+
+ })),
+ createEvent: (event: CalendarEvent) => new Promise((resolve, reject) => auth.getToken().then(myGoogleAuth => {
+ const payload = {
+ summary: event.title,
+ description: event.description,
+ start: {
+ dateTime: event.startTime,
+ timeZone: event.organizer.timeZone,
+ },
+ end: {
+ dateTime: event.endTime,
+ timeZone: event.organizer.timeZone,
+ },
+ attendees: event.attendees,
+ reminders: {
+ useDefault: false,
+ overrides: [
+ {'method': 'email', 'minutes': 60}
+ ],
+ },
+ };
- if (event.location) {
- payload['location'] = event.location;
- }
+ if (event.location) {
+ payload["location"] = event.location;
+ }
+
+ if (event.conferenceData) {
+ payload["conferenceData"] = event.conferenceData;
+ }
- const calendar = google.calendar({ version: "v3", auth: myGoogleAuth });
- calendar.events.insert(
- {
- auth: myGoogleAuth,
- calendarId: "primary",
- resource: payload,
- conferenceDataVersion: 1,
- },
- function (err, event) {
- if (err) {
- console.log(
- "There was an error contacting the Calendar service: " + err
- );
- return reject(err);
- }
- return resolve(event.data);
- }
- );
- }),
- updateEvent: (uid: String, event: CalendarEvent) =>
- new Promise((resolve, reject) => {
- const payload = {
- summary: event.title,
- description: event.description,
- start: {
- dateTime: event.startTime,
- timeZone: event.organizer.timeZone,
- },
- end: {
- dateTime: event.endTime,
- timeZone: event.organizer.timeZone,
- },
- attendees: event.attendees,
- reminders: {
- useDefault: false,
- overrides: [{ method: "email", minutes: 60 }],
- },
- };
+ const calendar = google.calendar({version: 'v3', auth: myGoogleAuth});
+ calendar.events.insert({
+ auth: myGoogleAuth,
+ calendarId: 'primary',
+ resource: payload,
+ }, function (err, event) {
+ if (err) {
+ console.error('There was an error contacting google calendar service: ', err);
+ return reject(err);
+ }
+ return resolve(event.data);
+ });
+ })),
+ updateEvent: (uid: String, event: CalendarEvent) => new Promise((resolve, reject) => auth.getToken().then(myGoogleAuth => {
+ const payload = {
+ summary: event.title,
+ description: event.description,
+ start: {
+ dateTime: event.startTime,
+ timeZone: event.organizer.timeZone,
+ },
+ end: {
+ dateTime: event.endTime,
+ timeZone: event.organizer.timeZone,
+ },
+ attendees: event.attendees,
+ reminders: {
+ useDefault: false,
+ overrides: [
+ {'method': 'email', 'minutes': 60}
+ ],
+ },
+ };
- if (event.location) {
- payload['location'] = event.location;
- }
+ if (event.location) {
+ payload["location"] = event.location;
+ }
- const calendar = google.calendar({ version: "v3", auth: myGoogleAuth });
- calendar.events.update(
- {
- auth: myGoogleAuth,
- calendarId: "primary",
- eventId: uid,
- sendNotifications: true,
- sendUpdates: "all",
- resource: payload,
- },
- function (err, event) {
- if (err) {
- console.log(
- "There was an error contacting the Calendar service: " + err
- );
- return reject(err);
- }
- return resolve(event.data);
- }
- );
- }),
- deleteEvent: (uid: String) =>
- new Promise((resolve, reject) => {
- const calendar = google.calendar({ version: "v3", auth: myGoogleAuth });
- calendar.events.delete(
- {
- auth: myGoogleAuth,
- calendarId: "primary",
- eventId: uid,
- sendNotifications: true,
- sendUpdates: "all",
- },
- function (err, event) {
- if (err) {
- console.log(
- "There was an error contacting the Calendar service: " + err
- );
- return reject(err);
- }
- return resolve(event.data);
- }
- );
- }),
- listCalendars: () =>
- new Promise((resolve, reject) => {
- const calendar = google.calendar({ version: "v3", auth: myGoogleAuth });
- calendar.calendarList
- .list()
- .then((cals) => {
- resolve(
- cals.data.items.map((cal) => {
- const calendar: IntegrationCalendar = {
- externalId: cal.id,
- integration: integrationType,
- name: cal.summary,
- primary: cal.primary,
- };
- return calendar;
+ const calendar = google.calendar({version: 'v3', auth: myGoogleAuth});
+ calendar.events.update({
+ auth: myGoogleAuth,
+ calendarId: 'primary',
+ eventId: uid,
+ sendNotifications: true,
+ sendUpdates: 'all',
+ resource: payload
+ }, function (err, event) {
+ if (err) {
+ console.error('There was an error contacting google calendar service: ', err);
+ return reject(err);
+ }
+ return resolve(event.data);
+ });
+ })),
+ deleteEvent: (uid: String) => new Promise( (resolve, reject) => auth.getToken().then(myGoogleAuth => {
+ const calendar = google.calendar({version: 'v3', auth: myGoogleAuth});
+ calendar.events.delete({
+ auth: myGoogleAuth,
+ calendarId: 'primary',
+ eventId: uid,
+ sendNotifications: true,
+ sendUpdates: 'all',
+ }, function (err, event) {
+ if (err) {
+ console.error('There was an error contacting google calendar service: ', err);
+ return reject(err);
+ }
+ return resolve(event.data);
+ });
+ })),
+ listCalendars: () => new Promise((resolve, reject) => auth.getToken().then(myGoogleAuth => {
+ const calendar = google.calendar({version: 'v3', auth: myGoogleAuth});
+ calendar.calendarList
+ .list()
+ .then(cals => {
+ resolve(cals.data.items.map(cal => {
+ const calendar: IntegrationCalendar = {
+ externalId: cal.id, integration: integrationType, name: cal.summary, primary: cal.primary
+ }
+ return calendar;
+ }))
})
- );
- })
- .catch((err) => {
- reject(err);
- });
- }),
- };
+ .catch((err) => {
+ console.error('There was an error contacting google calendar service: ', err);
+ reject(err);
+ });
+ }))
+ };
};
// factory
diff --cc pages/[user]/book.tsx
index 03ffb0cb665,31b7f23ab61..0266ef62115
--- a/pages/[user]/book.tsx
+++ b/pages/[user]/book.tsx
@@@ -47,68 -45,77 +47,86 @@@ export default function Book(props)
const locationLabels = {
[LocationType.InPerson]: 'In-person meeting',
[LocationType.Phone]: 'Phone call',
+ [LocationType.GoogleMeet]: 'Google Meet',
};
- const bookingHandler = (event) => {
- event.preventDefault();
-
- let notes = "";
- if (props.eventType.customInputs) {
- notes = props.eventType.customInputs.map(input => {
- const data = event.target["custom_" + input.id];
- if (!!data) {
- if (input.type === EventTypeCustomInputType.Bool) {
- return input.label + "\n" + (data.value ? "Yes" : "No")
- } else {
- return input.label + "\n" + data.value
+ const bookingHandler = event => {
+ const book = async () => {
+ setLoading(true);
+ setError(false);
+ let notes = "";
+ if (props.eventType.customInputs) {
+ notes = props.eventType.customInputs.map(input => {
+ const data = event.target["custom_" + input.id];
+ if (!!data) {
+ if (input.type === EventTypeCustomInputType.Bool) {
+ return input.label + "\n" + (data.value ? "Yes" : "No")
+ } else {
+ return input.label + "\n" + data.value
+ }
}
- }
- }).join("\n\n")
- }
- if (!!notes && !!event.target.notes.value) {
- notes += "\n\nAdditional notes:\n" + event.target.notes.value;
- } else {
- notes += event.target.notes.value;
- }
+ }).join("\n\n")
+ }
+ if (!!notes && !!event.target.notes.value) {
+ notes += "\n\nAdditional notes:\n" + event.target.notes.value;
+ } else {
+ notes += event.target.notes.value;
+ }
- let payload = {
- start: dayjs(date).format(),
- end: dayjs(date).add(props.eventType.length, 'minute').format(),
- name: event.target.name.value,
- email: event.target.email.value,
- notes: notes,
- timeZone: preferredTimeZone,
- eventTypeId: props.eventType.id,
- rescheduleUid: rescheduleUid
- };
+ let payload = {
+ start: dayjs(date).format(),
+ end: dayjs(date).add(props.eventType.length, 'minute').format(),
+ name: event.target.name.value,
+ email: event.target.email.value,
+ notes: notes,
+ timeZone: preferredTimeZone,
+ eventTypeId: props.eventType.id,
+ rescheduleUid: rescheduleUid
+ };
- if (selectedLocation) {
- payload['location'] = selectedLocation === LocationType.Phone ? event.target.phone.value : locationInfo(selectedLocation).address;
+ if (selectedLocation) {
+ switch (selectedLocation) {
+ case LocationType.Phone:
+ payload['location'] = event.target.phone.value
+ break
-
++
+ case LocationType.InPerson:
+ payload['location'] = locationInfo(selectedLocation).address
+ break
-
++
+ case LocationType.GoogleMeet:
+ payload['location'] = LocationType.GoogleMeet
+ break
}
+ }
- telemetry.withJitsu(jitsu => jitsu.track(telemetryEventTypes.bookingConfirmed, collectPageParameters()));
- const res = fetch(
- '/api/book/' + user,
- {
- body: JSON.stringify(payload),
- headers: {
- 'Content-Type': 'application/json'
- },
- method: 'POST'
- }
- );
+ telemetry.withJitsu(jitsu => jitsu.track(telemetryEventTypes.bookingConfirmed, collectPageParameters()));
+ const res = await fetch(
+ '/api/book/' + user,
+ {
+ body: JSON.stringify(payload),
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ method: 'POST'
+ }
+ );
- let successUrl = `/success?date=${date}&type=${props.eventType.id}&user=${props.user.username}&reschedule=${!!rescheduleUid}&name=${payload.name}`;
- if (payload['location']) {
- if (payload['location'].includes('integration')) {
- successUrl += "&location=" + encodeURIComponent("Web conferencing details to follow.");
- }
- else {
- successUrl += "&location=" + encodeURIComponent(payload['location']);
+ if (res.ok) {
+ let successUrl = `/success?date=${date}&type=${props.eventType.id}&user=${props.user.username}&reschedule=${!!rescheduleUid}&name=${payload.name}`;
+ if (payload['location']) {
- successUrl += "&location=" + encodeURIComponent(payload['location']);
++ if (payload['location'].includes('integration')) {
++ successUrl += "&location=" + encodeURIComponent("Web conferencing details to follow.");
++ }
++ else {
++ successUrl += "&location=" + encodeURIComponent(payload['location']);
++ }
+ }
+
+ await router.push(successUrl);
+ } else {
+ setLoading(false);
+ setError(true);
}
}
diff --cc pages/api/book/[user].ts
index e5fcd285ba4,d10358e440d..386f59ab4e8
--- a/pages/api/book/[user].ts
+++ b/pages/api/book/[user].ts
@@@ -56,6 -78,24 +78,24 @@@ export default async function handler(r
]
};
+ // If phone or inPerson use raw location
+ // set evt.location to req.body.location
- if (!rawLocation.includes('integration')) {
++ if (!rawLocation?.includes('integration')) {
+ evt.location = rawLocation
+ }
+
+
+ // If location is set to an integration location
+ // Build proper transforms for evt object
+ // Extend evt object with those transformations
- if (rawLocation.includes('integration')) {
++ if (rawLocation?.includes('integration')) {
+ let maybeLocationRequestObject = getLocationRequestFromIntegration({
+ location: rawLocation
+ })
+
+ evt = merge(evt, maybeLocationRequestObject)
+ }
+
const eventType = await prisma.eventType.findFirst({
where: {
userId: currentUser.id,