Merge branch 'main' of https://github.com/calendso/calendso into main

This commit is contained in:
Bailey Pumfleet committed 2021-07-08 10:23:48 +01:00
commit db7c467d73
27 files changed
+746 -327

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
import { useEffect, useState } from "react";
import { GetServerSideProps } from "next";
import Head from "next/head";
import { ClockIcon, GlobeIcon, ChevronDownIcon } from "@heroicons/react/solid";
import { ChevronDownIcon, ClockIcon, GlobeIcon } from "@heroicons/react/solid";
import prisma from "../../lib/prisma";
import { useRouter } from "next/router";
import { Dayjs } from "dayjs";
+10 -9
View File
@@ -1,14 +1,15 @@
import '../styles/globals.css';
import {createTelemetryClient, TelemetryProvider} from '../lib/telemetry';
import { Provider } from 'next-auth/client';
import "../styles/globals.css";
import { createTelemetryClient, TelemetryProvider } from "../lib/telemetry";
import { Provider } from "next-auth/client";
import type { AppProps } from "next/app";
function MyApp({ Component, pageProps }) {
function MyApp({ Component, pageProps }: AppProps) {
return (
<TelemetryProvider value={createTelemetryClient()}>
<Provider session={pageProps.session}>
<Component {...pageProps} />
</Provider>
</TelemetryProvider>
<TelemetryProvider value={createTelemetryClient()}>
<Provider session={pageProps.session}>
<Component {...pageProps} />
</Provider>
</TelemetryProvider>
);
}
+9 -10
View File
@@ -1,30 +1,29 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { getSession } from 'next-auth/client';
import prisma from '../../../lib/prisma';
import type { NextApiRequest, NextApiResponse } from "next";
import { getSession } from "next-auth/client";
import prisma from "../../../lib/prisma";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const session = await getSession({req: req});
const session = await getSession({ req: req });
if (!session) {
res.status(401).json({message: "Not authenticated"});
res.status(401).json({ message: "Not authenticated" });
return;
}
if (req.method == "PATCH") {
const startMins = req.body.start;
const endMins = req.body.end;
const updateWeek = await prisma.schedule.update({
await prisma.schedule.update({
where: {
id: session.user.id,
},
data: {
startTime: startMins,
endTime: endMins
endTime: endMins,
},
});
res.status(200).json({message: 'Start and end times updated successfully'});
res.status(200).json({ message: "Start and end times updated successfully" });
}
}
}
+75 -69
View File
@@ -1,10 +1,10 @@
import type { NextApiRequest, NextApiResponse } from "next";
import prisma from "../../../lib/prisma";
import { CalendarEvent, createEvent, updateEvent } from "../../../lib/calendarClient";
import { CalendarEvent, createEvent, getBusyCalendarTimes, updateEvent } from "../../../lib/calendarClient";
import async from "async";
import { v5 as uuidv5 } from "uuid";
import short from "short-uuid";
import { createMeeting, updateMeeting } from "../../../lib/videoClient";
import { createMeeting, getBusyVideoTimes, updateMeeting } from "../../../lib/videoClient";
import EventAttendeeMail from "../../../lib/emails/EventAttendeeMail";
import { getEventName } from "../../../lib/event";
import { LocationType } from "../../../lib/location";
@@ -13,37 +13,39 @@ import dayjs from "dayjs";
const translator = short();
// Commented out because unused and thus throwing an error in linter.
// const isAvailable = (busyTimes, time, length) => {
// // Check for conflicts
// let t = true;
// busyTimes.forEach((busyTime) => {
// const startTime = dayjs(busyTime.start);
// const endTime = dayjs(busyTime.end);
//
// // Check if start times are the same
// if (dayjs(time).format("HH:mm") == startTime.format("HH:mm")) {
// t = false;
// }
//
// // Check if time is between start and end times
// if (dayjs(time).isBetween(startTime, endTime)) {
// t = false;
// }
//
// // Check if slot end time is between start and end time
// if (dayjs(time).add(length, "minutes").isBetween(startTime, endTime)) {
// t = false;
// }
//
// // Check if startTime is between slot
// if (startTime.isBetween(dayjs(time), dayjs(time).add(length, "minutes"))) {
// t = false;
// }
// });
//
// return t;
// };
function isAvailable(busyTimes, time, length) {
// Check for conflicts
let t = true;
if (Array.isArray(busyTimes) && busyTimes.length > 0) {
busyTimes.forEach((busyTime) => {
const startTime = dayjs(busyTime.start);
const endTime = dayjs(busyTime.end);
// Check if start times are the same
if (dayjs(time).format("HH:mm") == startTime.format("HH:mm")) {
t = false;
}
// Check if time is between start and end times
if (dayjs(time).isBetween(startTime, endTime)) {
t = false;
}
// Check if slot end time is between start and end time
if (dayjs(time).add(length, "minutes").isBetween(startTime, endTime)) {
t = false;
}
// Check if startTime is between slot
if (startTime.isBetween(dayjs(time), dayjs(time).add(length, "minutes"))) {
t = false;
}
});
}
return t;
}
interface GetLocationRequestFromIntegrationRequest {
location: string;
@@ -91,46 +93,43 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
},
});
// Commented out because unused and thus throwing an error in linter.
// const selectedCalendars = await prisma.selectedCalendar.findMany({
// where: {
// userId: currentUser.id,
// },
// });
const selectedCalendars = await prisma.selectedCalendar.findMany({
where: {
userId: currentUser.id,
},
});
// Split credentials up into calendar credentials and video credentials
let calendarCredentials = currentUser.credentials.filter((cred) => cred.type.endsWith("_calendar"));
let videoCredentials = currentUser.credentials.filter((cred) => cred.type.endsWith("_video"));
// Commented out because unused and thus throwing an error in linter.
// 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 hasCalendarIntegrations =
currentUser.credentials.filter((cred) => cred.type.endsWith("_calendar")).length > 0;
const hasVideoIntegrations =
currentUser.credentials.filter((cred) => cred.type.endsWith("_video")).length > 0;
// Commented out because unused and thus throwing an error in linter.
// const calendarAvailability = await getBusyCalendarTimes(
// currentUser.credentials,
// dayjs(req.body.start).startOf("day").utc().format(),
// dayjs(req.body.end).endOf("day").utc().format(),
// selectedCalendars
// );
// const videoAvailability = await getBusyVideoTimes(
// currentUser.credentials,
// dayjs(req.body.start).startOf("day").utc().format(),
// dayjs(req.body.end).endOf("day").utc().format()
// );
// let commonAvailability = [];
const calendarAvailability = await getBusyCalendarTimes(
currentUser.credentials,
dayjs(req.body.start).startOf("day").utc().format(),
dayjs(req.body.end).endOf("day").utc().format(),
selectedCalendars
);
const videoAvailability = await getBusyVideoTimes(
currentUser.credentials,
dayjs(req.body.start).startOf("day").utc().format(),
dayjs(req.body.end).endOf("day").utc().format()
);
let commonAvailability = [];
// Commented out because unused and thus throwing an error in linter.
// if (hasCalendarIntegrations && hasVideoIntegrations) {
// commonAvailability = calendarAvailability.filter((availability) =>
// videoAvailability.includes(availability)
// );
// } else if (hasVideoIntegrations) {
// commonAvailability = videoAvailability;
// } else if (hasCalendarIntegrations) {
// commonAvailability = calendarAvailability;
// }
if (hasCalendarIntegrations && hasVideoIntegrations) {
commonAvailability = calendarAvailability.filter((availability) =>
videoAvailability.includes(availability)
);
} else if (hasVideoIntegrations) {
commonAvailability = videoAvailability;
} else if (hasCalendarIntegrations) {
commonAvailability = calendarAvailability;
}
// Now, get the newly stored credentials (new refresh token for example).
currentUser = await prisma.user.findFirst({
@@ -201,8 +200,15 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
},
});
// TODO isAvailable was throwing an error
const isAvailableToBeBooked = true; //isAvailable(commonAvailability, req.body.start, selectedEventType.length);
let isAvailableToBeBooked = true;
try {
isAvailableToBeBooked = isAvailable(commonAvailability, req.body.start, selectedEventType.length);
} catch {
console.debug({
message: "Unable set isAvailableToBeBooked. Using true. ",
});
}
if (!isAvailableToBeBooked) {
return res.status(400).json({ message: `${currentUser.name} is unavailable at this time.` });
+10 -12
View File
@@ -1,18 +1,16 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import prisma from '../../lib/prisma';
import {getSession} from "next-auth/client";
import type { NextApiRequest, NextApiResponse } from "next";
import prisma from "../../lib/prisma";
import { getSession } from "next-auth/client";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const session = await getSession({req: req});
const session = await getSession({ req: req });
if (!session) {
res.status(401).json({message: "Not authenticated"});
res.status(401).json({ message: "Not authenticated" });
return;
}
if (req.method === "POST") {
// TODO: Prevent creating a team with identical names?
const createTeam = await prisma.team.create({
@@ -21,17 +19,17 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
},
});
const createMembership = await prisma.membership.create({
await prisma.membership.create({
data: {
teamId: createTeam.id,
userId: session.user.id,
role: 'OWNER',
role: "OWNER",
accepted: true,
}
},
});
return res.status(201).setHeader('Location', process.env.BASE_URL + '/api/teams/1').send(null);
return res.status(201).json({ message: "Team created" });
}
res.status(404).send(null);
res.status(404).json({ message: "Team not found" });
}
+4 -3
View File
@@ -10,16 +10,17 @@ import Shell from "@components/Shell";
import { getSession } from "next-auth/client";
import { Scheduler } from "@components/ui/Scheduler";
import { LocationMarkerIcon, PlusCircleIcon, XIcon, PhoneIcon } from "@heroicons/react/outline";
import { LocationMarkerIcon, PhoneIcon, PlusCircleIcon, XIcon } from "@heroicons/react/outline";
import { EventTypeCustomInput, EventTypeCustomInputType } from "@lib/eventTypeInput";
import { PlusIcon } from "@heroicons/react/solid";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
dayjs.extend(utc);
import timezone from "dayjs/plugin/timezone";
import { EventType, User, Availability } from "@prisma/client";
import { Availability, EventType, User } from "@prisma/client";
import { validJson } from "@lib/jsonUtils";
dayjs.extend(utc);
dayjs.extend(timezone);
type Props = {
+1 -2
View File
@@ -2,10 +2,9 @@ import Head from "next/head";
import prisma from "../../lib/prisma";
import { getSession, useSession } from "next-auth/client";
import Shell from "../../components/Shell";
import dayjs from "dayjs";
export default function Bookings({ bookings }) {
const [session, loading] = useSession();
const [, loading] = useSession();
if (loading) {
return <p className="text-gray-400">Loading...</p>;
+108 -59
View File
@@ -1,31 +1,41 @@
import Head from 'next/head';
import prisma from '../../lib/prisma';
import Modal from '../../components/Modal';
import Shell from '../../components/Shell';
import SettingsShell from '../../components/Settings';
import { useEffect, useState } from 'react';
import { useSession, getSession } from 'next-auth/client';
import {
UsersIcon,
} from "@heroicons/react/outline";
import { GetServerSideProps } from "next";
import Head from "next/head";
import Shell from "../../components/Shell";
import SettingsShell from "../../components/Settings";
import { useEffect, useState } from "react";
import type { Session } from "next-auth";
import { getSession, useSession } from "next-auth/client";
import { UsersIcon } from "@heroicons/react/outline";
import TeamList from "../../components/team/TeamList";
import TeamListItem from "../../components/team/TeamListItem";
export default function Teams(props) {
const [session, loading] = useSession();
export default function Teams() {
const [, loading] = useSession();
const [teams, setTeams] = useState([]);
const [invites, setInvites] = useState([]);
const [showCreateTeamModal, setShowCreateTeamModal] = useState(false);
const loadTeams = () => fetch('/api/user/membership').then((res: any) => res.json()).then(
(data) => {
setTeams(data.membership.filter((m) => m.role !== "INVITEE"));
setInvites(data.membership.filter((m) => m.role === "INVITEE"));
const handleErrors = async (resp) => {
if (!resp.ok) {
const err = await resp.json();
throw new Error(err.message);
}
);
return resp.json();
};
useEffect(() => { loadTeams(); }, []);
const loadData = () => {
fetch("/api/user/membership")
.then(handleErrors)
.then((data) => {
setTeams(data.membership.filter((m) => m.role !== "INVITEE"));
setInvites(data.membership.filter((m) => m.role === "INVITEE"));
})
.catch(console.log);
};
useEffect(() => {
loadData();
}, []);
if (loading) {
return <p className="text-gray-400">Loading...</p>;
@@ -33,17 +43,18 @@ export default function Teams(props) {
const createTeam = (e) => {
e.preventDefault();
return fetch('/api/teams', {
method: 'POST',
body: JSON.stringify({ name: e.target.elements['name'].value }),
return fetch("/api/teams", {
method: "POST",
body: JSON.stringify({ name: e.target.elements["name"].value }),
headers: {
'Content-Type': 'application/json'
}
"Content-Type": "application/json",
},
}).then(() => {
loadTeams();
loadData();
setShowCreateTeamModal(false);
});
}
};
return (
<Shell heading="Teams">
@@ -60,10 +71,12 @@ export default function Teams(props) {
<p className="mt-1 text-sm text-gray-500 mb-4">
View, edit and create teams to organise relationships between users
</p>
{!(invites.length || teams.length) &&
{!(invites.length || teams.length) && (
<div className="bg-gray-50 sm:rounded-lg">
<div className="px-4 py-5 sm:p-6">
<h3 className="text-lg leading-6 font-medium text-gray-900">Create a team to get started</h3>
<h3 className="text-lg leading-6 font-medium text-gray-900">
Create a team to get started
</h3>
<div className="mt-2 max-w-xl text-sm text-gray-500">
<p>Create your first team and invite other users to work together with you.</p>
</div>
@@ -71,31 +84,35 @@ export default function Teams(props) {
<button
type="button"
onClick={() => setShowCreateTeamModal(true)}
className="btn btn-primary"
>
className="btn btn-primary">
Create new team
</button>
</div>
</div>
</div>
}
)}
</div>
{!!(invites.length || teams.length) && <div>
<button className="btn-sm btn-primary" onClick={() => setShowCreateTeamModal(true)}>Create new team</button>
</div>}
{!!(invites.length || teams.length) && (
<div>
<button className="btn-sm btn-primary" onClick={() => setShowCreateTeamModal(true)}>
Create new team
</button>
</div>
)}
</div>
<div>
{!!teams.length &&
<TeamList teams={teams} onChange={loadTeams}>
</TeamList>
}
{!!teams.length && <TeamList teams={teams} onChange={loadData}></TeamList>}
{!!invites.length && <div>
<h2 className="text-lg leading-6 font-medium text-gray-900">Open Invitations</h2>
<ul className="border px-2 rounded mt-2 mb-2 divide-y divide-gray-200">
{invites.map((team) => <TeamListItem onChange={loadTeams} key={team.id} team={team}></TeamListItem>)}
</ul>
</div>}
{!!invites.length && (
<div>
<h2 className="text-lg leading-6 font-medium text-gray-900">Open Invitations</h2>
<ul className="border px-2 rounded mt-2 mb-2 divide-y divide-gray-200">
{invites.map((team) => (
<TeamListItem onChange={loadData} key={team.id} team={team}></TeamListItem>
))}
</ul>
</div>
)}
</div>
{/*{teamsLoaded && <div className="flex justify-between">
<div>
@@ -111,12 +128,20 @@ export default function Teams(props) {
</div>}*/}
</div>
</div>
{showCreateTeamModal &&
<div className="fixed z-10 inset-0 overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
{showCreateTeamModal && (
<div
className="fixed z-10 inset-0 overflow-y-auto"
aria-labelledby="modal-title"
role="dialog"
aria-modal="true">
<div className="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
<div className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true"></div>
<div
className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"
aria-hidden="true"></div>
<span className="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
<span className="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">
&#8203;
</span>
<div className="inline-block align-bottom bg-white rounded-lg px-4 pt-5 pb-4 text-left shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full sm:p-6">
<div className="sm:flex sm:items-start mb-4">
@@ -124,33 +149,57 @@ export default function Teams(props) {
<UsersIcon className="h-6 w-6 text-blue-600" />
</div>
<div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
<h3 className="text-lg leading-6 font-medium text-gray-900" id="modal-title">Create a new team</h3>
<h3 className="text-lg leading-6 font-medium text-gray-900" id="modal-title">
Create a new team
</h3>
<div>
<p className="text-sm text-gray-400">
Create a new team to collaborate with users.
</p>
<p className="text-sm text-gray-400">Create a new team to collaborate with users.</p>
</div>
</div>
</div>
<form onSubmit={createTeam}>
<div className="mb-4">
<label htmlFor="name" className="block text-sm font-medium text-gray-700">Name</label>
<input type="text" name="name" id="name" placeholder="Acme Inc." required className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm" />
<label htmlFor="name" className="block text-sm font-medium text-gray-700">
Name
</label>
<input
type="text"
name="name"
id="name"
placeholder="Acme Inc."
required
className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
/>
</div>
<div className="mt-5 sm:mt-4 sm:flex sm:flex-row-reverse">
<button type="submit" className="btn btn-primary">
Create team
</button>
<button onClick={() => setShowCreateTeamModal(false)} type="button" className="btn btn-white mr-2">
</button>
<button
onClick={() => setShowCreateTeamModal(false)}
type="button"
className="btn btn-white mr-2">
Cancel
</button>
</button>
</div>
</form>
</div>
</div>
</div>
}
)}
</SettingsShell>
</Shell>
);
}
}
// Export the `session` prop to use sessions with Server Side Rendering
export const getServerSideProps: GetServerSideProps<{ session: Session | null }> = async (context) => {
const session = await getSession(context);
if (!session) {
return { redirect: { permanent: false, destination: "/auth/login" } };
}
return {
props: { session },
};
};