Merge branch 'main' into feature/zoom-integration

# Conflicts:
#	lib/calendarClient.ts
#	lib/emails/new-event.ts
#	pages/[user]/book.tsx
#	pages/api/availability/[user].ts
#	pages/api/book/[user].ts
#	pages/integrations/index.tsx
This commit is contained in:
nicolas 2021-06-20 16:37:51 +02:00
commit ebc42f0c96
25 changed files with 752 additions and 250 deletions

3
.gitignore vendored
View File

@ -35,3 +35,6 @@ yarn-error.log*
# vercel
.vercel
# Webstorm
.idea

View File

@ -110,6 +110,17 @@ paths:
summary: Deletes an event type
tags:
- Availability
/api/availability/calendars:
post:
description: Selects calendar for availability checking.
summary: Adds selected calendar
tags:
- Availability
delete:
description: Removes a calendar from availability checking.
summary: Deletes a selected calendar
tags:
- Availability
/api/book/:user:
post:
description: Creates a booking in the user's calendar.
@ -144,4 +155,4 @@ paths:
description: Updates a user's profile.
summary: Updates a user's profile
tags:
- User
- User

View File

@ -1,7 +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()

View File

@ -1,5 +1,5 @@
import ActiveLink from '../components/ActiveLink';
import { UserCircleIcon, KeyIcon, CodeIcon, UserGroupIcon } from '@heroicons/react/outline';
import {CodeIcon, CreditCardIcon, KeyIcon, UserCircleIcon, UserGroupIcon} from '@heroicons/react/outline';
export default function SettingsShell(props) {
return (
@ -37,6 +37,11 @@ export default function SettingsShell(props) {
<a><UserGroupIcon /> Teams</a>
</ActiveLink>
{/* Change/remove me, if you're self-hosting */}
<ActiveLink href="/settings/billing">
<a><CreditCardIcon /> Billing</a>
</ActiveLink>
{/* <Link href="/settings/notifications">
<a className={router.pathname == "/settings/notifications" ? "bg-blue-50 border-blue-500 text-blue-700 hover:bg-blue-50 hover:text-blue-700 group border-l-4 px-3 py-2 flex items-center text-sm font-medium" : "border-transparent text-gray-900 hover:bg-gray-50 hover:text-gray-900 group border-l-4 px-3 py-2 flex items-center text-sm font-medium"}>
<svg className={router.pathname == "/settings/notifications" ? "text-blue-500 group-hover:text-blue-500 flex-shrink-0 -ml-1 mr-3 h-6 w-6" : "text-gray-400 group-hover:text-gray-500 flex-shrink-0 -ml-1 mr-3 h-6 w-6"} xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">

View File

@ -74,6 +74,13 @@ interface CalendarEvent {
attendees: Person[];
};
interface IntegrationCalendar {
integration: string;
primary: boolean;
externalId: string;
name: string;
}
interface CalendarApiAdapter {
createEvent(event: CalendarEvent): Promise<any>;
@ -81,7 +88,9 @@ interface CalendarApiAdapter {
deleteEvent(uid: String);
getAvailability(dateFrom, dateTo): Promise<any>;
getAvailability(dateFrom, dateTo, selectedCalendars: IntegrationCalendar[]): Promise<any>;
listCalendars(): Promise<IntegrationCalendar[]>;
}
const MicrosoftOffice365Calendar = (credential): CalendarApiAdapter => {
@ -120,98 +129,127 @@ const MicrosoftOffice365Calendar = (credential): CalendarApiAdapter => {
}
};
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";
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)),
}
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 {
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) => {
@ -277,39 +315,55 @@ const GoogleCalendar = (credential): CalendarApiAdapter => {
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
@ -324,11 +378,18 @@ const calendars = (withCredentials): CalendarApiAdapter[] => withCredentials.map
}
}).filter(Boolean);
const getBusyCalendarTimes = (withCredentials, dateFrom, dateTo) => Promise.all(
calendars(withCredentials).map(c => c.getAvailability(dateFrom, dateTo))
const getBusyCalendarTimes = (withCredentials, dateFrom, dateTo, selectedCalendars) => Promise.all(
calendars(withCredentials).map(c => c.getAvailability(dateFrom, dateTo, selectedCalendars))
).then(
(results) => results.reduce((acc, availability) => acc.concat(availability), [])
(results) => {
return results.reduce((acc, availability) => acc.concat(availability), [])
}
);
const listCalendars = (withCredentials) => Promise.all(
calendars(withCredentials).map(c => c.listCalendars())
).then(
(results) => results.reduce((acc, calendars) => acc.concat(calendars), [])
);
const createEvent = async (credential, calEvent: CalendarEvent): Promise<any> => {
@ -377,4 +438,4 @@ const deleteEvent = (credential, uid: String): Promise<any> => {
return Promise.resolve({});
};
export {getBusyCalendarTimes, createEvent, updateEvent, deleteEvent, CalendarEvent};
export {getBusyCalendarTimes, createEvent, updateEvent, deleteEvent, CalendarEvent, listCalendars, IntegrationCalendar};

View File

@ -9,14 +9,14 @@ export default class EventOrganizerMail extends EventMail {
*/
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) {

5
lib/event.ts Normal file
View File

@ -0,0 +1,5 @@
export function getEventName(name: string, eventTitle: string, eventNameTemplate?: string) {
return eventNameTemplate
? eventNameTemplate.replace("{USER}", name)
: eventTitle + ' with ' + name
}

View File

@ -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(' ')
}
@ -55,9 +55,9 @@ export default function Type(props) {
setIs24h(!!localStorage.getItem('timeOption.is24hClock'));
}
useEffect(() => {
telemetry.withJitsu((jitsu) => jitsu.track(telemetryEventTypes.pageView, collectPageParameters()))
});
useEffect(() => {
telemetry.withJitsu((jitsu) => jitsu.track(telemetryEventTypes.pageView, collectPageParameters()))
}, []);
// Handle date change and timezone change
useEffect(() => {
@ -370,50 +370,56 @@ export default function Type(props) {
}
export async function getServerSideProps(context) {
const user = await prisma.user.findFirst({
where: {
username: context.query.user,
},
select: {
id: true,
username: true,
name: true,
email: true,
bio: true,
avatar: true,
eventTypes: true,
startTime: true,
timeZone: true,
endTime: true,
weekStart: true,
}
});
if (!user) {
return {
notFound: true,
}
const user = await prisma.user.findFirst({
where: {
username: context.query.user,
},
select: {
id: true,
username: true,
name: true,
email: true,
bio: true,
avatar: true,
eventTypes: true,
startTime: true,
timeZone: true,
endTime: true,
weekStart: true,
}
});
const eventType = await prisma.eventType.findFirst({
where: {
userId: user.id,
slug: {
equals: context.query.type,
},
},
select: {
id: true,
title: true,
description: true,
length: true
}
});
if (!user ) {
return {
props: {
user,
eventType,
},
notFound: true,
}
}
const eventType = await prisma.eventType.findFirst({
where: {
userId: user.id,
slug: {
equals: context.query.type,
},
},
select: {
id: true,
title: true,
description: true,
length: true
}
});
if (!eventType) {
return {
notFound: true
}
}
return {
props: {
user,
eventType,
},
}
}

View File

@ -56,7 +56,7 @@ export default function Book(props) {
email: event.target.email.value,
notes: event.target.notes.value,
timeZone: preferredTimeZone,
eventName: props.eventType.title,
eventTypeId: props.eventType.id,
rescheduleUid: rescheduleUid
};
@ -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=${!!rescheduleUid}&name=${payload.name}`;
if (payload['location']) {
successUrl += "&location=" + encodeURIComponent(payload['location']);
}
@ -217,4 +217,4 @@ export async function getServerSideProps(context) {
booking
},
}
}
}

View File

@ -2,6 +2,7 @@ import type {NextApiRequest, NextApiResponse} from 'next';
import prisma from '../../../lib/prisma';
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
@ -12,14 +13,21 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
},
select: {
credentials: true,
timeZone: true
timeZone: true,
bufferTime: true
}
});
const selectedCalendars = (await prisma.selectedCalendar.findMany({
where: {
userId: currentUser.id
}
}));
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);
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 = [];
@ -32,5 +40,10 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
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(commonAvailability);
}

View File

@ -0,0 +1,69 @@
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);
}
}

View File

@ -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) {
@ -13,6 +13,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
if (req.method == "PATCH") {
const startMins = req.body.start;
const endMins = req.body.end;
const bufferMins = req.body.buffer;
const updateDay = await prisma.user.update({
where: {
@ -20,10 +21,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
},
data: {
startTime: startMins,
endTime: endMins
endTime: endMins,
bufferTime: bufferMins
},
});
res.status(200).json({message: 'Start and end times updated successfully'});
}
}
}

View File

@ -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) {
@ -18,6 +18,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
length: parseInt(req.body.length),
hidden: req.body.hidden,
locations: req.body.locations,
eventName: req.body.eventName
};
if (req.method == "POST") {
@ -50,4 +51,4 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
res.status(200).json({message: 'Event deleted successfully'});
}
}
}

View File

@ -6,6 +6,7 @@ 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();
@ -31,9 +32,20 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
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,

View File

@ -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();
@ -27,6 +22,7 @@ export default function EventType(props) {
const descriptionRef = useRef<HTMLTextAreaElement>();
const lengthRef = useRef<HTMLInputElement>();
const isHiddenRef = useRef<HTMLInputElement>();
const eventNameRef = useRef<HTMLInputElement>();
if (loading) {
return <p className="text-gray-400">Loading...</p>;
@ -40,11 +36,12 @@ export default function EventType(props) {
const enteredDescription = descriptionRef.current.value;
const enteredLength = lengthRef.current.value;
const enteredIsHidden = isHiddenRef.current.checked;
const enteredEventName = eventNameRef.current.value;
// TODO: Add validation
const response = await fetch('/api/availability/eventtype', {
method: 'PATCH',
body: JSON.stringify({id: props.eventType.id, title: enteredTitle, slug: enteredSlug, description: enteredDescription, length: enteredLength, hidden: enteredIsHidden, locations }),
body: JSON.stringify({id: props.eventType.id, title: enteredTitle, slug: enteredSlug, description: enteredDescription, length: enteredLength, hidden: enteredIsHidden, locations, eventName: enteredEventName }),
headers: {
'Content-Type': 'application/json'
}
@ -140,8 +137,8 @@ export default function EventType(props) {
<link rel="icon" href="/favicon.ico" />
</Head>
<Shell heading={'Event Type - ' + props.eventType.title}>
<div className="grid grid-cols-3 gap-4">
<div className="col-span-3 sm:col-span-2">
<div>
<div className="mb-8">
<div className="bg-white overflow-hidden shadow rounded-lg">
<div className="px-4 py-5 sm:p-6">
<form onSubmit={updateEventTypeHandler}>
@ -232,6 +229,12 @@ export default function EventType(props) {
</div>
</div>
</div>
<div className="mb-4">
<label htmlFor="eventName" className="block text-sm font-medium text-gray-700">Calendar entry name</label>
<div className="mt-1 relative rounded-md shadow-sm">
<input ref={eventNameRef} type="text" name="title" id="title" className="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md" placeholder="Meeting with {USER}" defaultValue={props.eventType.eventName} />
</div>
</div>
<div className="my-8">
<div className="relative flex items-start">
<div className="flex items-center h-5">
@ -258,7 +261,7 @@ export default function EventType(props) {
</div>
</div>
</div>
<div className="col-span-3 sm:col-span-1">
<div>
<div className="bg-white shadow sm:rounded-lg">
<div className="px-4 py-5 sm:p-6">
<h3 className="text-lg mb-2 leading-6 font-medium text-gray-900">
@ -348,6 +351,7 @@ export async function getServerSideProps(context) {
length: true,
hidden: true,
locations: true,
eventName: true,
}
});
@ -357,4 +361,4 @@ export async function getServerSideProps(context) {
eventType
},
}
}
}

View File

@ -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();
@ -25,6 +24,8 @@ export default function Availability(props) {
const startMinsRef = useRef<HTMLInputElement>();
const endHoursRef = useRef<HTMLInputElement>();
const endMinsRef = useRef<HTMLInputElement>();
const bufferHoursRef = useRef<HTMLInputElement>();
const bufferMinsRef = useRef<HTMLInputElement>();
if (loading) {
return <p className="text-gray-400">Loading...</p>;
@ -80,15 +81,18 @@ export default function Availability(props) {
const enteredStartMins = parseInt(startMinsRef.current.value);
const enteredEndHours = parseInt(endHoursRef.current.value);
const enteredEndMins = parseInt(endMinsRef.current.value);
const enteredBufferHours = parseInt(bufferHoursRef.current.value);
const enteredBufferMins = parseInt(bufferMinsRef.current.value);
const startMins = enteredStartHours * 60 + enteredStartMins;
const endMins = enteredEndHours * 60 + enteredEndMins;
const bufferMins = enteredBufferHours * 60 + enteredBufferMins;
// TODO: Add validation
const response = await fetch('/api/availability/day', {
method: 'PATCH',
body: JSON.stringify({start: startMins, end: endMins}),
body: JSON.stringify({start: startMins, end: endMins, buffer: bufferMins}),
headers: {
'Content-Type': 'application/json'
}
@ -298,7 +302,7 @@ export default function Availability(props) {
</h3>
<div>
<p className="text-sm text-gray-500">
Set the start and end time of your day.
Set the start and end time of your day and a minimum buffer between your meetings.
</p>
</div>
</div>
@ -316,7 +320,7 @@ export default function Availability(props) {
<input ref={startMinsRef} type="number" name="minutes" id="minutes" className="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md" placeholder="30" defaultValue={convertMinsToHrsMins(props.user.startTime).split(":")[1]} />
</div>
</div>
<div className="flex">
<div className="flex mb-4">
<label className="w-1/4 pt-2 block text-sm font-medium text-gray-700">End time</label>
<div>
<label htmlFor="hours" className="sr-only">Hours</label>
@ -328,6 +332,18 @@ export default function Availability(props) {
<input ref={endMinsRef} type="number" name="minutes" id="minutes" className="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md" placeholder="30" defaultValue={convertMinsToHrsMins(props.user.endTime).split(":")[1]} />
</div>
</div>
<div className="flex mb-4">
<label className="w-1/4 pt-2 block text-sm font-medium text-gray-700">Buffer</label>
<div>
<label htmlFor="hours" className="sr-only">Hours</label>
<input ref={bufferHoursRef} type="number" name="hours" id="hours" className="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md" placeholder="0" defaultValue={convertMinsToHrsMins(props.user.bufferTime).split(":")[0]} />
</div>
<span className="mx-2 pt-1">:</span>
<div>
<label htmlFor="minutes" className="sr-only">Minutes</label>
<input ref={bufferMinsRef} type="number" name="minutes" id="minutes" className="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md" placeholder="10" defaultValue={convertMinsToHrsMins(props.user.bufferTime).split(":")[1]} />
</div>
</div>
<div className="mt-5 sm:mt-4 sm:flex sm:flex-row-reverse">
<button type="submit" className="btn btn-primary">
Update
@ -361,7 +377,8 @@ export async function getServerSideProps(context) {
id: true,
username: true,
startTime: true,
endTime: true
endTime: true,
bufferTime: true
}
});
@ -381,4 +398,4 @@ export async function getServerSideProps(context) {
return {
props: {user, types}, // will be passed to the page component as props
}
}
}

View File

@ -2,28 +2,82 @@ 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'
export default function Home({ integrations }) {
const [session, loading] = useSession();
const [showAddModal, setShowAddModal] = useState(false);
if (loading) {
return <p className="text-gray-400">Loading...</p>;
}
const [showSelectCalendarModal, setShowSelectCalendarModal] = useState(false);
const [selectableCalendars, setSelectableCalendars] = useState([]);
function toggleAddModal() {
setShowAddModal(!showAddModal);
}
function toggleShowCalendarModal() {
setShowSelectCalendarModal(!showSelectCalendarModal);
}
function loadCalendars() {
fetch('api/availability/calendar')
.then((response) => response.json())
.then(data => {
setSelectableCalendars(data)
});
}
function integrationHandler(type) {
fetch('/api/integrations/' + type.replace('_', '') + '/add')
.then((response) => response.json())
.then((data) => window.location.href = data.url);
}
function calendarSelectionHandler(calendar) {
return (selected) => {
let cals = [...selectableCalendars];
let i = cals.findIndex(c => c.externalId === calendar.externalId);
cals[i].selected = selected;
setSelectableCalendars(cals);
if (selected) {
fetch('api/availability/calendar', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(cals[i])
}).then((response) => response.json());
} else {
fetch('api/availability/calendar', {
method: 'DELETE', headers: {
'Content-Type': 'application/json'
}, body: JSON.stringify(cals[i])
}).then((response) => response.json());
}
}
}
function getCalendarIntegrationImage(integrationType: string){
switch (integrationType) {
case "google_calendar": return "integrations/google-calendar.png";
case "office365_calendar": return "integrations/office-365.png";
default: return "";
}
}
function classNames(...classes) {
return classes.filter(Boolean).join(' ')
}
useEffect(loadCalendars, [integrations]);
if (loading) {
return <p className="text-gray-400">Loading...</p>;
}
return (
<div>
<Head>
@ -38,7 +92,7 @@ export default function Home({ integrations }) {
Add new integration
</button>
</div>
<div className="bg-white shadow overflow-hidden rounded-lg">
<div className="bg-white shadow overflow-hidden rounded-lg mb-8">
{integrations.filter( (ig) => ig.credential ).length !== 0 ? <ul className="divide-y divide-gray-200">
{integrations.filter(ig => ig.credential).map( (ig) => (<li>
<Link href={"/integrations/" + ig.credential.id}>
@ -165,6 +219,104 @@ export default function Home({ integrations }) {
</div>
</div>
}
<div className="bg-white shadow rounded-lg">
<div className="px-4 py-5 sm:p-6">
<h3 className="text-lg leading-6 font-medium text-gray-900">
Select calendars
</h3>
<div className="mt-2 max-w-xl text-sm text-gray-500">
<p>
Select which calendars are checked for availability to prevent double bookings.
</p>
</div>
<div className="mt-5">
<button type="button" onClick={toggleShowCalendarModal} className="btn btn-primary">
Select calendars
</button>
</div>
</div>
</div>
{showSelectCalendarModal &&
<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">
{/* <!--
Background overlay, show/hide based on modal state.
Entering: "ease-out duration-300"
From: "opacity-0"
To: "opacity-100"
Leaving: "ease-in duration-200"
From: "opacity-100"
To: "opacity-0"
--> */}
<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>
{/* <!--
Modal panel, show/hide based on modal state.
Entering: "ease-out duration-300"
From: "opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
To: "opacity-100 translate-y-0 sm:scale-100"
Leaving: "ease-in duration-200"
From: "opacity-100 translate-y-0 sm:scale-100"
To: "opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
--> */}
<div className="inline-block align-bottom bg-white rounded-lg px-4 pt-5 pb-4 text-left overflow-hidden 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">
<div className="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-blue-100 sm:mx-0 sm:h-10 sm:w-10">
<CalendarIcon 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">
Select calendars
</h3>
<div>
<p className="text-sm text-gray-400">
If no entry is selected, all calendars will be checked
</p>
</div>
</div>
</div>
<div className="my-4">
<ul className="divide-y divide-gray-200">
{selectableCalendars.map( (calendar) => (<li className="flex py-4">
<div className="w-1/12 mr-4 pt-2">
<img className="h-8 w-8 mr-2" src={getCalendarIntegrationImage(calendar.integration)} alt={calendar.integration} />
</div>
<div className="w-10/12 pt-3">
<h2 className="text-gray-800 font-medium">{ calendar.name }</h2>
</div>
<div className="w-2/12 text-right pt-3">
<Switch
checked={calendar.selected}
onChange={calendarSelectionHandler(calendar)}
className={classNames(
calendar.selected ? 'bg-indigo-600' : 'bg-gray-200',
'relative inline-flex flex-shrink-0 h-6 w-11 border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500'
)}
>
<span className="sr-only">Select calendar</span>
<span
aria-hidden="true"
className={classNames(
calendar.selected ? 'translate-x-5' : 'translate-x-0',
'pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow transform ring-0 transition ease-in-out duration-200'
)}
/>
</Switch>
</div>
</li>))}
</ul>
</div>
<div className="mt-5 sm:mt-4 sm:flex sm:flex-row-reverse">
<button onClick={toggleShowCalendarModal} type="button" className="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:w-auto sm:text-sm">
Close
</button>
</div>
</div>
</div>
</div>
}
</Shell>
</div>
);

View File

@ -0,0 +1,66 @@
import Head from 'next/head';
import Shell from '../../components/Shell';
import SettingsShell from '../../components/Settings';
import prisma from '../../lib/prisma';
import {getSession, useSession} from 'next-auth/client';
export default function Billing(props) {
const [ session, loading ] = useSession();
if (loading) {
return <p className="text-gray-400">Loading...</p>;
}
return (
<Shell heading="Billing">
<Head>
<title>Billing | Calendso</title>
</Head>
<SettingsShell>
<div className="py-6 px-4 sm:p-6 lg:pb-8 lg:col-span-9">
<div className="mb-6">
<h2 className="text-lg leading-6 font-medium text-gray-900">
Change your Subscription
</h2>
<p className="mt-1 text-sm text-gray-500">
Cancel, update credit card or change plan
</p>
</div>
<div className="my-6">
<iframe
src="https://calendso.com/subscription-embed"
style={{minHeight: 800, width: "100%", border: 0 }}
/>
</div>
</div>
</SettingsShell>
</Shell>
);
}
export async function getServerSideProps(context) {
const session = await getSession(context);
if (!session) {
return { redirect: { permanent: false, destination: '/auth/login' } };
}
const user = await prisma.user.findFirst({
where: {
email: session.user.email,
},
select: {
id: true,
username: true,
name: true,
email: true,
bio: true,
avatar: true,
timeZone: true,
weekStart: true,
}
});
return {
props: {user}, // will be passed to the page component as props
}
}

View File

@ -2,14 +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);
@ -17,7 +18,7 @@ dayjs.extend(timezone);
export default function Success(props) {
const router = useRouter();
const { location } = router.query;
const {location, name} = router.query;
const [ is24h, setIs24h ] = useState(false);
const [ date, setDate ] = useState(dayjs.utc(router.query.date));
@ -27,6 +28,8 @@ export default function Success(props) {
setIs24h(!!localStorage.getItem('timeOption.is24hClock'));
}, []);
const eventName = getEventName(name, props.eventType.title, props.eventType.eventName);
function eventLink(): string {
let optional = {};
@ -35,9 +38,9 @@ export default function Success(props) {
}
const event = createEvent({
start: date.utc().toArray().slice(0, 6),
start: date.utc().toArray().slice(0, 6).map((v, i) => i === 1 ? v + 1 : v),
startInputType: 'utc',
title: props.eventType.title + ' with ' + props.user.name,
title: eventName,
description: props.eventType.description,
duration: { minutes: props.eventType.length },
...optional
@ -53,7 +56,7 @@ export default function Success(props) {
return(
<div>
<Head>
<title>Booking Confirmed | {props.eventType.title} with {props.user.name || props.user.username} | Calendso</title>
<title>Booking Confirmed | {eventName} | Calendso</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main className="max-w-3xl mx-auto my-24">
@ -76,7 +79,7 @@ export default function Success(props) {
</p>
</div>
<div className="mt-4 border-t border-b py-4">
<h2 className="text-lg font-medium text-gray-600 mb-2">{props.eventType.title} with {props.user.name}</h2>
<h2 className="text-lg font-medium text-gray-600 mb-2">{eventName}</h2>
<p className="text-gray-500 mb-1">
<ClockIcon className="inline-block w-4 h-4 mr-1 -mt-1" />
{props.eventType.length} minutes
@ -95,17 +98,17 @@ export default function Success(props) {
<div className="mt-5 sm:mt-6 text-center">
<span className="font-medium text-gray-500">Add to your calendar</span>
<div className="flex mt-2">
<Link href={`https://calendar.google.com/calendar/r/eventedit?dates=${date.utc().format('YYYYMMDDTHHmmss[Z]')}/${date.add(props.eventType.length, 'minute').utc().format('YYYYMMDDTHHmmss[Z]')}&text=${props.eventType.title} with ${props.user.name}&details=${props.eventType.description}` + ( location ? "&location=" + encodeURIComponent(location) : '')}>
<Link href={`https://calendar.google.com/calendar/r/eventedit?dates=${date.utc().format('YYYYMMDDTHHmmss[Z]')}/${date.add(props.eventType.length, 'minute').utc().format('YYYYMMDDTHHmmss[Z]')}&text=${eventName}&details=${props.eventType.description}` + ( location ? "&location=" + encodeURIComponent(location) : '')}>
<a className="mx-2 btn-wide btn-white">
<svg className="inline-block w-4 h-4 mr-1 -mt-1" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><title>Google</title><path d="M12.48 10.92v3.28h7.84c-.24 1.84-.853 3.187-1.787 4.133-1.147 1.147-2.933 2.4-6.053 2.4-4.827 0-8.6-3.893-8.6-8.72s3.773-8.72 8.6-8.72c2.6 0 4.507 1.027 5.907 2.347l2.307-2.307C18.747 1.44 16.133 0 12.48 0 5.867 0 .307 5.387.307 12s5.56 12 12.173 12c3.573 0 6.267-1.173 8.373-3.36 2.16-2.16 2.84-5.213 2.84-7.667 0-.76-.053-1.467-.173-2.053H12.48z"/></svg>
</a>
</Link>
<Link href={encodeURI("https://outlook.live.com/calendar/0/deeplink/compose?body=" + props.eventType.description + "&enddt=" + date.add(props.eventType.length, 'minute').format() + "&path=%2Fcalendar%2Faction%2Fcompose&rru=addevent&startdt=" + date.format() + "&subject=" + props.eventType.title + " with " + props.user.name) + (location ? "&location=" + location : '')}>
<Link href={encodeURI("https://outlook.live.com/calendar/0/deeplink/compose?body=" + props.eventType.description + "&enddt=" + date.add(props.eventType.length, 'minute').format() + "&path=%2Fcalendar%2Faction%2Fcompose&rru=addevent&startdt=" + date.format() + "&subject=" + eventName) + (location ? "&location=" + location : '')}>
<a className="mx-2 btn-wide btn-white">
<svg className="inline-block w-4 h-4 mr-1 -mt-1" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><title>Microsoft Outlook</title><path d="M7.88 12.04q0 .45-.11.87-.1.41-.33.74-.22.33-.58.52-.37.2-.87.2t-.85-.2q-.35-.21-.57-.55-.22-.33-.33-.75-.1-.42-.1-.86t.1-.87q.1-.43.34-.76.22-.34.59-.54.36-.2.87-.2t.86.2q.35.21.57.55.22.34.31.77.1.43.1.88zM24 12v9.38q0 .46-.33.8-.33.32-.8.32H7.13q-.46 0-.8-.33-.32-.33-.32-.8V18H1q-.41 0-.7-.3-.3-.29-.3-.7V7q0-.41.3-.7Q.58 6 1 6h6.5V2.55q0-.44.3-.75.3-.3.75-.3h12.9q.44 0 .75.3.3.3.3.75V10.85l1.24.72h.01q.1.07.18.18.07.12.07.25zm-6-8.25v3h3v-3zm0 4.5v3h3v-3zm0 4.5v1.83l3.05-1.83zm-5.25-9v3h3.75v-3zm0 4.5v3h3.75v-3zm0 4.5v2.03l2.41 1.5 1.34-.8v-2.73zM9 3.75V6h2l.13.01.12.04v-2.3zM5.98 15.98q.9 0 1.6-.3.7-.32 1.19-.86.48-.55.73-1.28.25-.74.25-1.61 0-.83-.25-1.55-.24-.71-.71-1.24t-1.15-.83q-.68-.3-1.55-.3-.92 0-1.64.3-.71.3-1.2.85-.5.54-.75 1.3-.25.74-.25 1.63 0 .85.26 1.56.26.72.74 1.23.48.52 1.17.81.69.3 1.56.3zM7.5 21h12.39L12 16.08V17q0 .41-.3.7-.29.3-.7.3H7.5zm15-.13v-7.24l-5.9 3.54Z"/></svg>
</a>
</Link>
<Link href={encodeURI("https://outlook.office.com/calendar/0/deeplink/compose?body=" + props.eventType.description + "&enddt=" + date.add(props.eventType.length, 'minute').format() + "&path=%2Fcalendar%2Faction%2Fcompose&rru=addevent&startdt=" + date.format() + "&subject=" + props.eventType.title + " with " + props.user.name) + (location ? "&location=" + location : '')}>
<Link href={encodeURI("https://outlook.office.com/calendar/0/deeplink/compose?body=" + props.eventType.description + "&enddt=" + date.add(props.eventType.length, 'minute').format() + "&path=%2Fcalendar%2Faction%2Fcompose&rru=addevent&startdt=" + date.format() + "&subject=" + eventName) + (location ? "&location=" + location : '')}>
<a className="mx-2 btn-wide btn-white">
<svg className="inline-block w-4 h-4 mr-1 -mt-1" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><title>Microsoft Office</title><path d="M21.53 4.306v15.363q0 .807-.472 1.433-.472.627-1.253.85l-6.888 1.974q-.136.037-.29.055-.156.019-.293.019-.396 0-.72-.105-.321-.106-.656-.292l-4.505-2.544q-.248-.137-.391-.366-.143-.23-.143-.515 0-.434.304-.738.304-.305.739-.305h5.831V4.964l-4.38 1.563q-.533.187-.856.658-.322.472-.322 1.03v8.078q0 .496-.248.912-.25.416-.683.651l-2.072 1.13q-.286.148-.571.148-.497 0-.844-.347-.348-.347-.348-.844V6.563q0-.62.33-1.19.328-.571.874-.881L11.07.285q.248-.136.534-.21.285-.075.57-.075.211 0 .38.031.166.031.364.093l6.888 1.899q.384.11.7.329.317.217.547.52.23.305.353.67.125.367.125.764zm-1.588 15.363V4.306q0-.273-.16-.478-.163-.204-.423-.28l-3.388-.93q-.397-.111-.794-.23-.397-.117-.794-.216v19.68l4.976-1.427q.26-.074.422-.28.161-.204.161-.477z"/></svg>
</a>
@ -149,7 +152,8 @@ export async function getServerSideProps(context) {
id: true,
title: true,
description: true,
length: true
length: true,
eventName: true
}
});

View File

@ -0,0 +1,26 @@
-- CreateEnum
CREATE TYPE "MembershipRole" AS ENUM ('MEMBER', 'OWNER');
-- CreateTable
CREATE TABLE "Team" (
"id" SERIAL NOT NULL,
"name" TEXT,
PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Membership" (
"teamId" INTEGER NOT NULL,
"userId" INTEGER NOT NULL,
"accepted" BOOLEAN NOT NULL DEFAULT false,
"role" "MembershipRole" NOT NULL,
PRIMARY KEY ("userId","teamId")
);
-- AddForeignKey
ALTER TABLE "Membership" ADD FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Membership" ADD FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;

View File

@ -0,0 +1,11 @@
-- CreateTable
CREATE TABLE "SelectedCalendar" (
"userId" INTEGER NOT NULL,
"integration" TEXT NOT NULL,
"externalId" TEXT NOT NULL,
PRIMARY KEY ("userId","integration","externalId")
);
-- AddForeignKey
ALTER TABLE "SelectedCalendar" ADD FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;

View File

@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "EventType" ADD COLUMN "eventName" TEXT;

View File

@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "users" ADD COLUMN "bufferTime" INTEGER NOT NULL DEFAULT 0;

View File

@ -0,0 +1,20 @@
-- AlterTable
ALTER TABLE "users" ADD COLUMN "emailVerified" TIMESTAMP(3);
-- CreateTable
CREATE TABLE "VerificationRequest" (
"id" SERIAL NOT NULL,
"identifier" TEXT NOT NULL,
"token" TEXT NOT NULL,
"expires" TIMESTAMP(3) NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "VerificationRequest.token_unique" ON "VerificationRequest"("token");
-- CreateIndex
CREATE UNIQUE INDEX "VerificationRequest.identifier_token_unique" ON "VerificationRequest"("identifier", "token");

View File

@ -21,6 +21,7 @@ model EventType {
user User? @relation(fields: [userId], references: [id])
userId Int?
bookings Booking[]
eventName String?
}
model Credential {
@ -44,11 +45,13 @@ model User {
weekStart String? @default("Sunday")
startTime Int @default(0)
endTime Int @default(1440)
bufferTime Int @default(0)
createdDate DateTime @default(now()) @map(name: "created")
eventTypes EventType[]
credentials Credential[]
teams Membership[]
bookings Booking[]
selectedCalendars SelectedCalendar[]
@@map(name: "users")
}
@ -119,4 +122,12 @@ model Booking {
createdAt DateTime @default(now())
updatedAt DateTime?
}
}
model SelectedCalendar {
user User @relation(fields: [userId], references: [id])
userId Int
integration String
externalId String
@@id([userId,integration,externalId])
}