Scheduling infrastructure for absolutely everyone.
Merge branch 'main' into feature/refresh-tokens-and-error-handling
Malte Delfs88ab985ac474
diff --cc lib/calendarClient.tsindex 70624264cb3,648a4a7b5f0..ff262819f24--- a/lib/calendarClient.ts+++ b/lib/calendarClient.ts@@@ -1,91 -1,60 +1,98 @@@+ import EventOrganizerMail from "./emails/EventOrganizerMail";+ import EventAttendeeMail from "./emails/EventAttendeeMail";+ import {v5 as uuidv5} from 'uuid';+ import short from 'short-uuid';+ import EventOrganizerRescheduledMail from "./emails/EventOrganizerRescheduledMail";+ import EventAttendeeRescheduledMail from "./emails/EventAttendeeRescheduledMail";++ const translator = short();++import prisma from "./prisma";+const {google} = require('googleapis');- import createNewEventEmail from "./emails/new-event";-const googleAuth = () => {+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]);+ 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]);++ 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;+ });++ return {+ getToken: () => !isExpired() ? Promise.resolve(myGoogleAuth) : refreshAccessToken()+ };-};function handleErrorsJson(response) {- if (!response.ok) {- response.json().then(e => console.error("O365 Error", e));- throw Error(response.statusText);- }- return response.json();+ if (!response.ok) {- response.json().then(console.log);++ response.json().then(e => console.error("O365 Error", e));+ throw Error(response.statusText);+ }+ return response.json();}function handleErrorsRaw(response) {- if (!response.ok) {- response.text().then(e => console.error("O365 Error", e));- throw Error(response.statusText);- }- return response.text();+ if (!response.ok) {- response.text().then(console.log);++ response.text().then(e => console.error("O365 Error", e));+ throw Error(response.statusText);+ }+ return response.text();}const o365Auth = (credential) => {- const isExpired = (expiryDate) => expiryDate < Math.round((+(new Date()) / 1000));- 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) => {++ 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)- };+ return {+ getToken: () => !isExpired(credential.key.expiry_date) ? Promise.resolve(credential.key.access_token) : refreshAccessToken(credential.key.refresh_token)+ };};interface Person {@@@ -283,69 -251,69 +290,69 @@@ const GoogleCalendar = (credential): Careject(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;- }- }),- createEvent: (event: CalendarEvent) => new Promise((resolve, reject) => {++ })),++ 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;+ }++ const calendar = google.calendar({version: 'v3', auth: myGoogleAuth});+ calendar.events.insert({+ auth: myGoogleAuth,+ calendarId: 'primary',+ resource: payload,+ }, function (err, event) {+ if (err) {- console.log('There was an error contacting the Calendar service: ' + 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) => {++ })),++ 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}+ ],+ },+ };- 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({diff --cc pages/[user]/[type].tsxindex 9c6a88c46ca,676ca906e06..941e86b600d--- a/pages/[user]/[type].tsx+++ b/pages/[user]/[type].tsx@@@ -2,18 -2,11 +2,18 @@@ import {useEffect, useMemo, useState} fimport Head from 'next/head';import Link from 'next/link';import prisma from '../../lib/prisma';- import { useRouter } from 'next/router';- import dayjs, { Dayjs } from 'dayjs';- import { Switch } from '@headlessui/react';+ import {useRouter} from 'next/router';+ import dayjs, {Dayjs} from 'dayjs';+ import {Switch} from '@headlessui/react';import TimezoneSelect from 'react-timezone-select';-import {ChevronDownIcon, ChevronLeftIcon, ChevronRightIcon, ClockIcon, GlobeIcon} from '@heroicons/react/solid';+import {+ ClockIcon,+ GlobeIcon,+ ChevronDownIcon,+ ChevronLeftIcon,+ ChevronRightIcon,+ XCircleIcon, ExclamationIcon+} from '@heroicons/react/solid';import isSameOrBefore from 'dayjs/plugin/isSameOrBefore';import isBetween from 'dayjs/plugin/isBetween';import utc from 'dayjs/plugin/utc';diff --cc pages/[user]/book.tsxindex 1aeec756812,98b475c8134..03ffb0cb665--- a/pages/[user]/book.tsx+++ b/pages/[user]/book.tsx@@@ -49,51 -48,60 +50,70 @@@ export default function Book(props)};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 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;- }-- 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;- }++ }).join("\n\n")++ }++ if (!!notes && !!event.target.notes.value) {++ notes += "\n\nAdditional notes:\n" + event.target.notes.value;++ } else {++ notes += event.target.notes.value;++ }+- 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'+ 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: event.target.notes.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;}- );- 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']);+ 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'+ }+ );++ if (res.ok) {- let successUrl = `/success?date=${date}&type=${props.eventType.id}&user=${props.user.username}&reschedule=1&name=${payload.name}`;++ 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']);+ }++ await router.push(successUrl);+ } else {+ setLoading(false);+ setError(true);+ }}- router.push(successUrl);+ event.preventDefault();+ book();}return (@@@ -155,12 -163,41 +175,41 @@@<PhoneInput name="phone" placeholder="Enter phone number" id="phone" required className="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md" onChange={() => {}} /></div></div>)}+ {props.eventType.customInputs && props.eventType.customInputs.sort((a,b) => a.id - b.id).map(input => (+ <div className="mb-4">+ {input.type !== EventTypeCustomInputType.Bool &&+ <label htmlFor={input.label} className="block text-sm font-medium text-gray-700 mb-1">{input.label}</label>}+ {input.type === EventTypeCustomInputType.TextLong &&+ <textarea name={"custom_" + input.id} id={"custom_" + input.id}+ required={input.required}+ rows={3}+ className="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md"+ placeholder=""/>}+ {input.type === EventTypeCustomInputType.Text &&+ <input type="text" name={"custom_" + input.id} id={"custom_" + input.id}+ required={input.required}+ className="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md"+ placeholder=""/>}+ {input.type === EventTypeCustomInputType.Number &&+ <input type="number" name={"custom_" + input.id} id={"custom_" + input.id}+ required={input.required}+ className="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md"+ placeholder=""/>}+ {input.type === EventTypeCustomInputType.Bool &&+ <div className="flex items-center h-5">+ <input type="checkbox" name={"custom_" + input.id} id={"custom_" + input.id}+ className="focus:ring-blue-500 h-4 w-4 text-blue-600 border-gray-300 rounded mr-2"+ placeholder=""/>+ <label htmlFor={input.label} className="block text-sm font-medium text-gray-700">{input.label}</label>+ </div>}+ </div>+ ))}<div className="mb-4"><label htmlFor="notes" className="block text-sm font-medium text-gray-700 mb-1">Additional notes</label>- <textarea name="notes" id="notes" rows={3} className="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md" placeholder="Please share anything that will help prepare for our meeting." defaultValue={props.booking ? props.booking.description : ''}></textarea>+ <textarea name="notes" id="notes" rows={3} className="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md" placeholder="Please share anything that will help prepare for our meeting." defaultValue={props.booking ? props.booking.description : ''}/></div><div className="flex items-start">- <Button type="submit" className="btn btn-primary">{rescheduleUid ? 'Reschedule' : 'Confirm'}</Button>+ <Button type="submit" loading={loading} className="btn btn-primary">{rescheduleUid ? 'Reschedule' : 'Confirm'}</Button><Link href={"/" + props.user.username + "/" + props.eventType.slug + (rescheduleUid ? "?rescheduleUid=" + rescheduleUid : "")}><a className="ml-2 btn btn-white">Cancel</a></Link>diff --cc pages/api/book/[user].tsindex 9f802bc7976,0c43637f190..9711f482b7d--- a/pages/api/book/[user].ts+++ b/pages/api/book/[user].ts@@@ -96,21 -88,25 +88,31 @@@ export default async function handler(r});// Use all integrations- results = await async.mapLimit(currentUser.credentials, 5, async (credential) => {+ results = results.concat(await async.mapLimit(calendarCredentials, 5, async (credential) => {const bookingRefUid = booking.references.filter((ref) => ref.type === credential.type)[0].uid;- return updateEvent(credential, bookingRefUid, appendLinksToEvents(evt))- const response = await updateEvent(credential, bookingRefUid, evt);-- return {- type: credential.type,- response- };++ return updateEvent(credential, bookingRefUid, evt)+ .then(response => ({type: credential.type, success: true, response}))+ .catch(e => {+ console.error("createEvent failed", e)+ return {type: credential.type, success: false}+ });- });+ }));++ results = results.concat(await async.mapLimit(videoCredentials, 5, async (credential) => {+ const bookingRefUid = booking.references.filter((ref) => ref.type === credential.type)[0].uid;- const response = await updateMeeting(credential, bookingRefUid, evt);- return {- type: credential.type,- response- };++ return updateMeeting(credential, bookingRefUid, evt)++ .then(response => ({type: credential.type, success: true, response}))++ .catch(e => {++ console.error("createEvent failed", e)++ return {type: credential.type, success: false}++ });+ }));+ if (results.every(res => !res.success)) {+ res.status(500).json({message: "Rescheduling failed"});+ return;+ }+// Clone elementsreferencesToCreate = [...booking.references];@@@ -138,66 -134,59 +140,77 @@@]);} else {// Schedule event- results = await async.mapLimit(currentUser.credentials, 5, async (credential) => {- return createEvent(credential, appendLinksToEvents(evt))+ results = results.concat(await async.mapLimit(calendarCredentials, 5, async (credential) => {- const response = await createEvent(credential, evt);- return {- type: credential.type,- response- };++ return createEvent(credential, evt)+ .then(response => ({type: credential.type, success: true, response}))+ .catch(e => {+ console.error("createEvent failed", e)+ return {type: credential.type, success: false}+ });- });+ }));++ results = results.concat(await async.mapLimit(videoCredentials, 5, async (credential) => {- const response = await createMeeting(credential, evt);- return {- type: credential.type,- response- };++ return createMeeting(credential, evt)++ .then(response => ({type: credential.type, success: true, response}))++ .catch(e => {++ console.error("createEvent failed", e)++ return {type: credential.type, success: false}++ });+ }));+ if (results.every(res => !res.success)) {+ res.status(500).json({message: "Booking failed"});+ return;+ }+- referencesToCreate = results.filter(res => res.success).map((result => {+ referencesToCreate = results.map((result => {return {type: result.type,- uid: result.response.id+ uid: result.response.createdEvent.id.toString()};}));}- // TODO Should just be set to the true case as soon as we have a "bare email" integration class.- // UID generation should happen in the integration itself, not here.+ const hashUID = results.length > 0 ? results[0].response.uid : translator.fromUUID(uuidv5(JSON.stringify(evt), uuidv5.URL));- if(results.length === 0) {- // Legacy as well, as soon as we have a separate email integration class. Just used- // to send an email even if there is no integration at all.- const mail = new EventAttendeeMail(evt, hashUID);- await mail.sendEmail();++ try {++ // TODO Should just be set to the true case as soon as we have a "bare email" integration class.++ // UID generation should happen in the integration itself, not here.++ if(results.length === 0) {++ // Legacy as well, as soon as we have a separate email integration class. Just used++ // to send an email even if there is no integration at all.++ const mail = new EventAttendeeMail(evt, hashUID);++ await mail.sendEmail();++ }++ } catch (e) {++ console.error("send EventAttendeeMail failed", e)+ }+- await prisma.booking.create({+ let booking;+ try {+ booking = await prisma.booking.create({- data: {- uid: hashUID,- userId: currentUser.id,- references: {- create: referencesToCreate- },- eventTypeId: eventType.id,+ data: {+ uid: hashUID,+ userId: currentUser.id,+ references: {+ create: referencesToCreate+ },+ eventTypeId: eventType.id,- title: evt.title,- description: evt.description,- startTime: evt.startTime,- endTime: evt.endTime,+ title: evt.title,+ description: evt.description,+ startTime: evt.startTime,+ endTime: evt.endTime,- attendees: {- create: evt.attendees+ attendees: {+ create: evt.attendees+ }}- }- });+ });+ } catch (e) {+ console.error("Error when saving booking to db", e);+ res.status(500).json({message: "Booking already exists"});+ return;+ }- try {- // If one of the integrations allows email confirmations or no integrations are added, send it.- // TODO: locally this is really slow (maybe only because the authentication for the mail service fails), so fire and forget would be nice here- if (currentUser.credentials.length === 0 || !results.every((result) => result.response.disableConfirmationEmail)) {- await createConfirmBookedEmail(- evt, cancelLink, rescheduleLink- );- }- } catch (e) {- console.error("createConfirmBookedEmail failed", e)- }-- res.status(204).send({});- res.status(200).json(results);++ res.status(204).json({});}