Skip to content

Scheduling infrastructure for absolutely everyone.

Merge branch 'main' into feature/zoom-integration

nicolasebc42f0c96ac
diff --cc components/ActiveLink.tsx
index f4da7d653a7,d7ae61c3104..67b3c1d6419
--- a/components/ActiveLink.tsx
+++ b/components/ActiveLink.tsx
@@@ -1,7 -1,6 +1,6 @@@
--import { useRouter } from 'next/router'
- import PropTypes from 'prop-types'
++import {useRouter} from 'next/router'
import Link from 'next/link'
--import React, { Children } from 'react'
++import React, {Children} from 'react'
const ActiveLink = ({ children, activeClassName, ...props }) => {
const { asPath } = useRouter()
diff --cc components/Settings.tsx
index ff23e35bd1d,bfbfd19c5b8..1969c1ff75d
--- a/components/Settings.tsx
+++ b/components/Settings.tsx
@@@ -1,5 -1,5 +1,5 @@@
import ActiveLink from '../components/ActiveLink';
- import { UserCircleIcon, KeyIcon, CodeIcon, UserGroupIcon } from '@heroicons/react/outline';
-import { UserCircleIcon, KeyIcon, CodeIcon, UserGroupIcon, CreditCardIcon } from '@heroicons/react/outline';
++import {CodeIcon, CreditCardIcon, KeyIcon, UserCircleIcon, UserGroupIcon} from '@heroicons/react/outline';
export default function SettingsShell(props) {
return (
diff --cc lib/calendarClient.ts
index d6ca21ff1a1,fa358fbfa27..648a4a7b5f0
--- a/lib/calendarClient.ts
+++ b/lib/calendarClient.ts
@@@ -64,317 -56,361 +64,378 @@@ interface Person
}
interface CalendarEvent {
- type: string;
- title: string;
- startTime: string;
- endTime: string;
- description?: string;
- location?: string;
- organizer: Person;
- attendees: Person[];
+ type: string;
+ title: string;
+ startTime: string;
+ endTime: string;
+ description?: string;
+ location?: string;
+ organizer: Person;
+ attendees: Person[];
};
+ interface IntegrationCalendar {
+ integration: string;
+ primary: boolean;
+ externalId: string;
+ name: string;
+ }
+
interface CalendarApiAdapter {
- createEvent(event: CalendarEvent): Promise<any>;
+ createEvent(event: CalendarEvent): Promise<any>;
- updateEvent(uid: String, event: CalendarEvent);
+ updateEvent(uid: String, event: CalendarEvent);
- deleteEvent(uid: String);
+ deleteEvent(uid: String);
- getAvailability(dateFrom, dateTo): Promise<any>;
+ getAvailability(dateFrom, dateTo, selectedCalendars: IntegrationCalendar[]): Promise<any>;
+
+ listCalendars(): Promise<IntegrationCalendar[]>;
}
const MicrosoftOffice365Calendar = (credential): CalendarApiAdapter => {
- const auth = o365Auth(credential);
+ const auth = o365Auth(credential);
- const translateEvent = (event: CalendarEvent) => {
+ const translateEvent = (event: CalendarEvent) => {
- let optional = {};
- if (event.location) {
- optional.location = {displayName: event.location};
- }
+ let optional = {};
+ if (event.location) {
+ optional.location = {displayName: event.location};
+ }
- return {
- subject: event.title,
- body: {
- contentType: 'HTML',
- content: event.description,
- },
- start: {
- dateTime: event.startTime,
- timeZone: event.organizer.timeZone,
- },
- end: {
- dateTime: event.endTime,
- timeZone: event.organizer.timeZone,
- },
- attendees: event.attendees.map(attendee => ({
- emailAddress: {
- address: attendee.email,
- name: attendee.name
- },
- type: "required"
- })),
- ...optional
- }
- };
+ return {
+ subject: event.title,
+ body: {
+ contentType: 'HTML',
+ content: event.description,
+ },
+ start: {
+ dateTime: event.startTime,
+ timeZone: event.organizer.timeZone,
+ },
+ end: {
+ dateTime: event.endTime,
+ timeZone: event.organizer.timeZone,
+ },
+ attendees: event.attendees.map(attendee => ({
+ emailAddress: {
+ address: attendee.email,
+ name: attendee.name
+ },
+ type: "required"
+ })),
+ ...optional
+ }
+ };
- return {
- getAvailability: (dateFrom, dateTo) => {
- const payload = {
- schedules: [credential.key.email],
- startTime: {
- dateTime: dateFrom,
- timeZone: 'UTC',
- },
- endTime: {
- dateTime: dateTo,
- timeZone: 'UTC',
- },
- availabilityViewInterval: 60
- };
+ const integrationType = "office365_calendar";
+
+ function listCalendars(): Promise<IntegrationCalendar[]> {
+ return auth.getToken().then(accessToken => fetch('https://graph.microsoft.com/v1.0/me/calendars', {
+ method: 'get',
+ headers: {
+ 'Authorization': 'Bearer ' + accessToken,
+ 'Content-Type': 'application/json'
+ },
+ }).then(handleErrorsJson)
+ .then(responseBody => {
+ return responseBody.value.map(cal => {
+ const calendar: IntegrationCalendar = {
+ externalId: cal.id, integration: integrationType, name: cal.name, primary: cal.isDefaultCalendar
+ }
+ return calendar;
+ });
+ })
+ )
+ }
- return auth.getToken().then(
- (accessToken) => fetch('https://graph.microsoft.com/v1.0/me/calendar/getSchedule', {
- method: 'post',
- headers: {
- 'Authorization': 'Bearer ' + accessToken,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(payload)
- })
- .then(handleErrorsJson)
- .then(responseBody => {
- return responseBody.value[0].scheduleItems.map((evt) => ({
- start: evt.start.dateTime + 'Z',
- end: evt.end.dateTime + 'Z'
- }))
- })
- ).catch((err) => {
- console.log(err);
- });
- },
- createEvent: (event: CalendarEvent) => auth.getToken().then(accessToken => fetch('https://graph.microsoft.com/v1.0/me/calendar/events', {
- method: 'POST',
- headers: {
- 'Authorization': 'Bearer ' + accessToken,
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(translateEvent(event))
- }).then(handleErrorsJson).then((responseBody) => ({
- ...responseBody,
- disableConfirmationEmail: true,
- }))),
- deleteEvent: (uid: String) => auth.getToken().then(accessToken => fetch('https://graph.microsoft.com/v1.0/me/calendar/events/' + uid, {
- method: 'DELETE',
- headers: {
- 'Authorization': 'Bearer ' + accessToken
- }
- }).then(handleErrorsRaw)),
- updateEvent: (uid: String, event: CalendarEvent) => auth.getToken().then(accessToken => fetch('https://graph.microsoft.com/v1.0/me/calendar/events/' + uid, {
- method: 'PATCH',
- headers: {
- 'Authorization': 'Bearer ' + accessToken,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(translateEvent(event))
- }).then(handleErrorsRaw)),
- }
+ return {
+ getAvailability: (dateFrom, dateTo, selectedCalendars) => {
+ const filter = "?$filter=start/dateTime ge '" + dateFrom + "' and end/dateTime le '" + dateTo + "'"
+ return auth.getToken().then(
+ (accessToken) => {
+ 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
+ return Promise.resolve([]);
+ }
+
+ return (selectedCalendarIds.length == 0
+ ? listCalendars().then(cals => cals.map(e => e.externalId))
+ : Promise.resolve(selectedCalendarIds).then(x => x)).then((ids: string[]) => {
+ const urls = ids.map(calendarId => 'https://graph.microsoft.com/v1.0/me/calendars/' + calendarId + '/events' + filter)
+ return Promise.all(urls.map(url => fetch(url, {
+ method: 'get',
+ headers: {
+ 'Authorization': 'Bearer ' + accessToken,
+ 'Prefer': 'outlook.timezone="Etc/GMT"'
+ }
+ })
+ .then(handleErrorsJson)
+ .then(responseBody => responseBody.value.map((evt) => ({
+ start: evt.start.dateTime + 'Z',
+ end: evt.end.dateTime + 'Z'
+ }))
+ ))).then(results => results.reduce((acc, events) => acc.concat(events), []))
+ })
+ }
+ ).catch((err) => {
+ console.log(err);
+ });
+ },
+ createEvent: (event: CalendarEvent) => auth.getToken().then(accessToken => fetch('https://graph.microsoft.com/v1.0/me/calendar/events', {
+ method: 'POST',
+ headers: {
+ 'Authorization': 'Bearer ' + accessToken,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(translateEvent(event))
+ }).then(handleErrorsJson).then((responseBody) => ({
+ ...responseBody,
+ disableConfirmationEmail: true,
+ }))),
+ deleteEvent: (uid: String) => auth.getToken().then(accessToken => fetch('https://graph.microsoft.com/v1.0/me/calendar/events/' + uid, {
+ method: 'DELETE',
+ headers: {
+ 'Authorization': 'Bearer ' + accessToken
+ }
+ }).then(handleErrorsRaw)),
+ updateEvent: (uid: String, event: CalendarEvent) => auth.getToken().then(accessToken => fetch('https://graph.microsoft.com/v1.0/me/calendar/events/' + uid, {
+ method: 'PATCH',
+ headers: {
+ 'Authorization': 'Bearer ' + accessToken,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(translateEvent(event))
+ }).then(handleErrorsRaw)),
+ listCalendars
+ }
};
const GoogleCalendar = (credential): CalendarApiAdapter => {
- const myGoogleAuth = googleAuth();
- myGoogleAuth.setCredentials(credential.key);
- return {
- getAvailability: (dateFrom, dateTo) => new Promise((resolve, reject) => {
- const calendar = google.calendar({version: 'v3', auth: myGoogleAuth});
- calendar.calendarList
- .list()
- .then(cals => {
- calendar.freebusy.query({
- requestBody: {
- timeMin: dateFrom,
- timeMax: dateTo,
- items: cals.data.items
- }
- }, (err, apires) => {
- if (err) {
- reject(err);
- }
- resolve(
- Object.values(apires.data.calendars).flatMap(
- (item) => item["busy"]
- )
- )
- });
- })
- .catch((err) => {
- reject(err);
- });
+ const myGoogleAuth = googleAuth();
+ myGoogleAuth.setCredentials(credential.key);
+ 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([]);
+ }
+ 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}
- ],
- },
- };
-
- if (event.location) {
- payload['location'] = event.location;
- }
+ }),
+ 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}
+ ],
+ },
+ };
+
+ 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);
+ 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.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}
- ],
- },
- };
-
- 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);
- });
- })
- };
+ 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;
+ }))
+ })
+ .catch((err) => {
+ reject(err);
+ });
+ })
+ };
};
// factory
const calendars = (withCredentials): CalendarApiAdapter[] => withCredentials.map((cred) => {
- switch (cred.type) {
- case 'google_calendar':
- return GoogleCalendar(cred);
- case 'office365_calendar':
- return MicrosoftOffice365Calendar(cred);
- default:
- return; // unknown credential, could be legacy? In any case, ignore
- }
+ switch (cred.type) {
+ case 'google_calendar':
+ return GoogleCalendar(cred);
+ case 'office365_calendar':
+ return MicrosoftOffice365Calendar(cred);
+ default:
+ return; // unknown credential, could be legacy? In any case, ignore
+ }
}).filter(Boolean);
-const getBusyTimes = (withCredentials, dateFrom, dateTo, selectedCalendars) => Promise.all(
++const getBusyCalendarTimes = (withCredentials, dateFrom, dateTo, selectedCalendars) => Promise.all(
+ calendars(withCredentials).map(c => c.getAvailability(dateFrom, dateTo, selectedCalendars))
+ ).then(
+ (results) => {
+ return results.reduce((acc, availability) => acc.concat(availability), [])
+ }
+ );
- const getBusyCalendarTimes = (withCredentials, dateFrom, dateTo) => Promise.all(
- calendars(withCredentials).map(c => c.getAvailability(dateFrom, dateTo))
+ const listCalendars = (withCredentials) => Promise.all(
+ calendars(withCredentials).map(c => c.listCalendars())
).then(
- (results) => results.reduce((acc, availability) => acc.concat(availability), [])
+ (results) => results.reduce((acc, calendars) => acc.concat(calendars), [])
);
-const createEvent = (credential, calEvent: CalendarEvent): Promise<any> => {
+const createEvent = async (credential, calEvent: CalendarEvent): Promise<any> => {
+ const uid: string = translator.fromUUID(uuidv5(JSON.stringify(calEvent), uuidv5.URL));
- createNewEventEmail(
- calEvent,
- );
+ const creationResult = credential ? await calendars([credential])[0].createEvent(calEvent) : null;
- if (credential) {
- return calendars([credential])[0].createEvent(calEvent);
- }
+ const organizerMail = new EventOrganizerMail(calEvent, uid);
+ const attendeeMail = new EventAttendeeMail(calEvent, uid);
+ await organizerMail.sendEmail();
- return Promise.resolve({});
+ if (!creationResult || !creationResult.disableConfirmationEmail) {
+ await attendeeMail.sendEmail();
+ }
+
+ return {
+ uid,
+ createdEvent: creationResult
+ };
};
-const updateEvent = (credential, uid: String, calEvent: CalendarEvent): Promise<any> => {
- if (credential) {
- return calendars([credential])[0].updateEvent(uid, calEvent);
- }
+const updateEvent = async (credential, uidToUpdate: String, calEvent: CalendarEvent): Promise<any> => {
+ const newUid: string = translator.fromUUID(uuidv5(JSON.stringify(calEvent), uuidv5.URL));
+
+ const updateResult = credential ? await calendars([credential])[0].updateEvent(uidToUpdate, calEvent) : null;
- return Promise.resolve({});
+ const organizerMail = new EventOrganizerRescheduledMail(calEvent, newUid);
+ const attendeeMail = new EventAttendeeRescheduledMail(calEvent, newUid);
+ await organizerMail.sendEmail();
+
+ if (!updateResult || !updateResult.disableConfirmationEmail) {
+ await attendeeMail.sendEmail();
+ }
+
+ return {
+ uid: newUid,
+ updatedEvent: updateResult
+ };
};
const deleteEvent = (credential, uid: String): Promise<any> => {
- if (credential) {
- return calendars([credential])[0].deleteEvent(uid);
- }
+ if (credential) {
+ return calendars([credential])[0].deleteEvent(uid);
+ }
- return Promise.resolve({});
+ return Promise.resolve({});
};
- export {getBusyCalendarTimes, createEvent, updateEvent, deleteEvent, CalendarEvent};
-export {getBusyTimes, createEvent, updateEvent, deleteEvent, CalendarEvent, listCalendars, IntegrationCalendar};
++export {getBusyCalendarTimes, createEvent, updateEvent, deleteEvent, CalendarEvent, listCalendars, IntegrationCalendar};
diff --cc lib/emails/EventOrganizerMail.ts
index 0f671efabae,00000000000..a5a687ce714
mode 100644,000000..100644
--- a/lib/emails/EventOrganizerMail.ts
+++ b/lib/emails/EventOrganizerMail.ts
@@@ -1,87 -1,0 +1,87 @@@
+import {createEvent} from "ics";
+import dayjs, {Dayjs} from "dayjs";
+import EventMail from "./EventMail";
+
+export default class EventOrganizerMail extends EventMail {
+ /**
+ * Returns the instance's event as an iCal event in string representation.
+ * @protected
+ */
+ protected getiCalEventAsString(): string {
+ const icsEvent = createEvent({
- start: dayjs(this.calEvent.startTime).utc().toArray().slice(0, 6),
++ start: dayjs(this.calEvent.startTime).utc().toArray().slice(0, 6).map((v, i) => i === 1 ? v + 1 : v),
+ startInputType: 'utc',
+ productId: 'calendso/ics',
+ title: `${this.calEvent.type} with ${this.calEvent.attendees[0].name}`,
- description: this.calEvent.description + this.stripHtml(this.getAdditionalBody()) + this.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) => ({name: attendee.name, email: attendee.email})),
++ description: this.calEvent.description,
++ 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) => ({ name: attendee.name, email: attendee.email }) ),
+ status: "CONFIRMED",
+ });
+ if (icsEvent.error) {
+ throw icsEvent.error;
+ }
+ return icsEvent.value;
+ }
+
+ /**
+ * Returns the email text as HTML representation.
+ *
+ * @protected
+ */
+ protected getHtmlRepresentation(): string {
+ return `
+ <div>
+ Hi ${this.calEvent.organizer.name},<br />
+ <br />
+ A new event has been scheduled.<br />
+ <br />
+ <strong>Event Type:</strong><br />
+ ${this.calEvent.type}<br />
+ <br />
+ <strong>Invitee Email:</strong><br />
+ <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 />
+ ` : ''
+ ) +
+ `<strong>Invitee Time Zone:</strong><br />
+ ${this.calEvent.attendees[0].timeZone}<br />
+ <br />
+ <strong>Additional notes:</strong><br />
+ ${this.calEvent.description}
+ ` + this.getAdditionalFooter() + `
+ </div>
+ `;
+ }
+
+ /**
+ * Returns the payload object for the nodemailer.
+ *
+ * @protected
+ */
+ protected getNodeMailerPayload(): Object {
+ const organizerStart: Dayjs = <Dayjs>dayjs(this.calEvent.startTime).tz(this.calEvent.organizer.timeZone);
+
+ return {
+ icalEvent: {
+ filename: 'event.ics',
+ content: this.getiCalEventAsString(),
+ },
+ from: `Calendso <${this.getMailerOptions().from}>`,
+ to: this.calEvent.organizer.email,
+ subject: `New event: ${this.calEvent.attendees[0].name} - ${organizerStart.format('LT dddd, LL')} - ${this.calEvent.type}`,
+ html: this.getHtmlRepresentation(),
+ text: this.getPlainTextRepresentation(),
+ };
+ }
+
+ protected printNodeMailerError(error: string): void {
+ console.error("SEND_NEW_EVENT_NOTIFICATION_ERROR", this.calEvent.organizer.email, error);
+ }
+}
diff --cc pages/[user]/[type].tsx
index 36cc1c79f10,aa57bd48067..676ca906e06
--- a/pages/[user]/[type].tsx
+++ b/pages/[user]/[type].tsx
@@@ -1,25 -1,25 +1,25 @@@
--import {useEffect, useState, useMemo} from 'react';
++import {useEffect, useMemo, useState} from 'react';
import 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 { ClockIcon, GlobeIcon, ChevronDownIcon, ChevronLeftIcon, ChevronRightIcon } from '@heroicons/react/solid';
++import {ChevronDownIcon, ChevronLeftIcon, ChevronRightIcon, ClockIcon, GlobeIcon} from '@heroicons/react/solid';
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore';
import isBetween from 'dayjs/plugin/isBetween';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
import Avatar from '../../components/Avatar';
++import getSlots from '../../lib/slots';
++import {collectPageParameters, telemetryEventTypes, useTelemetry} from "../../lib/telemetry";
++
dayjs.extend(isSameOrBefore);
dayjs.extend(isBetween);
dayjs.extend(utc);
dayjs.extend(timezone);
--import getSlots from '../../lib/slots';
--import {collectPageParameters, telemetryEventTypes, useTelemetry} from "../../lib/telemetry";
--
function classNames(...classes) {
return classes.filter(Boolean).join(' ')
}
diff --cc pages/[user]/book.tsx
index 4598adcd46c,fb9165e9ad3..2bf300ec751
--- a/pages/[user]/book.tsx
+++ b/pages/[user]/book.tsx
@@@ -76,7 -76,7 +76,7 @@@ export default function Book(props)
}
);
- let successUrl = `/success?date=${date}&type=${props.eventType.id}&user=${props.user.username}&reschedule=${!!rescheduleUid}`;
- 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']);
}
diff --cc pages/api/availability/[user].ts
index 4eb706836e9,824887a7aaf..3b07c2e49f7
--- a/pages/api/availability/[user].ts
+++ b/pages/api/availability/[user].ts
@@@ -1,7 -1,7 +1,8 @@@
-import type { NextApiRequest, NextApiResponse } from 'next';
+import type {NextApiRequest, NextApiResponse} from 'next';
import prisma from '../../../lib/prisma';
-import { getBusyTimes } from '../../../lib/calendarClient';
+import {getBusyCalendarTimes} from '../../../lib/calendarClient';
+import {getBusyVideoTimes} from '../../../lib/videoClient';
+ import dayjs from "dayjs";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { user } = req.query
@@@ -16,21 -17,18 +18,32 @@@
}
});
+ const selectedCalendars = (await prisma.selectedCalendar.findMany({
+ where: {
+ userId: currentUser.id
+ }
+ }));
+
- let availability = await getBusyTimes(currentUser.credentials, req.query.dateFrom, req.query.dateTo, selectedCalendars);
+ const hasCalendarIntegrations = currentUser.credentials.filter((cred) => cred.type.endsWith('_calendar')).length > 0;
+ const hasVideoIntegrations = currentUser.credentials.filter((cred) => cred.type.endsWith('_video')).length > 0;
- const calendarAvailability = await getBusyCalendarTimes(currentUser.credentials, req.query.dateFrom, req.query.dateTo);
- availability = availability.map(a => ({
++ const calendarAvailability = await getBusyCalendarTimes(currentUser.credentials, req.query.dateFrom, req.query.dateTo, selectedCalendars);
+ const videoAvailability = await getBusyVideoTimes(currentUser.credentials, req.query.dateFrom, req.query.dateTo);
+
+ let commonAvailability = [];
+
+ if(hasCalendarIntegrations && hasVideoIntegrations) {
+ commonAvailability = calendarAvailability.filter(availability => videoAvailability.includes(availability));
+ } else if(hasVideoIntegrations) {
+ commonAvailability = videoAvailability;
+ } else if(hasCalendarIntegrations) {
+ commonAvailability = calendarAvailability;
+ }
+
++ commonAvailability = commonAvailability.map(a => ({
+ start: dayjs(a.start).subtract(currentUser.bufferTime, 'minute').toString(),
+ end: dayjs(a.end).add(currentUser.bufferTime, 'minute').toString()
+ }));
-
- res.status(200).json(availability);
++
+ res.status(200).json(commonAvailability);
}
diff --cc pages/api/availability/calendar.ts
index 00000000000,43bc929d70c..bebfbbbf0f5
mode 000000,100644..100644
--- a/pages/api/availability/calendar.ts
+++ b/pages/api/availability/calendar.ts
@@@ -1,0 -1,69 +1,69 @@@
-import type { NextApiRequest, NextApiResponse } from 'next';
-import { getSession } from 'next-auth/client';
++import type {NextApiRequest, NextApiResponse} from 'next';
++import {getSession} from 'next-auth/client';
+ import prisma from '../../../lib/prisma';
+ import {IntegrationCalendar, listCalendars} from "../../../lib/calendarClient";
+
+ export default async function handler(req: NextApiRequest, res: NextApiResponse) {
+ const session = await getSession({req: req});
+
+ if (!session) {
+ res.status(401).json({message: "Not authenticated"});
+ return;
+ }
+
+ const currentUser = await prisma.user.findFirst({
+ where: {
+ id: session.user.id,
+ },
+ select: {
+ credentials: true,
+ timeZone: true,
+ id: true
+ }
+ });
+
+ if (req.method == "POST") {
+ await prisma.selectedCalendar.create({
+ data: {
+ user: {
+ connect: {
+ id: currentUser.id
+ }
+ },
+ integration: req.body.integration,
+ externalId: req.body.externalId
+ }
+ });
+ res.status(200).json({message: "Calendar Selection Saved"});
+
+ }
+
+ if (req.method == "DELETE") {
+ await prisma.selectedCalendar.delete({
+ where: {
+ userId_integration_externalId: {
+ userId: currentUser.id,
+ externalId: req.body.externalId,
+ integration: req.body.integration
+ }
+ }
+ });
+
+ res.status(200).json({message: "Calendar Selection Saved"});
+ }
+
+ if (req.method == "GET") {
+ const selectedCalendarIds = await prisma.selectedCalendar.findMany({
+ where: {
+ userId: currentUser.id
+ },
+ select: {
+ externalId: true
+ }
+ });
+
+ const calendars: IntegrationCalendar[] = await listCalendars(currentUser.credentials);
+ const selectableCalendars = calendars.map(cal => {return {selected: selectedCalendarIds.findIndex(s => s.externalId === cal.externalId) > -1, ...cal}});
+ res.status(200).json(selectableCalendars);
+ }
+ }
diff --cc pages/api/availability/day.ts
index b11b0400f18,31e0894a905..e81e0b47248
--- a/pages/api/availability/day.ts
+++ b/pages/api/availability/day.ts
@@@ -1,5 -1,5 +1,5 @@@
--import type { NextApiRequest, NextApiResponse } from 'next';
--import { getSession } from 'next-auth/client';
++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) {
diff --cc pages/api/availability/eventtype.ts
index 8f03e3e91b4,35d8c114e87..27a8a96b892
--- a/pages/api/availability/eventtype.ts
+++ b/pages/api/availability/eventtype.ts
@@@ -1,5 -1,5 +1,5 @@@
--import type { NextApiRequest, NextApiResponse } from 'next';
--import { getSession } from 'next-auth/client';
++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) {
diff --cc pages/api/book/[user].ts
index 83707bf2489,9c1f4f3e745..0c43637f190
--- a/pages/api/book/[user].ts
+++ b/pages/api/book/[user].ts
@@@ -4,8 -4,8 +4,9 @@@ import {CalendarEvent, createEvent, upd
import async from 'async';
import {v5 as uuidv5} from 'uuid';
import short from 'short-uuid';
+import {createMeeting, updateMeeting} from "../../../lib/videoClient";
+import EventAttendeeMail from "../../../lib/emails/EventAttendeeMail";
+ import {getEventName} from "../../../lib/event";
const translator = short();
@@@ -25,15 -25,22 +26,26 @@@ export default async function handler(r
}
});
+ // Split credentials up into calendar credentials and video credentials
+ const calendarCredentials = currentUser.credentials.filter(cred => cred.type.endsWith('_calendar'));
+ const videoCredentials = currentUser.credentials.filter(cred => cred.type.endsWith('_video'));
+
const rescheduleUid = req.body.rescheduleUid;
+ const selectedEventType = await prisma.eventType.findFirst({
+ where: {
+ userId: currentUser.id,
+ id: req.body.eventTypeId
+ },
+ select: {
+ eventName: true,
+ title: true
+ }
+ });
+
const evt: CalendarEvent = {
- type: req.body.eventName,
- title: req.body.eventName + ' with ' + req.body.name,
+ type: selectedEventType.title,
+ title: getEventName(req.body.name, selectedEventType.title, selectedEventType.eventName),
description: req.body.notes,
startTime: req.body.start,
endTime: req.body.end,
diff --cc pages/availability/event/[type].tsx
index ed575f25f12,f9ffd40a6ad..635f5c0d8bc
--- a/pages/availability/event/[type].tsx
+++ b/pages/availability/event/[type].tsx
@@@ -1,18 -1,18 +1,13 @@@
import Head from 'next/head';
import Link from 'next/link';
--import { useRouter } from 'next/router';
--import { useRef, useState } from 'react';
--import Select, { OptionBase } from 'react-select';
++import {useRouter} from 'next/router';
++import {useRef, useState} from 'react';
++import Select, {OptionBase} from 'react-select';
import prisma from '../../../lib/prisma';
--import { LocationType } from '../../../lib/location';
++import {LocationType} from '../../../lib/location';
import Shell from '../../../components/Shell';
--import { useSession, getSession } from 'next-auth/client';
--import {
-- LocationMarkerIcon,
-- PlusCircleIcon,
-- XIcon,
-- PhoneIcon,
--} from '@heroicons/react/outline';
++import {getSession, useSession} from 'next-auth/client';
++import {LocationMarkerIcon, PhoneIcon, PlusCircleIcon, XIcon,} from '@heroicons/react/outline';
export default function EventType(props) {
const router = useRouter();
diff --cc pages/availability/index.tsx
index d79b5072fb7,1b7bbc6766b..1d17098686c
--- a/pages/availability/index.tsx
+++ b/pages/availability/index.tsx
@@@ -3,11 -3,11 +3,10 @@@ import Link from 'next/link'
import prisma from '../../lib/prisma';
import Modal from '../../components/Modal';
import Shell from '../../components/Shell';
--import { useRouter } from 'next/router';
--import { useRef } from 'react';
--import { useState } from 'react';
--import { useSession, getSession } from 'next-auth/client';
--import { PlusIcon, ClockIcon } from '@heroicons/react/outline';
++import {useRouter} from 'next/router';
++import {useRef, useState} from 'react';
++import {getSession, useSession} from 'next-auth/client';
++import {ClockIcon, PlusIcon} from '@heroicons/react/outline';
export default function Availability(props) {
const [ session, loading ] = useSession();
diff --cc pages/integrations/index.tsx
index 040d47dc45a,7e132e3b9fb..023a8a2b63f
--- a/pages/integrations/index.tsx
+++ b/pages/integrations/index.tsx
@@@ -2,10 -2,11 +2,11 @@@ import Head from 'next/head'
import Link from 'next/link';
import prisma from '../../lib/prisma';
import Shell from '../../components/Shell';
- import {useState} from 'react';
+ import {useEffect, useState} from 'react';
import {getSession, useSession} from 'next-auth/client';
- import {CheckCircleIcon, ChevronRightIcon, PlusIcon, XCircleIcon} from '@heroicons/react/solid';
+ import {CalendarIcon, CheckCircleIcon, ChevronRightIcon, PlusIcon, XCircleIcon} from '@heroicons/react/solid';
import {InformationCircleIcon} from '@heroicons/react/outline';
-import { Switch } from '@headlessui/react'
++import {Switch} from '@headlessui/react'
export default function Home({ integrations }) {
const [session, loading] = useSession();
diff --cc pages/success.tsx
index c36ab1731ec,0d962393402..c8f27ecdc50
--- a/pages/success.tsx
+++ b/pages/success.tsx
@@@ -2,14 -2,15 +2,15 @@@ import Head from 'next/head'
import Link from 'next/link';
import prisma from '../lib/prisma';
import {useEffect, useState} from "react";
--import { useRouter } from 'next/router';
--import { CheckIcon } from '@heroicons/react/outline';
--import { ClockIcon, CalendarIcon, LocationMarkerIcon } from '@heroicons/react/solid';
++import {useRouter} from 'next/router';
++import {CheckIcon} from '@heroicons/react/outline';
++import {CalendarIcon, ClockIcon, LocationMarkerIcon} from '@heroicons/react/solid';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import toArray from 'dayjs/plugin/toArray';
import timezone from 'dayjs/plugin/timezone';
--import { createEvent } from 'ics';
++import {createEvent} from 'ics';
+ import {getEventName} from "../lib/event";
dayjs.extend(utc);
dayjs.extend(toArray);