Migrates all tRPC code to a monorepo package (#3484)
* WIP * WIP * Type and migration fixes * Adds missing default import * Fixes import * Fixes tRPC imports in App Store * Migrate stripe helpers * WIP * Type fixes * Type fix? * Test fixes * Adds missing stripe packages * Moved queries to lib instead Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
e82bcb6dba
commit
9447f16b82
152 files changed
+1066
-724
No files matched your search
@@ -4,10 +4,9 @@ import { useState, useEffect, useRef } from "react";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { deriveAppDictKeyFromType } from "@calcom/lib/deriveAppDictKeyFromType";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import type { App } from "@calcom/types/App";
|
||||
|
||||
import { trpc } from "@lib/trpc";
|
||||
|
||||
import { UpgradeToProDialog } from "@components/UpgradeToProDialog";
|
||||
|
||||
import { InstallAppButtonMap } from "./apps.browser.generated";
|
||||
|
||||
@@ -4,9 +4,9 @@ import { useRouter } from "next/router";
|
||||
import { CAL_URL } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import showToast from "@calcom/lib/notification";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Switch } from "@calcom/ui";
|
||||
import { DialogTrigger, Dialog } from "@calcom/ui/Dialog";
|
||||
import { trpc } from "@calcom/web/lib/trpc";
|
||||
|
||||
import ConfirmationDialogContent from "@components/dialog/ConfirmationDialogContent";
|
||||
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import { TrashIcon, PlusIcon, ArrowUpIcon, CollectionIcon, ArrowDownIcon } from "@heroicons/react/solid";
|
||||
import { ArrowDownIcon, ArrowUpIcon, CollectionIcon, PlusIcon, TrashIcon } from "@heroicons/react/solid";
|
||||
import { useRouter } from "next/router";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useForm, UseFormReturn, useFieldArray, Controller } from "react-hook-form";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Controller, useFieldArray, useForm, UseFormReturn } from "react-hook-form";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import classNames from "@calcom/lib/classNames";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import showToast from "@calcom/lib/notification";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { AppGetServerSidePropsContext, AppPrisma, AppUser } from "@calcom/types/AppGetServerSideProps";
|
||||
import { Button, Select, BooleanToggleGroup, EmptyScreen } from "@calcom/ui";
|
||||
import { BooleanToggleGroup, Button, EmptyScreen, Select } from "@calcom/ui";
|
||||
import { Form, TextArea } from "@calcom/ui/form/fields";
|
||||
import { trpc } from "@calcom/web/lib/trpc";
|
||||
|
||||
import { inferSSRProps } from "@lib/types/inferSSRProps";
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ import classNames from "@calcom/lib/classNames";
|
||||
import { CAL_URL } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import showToast from "@calcom/lib/notification";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { AppGetServerSidePropsContext, AppPrisma, AppUser } from "@calcom/types/AppGetServerSideProps";
|
||||
import { Button, EmptyScreen, Tooltip } from "@calcom/ui";
|
||||
import Dropdown, {
|
||||
@@ -25,7 +26,6 @@ import Dropdown, {
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@calcom/ui/Dropdown";
|
||||
import { trpc } from "@calcom/web/lib/trpc";
|
||||
|
||||
import { inferSSRProps } from "@lib/types/inferSSRProps";
|
||||
|
||||
|
||||
@@ -7,11 +7,11 @@ import { JsonTree, ImmutableTree, BuilderProps } from "react-awesome-query-build
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import showToast from "@calcom/lib/notification";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { AppGetServerSidePropsContext, AppPrisma, AppUser } from "@calcom/types/AppGetServerSideProps";
|
||||
import { inferSSRProps } from "@calcom/types/inferSSRProps";
|
||||
import { Button } from "@calcom/ui";
|
||||
import { Label } from "@calcom/ui/form/fields";
|
||||
import { trpc } from "@calcom/web/lib/trpc";
|
||||
|
||||
import PencilEdit from "@components/PencilEdit";
|
||||
import { SelectWithValidation as Select } from "@components/ui/form/Select";
|
||||
|
||||
@@ -7,10 +7,10 @@ import { Toaster } from "react-hot-toast";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import showToast from "@calcom/lib/notification";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { AppGetServerSidePropsContext, AppPrisma } from "@calcom/types/AppGetServerSideProps";
|
||||
import { inferSSRProps } from "@calcom/types/inferSSRProps";
|
||||
import { Button } from "@calcom/ui";
|
||||
import { trpc } from "@calcom/web/lib/trpc";
|
||||
|
||||
import { getSerializableForm } from "../../utils";
|
||||
import { getQueryBuilderConfig } from "../route-builder/[...appPages]";
|
||||
|
||||
@@ -2,12 +2,12 @@ import { Prisma, WebhookTriggerEvents } from "@prisma/client";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { z } from "zod";
|
||||
|
||||
import { TRPCError } from "@calcom/trpc/server";
|
||||
import { createProtectedRouter, createRouter } from "@calcom/trpc/server/createRouter";
|
||||
|
||||
import { sendGenericWebhookPayload } from "@lib/webhooks/sendPayload";
|
||||
import getWebhooks from "@lib/webhooks/subscriptions";
|
||||
|
||||
import { createProtectedRouter, createRouter } from "@server/createRouter";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { zodFields, zodRoutes } from "./zod";
|
||||
|
||||
const app_RoutingForms = createRouter()
|
||||
|
||||
@@ -1,19 +1,18 @@
|
||||
import { ClockIcon, XIcon } from "@heroicons/react/outline";
|
||||
import { Dispatch, SetStateAction } from "react";
|
||||
import { useState } from "react";
|
||||
import { ClockIcon } from "@heroicons/react/outline";
|
||||
import { Dispatch, SetStateAction, useState } from "react";
|
||||
import { useMutation } from "react-query";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import showToast from "@calcom/lib/notification";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import Button from "@calcom/ui/Button";
|
||||
import { Dialog, DialogClose, DialogContent, DialogFooter, DialogHeader } from "@calcom/ui/Dialog";
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader } from "@calcom/ui/Dialog";
|
||||
|
||||
interface IConfirmDialogWipe {
|
||||
isOpenDialog: boolean;
|
||||
setIsOpenDialog: Dispatch<SetStateAction<boolean>>;
|
||||
trpc: any;
|
||||
}
|
||||
|
||||
interface IWipeMyCalAction {
|
||||
@@ -45,7 +44,7 @@ const wipeMyCalAction = async (props: IWipeMyCalAction) => {
|
||||
|
||||
export const ConfirmDialog = (props: IConfirmDialogWipe) => {
|
||||
const { t } = useLocale();
|
||||
const { isOpenDialog, setIsOpenDialog, trpc } = props;
|
||||
const { isOpenDialog, setIsOpenDialog } = props;
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const today = dayjs();
|
||||
const initialDate = today.startOf("day");
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import { useState } from "react";
|
||||
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import Button from "@calcom/ui/Button";
|
||||
|
||||
import { ConfirmDialog } from "./confirmDialog";
|
||||
|
||||
interface IWipeMyCalActionButtonProps {
|
||||
trpc: any;
|
||||
bookingsEmpty: boolean;
|
||||
bookingStatus: "upcoming" | "recurring" | "past" | "cancelled";
|
||||
}
|
||||
|
||||
const WipeMyCalActionButton = (props: IWipeMyCalActionButtonProps) => {
|
||||
const { trpc, bookingsEmpty, bookingStatus } = props;
|
||||
const { bookingsEmpty, bookingStatus } = props;
|
||||
const [openDialog, setOpenDialog] = useState(false);
|
||||
const { isSuccess, isLoading, data } = trpc.useQuery([
|
||||
"viewer.integrations",
|
||||
@@ -21,9 +21,7 @@ const WipeMyCalActionButton = (props: IWipeMyCalActionButtonProps) => {
|
||||
if (bookingStatus !== "upcoming" || bookingsEmpty) {
|
||||
return <></>;
|
||||
}
|
||||
const wipeMyCalCredentials: { credentialIds: number[] } = data?.items.find(
|
||||
(item: { type: string }) => item.type === "wipemycal_other"
|
||||
);
|
||||
const wipeMyCalCredentials = data?.items.find((item: { type: string }) => item.type === "wipemycal_other");
|
||||
|
||||
const [credentialId] = wipeMyCalCredentials?.credentialIds || [false];
|
||||
|
||||
@@ -31,7 +29,7 @@ const WipeMyCalActionButton = (props: IWipeMyCalActionButtonProps) => {
|
||||
<div>
|
||||
{data && isSuccess && !isLoading && credentialId && (
|
||||
<>
|
||||
<ConfirmDialog trpc={trpc} isOpenDialog={openDialog} setIsOpenDialog={setOpenDialog} />
|
||||
<ConfirmDialog isOpenDialog={openDialog} setIsOpenDialog={setOpenDialog} />
|
||||
<Button onClick={() => setOpenDialog(true)} data-testid="wipe-today-button">
|
||||
Wipe Today
|
||||
</Button>
|
||||
|
||||
@@ -6,11 +6,9 @@ import { Toaster } from "react-hot-toast";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import showToast from "@calcom/lib/notification";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button, Loader, Tooltip } from "@calcom/ui";
|
||||
|
||||
/** TODO: Maybe extract this into a package to prevent circular dependencies */
|
||||
import { trpc } from "@calcom/web/lib/trpc";
|
||||
|
||||
export interface IZapierSetupProps {
|
||||
inviteLink: string;
|
||||
}
|
||||
@@ -21,11 +19,7 @@ export default function ZapierSetup(props: IZapierSetupProps) {
|
||||
const [newApiKey, setNewApiKey] = useState("");
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useContext();
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
const integrations = trpc.useQuery(["viewer.integrations", { variant: "other" }]);
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
const oldApiKey = trpc.useQuery(["viewer.apiKeys.findKeyOfType", { appId: ZAPIER }]);
|
||||
|
||||
const deleteApiKey = trpc.useMutation("viewer.apiKeys.delete");
|
||||
@@ -38,8 +32,6 @@ export default function ZapierSetup(props: IZapierSetupProps) {
|
||||
|
||||
async function createApiKey() {
|
||||
const event = { note: "Zapier", expiresAt: null, appId: ZAPIER };
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
const apiKey = await utils.client.mutation("viewer.apiKeys.create", event);
|
||||
if (oldApiKey.data) {
|
||||
deleteApiKey.mutate({
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
const path = require("path");
|
||||
|
||||
/** @type {import("next-i18next").UserConfig} */
|
||||
const config = {
|
||||
i18n: {
|
||||
defaultLocale: "en",
|
||||
locales: [
|
||||
"en",
|
||||
"fr",
|
||||
"it",
|
||||
"ru",
|
||||
"es",
|
||||
"de",
|
||||
"pt",
|
||||
"ro",
|
||||
"nl",
|
||||
"pt-BR",
|
||||
"es-419",
|
||||
"ko",
|
||||
"ja",
|
||||
"pl",
|
||||
"ar",
|
||||
"iw",
|
||||
"zh-CN",
|
||||
"zh-TW",
|
||||
"cs",
|
||||
"sr",
|
||||
"sv",
|
||||
"vi",
|
||||
],
|
||||
},
|
||||
reloadOnPrerender: process.env.NODE_ENV !== "production",
|
||||
};
|
||||
|
||||
module.exports = config;
|
||||
@@ -2,7 +2,7 @@ import { createEvent, DateArray, Person } from "ics";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { getCancelLink } from "@calcom/lib/CalEventParser";
|
||||
import { CalendarEvent } from "@calcom/types/Calendar";
|
||||
import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
import { renderEmail } from "../";
|
||||
import OrganizerScheduledEmail from "./organizer-scheduled-email";
|
||||
|
||||
@@ -2,7 +2,7 @@ import { createEvent, DateArray, Person } from "ics";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { getRichDescription } from "@calcom/lib/CalEventParser";
|
||||
import { CalendarEvent } from "@calcom/types/Calendar";
|
||||
import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
import { renderEmail } from "../";
|
||||
import OrganizerScheduledEmail from "./organizer-scheduled-email";
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { compare, hash } from "bcryptjs";
|
||||
import { Session } from "next-auth";
|
||||
import { getSession as getSessionInner, GetSessionParams } from "next-auth/react";
|
||||
|
||||
export async function hashPassword(password: string) {
|
||||
const hashedPassword = await hash(password, 12);
|
||||
@@ -9,3 +11,10 @@ export async function verifyPassword(password: string, hashedPassword: string) {
|
||||
const isValid = await compare(password, hashedPassword);
|
||||
return isValid;
|
||||
}
|
||||
|
||||
export async function getSession(options: GetSessionParams): Promise<Session | null> {
|
||||
const session = await getSessionInner(options);
|
||||
|
||||
// that these are equal are ensured in `[...nextauth]`'s callback
|
||||
return session as Session | null;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
import parser from "accept-language-parser";
|
||||
import { IncomingMessage } from "http";
|
||||
|
||||
import prisma from "@calcom/prisma";
|
||||
import { Maybe } from "@calcom/trpc/server";
|
||||
|
||||
import { getSession } from "./auth";
|
||||
|
||||
const { i18n } = require("@calcom/config/next-i18next.config");
|
||||
|
||||
export function getLocaleFromHeaders(req: IncomingMessage): string {
|
||||
let preferredLocale: string | null | undefined;
|
||||
if (req.headers["accept-language"]) {
|
||||
preferredLocale = parser.pick(i18n.locales, req.headers["accept-language"]) as Maybe<string>;
|
||||
}
|
||||
return preferredLocale ?? i18n.defaultLocale;
|
||||
}
|
||||
|
||||
export const getOrSetUserLocaleFromHeaders = async (req: IncomingMessage): Promise<string> => {
|
||||
const session = await getSession({ req });
|
||||
const preferredLocale = getLocaleFromHeaders(req);
|
||||
|
||||
if (session?.user?.id) {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: session.user.id,
|
||||
},
|
||||
select: {
|
||||
locale: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (user?.locale) {
|
||||
return user.locale;
|
||||
}
|
||||
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: session.user.id,
|
||||
},
|
||||
data: {
|
||||
locale: preferredLocale,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return preferredLocale;
|
||||
};
|
||||
@@ -0,0 +1,41 @@
|
||||
import { EventType, PeriodType } from "@prisma/client";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
|
||||
function isOutOfBounds(
|
||||
time: dayjs.ConfigType,
|
||||
{
|
||||
periodType,
|
||||
periodDays,
|
||||
periodCountCalendarDays,
|
||||
periodStartDate,
|
||||
periodEndDate,
|
||||
}: Pick<
|
||||
EventType,
|
||||
"periodType" | "periodDays" | "periodCountCalendarDays" | "periodStartDate" | "periodEndDate"
|
||||
>
|
||||
) {
|
||||
const date = dayjs(time);
|
||||
periodDays = periodDays || 0;
|
||||
|
||||
switch (periodType) {
|
||||
case PeriodType.ROLLING: {
|
||||
const periodRollingEndDay = periodCountCalendarDays
|
||||
? dayjs().utcOffset(date.utcOffset()).add(periodDays, "days").endOf("day")
|
||||
: dayjs().utcOffset(date.utcOffset()).businessDaysAdd(periodDays).endOf("day");
|
||||
return date.endOf("day").isAfter(periodRollingEndDay);
|
||||
}
|
||||
|
||||
case PeriodType.RANGE: {
|
||||
const periodRangeStartDay = dayjs(periodStartDate).utcOffset(date.utcOffset()).endOf("day");
|
||||
const periodRangeEndDay = dayjs(periodEndDate).utcOffset(date.utcOffset()).endOf("day");
|
||||
return date.endOf("day").isBefore(periodRangeStartDay) || date.endOf("day").isAfter(periodRangeEndDay);
|
||||
}
|
||||
|
||||
case PeriodType.UNLIMITED:
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export default isOutOfBounds;
|
||||
@@ -0,0 +1,40 @@
|
||||
import jackson, { IAPIController, IOAuthController, JacksonOption } from "@boxyhq/saml-jackson";
|
||||
|
||||
import { WEBAPP_URL } from "./constants";
|
||||
import { samlDatabaseUrl } from "./saml";
|
||||
|
||||
// Set the required options. Refer to https://github.com/boxyhq/jackson#configuration for the full list
|
||||
const opts: JacksonOption = {
|
||||
externalUrl: WEBAPP_URL,
|
||||
samlPath: "/api/auth/saml/callback",
|
||||
db: {
|
||||
engine: "sql",
|
||||
type: "postgres",
|
||||
url: samlDatabaseUrl,
|
||||
encryptionKey: process.env.CALENDSO_ENCRYPTION_KEY,
|
||||
},
|
||||
samlAudience: "https://saml.cal.com",
|
||||
};
|
||||
|
||||
let apiController: IAPIController;
|
||||
let oauthController: IOAuthController;
|
||||
|
||||
const g = global as any;
|
||||
|
||||
export default async function init() {
|
||||
if (!g.apiController || !g.oauthController) {
|
||||
const ret = await jackson(opts);
|
||||
apiController = ret.apiController;
|
||||
oauthController = ret.oauthController;
|
||||
g.apiController = apiController;
|
||||
g.oauthController = oauthController;
|
||||
} else {
|
||||
apiController = g.apiController;
|
||||
oauthController = g.oauthController;
|
||||
}
|
||||
|
||||
return {
|
||||
apiController,
|
||||
oauthController,
|
||||
};
|
||||
}
|
||||
@@ -11,6 +11,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@calcom/dayjs": "*",
|
||||
"@calcom/config": "*",
|
||||
"@prisma/client": "^4.1.0",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"ical.js": "^1.4.0",
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import crypto from "crypto";
|
||||
|
||||
export const defaultAvatarSrc = function ({ email, md5 }: { md5?: string; email?: string }) {
|
||||
if (!email && !md5) return "";
|
||||
|
||||
if (email && !md5) {
|
||||
md5 = crypto.createHash("md5").update(email).digest("hex");
|
||||
}
|
||||
|
||||
return `https://www.gravatar.com/avatar/${md5}?s=160&d=identicon&r=PG`;
|
||||
};
|
||||
@@ -0,0 +1,59 @@
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
|
||||
import { TRPCError } from "@calcom/trpc/server";
|
||||
|
||||
import { WEBAPP_URL } from "./constants";
|
||||
|
||||
export const samlDatabaseUrl = process.env.SAML_DATABASE_URL || "";
|
||||
export const samlLoginUrl = WEBAPP_URL;
|
||||
|
||||
export const isSAMLLoginEnabled = samlDatabaseUrl.length > 0;
|
||||
|
||||
export const samlTenantID = "Cal.com";
|
||||
export const samlProductID = "Cal.com";
|
||||
|
||||
const samlAdmins = (process.env.SAML_ADMINS || "").split(",");
|
||||
export const hostedCal = WEBAPP_URL === "https://app.cal.com";
|
||||
export const tenantPrefix = "team-";
|
||||
|
||||
export const isSAMLAdmin = (email: string) => {
|
||||
for (const admin of samlAdmins) {
|
||||
if (admin.toLowerCase() === email.toLowerCase() && admin.toUpperCase() === email.toUpperCase()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
export const samlTenantProduct = async (prisma: PrismaClient, email: string) => {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
email,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
invitedTo: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "Unauthorized Request",
|
||||
});
|
||||
}
|
||||
|
||||
if (!user.invitedTo) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message:
|
||||
"Could not find a SAML Identity Provider for your email. Please contact your admin to ensure you have been given access to Cal",
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
tenant: tenantPrefix + user.invitedTo,
|
||||
product: samlProductID,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
export async function checkRegularUsername(_username: string) {
|
||||
const username = slugify(_username);
|
||||
const premium = !!process.env.NEXT_PUBLIC_IS_E2E && username.length < 5;
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { username },
|
||||
select: {
|
||||
username: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (user) {
|
||||
return {
|
||||
available: false as const,
|
||||
premium,
|
||||
message: "A user exists with that username",
|
||||
};
|
||||
}
|
||||
return {
|
||||
available: true as const,
|
||||
premium,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { checkPremiumUsername } from "@calcom/ee/lib/core/checkPremiumUsername";
|
||||
import { IS_SELF_HOSTED } from "@calcom/lib/constants";
|
||||
|
||||
import { checkRegularUsername } from "./checkRegularUsername";
|
||||
|
||||
export const checkUsername = IS_SELF_HOSTED ? checkRegularUsername : checkPremiumUsername;
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./teams";
|
||||
@@ -0,0 +1,90 @@
|
||||
import { Prisma, UserPlan } from "@prisma/client";
|
||||
|
||||
import prisma, { baseEventTypeSelect } from "@calcom/prisma";
|
||||
|
||||
export type TeamWithMembers = Awaited<ReturnType<typeof getTeamWithMembers>>;
|
||||
|
||||
export async function getTeamWithMembers(id?: number, slug?: string) {
|
||||
const userSelect = Prisma.validator<Prisma.UserSelect>()({
|
||||
username: true,
|
||||
email: true,
|
||||
name: true,
|
||||
id: true,
|
||||
plan: true,
|
||||
bio: true,
|
||||
});
|
||||
|
||||
const teamSelect = Prisma.validator<Prisma.TeamSelect>()({
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
logo: true,
|
||||
bio: true,
|
||||
hideBranding: true,
|
||||
members: {
|
||||
select: {
|
||||
user: {
|
||||
select: userSelect,
|
||||
},
|
||||
},
|
||||
},
|
||||
eventTypes: {
|
||||
where: {
|
||||
hidden: false,
|
||||
},
|
||||
select: {
|
||||
users: {
|
||||
select: userSelect,
|
||||
},
|
||||
...baseEventTypeSelect,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const team = await prisma.team.findUnique({
|
||||
where: id ? { id } : { slug },
|
||||
select: teamSelect,
|
||||
});
|
||||
|
||||
if (!team) return null;
|
||||
|
||||
const memberships = await prisma.membership.findMany({
|
||||
where: {
|
||||
teamId: team.id,
|
||||
},
|
||||
});
|
||||
|
||||
const members = team.members.map((obj) => {
|
||||
const membership = memberships.find((membership) => obj.user.id === membership.userId);
|
||||
return {
|
||||
...obj.user,
|
||||
isMissingSeat: obj.user.plan === UserPlan.FREE,
|
||||
role: membership?.role,
|
||||
accepted: membership?.accepted,
|
||||
disableImpersonation: membership?.disableImpersonation,
|
||||
};
|
||||
});
|
||||
|
||||
return { ...team, members };
|
||||
}
|
||||
// also returns team
|
||||
export async function isTeamAdmin(userId: number, teamId: number) {
|
||||
return (
|
||||
(await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
teamId,
|
||||
OR: [{ role: "ADMIN" }, { role: "OWNER" }],
|
||||
},
|
||||
})) || false
|
||||
);
|
||||
}
|
||||
export async function isTeamOwner(userId: number, teamId: number) {
|
||||
return !!(await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
teamId,
|
||||
role: "OWNER",
|
||||
},
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import dayjs, { Dayjs } from "@calcom/dayjs";
|
||||
import { WorkingHours } from "@calcom/types/schedule";
|
||||
|
||||
import { getWorkingHours } from "./availability";
|
||||
|
||||
export type GetSlots = {
|
||||
inviteeDate: Dayjs;
|
||||
frequency: number;
|
||||
workingHours: WorkingHours[];
|
||||
minimumBookingNotice: number;
|
||||
eventLength: number;
|
||||
};
|
||||
export type WorkingHoursTimeFrame = { startTime: number; endTime: number };
|
||||
|
||||
const splitAvailableTime = (
|
||||
startTimeMinutes: number,
|
||||
endTimeMinutes: number,
|
||||
frequency: number,
|
||||
eventLength: number
|
||||
): Array<WorkingHoursTimeFrame> => {
|
||||
let initialTime = startTimeMinutes;
|
||||
const finalizationTime = endTimeMinutes;
|
||||
const result = [] as Array<WorkingHoursTimeFrame>;
|
||||
while (initialTime < finalizationTime) {
|
||||
const periodTime = initialTime + frequency;
|
||||
const slotEndTime = initialTime + eventLength;
|
||||
/*
|
||||
check if the slot end time surpasses availability end time of the user
|
||||
1 minute is added to round up the hour mark so that end of the slot is considered in the check instead of x9
|
||||
eg: if finalization time is 11:59, slotEndTime is 12:00, we ideally want the slot to be available
|
||||
*/
|
||||
if (slotEndTime <= finalizationTime + 1) result.push({ startTime: initialTime, endTime: periodTime });
|
||||
initialTime += frequency;
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
const getSlots = ({ inviteeDate, frequency, minimumBookingNotice, workingHours, eventLength }: GetSlots) => {
|
||||
// current date in invitee tz
|
||||
const startDate = dayjs().add(minimumBookingNotice, "minute");
|
||||
const startOfDay = dayjs.utc().startOf("day");
|
||||
const startOfInviteeDay = inviteeDate.startOf("day");
|
||||
// checks if the start date is in the past
|
||||
|
||||
/**
|
||||
* TODO: change "day" for "hour" to stop displaying 1 day before today
|
||||
* This is displaying a day as available as sometimes difference between two dates is < 24 hrs.
|
||||
* But when doing timezones an available day for an owner can be 2 days available in other users tz.
|
||||
*
|
||||
* */
|
||||
if (inviteeDate.isBefore(startDate, "day")) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const localWorkingHours = getWorkingHours(
|
||||
{ utcOffset: -inviteeDate.utcOffset() },
|
||||
workingHours.map((schedule) => ({
|
||||
days: schedule.days,
|
||||
startTime: startOfDay.add(schedule.startTime, "minute"),
|
||||
endTime: startOfDay.add(schedule.endTime, "minute"),
|
||||
}))
|
||||
).filter((hours) => hours.days.includes(inviteeDate.day()));
|
||||
|
||||
const slots: Dayjs[] = [];
|
||||
|
||||
const slotsTimeFrameAvailable = [] as Array<WorkingHoursTimeFrame>;
|
||||
// Here we split working hour in chunks for every frequency available that can fit in whole working hours
|
||||
const computedLocalWorkingHours: WorkingHoursTimeFrame[] = [];
|
||||
let tempComputeTimeFrame: WorkingHoursTimeFrame | undefined;
|
||||
const computeLength = localWorkingHours.length - 1;
|
||||
const makeTimeFrame = (item: typeof localWorkingHours[0]): WorkingHoursTimeFrame => ({
|
||||
startTime: item.startTime,
|
||||
endTime: item.endTime,
|
||||
});
|
||||
localWorkingHours.forEach((item, index) => {
|
||||
if (!tempComputeTimeFrame) {
|
||||
tempComputeTimeFrame = makeTimeFrame(item);
|
||||
} else {
|
||||
// please check the comment in splitAvailableTime func for the added 1 minute
|
||||
if (tempComputeTimeFrame.endTime + 1 === item.startTime) {
|
||||
// to deal with time that across the day, e.g. from 11:59 to to 12:01
|
||||
tempComputeTimeFrame.endTime = item.endTime;
|
||||
} else {
|
||||
computedLocalWorkingHours.push(tempComputeTimeFrame);
|
||||
tempComputeTimeFrame = makeTimeFrame(item);
|
||||
}
|
||||
}
|
||||
if (index == computeLength) {
|
||||
computedLocalWorkingHours.push(tempComputeTimeFrame);
|
||||
}
|
||||
});
|
||||
computedLocalWorkingHours.forEach((item) => {
|
||||
slotsTimeFrameAvailable.push(...splitAvailableTime(item.startTime, item.endTime, frequency, eventLength));
|
||||
});
|
||||
|
||||
slotsTimeFrameAvailable.forEach((item) => {
|
||||
const slot = startOfInviteeDay.add(item.startTime, "minute");
|
||||
// Validating slot its not on the past
|
||||
if (!slot.isBefore(startDate)) {
|
||||
slots.push(slot);
|
||||
}
|
||||
});
|
||||
|
||||
const uniq = (a: Dayjs[]) => {
|
||||
const seen: Record<string, boolean> = {};
|
||||
return a.filter((item) => {
|
||||
return seen.hasOwnProperty(item.format()) ? false : (seen[item.format()] = true);
|
||||
});
|
||||
};
|
||||
|
||||
return uniq(slots);
|
||||
};
|
||||
|
||||
export default getSlots;
|
||||
@@ -3,6 +3,6 @@
|
||||
"compilerOptions": {
|
||||
"target": "es5"
|
||||
},
|
||||
"include": ["."],
|
||||
"include": [".", "../types/next-auth.d.ts"],
|
||||
"exclude": ["dist", "build", "node_modules"]
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { WebhookTriggerEvents } from "@prisma/client";
|
||||
|
||||
// this is exported as we can't use `WebhookTriggerEvents` in the frontend straight-off
|
||||
|
||||
export const WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP = {
|
||||
core: [
|
||||
WebhookTriggerEvents.BOOKING_CANCELLED,
|
||||
WebhookTriggerEvents.BOOKING_CREATED,
|
||||
WebhookTriggerEvents.BOOKING_RESCHEDULED,
|
||||
] as ["BOOKING_CANCELLED", "BOOKING_CREATED", "BOOKING_RESCHEDULED"],
|
||||
routing_forms: [WebhookTriggerEvents.FORM_SUBMITTED] as ["FORM_SUBMITTED"],
|
||||
};
|
||||
|
||||
export const WEBHOOK_TRIGGER_EVENTS = [
|
||||
...WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP.core,
|
||||
...WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP.routing_forms,
|
||||
] as ["BOOKING_CANCELLED", "BOOKING_CREATED", "BOOKING_RESCHEDULED", "FORM_SUBMITTED"];
|
||||
@@ -0,0 +1,28 @@
|
||||
const supportedWebhookIntegrationList = ["https://discord.com/api/webhooks/"];
|
||||
|
||||
type WebhookIntegrationProps = {
|
||||
url: string;
|
||||
};
|
||||
|
||||
export const hasTemplateIntegration = (props: WebhookIntegrationProps) => {
|
||||
const ind = supportedWebhookIntegrationList.findIndex((integration) => {
|
||||
return props.url.includes(integration);
|
||||
});
|
||||
return ind > -1;
|
||||
};
|
||||
|
||||
const customTemplate = (props: WebhookIntegrationProps) => {
|
||||
const ind = supportedWebhookIntegrationList.findIndex((integration) => {
|
||||
return props.url.includes(integration);
|
||||
});
|
||||
return integrationTemplate(supportedWebhookIntegrationList[ind]) || "";
|
||||
};
|
||||
|
||||
const integrationTemplate = (webhookIntegration: string) => {
|
||||
switch (webhookIntegration) {
|
||||
case "https://discord.com/api/webhooks/":
|
||||
return '{"content": "An event has been scheduled/updated","embeds": [{"color": 2697513,"fields": [{"name": "Event Trigger","value": "{{triggerEvent}}"}, {"name": "What","value": "{{title}} ({{type}})"},{"name": "When","value": "Start: {{startTime}} \\n End: {{endTime}} \\n Timezone: ({{organizer.timeZone}})"},{"name": "Who","value": "Organizer: {{organizer.name}} ({{organizer.email}}) \\n Booker: {{attendees.0.name}} ({{attendees.0.email}})" },{"name":"Description", "value":": {{description}}"},{"name":"Where","value":": {{location}} "}]}]}';
|
||||
}
|
||||
};
|
||||
|
||||
export default customTemplate;
|
||||
@@ -0,0 +1,108 @@
|
||||
import { Webhook } from "@prisma/client";
|
||||
import { createHmac } from "crypto";
|
||||
import { compile } from "handlebars";
|
||||
|
||||
import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
type ContentType = "application/json" | "application/x-www-form-urlencoded";
|
||||
|
||||
function applyTemplate(template: string, data: CalendarEvent, contentType: ContentType) {
|
||||
const compiled = compile(template)(data);
|
||||
if (contentType === "application/json") {
|
||||
return JSON.stringify(jsonParse(compiled));
|
||||
}
|
||||
return compiled;
|
||||
}
|
||||
|
||||
function jsonParse(jsonString: string) {
|
||||
try {
|
||||
return JSON.parse(jsonString);
|
||||
} catch (e) {
|
||||
// don't do anything.
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const sendPayload = async (
|
||||
secretKey: string | null,
|
||||
triggerEvent: string,
|
||||
createdAt: string,
|
||||
webhook: Pick<Webhook, "subscriberUrl" | "appId" | "payloadTemplate">,
|
||||
data: CalendarEvent & {
|
||||
metadata?: { [key: string]: string };
|
||||
rescheduleUid?: string;
|
||||
bookingId?: number;
|
||||
}
|
||||
) => {
|
||||
const { appId, payloadTemplate: template } = webhook;
|
||||
|
||||
const contentType =
|
||||
!template || jsonParse(template) ? "application/json" : "application/x-www-form-urlencoded";
|
||||
|
||||
data.description = data.description || data.additionalNotes;
|
||||
|
||||
let body;
|
||||
|
||||
/* Zapier id is hardcoded in the DB, we send the raw data for this case */
|
||||
if (appId === "zapier") {
|
||||
body = JSON.stringify(data);
|
||||
} else if (template) {
|
||||
body = applyTemplate(template, data, contentType);
|
||||
} else {
|
||||
body = JSON.stringify({
|
||||
triggerEvent: triggerEvent,
|
||||
createdAt: createdAt,
|
||||
payload: data,
|
||||
});
|
||||
}
|
||||
|
||||
return _sendPayload(secretKey, triggerEvent, createdAt, webhook, body, contentType);
|
||||
};
|
||||
|
||||
export const sendGenericWebhookPayload = async (
|
||||
secretKey: string | null,
|
||||
triggerEvent: string,
|
||||
createdAt: string,
|
||||
webhook: Pick<Webhook, "subscriberUrl" | "appId" | "payloadTemplate">,
|
||||
data: Record<string, unknown>
|
||||
) => {
|
||||
const body = JSON.stringify(data);
|
||||
return _sendPayload(secretKey, triggerEvent, createdAt, webhook, body, "application/json");
|
||||
};
|
||||
|
||||
const _sendPayload = async (
|
||||
secretKey: string | null,
|
||||
triggerEvent: string,
|
||||
createdAt: string,
|
||||
webhook: Pick<Webhook, "subscriberUrl" | "appId" | "payloadTemplate">,
|
||||
body: string,
|
||||
contentType: "application/json" | "application/x-www-form-urlencoded"
|
||||
) => {
|
||||
const { subscriberUrl } = webhook;
|
||||
if (!subscriberUrl || !body) {
|
||||
throw new Error("Missing required elements to send webhook payload.");
|
||||
}
|
||||
|
||||
const secretSignature = secretKey
|
||||
? createHmac("sha256", secretKey).update(`${body}`).digest("hex")
|
||||
: "no-secret-provided";
|
||||
|
||||
const response = await fetch(subscriberUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": contentType,
|
||||
"X-Cal-Signature-256": secretSignature,
|
||||
},
|
||||
body,
|
||||
});
|
||||
|
||||
const text = await response.text();
|
||||
|
||||
return {
|
||||
ok: response.ok,
|
||||
status: response.status,
|
||||
message: text,
|
||||
};
|
||||
};
|
||||
|
||||
export default sendPayload;
|
||||
@@ -0,0 +1,43 @@
|
||||
import { WebhookTriggerEvents } from "@prisma/client";
|
||||
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
export type GetSubscriberOptions = {
|
||||
userId: number;
|
||||
eventTypeId: number;
|
||||
triggerEvent: WebhookTriggerEvents;
|
||||
};
|
||||
|
||||
const getWebhooks = async (options: GetSubscriberOptions) => {
|
||||
const { userId, eventTypeId } = options;
|
||||
const allWebhooks = await prisma.webhook.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{
|
||||
userId,
|
||||
},
|
||||
{
|
||||
eventTypeId,
|
||||
},
|
||||
],
|
||||
AND: {
|
||||
eventTriggers: {
|
||||
has: options.triggerEvent,
|
||||
},
|
||||
active: {
|
||||
equals: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
subscriberUrl: true,
|
||||
payloadTemplate: true,
|
||||
appId: true,
|
||||
secret: true,
|
||||
},
|
||||
});
|
||||
|
||||
return allWebhooks;
|
||||
};
|
||||
|
||||
export default getWebhooks;
|
||||
@@ -19,14 +19,14 @@ generator zod {
|
||||
}
|
||||
|
||||
enum SchedulingType {
|
||||
ROUND_ROBIN @map("roundRobin")
|
||||
COLLECTIVE @map("collective")
|
||||
ROUND_ROBIN @map("roundRobin")
|
||||
COLLECTIVE @map("collective")
|
||||
}
|
||||
|
||||
enum PeriodType {
|
||||
UNLIMITED @map("unlimited")
|
||||
ROLLING @map("rolling")
|
||||
RANGE @map("range")
|
||||
UNLIMITED @map("unlimited")
|
||||
ROLLING @map("rolling")
|
||||
RANGE @map("range")
|
||||
}
|
||||
|
||||
model EventType {
|
||||
@@ -253,10 +253,10 @@ model Attendee {
|
||||
}
|
||||
|
||||
enum BookingStatus {
|
||||
CANCELLED @map("cancelled")
|
||||
ACCEPTED @map("accepted")
|
||||
REJECTED @map("rejected")
|
||||
PENDING @map("pending")
|
||||
CANCELLED @map("cancelled")
|
||||
ACCEPTED @map("accepted")
|
||||
REJECTED @map("rejected")
|
||||
PENDING @map("pending")
|
||||
}
|
||||
|
||||
model DailyEventReference {
|
||||
@@ -335,10 +335,10 @@ model SelectedCalendar {
|
||||
}
|
||||
|
||||
enum EventTypeCustomInputType {
|
||||
TEXT @map("text")
|
||||
TEXTLONG @map("textLong")
|
||||
NUMBER @map("number")
|
||||
BOOL @map("bool")
|
||||
TEXT @map("text")
|
||||
TEXTLONG @map("textLong")
|
||||
NUMBER @map("number")
|
||||
BOOL @map("bool")
|
||||
}
|
||||
|
||||
model EventTypeCustomInput {
|
||||
@@ -575,9 +575,9 @@ model WorkflowsOnEventTypes {
|
||||
}
|
||||
|
||||
enum TimeUnit {
|
||||
DAY @map("day")
|
||||
HOUR @map("hour")
|
||||
MINUTE @map("minute")
|
||||
DAY @map("day")
|
||||
HOUR @map("hour")
|
||||
MINUTE @map("minute")
|
||||
}
|
||||
|
||||
model WorkflowReminder {
|
||||
|
||||
@@ -11,12 +11,18 @@
|
||||
"ts-node": "^10.6.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@calcom/app-store": "*",
|
||||
"@calcom/dayjs": "*",
|
||||
"@calcom/ee": "*",
|
||||
"@calcom/emails": "*",
|
||||
"@calcom/lib": "*",
|
||||
"@calcom/prisma": "*",
|
||||
"@calcom/types": "*",
|
||||
"@stripe/react-stripe-js": "^1.8.0",
|
||||
"@stripe/stripe-js": "^1.29.0",
|
||||
"stripe": "^9.1.0"
|
||||
"stripe": "^9.1.0",
|
||||
"uuid": "^8.3.2",
|
||||
"zod": "^3.16.0"
|
||||
},
|
||||
"main": "index.ts",
|
||||
"types": "index.d.ts",
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
import { PaymentType, Prisma } from "@prisma/client";
|
||||
import Stripe from "stripe";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { z } from "zod";
|
||||
|
||||
import getAppKeysFromSlug from "@calcom/app-store/_utils/getAppKeysFromSlug";
|
||||
import { sendAwaitingPaymentEmail, sendOrganizerPaymentRefundFailedEmail } from "@calcom/emails";
|
||||
import { getErrorFromUnknown } from "@calcom/lib/errors";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
import { createPaymentLink } from "./client";
|
||||
|
||||
export type PaymentData = Stripe.Response<Stripe.PaymentIntent> & {
|
||||
stripe_publishable_key: string;
|
||||
stripeAccount: string;
|
||||
@@ -28,4 +38,173 @@ const stripe = new Stripe(stripePrivateKey, {
|
||||
apiVersion: "2020-08-27",
|
||||
});
|
||||
|
||||
const stripeKeysSchema = z.object({
|
||||
payment_fee_fixed: z.number(),
|
||||
payment_fee_percentage: z.number(),
|
||||
});
|
||||
|
||||
const stripeCredentialSchema = z.object({
|
||||
stripe_user_id: z.string(),
|
||||
stripe_publishable_key: z.string(),
|
||||
});
|
||||
|
||||
export async function handlePayment(
|
||||
evt: CalendarEvent,
|
||||
selectedEventType: {
|
||||
price: number;
|
||||
currency: string;
|
||||
},
|
||||
stripeCredential: { key: Prisma.JsonValue },
|
||||
booking: {
|
||||
user: { email: string | null; name: string | null; timeZone: string } | null;
|
||||
id: number;
|
||||
startTime: { toISOString: () => string };
|
||||
uid: string;
|
||||
}
|
||||
) {
|
||||
const appKeys = await getAppKeysFromSlug("stripe");
|
||||
const { payment_fee_fixed, payment_fee_percentage } = stripeKeysSchema.parse(appKeys);
|
||||
|
||||
const paymentFee = Math.round(selectedEventType.price * payment_fee_percentage + payment_fee_fixed);
|
||||
const { stripe_user_id, stripe_publishable_key } = stripeCredentialSchema.parse(stripeCredential.key);
|
||||
|
||||
const params: Stripe.PaymentIntentCreateParams = {
|
||||
amount: selectedEventType.price,
|
||||
currency: selectedEventType.currency,
|
||||
payment_method_types: ["card"],
|
||||
application_fee_amount: paymentFee,
|
||||
};
|
||||
|
||||
const paymentIntent = await stripe.paymentIntents.create(params, { stripeAccount: stripe_user_id });
|
||||
|
||||
const payment = await prisma.payment.create({
|
||||
data: {
|
||||
type: PaymentType.STRIPE,
|
||||
uid: uuidv4(),
|
||||
booking: {
|
||||
connect: {
|
||||
id: booking.id,
|
||||
},
|
||||
},
|
||||
amount: selectedEventType.price,
|
||||
fee: paymentFee,
|
||||
currency: selectedEventType.currency,
|
||||
success: false,
|
||||
refunded: false,
|
||||
data: Object.assign({}, paymentIntent, {
|
||||
stripe_publishable_key,
|
||||
stripeAccount: stripe_user_id,
|
||||
}) /* We should treat this */ as PaymentData /* but Prisma doesn't know how to handle it, so it we treat it */ as unknown /* and then */ as Prisma.InputJsonValue,
|
||||
externalId: paymentIntent.id,
|
||||
},
|
||||
});
|
||||
|
||||
await sendAwaitingPaymentEmail({
|
||||
...evt,
|
||||
paymentInfo: {
|
||||
link: createPaymentLink({
|
||||
paymentUid: payment.uid,
|
||||
name: booking.user?.name,
|
||||
email: booking.user?.email,
|
||||
date: booking.startTime.toISOString(),
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
return payment;
|
||||
}
|
||||
|
||||
export async function refund(
|
||||
booking: {
|
||||
id: number;
|
||||
uid: string;
|
||||
startTime: Date;
|
||||
payment: {
|
||||
id: number;
|
||||
success: boolean;
|
||||
refunded: boolean;
|
||||
externalId: string;
|
||||
data: Prisma.JsonValue;
|
||||
type: PaymentType;
|
||||
}[];
|
||||
},
|
||||
calEvent: CalendarEvent
|
||||
) {
|
||||
try {
|
||||
const payment = booking.payment.find((e) => e.success && !e.refunded);
|
||||
if (!payment) return;
|
||||
|
||||
if (payment.type !== PaymentType.STRIPE) {
|
||||
await handleRefundError({
|
||||
event: calEvent,
|
||||
reason: "cannot refund non Stripe payment",
|
||||
paymentId: "unknown",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const refund = await stripe.refunds.create(
|
||||
{
|
||||
payment_intent: payment.externalId,
|
||||
},
|
||||
{ stripeAccount: (payment.data as unknown as PaymentData)["stripeAccount"] }
|
||||
);
|
||||
|
||||
if (!refund || refund.status === "failed") {
|
||||
await handleRefundError({
|
||||
event: calEvent,
|
||||
reason: refund?.failure_reason || "unknown",
|
||||
paymentId: payment.externalId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await prisma.payment.update({
|
||||
where: {
|
||||
id: payment.id,
|
||||
},
|
||||
data: {
|
||||
refunded: true,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
const err = getErrorFromUnknown(e);
|
||||
console.error(err, "Refund failed");
|
||||
await handleRefundError({
|
||||
event: calEvent,
|
||||
reason: err.message || "unknown",
|
||||
paymentId: "unknown",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const closePayments = async (paymentIntentId: string, stripeAccount: string) => {
|
||||
try {
|
||||
// Expire all current sessions
|
||||
const sessions = await stripe.checkout.sessions.list(
|
||||
{
|
||||
payment_intent: paymentIntentId,
|
||||
},
|
||||
{ stripeAccount }
|
||||
);
|
||||
for (const session of sessions.data) {
|
||||
await stripe.checkout.sessions.expire(session.id, { stripeAccount });
|
||||
}
|
||||
// Then cancel the payment intent
|
||||
await stripe.paymentIntents.cancel(paymentIntentId, { stripeAccount });
|
||||
return;
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
async function handleRefundError(opts: { event: CalendarEvent; reason: string; paymentId: string }) {
|
||||
console.error(`refund failed: ${opts.reason} for booking '${opts.event.uid}'`);
|
||||
await sendOrganizerPaymentRefundFailedEmail({
|
||||
...opts.event,
|
||||
paymentInfo: { reason: opts.reason, id: opts.paymentId },
|
||||
});
|
||||
}
|
||||
|
||||
export default stripe;
|
||||
@@ -0,0 +1 @@
|
||||
export * from "@trpc/client";
|
||||
@@ -0,0 +1 @@
|
||||
export * from "@trpc/client/links/httpBatchLink";
|
||||
@@ -0,0 +1 @@
|
||||
export * from "@trpc/client/links/httpLink";
|
||||
@@ -0,0 +1 @@
|
||||
export * from "@trpc/client/links/loggerLink";
|
||||
@@ -0,0 +1 @@
|
||||
export * from "@trpc/client/links/splitLink";
|
||||
@@ -0,0 +1,4 @@
|
||||
export * from "./client";
|
||||
export * from "./next";
|
||||
export * from "./react";
|
||||
export * from "./server";
|
||||
@@ -0,0 +1 @@
|
||||
export * from "@trpc/next";
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "@calcom/trpc",
|
||||
"description": "Shared tRPC library for Cal.com",
|
||||
"authors": "zomars",
|
||||
"version": "1.0.0",
|
||||
"main": "index.ts",
|
||||
"dependencies": {
|
||||
"@trpc/client": "^9.25.2",
|
||||
"@trpc/next": "^9.25.2",
|
||||
"@trpc/react": "^9.25.2",
|
||||
"@trpc/server": "^9.25.2",
|
||||
"superjson": "1.9.1",
|
||||
"zod": "^3.16.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "@trpc/react";
|
||||
export * from "./trpc";
|
||||
@@ -0,0 +1 @@
|
||||
export * from "@trpc/react/ssg";
|
||||
@@ -0,0 +1,33 @@
|
||||
import superjson from "superjson";
|
||||
|
||||
import { createReactQueryHooks } from "../react";
|
||||
// ℹ️ Type-only import:
|
||||
// https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#type-only-imports-and-export
|
||||
import type { inferProcedureInput, inferProcedureOutput } from "../server";
|
||||
import type { AppRouter } from "../server/routers/_app";
|
||||
|
||||
/**
|
||||
* A set of strongly-typed React hooks from your `AppRouter` type signature with `createReactQueryHooks`.
|
||||
* @link https://trpc.io/docs/react#3-create-trpc-hooks
|
||||
*/
|
||||
export const trpc = createReactQueryHooks<AppRouter>();
|
||||
|
||||
export const transformer = superjson;
|
||||
/**
|
||||
* This is a helper method to infer the output of a query resolver
|
||||
* @example type HelloOutput = inferQueryOutput<'hello'>
|
||||
*/
|
||||
export type inferQueryOutput<TRouteKey extends keyof AppRouter["_def"]["queries"]> = inferProcedureOutput<
|
||||
AppRouter["_def"]["queries"][TRouteKey]
|
||||
>;
|
||||
|
||||
export type inferQueryInput<TRouteKey extends keyof AppRouter["_def"]["queries"]> = inferProcedureInput<
|
||||
AppRouter["_def"]["queries"][TRouteKey]
|
||||
>;
|
||||
|
||||
export type inferMutationInput<TRouteKey extends keyof AppRouter["_def"]["mutations"]> = inferProcedureInput<
|
||||
AppRouter["_def"]["mutations"][TRouteKey]
|
||||
>;
|
||||
|
||||
export type inferMutationOutput<TRouteKey extends keyof AppRouter["_def"]["mutations"]> =
|
||||
inferProcedureOutput<AppRouter["_def"]["mutations"][TRouteKey]>;
|
||||
@@ -0,0 +1 @@
|
||||
export * from "@trpc/server/adapters/next";
|
||||
@@ -0,0 +1,120 @@
|
||||
import { GetServerSidePropsContext } from "next";
|
||||
import { Session } from "next-auth";
|
||||
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
|
||||
|
||||
import { getSession } from "@calcom/lib/auth";
|
||||
import { defaultAvatarSrc } from "@calcom/lib/profile";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
import { getLocaleFromHeaders } from "@lib/core/i18n/i18n.utils";
|
||||
|
||||
import * as trpc from "@trpc/server";
|
||||
import { Maybe } from "@trpc/server";
|
||||
import * as trpcNext from "@trpc/server/adapters/next";
|
||||
|
||||
type CreateContextOptions = trpcNext.CreateNextContextOptions | GetServerSidePropsContext;
|
||||
|
||||
async function getUserFromSession({
|
||||
session,
|
||||
req,
|
||||
}: {
|
||||
session: Maybe<Session>;
|
||||
req: CreateContextOptions["req"];
|
||||
}) {
|
||||
if (!session?.user?.id) {
|
||||
return null;
|
||||
}
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: session.user.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
name: true,
|
||||
email: true,
|
||||
bio: true,
|
||||
timeZone: true,
|
||||
weekStart: true,
|
||||
startTime: true,
|
||||
endTime: true,
|
||||
defaultScheduleId: true,
|
||||
bufferTime: true,
|
||||
theme: true,
|
||||
createdDate: true,
|
||||
hideBranding: true,
|
||||
avatar: true,
|
||||
twoFactorEnabled: true,
|
||||
disableImpersonation: true,
|
||||
identityProvider: true,
|
||||
brandColor: true,
|
||||
darkBrandColor: true,
|
||||
plan: true,
|
||||
away: true,
|
||||
credentials: {
|
||||
select: {
|
||||
id: true,
|
||||
type: true,
|
||||
key: true,
|
||||
userId: true,
|
||||
appId: true,
|
||||
},
|
||||
orderBy: {
|
||||
id: "asc",
|
||||
},
|
||||
},
|
||||
selectedCalendars: {
|
||||
select: {
|
||||
externalId: true,
|
||||
integration: true,
|
||||
},
|
||||
},
|
||||
completedOnboarding: true,
|
||||
destinationCalendar: true,
|
||||
locale: true,
|
||||
timeFormat: true,
|
||||
trialEndsAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
// some hacks to make sure `username` and `email` are never inferred as `null`
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
const { email, username } = user;
|
||||
if (!email) {
|
||||
return null;
|
||||
}
|
||||
const avatar = user.avatar || defaultAvatarSrc({ email });
|
||||
|
||||
const locale = user.locale || getLocaleFromHeaders(req);
|
||||
return {
|
||||
...user,
|
||||
avatar,
|
||||
email,
|
||||
username,
|
||||
locale,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates context for an incoming request
|
||||
* @link https://trpc.io/docs/context
|
||||
*/
|
||||
export const createContext = async ({ req }: CreateContextOptions) => {
|
||||
// for API-response caching see https://trpc.io/docs/caching
|
||||
const session = await getSession({ req });
|
||||
|
||||
const user = await getUserFromSession({ session, req });
|
||||
const locale = user?.locale ?? getLocaleFromHeaders(req);
|
||||
const i18n = await serverSideTranslations(locale, ["common", "vital"]);
|
||||
return {
|
||||
i18n,
|
||||
prisma,
|
||||
session,
|
||||
user,
|
||||
locale,
|
||||
};
|
||||
};
|
||||
|
||||
export type Context = trpc.inferAsyncReturnType<typeof createContext>;
|
||||
@@ -0,0 +1,34 @@
|
||||
import { performance } from "@calcom/lib/server/perfObserver";
|
||||
|
||||
import * as trpc from "@trpc/server";
|
||||
|
||||
import { Context } from "./createContext";
|
||||
|
||||
/**
|
||||
* Helper function to create a router with context
|
||||
*/
|
||||
export function createRouter() {
|
||||
return trpc.router<Context>().middleware(async ({ path, type, next }) => {
|
||||
performance.mark("Start");
|
||||
const result = await next();
|
||||
performance.mark("End");
|
||||
performance.measure(`[${result.ok ? "OK" : "ERROR"}][$1] ${type} '${path}'`, "Start", "End");
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
export function createProtectedRouter() {
|
||||
return createRouter().middleware(({ ctx, next }) => {
|
||||
if (!ctx.user || !ctx.session) {
|
||||
throw new trpc.TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
return next({
|
||||
ctx: {
|
||||
...ctx,
|
||||
// infers that `user` and `session` are non-nullable to downstream procedures
|
||||
session: ctx.session,
|
||||
user: ctx.user,
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from "@trpc/server";
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* This file contains the root router of your tRPC-backend
|
||||
*/
|
||||
import superjson from "superjson";
|
||||
|
||||
import { createRouter } from "../createRouter";
|
||||
import { viewerRouter } from "./viewer";
|
||||
|
||||
/**
|
||||
* Create your application's root router
|
||||
* If you want to use SSG, you need export this
|
||||
* @link https://trpc.io/docs/ssg
|
||||
* @link https://trpc.io/docs/router
|
||||
*/
|
||||
export const appRouter = createRouter()
|
||||
/**
|
||||
* Add data transformers
|
||||
* @link https://trpc.io/docs/data-transformers
|
||||
*/
|
||||
.transformer(superjson)
|
||||
/**
|
||||
* Optionally do custom error (type safe!) formatting
|
||||
* @link https://trpc.io/docs/error-formatting
|
||||
*/
|
||||
// .formatError(({ shape, error }) => { })
|
||||
.merge("viewer.", viewerRouter);
|
||||
|
||||
export type AppRouter = typeof appRouter;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,132 @@
|
||||
import { v4 } from "uuid";
|
||||
import { z } from "zod";
|
||||
|
||||
import { generateUniqueAPIKey } from "@calcom/ee/lib/api/apiKeys";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
|
||||
export const apiKeysRouter = createProtectedRouter()
|
||||
.query("list", {
|
||||
async resolve({ ctx }) {
|
||||
return await ctx.prisma.apiKey.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
OR: [
|
||||
{
|
||||
NOT: {
|
||||
appId: "zapier",
|
||||
},
|
||||
},
|
||||
{
|
||||
appId: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
},
|
||||
})
|
||||
.query("findKeyOfType", {
|
||||
input: z.object({
|
||||
appId: z.string().optional().nullable(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
return await ctx.prisma.apiKey.findFirst({
|
||||
where: {
|
||||
AND: [
|
||||
{
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
{
|
||||
appId: input.appId,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("create", {
|
||||
input: z.object({
|
||||
note: z.string().optional().nullish(),
|
||||
expiresAt: z.date().optional().nullable(),
|
||||
neverExpires: z.boolean().optional(),
|
||||
appId: z.string().optional().nullable(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const [hashedApiKey, apiKey] = generateUniqueAPIKey();
|
||||
// Here we snap never expires before deleting it so it's not passed to prisma create call.
|
||||
const neverExpires = input.neverExpires;
|
||||
delete input.neverExpires;
|
||||
await ctx.prisma.apiKey.create({
|
||||
data: {
|
||||
id: v4(),
|
||||
userId: ctx.user.id,
|
||||
...input,
|
||||
// And here we pass a null to expiresAt if never expires is true. otherwise just pass expiresAt from input
|
||||
expiresAt: neverExpires ? null : input.expiresAt,
|
||||
hashedKey: hashedApiKey,
|
||||
},
|
||||
});
|
||||
const prefixedApiKey = `${process.env.API_KEY_PREFIX ?? "cal_"}${apiKey}`;
|
||||
return prefixedApiKey;
|
||||
},
|
||||
})
|
||||
.mutation("edit", {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
note: z.string().optional().nullish(),
|
||||
expiresAt: z.date().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const { id, ...data } = input;
|
||||
const {
|
||||
apiKeys: [updatedApiKey],
|
||||
} = await ctx.prisma.user.update({
|
||||
where: {
|
||||
id: ctx.user.id,
|
||||
},
|
||||
data: {
|
||||
apiKeys: {
|
||||
update: {
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
data,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
apiKeys: {
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
return updatedApiKey;
|
||||
},
|
||||
})
|
||||
.mutation("delete", {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
eventTypeId: z.number().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const { id } = input;
|
||||
await ctx.prisma.user.update({
|
||||
where: {
|
||||
id: ctx.user.id,
|
||||
},
|
||||
data: {
|
||||
apiKeys: {
|
||||
delete: {
|
||||
id,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
return {
|
||||
id,
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,253 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { z } from "zod";
|
||||
|
||||
import { getAvailabilityFromSchedule } from "@calcom/lib/availability";
|
||||
import { Schedule } from "@calcom/types/schedule";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
|
||||
export const availabilityRouter = createProtectedRouter()
|
||||
.query("list", {
|
||||
async resolve({ ctx }) {
|
||||
const { prisma, user } = ctx;
|
||||
const schedules = await prisma.schedule.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
availability: true,
|
||||
timeZone: true,
|
||||
},
|
||||
orderBy: {
|
||||
id: "asc",
|
||||
},
|
||||
});
|
||||
return {
|
||||
schedules: schedules.map((schedule) => ({
|
||||
...schedule,
|
||||
isDefault: user.defaultScheduleId === schedule.id || schedules.length === 1,
|
||||
})),
|
||||
};
|
||||
},
|
||||
})
|
||||
.query("schedule", {
|
||||
input: z.object({
|
||||
scheduleId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const { prisma, user } = ctx;
|
||||
const schedule = await prisma.schedule.findUnique({
|
||||
where: {
|
||||
id: input.scheduleId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
name: true,
|
||||
availability: true,
|
||||
timeZone: true,
|
||||
},
|
||||
});
|
||||
if (!schedule || schedule.userId !== user.id) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
}
|
||||
const availability = schedule.availability.reduce(
|
||||
(schedule: Schedule, availability) => {
|
||||
availability.days.forEach((day) => {
|
||||
schedule[day].push({
|
||||
start: new Date(
|
||||
Date.UTC(
|
||||
new Date().getUTCFullYear(),
|
||||
new Date().getUTCMonth(),
|
||||
new Date().getUTCDate(),
|
||||
availability.startTime.getUTCHours(),
|
||||
availability.startTime.getUTCMinutes()
|
||||
)
|
||||
),
|
||||
end: new Date(
|
||||
Date.UTC(
|
||||
new Date().getUTCFullYear(),
|
||||
new Date().getUTCMonth(),
|
||||
new Date().getUTCDate(),
|
||||
availability.endTime.getUTCHours(),
|
||||
availability.endTime.getUTCMinutes()
|
||||
)
|
||||
),
|
||||
});
|
||||
});
|
||||
return schedule;
|
||||
},
|
||||
Array.from([...Array(7)]).map(() => [])
|
||||
);
|
||||
return {
|
||||
schedule,
|
||||
availability,
|
||||
timeZone: schedule.timeZone || user.timeZone,
|
||||
isDefault: !user.defaultScheduleId || user.defaultScheduleId === schedule.id,
|
||||
};
|
||||
},
|
||||
})
|
||||
.mutation("schedule.create", {
|
||||
input: z.object({
|
||||
name: z.string(),
|
||||
copyScheduleId: z.number().optional(),
|
||||
schedule: z
|
||||
.array(
|
||||
z.array(
|
||||
z.object({
|
||||
start: z.date(),
|
||||
end: z.date(),
|
||||
})
|
||||
)
|
||||
)
|
||||
.optional(),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
const { user, prisma } = ctx;
|
||||
const data: Prisma.ScheduleCreateInput = {
|
||||
name: input.name,
|
||||
user: {
|
||||
connect: {
|
||||
id: user.id,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
if (input.schedule) {
|
||||
const availability = getAvailabilityFromSchedule(input.schedule);
|
||||
data.availability = {
|
||||
createMany: {
|
||||
data: availability.map((schedule) => ({
|
||||
days: schedule.days,
|
||||
startTime: schedule.startTime,
|
||||
endTime: schedule.endTime,
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
const schedule = await prisma.schedule.create({
|
||||
data,
|
||||
});
|
||||
return { schedule };
|
||||
},
|
||||
})
|
||||
.mutation("schedule.delete", {
|
||||
input: z.object({
|
||||
scheduleId: z.number(),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
const { user, prisma } = ctx;
|
||||
|
||||
const scheduleToDelete = await prisma.schedule.findFirst({
|
||||
where: {
|
||||
id: input.scheduleId,
|
||||
},
|
||||
select: {
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (scheduleToDelete?.userId !== user.id) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
if (user.defaultScheduleId === input.scheduleId) {
|
||||
// unset default
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
data: {
|
||||
defaultScheduleId: undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
await prisma.schedule.delete({
|
||||
where: {
|
||||
id: input.scheduleId,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("schedule.update", {
|
||||
input: z.object({
|
||||
scheduleId: z.number(),
|
||||
timeZone: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
isDefault: z.boolean().optional(),
|
||||
schedule: z.array(
|
||||
z.array(
|
||||
z.object({
|
||||
start: z.date(),
|
||||
end: z.date(),
|
||||
})
|
||||
)
|
||||
),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
const { user, prisma } = ctx;
|
||||
const availability = getAvailabilityFromSchedule(input.schedule);
|
||||
|
||||
if (input.isDefault) {
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
data: {
|
||||
defaultScheduleId: input.scheduleId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Not able to update the schedule with userId where clause, so fetch schedule separately and then validate
|
||||
// Bug: https://github.com/prisma/prisma/issues/7290
|
||||
const userSchedule = await prisma.schedule.findUnique({
|
||||
where: {
|
||||
id: input.scheduleId,
|
||||
},
|
||||
select: {
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (userSchedule?.userId !== user.id) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
if (!userSchedule || userSchedule.userId !== user.id) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
}
|
||||
|
||||
const schedule = await prisma.schedule.update({
|
||||
where: {
|
||||
id: input.scheduleId,
|
||||
},
|
||||
data: {
|
||||
timeZone: input.timeZone,
|
||||
name: input.name,
|
||||
availability: {
|
||||
deleteMany: {
|
||||
scheduleId: {
|
||||
equals: input.scheduleId,
|
||||
},
|
||||
},
|
||||
createMany: {
|
||||
data: availability.map((schedule) => ({
|
||||
days: schedule.days,
|
||||
startTime: schedule.startTime,
|
||||
endTime: schedule.endTime,
|
||||
})),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
schedule,
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
import { SchedulingType } from "@prisma/client";
|
||||
import { z } from "zod";
|
||||
|
||||
import EventManager from "@calcom/core/EventManager";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { sendLocationChangeEmails } from "@calcom/emails";
|
||||
import { parseRecurringEvent } from "@calcom/lib";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import type { AdditionalInformation, CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
|
||||
// Common data for all endpoints under webhook
|
||||
const commonBookingSchema = z.object({
|
||||
bookingId: z.number(),
|
||||
});
|
||||
|
||||
export const bookingsRouter = createProtectedRouter()
|
||||
.middleware(async ({ ctx, rawInput, next }) => {
|
||||
// Endpoints that just read the logged in user's data - like 'list' don't necessary have any input
|
||||
if (!rawInput) return next({ ctx: { ...ctx, booking: null } });
|
||||
|
||||
const webhookIdAndEventTypeId = commonBookingSchema.safeParse(rawInput);
|
||||
if (!webhookIdAndEventTypeId.success) throw new TRPCError({ code: "PARSE_ERROR" });
|
||||
|
||||
const { bookingId } = webhookIdAndEventTypeId.data;
|
||||
const booking = await ctx.prisma.booking.findFirst({
|
||||
where: {
|
||||
OR: [
|
||||
/* If user is organizer */
|
||||
{ userId: ctx.user.id, id: bookingId },
|
||||
/* Or part of a collective booking */
|
||||
{
|
||||
eventType: {
|
||||
schedulingType: SchedulingType.COLLECTIVE,
|
||||
users: {
|
||||
some: {
|
||||
id: ctx.user.id,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
include: {
|
||||
attendees: true,
|
||||
eventType: true,
|
||||
user: {
|
||||
include: { destinationCalendar: true },
|
||||
},
|
||||
destinationCalendar: true,
|
||||
},
|
||||
});
|
||||
return next({ ctx: { ...ctx, booking } });
|
||||
})
|
||||
.middleware(async ({ ctx, next }) => {
|
||||
// So TS doesn't compain in the previous middleware.
|
||||
// This means the user doesn't have access to this booking
|
||||
if (!ctx.booking) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
// Booking here is non-nullable anymore
|
||||
return next({ ctx: { ...ctx, booking: ctx.booking } });
|
||||
})
|
||||
.mutation("editLocation", {
|
||||
input: commonBookingSchema.extend({
|
||||
newLocation: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const { bookingId, newLocation: location } = input;
|
||||
const { booking } = ctx;
|
||||
|
||||
try {
|
||||
await ctx.prisma.booking.update({
|
||||
where: { id: bookingId },
|
||||
data: { location },
|
||||
});
|
||||
|
||||
const organizer = await ctx.prisma.user.findFirst({
|
||||
where: {
|
||||
id: booking.userId || 0,
|
||||
},
|
||||
select: {
|
||||
name: true,
|
||||
email: true,
|
||||
timeZone: true,
|
||||
locale: true,
|
||||
},
|
||||
rejectOnNotFound: true,
|
||||
});
|
||||
|
||||
const tOrganizer = await getTranslation(organizer.locale ?? "en", "common");
|
||||
|
||||
const attendeesListPromises = booking.attendees.map(async (attendee) => {
|
||||
return {
|
||||
name: attendee.name,
|
||||
email: attendee.email,
|
||||
timeZone: attendee.timeZone,
|
||||
language: {
|
||||
translate: await getTranslation(attendee.locale ?? "en", "common"),
|
||||
locale: attendee.locale ?? "en",
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const attendeesList = await Promise.all(attendeesListPromises);
|
||||
|
||||
const evt: CalendarEvent = {
|
||||
title: booking.title || "",
|
||||
type: (booking.eventType?.title as string) || booking?.title || "",
|
||||
description: booking.description || "",
|
||||
startTime: booking.startTime ? dayjs(booking.startTime).format() : "",
|
||||
endTime: booking.endTime ? dayjs(booking.endTime).format() : "",
|
||||
organizer: {
|
||||
email: organizer.email,
|
||||
name: organizer.name ?? "Nameless",
|
||||
timeZone: organizer.timeZone,
|
||||
language: { translate: tOrganizer, locale: organizer.locale ?? "en" },
|
||||
},
|
||||
attendees: attendeesList,
|
||||
uid: booking.uid,
|
||||
recurringEvent: parseRecurringEvent(booking.eventType?.recurringEvent),
|
||||
location,
|
||||
destinationCalendar: booking?.destinationCalendar || booking?.user?.destinationCalendar,
|
||||
};
|
||||
|
||||
const eventManager = new EventManager(ctx.user);
|
||||
// TODO: This is causing duplicate calendar events when updating location
|
||||
const scheduleResult = await eventManager.create(evt);
|
||||
|
||||
const results = scheduleResult.results;
|
||||
if (results.length > 0 && results.every((res) => !res.success)) {
|
||||
const error = {
|
||||
errorCode: "BookingUpdateLocationFailed",
|
||||
message: "Updating location failed",
|
||||
};
|
||||
logger.error(`Booking ${ctx.user.username} failed`, error, results);
|
||||
} else {
|
||||
const metadata: AdditionalInformation = {};
|
||||
if (results.length) {
|
||||
metadata.hangoutLink = results[0].createdEvent?.hangoutLink;
|
||||
metadata.conferenceData = results[0].createdEvent?.conferenceData;
|
||||
metadata.entryPoints = results[0].createdEvent?.entryPoints;
|
||||
}
|
||||
try {
|
||||
await sendLocationChangeEmails({ ...evt, additionalInformation: metadata });
|
||||
} catch (error) {
|
||||
console.log("Error sending LocationChangeEmails");
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
|
||||
}
|
||||
return { message: "Location updated" };
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,409 @@
|
||||
import { EventTypeCustomInput, MembershipRole, PeriodType, Prisma } from "@prisma/client";
|
||||
import { PrismaClientKnownRequestError } from "@prisma/client/runtime";
|
||||
import { z } from "zod";
|
||||
|
||||
import getAppKeysFromSlug from "@calcom/app-store/_utils/getAppKeysFromSlug";
|
||||
import { _DestinationCalendarModel, _EventTypeCustomInputModel, _EventTypeModel } from "@calcom/prisma/zod";
|
||||
import { stringOrNumber } from "@calcom/prisma/zod-utils";
|
||||
import { createEventTypeInput } from "@calcom/prisma/zod/custom/eventtype";
|
||||
import { stripeDataSchema } from "@calcom/stripe/server";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
import { viewerRouter } from "../viewer";
|
||||
|
||||
function isPeriodType(keyInput: string): keyInput is PeriodType {
|
||||
return Object.keys(PeriodType).includes(keyInput);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that it is a valid HTTP URL
|
||||
* It automatically avoids
|
||||
* - XSS attempts through javascript:alert('hi')
|
||||
* - mailto: links
|
||||
*/
|
||||
function assertValidUrl(url: string | null | undefined) {
|
||||
if (!url) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!url.startsWith("http://") && !url.startsWith("https://")) {
|
||||
throw new TRPCError({ code: "PARSE_ERROR", message: "Invalid URL" });
|
||||
}
|
||||
}
|
||||
|
||||
function handlePeriodType(periodType: string | undefined): PeriodType | undefined {
|
||||
if (typeof periodType !== "string") return undefined;
|
||||
const passedPeriodType = periodType.toUpperCase();
|
||||
if (!isPeriodType(passedPeriodType)) return undefined;
|
||||
return PeriodType[passedPeriodType];
|
||||
}
|
||||
|
||||
function handleCustomInputs(customInputs: EventTypeCustomInput[], eventTypeId: number) {
|
||||
const cInputsIdsToDelete = customInputs.filter((input) => input.id > 0).map((e) => e.id);
|
||||
const cInputsToCreate = customInputs
|
||||
.filter((input) => input.id < 0)
|
||||
.map((input) => ({
|
||||
type: input.type,
|
||||
label: input.label,
|
||||
required: input.required,
|
||||
placeholder: input.placeholder,
|
||||
}));
|
||||
const cInputsToUpdate = customInputs
|
||||
.filter((input) => input.id > 0)
|
||||
.map((input) => ({
|
||||
data: {
|
||||
type: input.type,
|
||||
label: input.label,
|
||||
required: input.required,
|
||||
placeholder: input.placeholder,
|
||||
},
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
}));
|
||||
|
||||
return {
|
||||
deleteMany: {
|
||||
eventTypeId,
|
||||
NOT: {
|
||||
id: { in: cInputsIdsToDelete },
|
||||
},
|
||||
},
|
||||
createMany: {
|
||||
data: cInputsToCreate,
|
||||
},
|
||||
update: cInputsToUpdate,
|
||||
};
|
||||
}
|
||||
|
||||
const EventTypeUpdateInput = _EventTypeModel
|
||||
/** Optional fields */
|
||||
.extend({
|
||||
customInputs: z.array(_EventTypeCustomInputModel),
|
||||
destinationCalendar: _DestinationCalendarModel.pick({
|
||||
integration: true,
|
||||
externalId: true,
|
||||
}),
|
||||
users: z.array(stringOrNumber).optional(),
|
||||
schedule: z.number().optional(),
|
||||
hashedLink: z.string(),
|
||||
})
|
||||
.partial()
|
||||
.merge(
|
||||
_EventTypeModel
|
||||
/** Required fields */
|
||||
.pick({
|
||||
id: true,
|
||||
})
|
||||
);
|
||||
|
||||
export const eventTypesRouter = createProtectedRouter()
|
||||
.query("list", {
|
||||
async resolve({ ctx }) {
|
||||
return await ctx.prisma.webhook.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("create", {
|
||||
input: createEventTypeInput,
|
||||
async resolve({ ctx, input }) {
|
||||
const { schedulingType, teamId, ...rest } = input;
|
||||
const userId = ctx.user.id;
|
||||
|
||||
const data: Prisma.EventTypeCreateInput = {
|
||||
...rest,
|
||||
owner: teamId ? undefined : { connect: { id: userId } },
|
||||
users: {
|
||||
connect: {
|
||||
id: userId,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const appKeys = await getAppKeysFromSlug("daily-video");
|
||||
if (typeof appKeys.api_key === "string") {
|
||||
data.locations = [{ type: "integrations:daily" }];
|
||||
}
|
||||
|
||||
if (teamId && schedulingType) {
|
||||
const hasMembership = await ctx.prisma.membership.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
teamId: teamId,
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!hasMembership) {
|
||||
console.warn(`User ${userId} does not have permission to create this new event type`);
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
|
||||
data.team = {
|
||||
connect: {
|
||||
id: teamId,
|
||||
},
|
||||
};
|
||||
data.schedulingType = schedulingType;
|
||||
}
|
||||
|
||||
try {
|
||||
const eventType = await ctx.prisma.eventType.create({ data });
|
||||
return { eventType };
|
||||
} catch (e) {
|
||||
if (e instanceof PrismaClientKnownRequestError) {
|
||||
if (e.code === "P2002" && Array.isArray(e.meta?.target) && e.meta?.target.includes("slug")) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "URL Slug already exists for given user." });
|
||||
}
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
})
|
||||
// Prevent non-owners to update/delete a team event
|
||||
.middleware(async ({ ctx, rawInput, next }) => {
|
||||
const event = await ctx.prisma.eventType.findUnique({
|
||||
where: { id: (rawInput as Record<"id", number>)?.id },
|
||||
include: {
|
||||
users: true,
|
||||
team: {
|
||||
select: {
|
||||
members: {
|
||||
select: {
|
||||
userId: true,
|
||||
role: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!event) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
|
||||
const isAuthorized = (function () {
|
||||
if (event.team) {
|
||||
return event.team.members
|
||||
.filter((member) => member.role === MembershipRole.OWNER || member.role === MembershipRole.ADMIN)
|
||||
.map((member) => member.userId)
|
||||
.includes(ctx.user.id);
|
||||
}
|
||||
return event.userId === ctx.user.id || event.users.find((user) => user.id === ctx.user.id);
|
||||
})();
|
||||
|
||||
if (!isAuthorized) {
|
||||
console.warn(`User ${ctx.user.id} attempted to an access an event ${event.id} they do not own.`);
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
|
||||
const inputUsers = (rawInput as any).users || [];
|
||||
|
||||
const isAllowed = (function () {
|
||||
if (event.team) {
|
||||
const allTeamMembers = event.team.members.map((member) => member.userId);
|
||||
return inputUsers.every((userId: string) => allTeamMembers.includes(Number.parseInt(userId)));
|
||||
}
|
||||
return inputUsers.every((userId: string) => Number.parseInt(userId) === ctx.user.id);
|
||||
})();
|
||||
|
||||
if (!isAllowed) {
|
||||
console.warn(`User ${ctx.user.id} attempted to an create an event for users ${inputUsers.join(", ")}.`);
|
||||
throw new TRPCError({ code: "FORBIDDEN" });
|
||||
}
|
||||
|
||||
return next();
|
||||
})
|
||||
.query("get", {
|
||||
input: z.object({
|
||||
id: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const user = await ctx.prisma.user.findUnique({
|
||||
where: {
|
||||
id: ctx.user.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
name: true,
|
||||
startTime: true,
|
||||
endTime: true,
|
||||
bufferTime: true,
|
||||
avatar: true,
|
||||
plan: true,
|
||||
},
|
||||
});
|
||||
if (!user) {
|
||||
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
|
||||
}
|
||||
return await ctx.prisma.eventType.findUnique({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
include: {
|
||||
team: true,
|
||||
users: true,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("update", {
|
||||
input: EventTypeUpdateInput.strict(),
|
||||
async resolve({ ctx, input }) {
|
||||
const {
|
||||
schedule,
|
||||
periodType,
|
||||
locations,
|
||||
destinationCalendar,
|
||||
customInputs,
|
||||
recurringEvent,
|
||||
users,
|
||||
id,
|
||||
hashedLink,
|
||||
...rest
|
||||
} = input;
|
||||
assertValidUrl(input.successRedirectUrl);
|
||||
const data: Prisma.EventTypeUpdateInput = rest;
|
||||
data.locations = locations ?? undefined;
|
||||
if (periodType) {
|
||||
data.periodType = handlePeriodType(periodType);
|
||||
}
|
||||
|
||||
if (recurringEvent) {
|
||||
data.recurringEvent = {
|
||||
dstart: recurringEvent.dtstart as unknown as Prisma.InputJsonObject,
|
||||
interval: recurringEvent.interval,
|
||||
count: recurringEvent.count,
|
||||
freq: recurringEvent.freq,
|
||||
until: recurringEvent.until as unknown as Prisma.InputJsonObject,
|
||||
tzid: recurringEvent.tzid,
|
||||
};
|
||||
} else {
|
||||
data.recurringEvent = Prisma.DbNull;
|
||||
}
|
||||
|
||||
if (destinationCalendar) {
|
||||
/** We connect or create a destination calendar to the event type instead of the user */
|
||||
await viewerRouter.createCaller(ctx).mutation("setDestinationCalendar", {
|
||||
...destinationCalendar,
|
||||
eventTypeId: id,
|
||||
});
|
||||
}
|
||||
|
||||
if (customInputs) {
|
||||
data.customInputs = handleCustomInputs(customInputs, id);
|
||||
}
|
||||
|
||||
if (schedule) {
|
||||
data.schedule = {
|
||||
connect: {
|
||||
id: schedule,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (users) {
|
||||
data.users = {
|
||||
set: [],
|
||||
connect: users.map((userId: number) => ({ id: userId })),
|
||||
};
|
||||
}
|
||||
|
||||
if (input?.price) {
|
||||
const paymentCredential = await ctx.prisma.credential.findFirst({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
type: {
|
||||
contains: "_payment",
|
||||
},
|
||||
},
|
||||
select: {
|
||||
type: true,
|
||||
key: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (paymentCredential?.type === "stripe_payment") {
|
||||
const { default_currency } = stripeDataSchema.parse(paymentCredential.key);
|
||||
data.currency = default_currency;
|
||||
}
|
||||
}
|
||||
|
||||
const connectedLink = await ctx.prisma.hashedLink.findFirst({
|
||||
where: {
|
||||
eventTypeId: input.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (hashedLink) {
|
||||
// check if hashed connection existed. If it did, do nothing. If it didn't, add a new connection
|
||||
if (!connectedLink) {
|
||||
// create a hashed link
|
||||
await ctx.prisma.hashedLink.upsert({
|
||||
where: {
|
||||
eventTypeId: input.id,
|
||||
},
|
||||
update: {
|
||||
link: hashedLink,
|
||||
},
|
||||
create: {
|
||||
link: hashedLink,
|
||||
eventType: {
|
||||
connect: { id: input.id },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// check if hashed connection exists. If it does, disconnect
|
||||
if (connectedLink) {
|
||||
await ctx.prisma.hashedLink.delete({
|
||||
where: {
|
||||
eventTypeId: input.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const eventType = await ctx.prisma.eventType.update({
|
||||
where: { id },
|
||||
data,
|
||||
});
|
||||
|
||||
return { eventType };
|
||||
},
|
||||
})
|
||||
.mutation("delete", {
|
||||
input: z.object({
|
||||
id: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const { id } = input;
|
||||
|
||||
await ctx.prisma.eventTypeCustomInput.deleteMany({
|
||||
where: {
|
||||
eventTypeId: id,
|
||||
},
|
||||
});
|
||||
|
||||
await ctx.prisma.eventType.delete({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
id,
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,285 @@
|
||||
import { SchedulingType } from "@prisma/client";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { CurrentSeats } from "@calcom/core/getUserAvailability";
|
||||
import { getUserAvailability } from "@calcom/core/getUserAvailability";
|
||||
import dayjs, { Dayjs } from "@calcom/dayjs";
|
||||
import isOutOfBounds from "@calcom/lib/isOutOfBounds";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import getSlots from "@calcom/lib/slots";
|
||||
import prisma, { availabilityUserSelect } from "@calcom/prisma";
|
||||
import { TimeRange } from "@calcom/types/schedule";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createRouter } from "../../createRouter";
|
||||
|
||||
const getScheduleSchema = z
|
||||
.object({
|
||||
// startTime ISOString
|
||||
startTime: z.string(),
|
||||
// endTime ISOString
|
||||
endTime: z.string(),
|
||||
// Event type ID
|
||||
eventTypeId: z.number().optional(),
|
||||
// invitee timezone
|
||||
timeZone: z.string().optional(),
|
||||
// or list of users (for dynamic events)
|
||||
usernameList: z.array(z.string()).optional(),
|
||||
debug: z.boolean().optional(),
|
||||
})
|
||||
.refine(
|
||||
(data) => !!data.eventTypeId || !!data.usernameList,
|
||||
"Either usernameList or eventTypeId should be filled in."
|
||||
);
|
||||
|
||||
export type Slot = {
|
||||
time: string;
|
||||
attendees?: number;
|
||||
bookingUid?: string;
|
||||
users?: string[];
|
||||
};
|
||||
|
||||
const checkForAvailability = ({
|
||||
time,
|
||||
busy,
|
||||
eventLength,
|
||||
beforeBufferTime,
|
||||
currentSeats,
|
||||
}: {
|
||||
time: Dayjs;
|
||||
busy: (TimeRange | { start: string; end: string })[];
|
||||
eventLength: number;
|
||||
beforeBufferTime: number;
|
||||
currentSeats?: CurrentSeats;
|
||||
}) => {
|
||||
if (currentSeats?.some((booking) => booking.startTime.toISOString() === time.toISOString())) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const slotEndTime = time.add(eventLength, "minutes").utc();
|
||||
const slotStartTime = time.subtract(beforeBufferTime, "minutes").utc();
|
||||
|
||||
return busy.every((busyTime) => {
|
||||
const startTime = dayjs.utc(busyTime.start);
|
||||
const endTime = dayjs.utc(busyTime.end);
|
||||
|
||||
if (endTime.isBefore(slotStartTime) || startTime.isAfter(slotEndTime)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (slotStartTime.isBetween(startTime, endTime, null, "[)")) {
|
||||
return false;
|
||||
} else if (slotEndTime.isBetween(startTime, endTime, null, "(]")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if start times are the same
|
||||
if (time.utc().isBetween(startTime, endTime, null, "[)")) {
|
||||
return false;
|
||||
}
|
||||
// Check if slot end time is between start and end time
|
||||
else if (slotEndTime.isBetween(startTime, endTime)) {
|
||||
return false;
|
||||
}
|
||||
// Check if startTime is between slot
|
||||
else if (startTime.isBetween(time, slotEndTime)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
};
|
||||
|
||||
export const slotsRouter = createRouter().query("getSchedule", {
|
||||
input: getScheduleSchema,
|
||||
async resolve({ input, ctx }) {
|
||||
return await getSchedule(input, ctx);
|
||||
},
|
||||
});
|
||||
|
||||
export async function getSchedule(
|
||||
input: {
|
||||
timeZone?: string | undefined;
|
||||
eventTypeId?: number | undefined;
|
||||
usernameList?: string[] | undefined;
|
||||
debug?: boolean | undefined;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
},
|
||||
ctx: { prisma: typeof prisma }
|
||||
) {
|
||||
if (input.debug === true) {
|
||||
logger.setSettings({ minLevel: "debug" });
|
||||
}
|
||||
if (process.env.INTEGRATION_TEST_MODE === "true") {
|
||||
logger.setSettings({ minLevel: "silly" });
|
||||
}
|
||||
const startPrismaEventTypeGet = performance.now();
|
||||
const eventType = await ctx.prisma.eventType.findUnique({
|
||||
where: {
|
||||
id: input.eventTypeId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
minimumBookingNotice: true,
|
||||
length: true,
|
||||
seatsPerTimeSlot: true,
|
||||
timeZone: true,
|
||||
slotInterval: true,
|
||||
beforeEventBuffer: true,
|
||||
afterEventBuffer: true,
|
||||
schedulingType: true,
|
||||
periodType: true,
|
||||
periodStartDate: true,
|
||||
periodEndDate: true,
|
||||
periodCountCalendarDays: true,
|
||||
periodDays: true,
|
||||
schedule: {
|
||||
select: {
|
||||
availability: true,
|
||||
timeZone: true,
|
||||
},
|
||||
},
|
||||
availability: {
|
||||
select: {
|
||||
startTime: true,
|
||||
endTime: true,
|
||||
days: true,
|
||||
},
|
||||
},
|
||||
users: {
|
||||
select: {
|
||||
username: true,
|
||||
...availabilityUserSelect,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const endPrismaEventTypeGet = performance.now();
|
||||
logger.debug(
|
||||
`Prisma eventType get took ${endPrismaEventTypeGet - startPrismaEventTypeGet}ms for event:${
|
||||
input.eventTypeId
|
||||
}`
|
||||
);
|
||||
if (!eventType) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
|
||||
const startTime =
|
||||
input.timeZone === "Etc/GMT"
|
||||
? dayjs.utc(input.startTime)
|
||||
: dayjs(input.startTime).utc().tz(input.timeZone);
|
||||
const endTime =
|
||||
input.timeZone === "Etc/GMT" ? dayjs.utc(input.endTime) : dayjs(input.endTime).utc().tz(input.timeZone);
|
||||
|
||||
if (!startTime.isValid() || !endTime.isValid()) {
|
||||
throw new TRPCError({ message: "Invalid time range given.", code: "BAD_REQUEST" });
|
||||
}
|
||||
let currentSeats: CurrentSeats | undefined = undefined;
|
||||
|
||||
const userSchedules = await Promise.all(
|
||||
eventType.users.map(async (currentUser) => {
|
||||
const {
|
||||
busy,
|
||||
workingHours,
|
||||
currentSeats: _currentSeats,
|
||||
} = await getUserAvailability(
|
||||
{
|
||||
userId: currentUser.id,
|
||||
dateFrom: startTime.format(),
|
||||
dateTo: endTime.format(),
|
||||
eventTypeId: input.eventTypeId,
|
||||
afterEventBuffer: eventType.afterEventBuffer,
|
||||
},
|
||||
{ user: currentUser, eventType, currentSeats }
|
||||
);
|
||||
if (!currentSeats && _currentSeats) currentSeats = _currentSeats;
|
||||
|
||||
return {
|
||||
workingHours,
|
||||
busy,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
const workingHours = userSchedules.flatMap((s) => s.workingHours);
|
||||
|
||||
const slots: Record<string, Slot[]> = {};
|
||||
const availabilityCheckProps = {
|
||||
eventLength: eventType.length,
|
||||
beforeBufferTime: eventType.beforeEventBuffer,
|
||||
currentSeats,
|
||||
};
|
||||
const isWithinBounds = (_time: Parameters<typeof isOutOfBounds>[0]) =>
|
||||
!isOutOfBounds(_time, {
|
||||
periodType: eventType.periodType,
|
||||
periodStartDate: eventType.periodStartDate,
|
||||
periodEndDate: eventType.periodEndDate,
|
||||
periodCountCalendarDays: eventType.periodCountCalendarDays,
|
||||
periodDays: eventType.periodDays,
|
||||
});
|
||||
|
||||
let time = startTime;
|
||||
let getSlotsTime = 0;
|
||||
let checkForAvailabilityTime = 0;
|
||||
let getSlotsCount = 0;
|
||||
let checkForAvailabilityCount = 0;
|
||||
do {
|
||||
const startGetSlots = performance.now();
|
||||
// get slots retrieves the available times for a given day
|
||||
const times = getSlots({
|
||||
inviteeDate: time,
|
||||
eventLength: eventType.length,
|
||||
workingHours,
|
||||
minimumBookingNotice: eventType.minimumBookingNotice,
|
||||
frequency: eventType.slotInterval || eventType.length,
|
||||
});
|
||||
const endGetSlots = performance.now();
|
||||
getSlotsTime += endGetSlots - startGetSlots;
|
||||
getSlotsCount++;
|
||||
// if ROUND_ROBIN - slots stay available on some() - if normal / COLLECTIVE - slots only stay available on every()
|
||||
const filterStrategy =
|
||||
!eventType.schedulingType || eventType.schedulingType === SchedulingType.COLLECTIVE
|
||||
? ("every" as const)
|
||||
: ("some" as const);
|
||||
|
||||
const filteredTimes = times.filter(isWithinBounds).filter((time) =>
|
||||
userSchedules[filterStrategy]((schedule) => {
|
||||
const startCheckForAvailability = performance.now();
|
||||
const result = checkForAvailability({ time, ...schedule, ...availabilityCheckProps });
|
||||
const endCheckForAvailability = performance.now();
|
||||
checkForAvailabilityCount++;
|
||||
checkForAvailabilityTime += endCheckForAvailability - startCheckForAvailability;
|
||||
return result;
|
||||
})
|
||||
);
|
||||
|
||||
slots[time.format("YYYY-MM-DD")] = filteredTimes.map((time) => ({
|
||||
time: time.toISOString(),
|
||||
users: eventType.users.map((user) => user.username || ""),
|
||||
// Conditionally add the attendees and booking id to slots object if there is already a booking during that time
|
||||
...(currentSeats?.some((booking) => booking.startTime.toISOString() === time.toISOString()) && {
|
||||
attendees:
|
||||
currentSeats[
|
||||
currentSeats.findIndex((booking) => booking.startTime.toISOString() === time.toISOString())
|
||||
]._count.attendees,
|
||||
bookingUid:
|
||||
currentSeats[
|
||||
currentSeats.findIndex((booking) => booking.startTime.toISOString() === time.toISOString())
|
||||
].uid,
|
||||
}),
|
||||
}));
|
||||
time = time.add(1, "day");
|
||||
} while (time.isBefore(endTime));
|
||||
|
||||
logger.debug(`getSlots took ${getSlotsTime}ms and executed ${getSlotsCount} times`);
|
||||
|
||||
logger.debug(
|
||||
`checkForAvailability took ${checkForAvailabilityTime}ms and executed ${checkForAvailabilityCount} times`
|
||||
);
|
||||
logger.silly(`Available slots: ${JSON.stringify(slots)}`);
|
||||
return {
|
||||
slots,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,515 @@
|
||||
import { MembershipRole, Prisma, UserPlan } from "@prisma/client";
|
||||
import { randomBytes } from "crypto";
|
||||
import { z } from "zod";
|
||||
|
||||
import { getUserAvailability } from "@calcom/core/getUserAvailability";
|
||||
import { sendTeamInviteEmail } from "@calcom/emails";
|
||||
import { HOSTED_CAL_FEATURES, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { getTeamWithMembers, isTeamAdmin, isTeamOwner } from "@calcom/lib/server/queries/teams";
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
import { availabilityUserSelect } from "@calcom/prisma";
|
||||
import {
|
||||
addSeat,
|
||||
downgradeTeamMembers,
|
||||
ensureSubscriptionQuantityCorrectness,
|
||||
getTeamSeatStats,
|
||||
removeSeat,
|
||||
upgradeTeam,
|
||||
} from "@calcom/stripe/team-billing";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
|
||||
export const viewerTeamsRouter = createProtectedRouter()
|
||||
// Retrieves team by id
|
||||
.query("get", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const team = await getTeamWithMembers(input.teamId);
|
||||
if (!team?.members.find((m) => m.id === ctx.user.id)) {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED", message: "You are not a member of this team." });
|
||||
}
|
||||
const membership = team?.members.find((membership) => membership.id === ctx.user.id);
|
||||
return {
|
||||
...team,
|
||||
membership: {
|
||||
role: membership?.role as MembershipRole,
|
||||
isMissingSeat: membership?.plan === UserPlan.FREE,
|
||||
},
|
||||
requiresUpgrade: HOSTED_CAL_FEATURES ? !!team.members.find((m) => m.plan !== UserPlan.PRO) : false,
|
||||
};
|
||||
},
|
||||
})
|
||||
// Returns teams I a member of
|
||||
.query("list", {
|
||||
async resolve({ ctx }) {
|
||||
const memberships = await ctx.prisma.membership.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
orderBy: { role: "desc" },
|
||||
});
|
||||
const teams = await ctx.prisma.team.findMany({
|
||||
where: {
|
||||
id: {
|
||||
in: memberships.map((membership) => membership.teamId),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return memberships.map((membership) => ({
|
||||
role: membership.role,
|
||||
accepted: membership.accepted,
|
||||
...teams.find((team) => team.id === membership.teamId),
|
||||
}));
|
||||
},
|
||||
})
|
||||
.mutation("create", {
|
||||
input: z.object({
|
||||
name: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
if (ctx.user.plan === "FREE") {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED", message: "You are not a pro user." });
|
||||
}
|
||||
|
||||
const slug = slugify(input.name);
|
||||
|
||||
const nameCollisions = await ctx.prisma.team.count({
|
||||
where: {
|
||||
OR: [{ name: input.name }, { slug: slug }],
|
||||
},
|
||||
});
|
||||
|
||||
if (nameCollisions > 0)
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Team name already taken." });
|
||||
|
||||
const createTeam = await ctx.prisma.team.create({
|
||||
data: {
|
||||
name: input.name,
|
||||
slug: slug,
|
||||
},
|
||||
});
|
||||
|
||||
await ctx.prisma.membership.create({
|
||||
data: {
|
||||
teamId: createTeam.id,
|
||||
userId: ctx.user.id,
|
||||
role: "OWNER",
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
// Allows team owner to update team metadata
|
||||
.mutation("update", {
|
||||
input: z.object({
|
||||
id: z.number(),
|
||||
bio: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
logo: z.string().optional(),
|
||||
slug: z.string().optional(),
|
||||
hideBranding: z.boolean().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
if (!(await isTeamAdmin(ctx.user?.id, input.id))) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
if (input.slug) {
|
||||
const userConflict = await ctx.prisma.team.findMany({
|
||||
where: {
|
||||
slug: input.slug,
|
||||
},
|
||||
});
|
||||
if (userConflict.some((t) => t.id !== input.id)) return;
|
||||
}
|
||||
await ctx.prisma.team.update({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
data: {
|
||||
name: input.name,
|
||||
slug: input.slug,
|
||||
logo: input.logo,
|
||||
bio: input.bio,
|
||||
hideBranding: input.hideBranding,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("delete", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
if (!(await isTeamOwner(ctx.user?.id, input.teamId))) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
if (process.env.STRIPE_PRIVATE_KEY) {
|
||||
await downgradeTeamMembers(input.teamId);
|
||||
}
|
||||
|
||||
// delete all memberships
|
||||
await ctx.prisma.membership.deleteMany({
|
||||
where: {
|
||||
teamId: input.teamId,
|
||||
},
|
||||
});
|
||||
|
||||
await ctx.prisma.team.delete({
|
||||
where: {
|
||||
id: input.teamId,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
// Allows owner to remove member from team
|
||||
.mutation("removeMember", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
if (!(await isTeamAdmin(ctx.user?.id, input.teamId))) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
// Only a team owner can remove another team owner.
|
||||
if (
|
||||
(await isTeamOwner(input.memberId, input.teamId)) &&
|
||||
!(await isTeamOwner(ctx.user?.id, input.teamId))
|
||||
)
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
if (ctx.user?.id === input.memberId)
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "You can not remove yourself from a team you own.",
|
||||
});
|
||||
await ctx.prisma.membership.delete({
|
||||
where: {
|
||||
userId_teamId: { userId: input.memberId, teamId: input.teamId },
|
||||
},
|
||||
});
|
||||
|
||||
if (HOSTED_CAL_FEATURES) await removeSeat(ctx.user.id, input.teamId, input.memberId);
|
||||
},
|
||||
})
|
||||
.mutation("inviteMember", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
usernameOrEmail: z.string(),
|
||||
role: z.nativeEnum(MembershipRole),
|
||||
language: z.string(),
|
||||
sendEmailInvitation: z.boolean(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
if (!(await isTeamAdmin(ctx.user?.id, input.teamId))) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
if (input.role === MembershipRole.OWNER && !(await isTeamOwner(ctx.user?.id, input.teamId)))
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
const translation = await getTranslation(input.language ?? "en", "common");
|
||||
|
||||
const team = await ctx.prisma.team.findFirst({
|
||||
where: {
|
||||
id: input.teamId,
|
||||
},
|
||||
});
|
||||
|
||||
if (!team) throw new TRPCError({ code: "NOT_FOUND", message: "Team not found" });
|
||||
|
||||
const invitee = await ctx.prisma.user.findFirst({
|
||||
where: {
|
||||
OR: [{ username: input.usernameOrEmail }, { email: input.usernameOrEmail }],
|
||||
},
|
||||
});
|
||||
|
||||
let inviteeUserId: number | undefined = invitee?.id;
|
||||
|
||||
if (!invitee) {
|
||||
// liberal email match
|
||||
const isEmail = (str: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str);
|
||||
|
||||
if (!isEmail(input.usernameOrEmail))
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: `Invite failed because there is no corresponding user for ${input.usernameOrEmail}`,
|
||||
});
|
||||
|
||||
// valid email given, create User and add to team
|
||||
const user = await ctx.prisma.user.create({
|
||||
data: {
|
||||
email: input.usernameOrEmail,
|
||||
invitedTo: input.teamId,
|
||||
teams: {
|
||||
create: {
|
||||
teamId: input.teamId,
|
||||
role: input.role as MembershipRole,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
inviteeUserId = user.id;
|
||||
|
||||
const token: string = randomBytes(32).toString("hex");
|
||||
|
||||
await ctx.prisma.verificationToken.create({
|
||||
data: {
|
||||
identifier: input.usernameOrEmail,
|
||||
token,
|
||||
expires: new Date(new Date().setHours(168)), // +1 week
|
||||
},
|
||||
});
|
||||
|
||||
if (ctx?.user?.name && team?.name) {
|
||||
await sendTeamInviteEmail({
|
||||
language: translation,
|
||||
from: ctx.user.name,
|
||||
to: input.usernameOrEmail,
|
||||
teamName: team.name,
|
||||
joinLink: `${WEBAPP_URL}/auth/signup?token=${token}&callbackUrl=${
|
||||
WEBAPP_URL + "/settings/teams"
|
||||
}`,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// create provisional membership
|
||||
try {
|
||||
await ctx.prisma.membership.create({
|
||||
data: {
|
||||
teamId: input.teamId,
|
||||
userId: invitee.id,
|
||||
role: input.role as MembershipRole,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
if (e.code === "P2002") {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "This user is a member of this team / has a pending invitation.",
|
||||
});
|
||||
}
|
||||
} else throw e;
|
||||
}
|
||||
|
||||
// inform user of membership by email
|
||||
if (input.sendEmailInvitation && ctx?.user?.name && team?.name) {
|
||||
await sendTeamInviteEmail({
|
||||
language: translation,
|
||||
from: ctx.user.name,
|
||||
to: input.usernameOrEmail,
|
||||
teamName: team.name,
|
||||
joinLink: WEBAPP_URL + "/settings/teams",
|
||||
});
|
||||
}
|
||||
}
|
||||
try {
|
||||
if (HOSTED_CAL_FEATURES) await addSeat(ctx.user.id, team.id, inviteeUserId);
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
}
|
||||
},
|
||||
})
|
||||
.mutation("acceptOrLeave", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
accept: z.boolean(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
if (input.accept) {
|
||||
await ctx.prisma.membership.update({
|
||||
where: {
|
||||
userId_teamId: { userId: ctx.user.id, teamId: input.teamId },
|
||||
},
|
||||
data: {
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
try {
|
||||
//get team owner so we can alter their subscription seat count
|
||||
const teamOwner = await ctx.prisma.membership.findFirst({
|
||||
where: { teamId: input.teamId, role: MembershipRole.OWNER },
|
||||
});
|
||||
|
||||
// TODO: disable if not hosted by Cal
|
||||
if (teamOwner) await removeSeat(teamOwner.userId, input.teamId, ctx.user.id);
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
}
|
||||
await ctx.prisma.membership.delete({
|
||||
where: {
|
||||
userId_teamId: { userId: ctx.user.id, teamId: input.teamId },
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
})
|
||||
.mutation("changeMemberRole", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
role: z.nativeEnum(MembershipRole),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
if (!(await isTeamAdmin(ctx.user?.id, input.teamId))) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
// Only owners can award owner role.
|
||||
if (input.role === MembershipRole.OWNER && !(await isTeamOwner(ctx.user?.id, input.teamId)))
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
const memberships = await ctx.prisma.membership.findMany({
|
||||
where: {
|
||||
teamId: input.teamId,
|
||||
},
|
||||
});
|
||||
|
||||
const targetMembership = memberships.find((m) => m.userId === input.memberId);
|
||||
const myMembership = memberships.find((m) => m.userId === ctx.user.id);
|
||||
const teamHasMoreThanOneOwner = memberships.some((m) => m.role === MembershipRole.OWNER);
|
||||
|
||||
if (myMembership?.role === MembershipRole.ADMIN && targetMembership?.role === MembershipRole.OWNER) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "You can not change the role of an owner if you are an admin.",
|
||||
});
|
||||
}
|
||||
|
||||
if (!teamHasMoreThanOneOwner) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "You can not change the role of the only owner of a team.",
|
||||
});
|
||||
}
|
||||
|
||||
if (myMembership?.role === MembershipRole.ADMIN && input.memberId === ctx.user.id) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "You can not change yourself to a higher role.",
|
||||
});
|
||||
}
|
||||
|
||||
await ctx.prisma.membership.update({
|
||||
where: {
|
||||
userId_teamId: { userId: input.memberId, teamId: input.teamId },
|
||||
},
|
||||
data: {
|
||||
role: input.role,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.query("getMemberAvailability", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
timezone: z.string(),
|
||||
dateFrom: z.string(),
|
||||
dateTo: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const team = await isTeamAdmin(ctx.user?.id, input.teamId);
|
||||
if (!team) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
// verify member is in team
|
||||
const members = await ctx.prisma.membership.findMany({
|
||||
where: { teamId: input.teamId },
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
username: true,
|
||||
...availabilityUserSelect,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const member = members?.find((m) => m.userId === input.memberId);
|
||||
if (!member) throw new TRPCError({ code: "NOT_FOUND", message: "Member not found" });
|
||||
if (!member.user.username)
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Member doesn't have a username" });
|
||||
|
||||
// get availability for this member
|
||||
return await getUserAvailability(
|
||||
{
|
||||
username: member.user.username,
|
||||
timezone: input.timezone,
|
||||
dateFrom: input.dateFrom,
|
||||
dateTo: input.dateTo,
|
||||
},
|
||||
{ user: member.user }
|
||||
);
|
||||
},
|
||||
})
|
||||
.mutation("upgradeTeam", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
if (!HOSTED_CAL_FEATURES)
|
||||
throw new TRPCError({ code: "FORBIDDEN", message: "Team billing is not enabled" });
|
||||
return await upgradeTeam(ctx.user.id, input.teamId);
|
||||
},
|
||||
})
|
||||
.query("getTeamSeats", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
}),
|
||||
async resolve({ input }) {
|
||||
return await getTeamSeatStats(input.teamId);
|
||||
},
|
||||
})
|
||||
.mutation("ensureSubscriptionQuantityCorrectness", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
return await ensureSubscriptionQuantityCorrectness(ctx.user.id, input.teamId);
|
||||
},
|
||||
})
|
||||
.query("getMembershipbyUser", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
if (ctx.user.id !== input.memberId) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "You cannot view memberships that are not your own.",
|
||||
});
|
||||
}
|
||||
|
||||
return await ctx.prisma.membership.findUnique({
|
||||
where: {
|
||||
userId_teamId: {
|
||||
userId: input.memberId,
|
||||
teamId: input.teamId,
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("updateMembership", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
disableImpersonation: z.boolean(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
if (ctx.user.id !== input.memberId) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "You cannot edit memberships that are not your own.",
|
||||
});
|
||||
}
|
||||
|
||||
return await ctx.prisma.membership.update({
|
||||
where: {
|
||||
userId_teamId: {
|
||||
userId: input.memberId,
|
||||
teamId: input.teamId,
|
||||
},
|
||||
},
|
||||
data: {
|
||||
disableImpersonation: input.disableImpersonation,
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,248 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { v4 } from "uuid";
|
||||
import { z } from "zod";
|
||||
|
||||
import { getErrorFromUnknown } from "@calcom/lib/errors";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { WEBHOOK_TRIGGER_EVENTS } from "@calcom/lib/webhooks/constants";
|
||||
import sendPayload from "@calcom/lib/webhooks/sendPayload";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
|
||||
// Common data for all endpoints under webhook
|
||||
const webhookIdAndEventTypeIdSchema = z.object({
|
||||
// Webhook ID
|
||||
id: z.string().optional(),
|
||||
// Event type ID
|
||||
eventTypeId: z.number().optional(),
|
||||
});
|
||||
|
||||
export const webhookRouter = createProtectedRouter()
|
||||
.middleware(async ({ ctx, rawInput, next }) => {
|
||||
// Endpoints that just read the logged in user's data - like 'list' don't necessary have any input
|
||||
if (!rawInput) {
|
||||
return next();
|
||||
}
|
||||
const webhookIdAndEventTypeId = webhookIdAndEventTypeIdSchema.safeParse(rawInput);
|
||||
if (!webhookIdAndEventTypeId.success) {
|
||||
throw new TRPCError({ code: "PARSE_ERROR" });
|
||||
}
|
||||
const { eventTypeId, id } = webhookIdAndEventTypeId.data;
|
||||
|
||||
// A webhook is either linked to Event Type or to a user.
|
||||
if (eventTypeId) {
|
||||
const team = await ctx.prisma.team.findFirst({
|
||||
where: {
|
||||
eventTypes: {
|
||||
some: {
|
||||
id: eventTypeId,
|
||||
},
|
||||
},
|
||||
},
|
||||
include: {
|
||||
members: true,
|
||||
},
|
||||
});
|
||||
|
||||
// Team should be available and the user should be a member of the team
|
||||
if (!team?.members.some((membership) => membership.userId === ctx.user.id)) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
}
|
||||
} else if (id) {
|
||||
const authorizedHook = await ctx.prisma.webhook.findFirst({
|
||||
where: {
|
||||
id: id,
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
});
|
||||
if (!authorizedHook) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
}
|
||||
}
|
||||
return next();
|
||||
})
|
||||
.query("list", {
|
||||
input: z
|
||||
.object({
|
||||
eventTypeId: z.number().optional(),
|
||||
appId: z.string().optional(),
|
||||
})
|
||||
.optional(),
|
||||
async resolve({ ctx, input }) {
|
||||
const where: Prisma.WebhookWhereInput = {
|
||||
/* Don't mixup zapier webhooks with normal ones */
|
||||
AND: [{ appId: !input?.appId ? null : input.appId }],
|
||||
};
|
||||
if (Array.isArray(where.AND)) {
|
||||
if (input?.eventTypeId) {
|
||||
where.AND?.push({ eventTypeId: input.eventTypeId });
|
||||
} else {
|
||||
where.AND?.push({ userId: ctx.user.id });
|
||||
}
|
||||
}
|
||||
|
||||
return await ctx.prisma.webhook.findMany({
|
||||
where,
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("create", {
|
||||
input: z.object({
|
||||
subscriberUrl: z.string().url(),
|
||||
eventTriggers: z.enum(WEBHOOK_TRIGGER_EVENTS).array(),
|
||||
active: z.boolean(),
|
||||
payloadTemplate: z.string().nullable(),
|
||||
eventTypeId: z.number().optional(),
|
||||
appId: z.string().optional().nullable(),
|
||||
secret: z.string().optional().nullable(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
if (input.eventTypeId) {
|
||||
return await ctx.prisma.webhook.create({
|
||||
data: {
|
||||
id: v4(),
|
||||
...input,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return await ctx.prisma.webhook.create({
|
||||
data: {
|
||||
id: v4(),
|
||||
userId: ctx.user.id,
|
||||
...input,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("edit", {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
subscriberUrl: z.string().url().optional(),
|
||||
eventTriggers: z.enum(WEBHOOK_TRIGGER_EVENTS).array().optional(),
|
||||
active: z.boolean().optional(),
|
||||
payloadTemplate: z.string().nullable(),
|
||||
eventTypeId: z.number().optional(),
|
||||
appId: z.string().optional().nullable(),
|
||||
secret: z.string().optional().nullable(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const { id, ...data } = input;
|
||||
const webhook = input.eventTypeId
|
||||
? await ctx.prisma.webhook.findFirst({
|
||||
where: {
|
||||
eventTypeId: input.eventTypeId,
|
||||
id,
|
||||
},
|
||||
})
|
||||
: await ctx.prisma.webhook.findFirst({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
id,
|
||||
},
|
||||
});
|
||||
if (!webhook) {
|
||||
// user does not own this webhook
|
||||
// team event doesn't own this webhook
|
||||
return null;
|
||||
}
|
||||
return await ctx.prisma.webhook.update({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
data,
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("delete", {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
eventTypeId: z.number().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const { id } = input;
|
||||
input.eventTypeId
|
||||
? await ctx.prisma.eventType.update({
|
||||
where: {
|
||||
id: input.eventTypeId,
|
||||
},
|
||||
data: {
|
||||
webhooks: {
|
||||
delete: {
|
||||
id,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
: await ctx.prisma.user.update({
|
||||
where: {
|
||||
id: ctx.user.id,
|
||||
},
|
||||
data: {
|
||||
webhooks: {
|
||||
delete: {
|
||||
id,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
return {
|
||||
id,
|
||||
};
|
||||
},
|
||||
})
|
||||
.mutation("testTrigger", {
|
||||
input: z.object({
|
||||
url: z.string().url(),
|
||||
type: z.string(),
|
||||
payloadTemplate: z.string().optional().nullable(),
|
||||
}),
|
||||
async resolve({ input }) {
|
||||
const { url, type, payloadTemplate = null } = input;
|
||||
const translation = await getTranslation("en", "common");
|
||||
const language = {
|
||||
locale: "en",
|
||||
translate: translation,
|
||||
};
|
||||
|
||||
const data = {
|
||||
type: "Test",
|
||||
title: "Test trigger event",
|
||||
description: "",
|
||||
startTime: new Date().toISOString(),
|
||||
endTime: new Date().toISOString(),
|
||||
attendees: [
|
||||
{
|
||||
email: "[email protected]",
|
||||
name: "John Doe",
|
||||
timeZone: "Europe/London",
|
||||
language,
|
||||
},
|
||||
],
|
||||
organizer: {
|
||||
name: "Cal",
|
||||
email: "[email protected]",
|
||||
timeZone: "Europe/London",
|
||||
language,
|
||||
},
|
||||
};
|
||||
|
||||
try {
|
||||
const webhook = { subscriberUrl: url, payloadTemplate, appId: null, secret: null };
|
||||
return await sendPayload(null, type, new Date().toISOString(), webhook, data);
|
||||
} catch (_err) {
|
||||
const error = getErrorFromUnknown(_err);
|
||||
return {
|
||||
ok: false,
|
||||
status: 500,
|
||||
message: error.message,
|
||||
};
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,679 @@
|
||||
import {
|
||||
Prisma,
|
||||
PrismaPromise,
|
||||
WorkflowTemplates,
|
||||
WorkflowActions,
|
||||
WorkflowTriggerEvents,
|
||||
BookingStatus,
|
||||
WorkflowMethods,
|
||||
} from "@prisma/client";
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
WORKFLOW_TEMPLATES,
|
||||
WORKFLOW_TRIGGER_EVENTS,
|
||||
WORKFLOW_ACTIONS,
|
||||
TIME_UNIT,
|
||||
} from "@ee/lib/workflows/constants";
|
||||
import {
|
||||
deleteScheduledEmailReminder,
|
||||
scheduleEmailReminder,
|
||||
} from "@ee/lib/workflows/reminders/emailReminderManager";
|
||||
import {
|
||||
deleteScheduledSMSReminder,
|
||||
scheduleSMSReminder,
|
||||
} from "@ee/lib/workflows/reminders/smsReminderManager";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
|
||||
export const workflowsRouter = createProtectedRouter()
|
||||
.query("list", {
|
||||
async resolve({ ctx }) {
|
||||
const workflows = await ctx.prisma.workflow.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
include: {
|
||||
activeOn: {
|
||||
include: {
|
||||
eventType: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: {
|
||||
id: "asc",
|
||||
},
|
||||
});
|
||||
return { workflows };
|
||||
},
|
||||
})
|
||||
.query("get", {
|
||||
input: z.object({
|
||||
id: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const workflow = await ctx.prisma.workflow.findFirst({
|
||||
where: {
|
||||
AND: [
|
||||
{
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
{
|
||||
id: input.id,
|
||||
},
|
||||
],
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
time: true,
|
||||
timeUnit: true,
|
||||
activeOn: {
|
||||
select: {
|
||||
eventType: true,
|
||||
},
|
||||
},
|
||||
trigger: true,
|
||||
steps: {
|
||||
orderBy: {
|
||||
stepNumber: "asc",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!workflow) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
}
|
||||
return workflow;
|
||||
},
|
||||
})
|
||||
.mutation("create", {
|
||||
input: z.object({
|
||||
name: z.string(),
|
||||
trigger: z.enum(WORKFLOW_TRIGGER_EVENTS),
|
||||
action: z.enum(WORKFLOW_ACTIONS),
|
||||
timeUnit: z.enum(TIME_UNIT).optional(),
|
||||
time: z.number().optional(),
|
||||
sendTo: z.string().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const { name, trigger, action, timeUnit, time, sendTo } = input;
|
||||
const userId = ctx.user.id;
|
||||
|
||||
try {
|
||||
const workflow = await ctx.prisma.workflow.create({
|
||||
data: {
|
||||
name,
|
||||
trigger,
|
||||
userId,
|
||||
timeUnit: time ? timeUnit : undefined,
|
||||
time,
|
||||
},
|
||||
});
|
||||
|
||||
await ctx.prisma.workflowStep.create({
|
||||
data: {
|
||||
stepNumber: 1,
|
||||
action,
|
||||
workflowId: workflow.id,
|
||||
sendTo,
|
||||
},
|
||||
});
|
||||
return { workflow };
|
||||
} catch (e) {
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
})
|
||||
.mutation("delete", {
|
||||
input: z.object({
|
||||
id: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const { id } = input;
|
||||
|
||||
//delete all scheduled reminders of this workflow
|
||||
const scheduledReminders = await ctx.prisma.workflowReminder.findMany({
|
||||
where: {
|
||||
workflowStep: {
|
||||
workflowId: id,
|
||||
},
|
||||
scheduled: true,
|
||||
NOT: {
|
||||
referenceId: null,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
scheduledReminders.forEach((reminder) => {
|
||||
if (reminder.referenceId) {
|
||||
if (reminder.method === WorkflowMethods.EMAIL) {
|
||||
deleteScheduledEmailReminder(reminder.referenceId);
|
||||
} else if (reminder.method === WorkflowMethods.SMS) {
|
||||
deleteScheduledSMSReminder(reminder.referenceId);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await ctx.prisma.workflow.deleteMany({
|
||||
where: {
|
||||
AND: [
|
||||
{
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
{
|
||||
id,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
id,
|
||||
};
|
||||
},
|
||||
})
|
||||
.mutation("update", {
|
||||
input: z.object({
|
||||
id: z.number(),
|
||||
name: z.string(),
|
||||
activeOn: z.number().array(),
|
||||
steps: z
|
||||
.object({
|
||||
id: z.number(),
|
||||
stepNumber: z.number(),
|
||||
action: z.enum(WORKFLOW_ACTIONS),
|
||||
workflowId: z.number(),
|
||||
sendTo: z.string().optional().nullable(),
|
||||
reminderBody: z.string().optional().nullable(),
|
||||
emailSubject: z.string().optional().nullable(),
|
||||
template: z.enum(WORKFLOW_TEMPLATES),
|
||||
})
|
||||
.array(),
|
||||
trigger: z.enum(WORKFLOW_TRIGGER_EVENTS),
|
||||
time: z.number().nullable(),
|
||||
timeUnit: z.enum(TIME_UNIT).nullable(),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
const { user } = ctx;
|
||||
const { id, name, activeOn, steps, trigger, time, timeUnit } = input;
|
||||
|
||||
const userWorkflow = await ctx.prisma.workflow.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
select: {
|
||||
userId: true,
|
||||
steps: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!userWorkflow || userWorkflow.userId !== user.id) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
//remove all scheduled Email and SMS reminders for eventTypes that are not active any more
|
||||
const oldActiveOnEventTypes = await ctx.prisma.workflowsOnEventTypes.findMany({
|
||||
where: {
|
||||
workflowId: id,
|
||||
},
|
||||
select: {
|
||||
eventTypeId: true,
|
||||
},
|
||||
});
|
||||
|
||||
const removedEventTypes = oldActiveOnEventTypes
|
||||
.map((eventType) => {
|
||||
return eventType.eventTypeId;
|
||||
})
|
||||
.filter((eventType) => {
|
||||
if (!activeOn.includes(eventType)) {
|
||||
return eventType;
|
||||
}
|
||||
});
|
||||
|
||||
const remindersToDeletePromise: PrismaPromise<
|
||||
{
|
||||
id: number;
|
||||
referenceId: string | null;
|
||||
method: string;
|
||||
scheduled: boolean;
|
||||
}[]
|
||||
>[] = [];
|
||||
removedEventTypes.forEach((eventTypeId) => {
|
||||
const reminderToDelete = ctx.prisma.workflowReminder.findMany({
|
||||
where: {
|
||||
booking: {
|
||||
eventTypeId: eventTypeId,
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
workflowStepId: {
|
||||
in: userWorkflow.steps.map((step) => {
|
||||
return step.id;
|
||||
}),
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
referenceId: true,
|
||||
method: true,
|
||||
scheduled: true,
|
||||
},
|
||||
});
|
||||
remindersToDeletePromise.push(reminderToDelete);
|
||||
});
|
||||
|
||||
const remindersToDelete = await Promise.all(remindersToDeletePromise);
|
||||
|
||||
const deleteReminderPromise: PrismaPromise<Prisma.BatchPayload>[] = [];
|
||||
remindersToDelete.flat().forEach((reminder) => {
|
||||
//already scheduled reminders
|
||||
if (reminder.referenceId) {
|
||||
if (reminder.method === WorkflowMethods.EMAIL) {
|
||||
deleteScheduledEmailReminder(reminder.referenceId);
|
||||
} else if (reminder.method === WorkflowMethods.SMS) {
|
||||
deleteScheduledSMSReminder(reminder.referenceId);
|
||||
}
|
||||
}
|
||||
const deleteReminder = ctx.prisma.workflowReminder.deleteMany({
|
||||
where: {
|
||||
id: reminder.id,
|
||||
booking: {
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
deleteReminderPromise.push(deleteReminder);
|
||||
});
|
||||
|
||||
await Promise.all(deleteReminderPromise);
|
||||
|
||||
//update active on & reminders for new eventTypes
|
||||
await ctx.prisma.workflowsOnEventTypes.deleteMany({
|
||||
where: {
|
||||
workflowId: id,
|
||||
},
|
||||
});
|
||||
|
||||
let newEventTypes: number[] = [];
|
||||
if (activeOn.length) {
|
||||
if (trigger === WorkflowTriggerEvents.BEFORE_EVENT) {
|
||||
newEventTypes = activeOn.filter((eventType) => {
|
||||
if (
|
||||
!oldActiveOnEventTypes ||
|
||||
!oldActiveOnEventTypes
|
||||
.map((oldEventType) => {
|
||||
return oldEventType.eventTypeId;
|
||||
})
|
||||
.includes(eventType)
|
||||
) {
|
||||
return eventType;
|
||||
}
|
||||
});
|
||||
}
|
||||
if (newEventTypes.length > 0) {
|
||||
//create reminders for all bookings with newEventTypes
|
||||
const bookingsForReminders = await ctx.prisma.booking.findMany({
|
||||
where: {
|
||||
eventTypeId: { in: newEventTypes },
|
||||
status: BookingStatus.ACCEPTED,
|
||||
startTime: {
|
||||
gte: new Date(),
|
||||
},
|
||||
},
|
||||
include: {
|
||||
attendees: true,
|
||||
eventType: true,
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
|
||||
steps.forEach(async (step) => {
|
||||
if (step.action !== WorkflowActions.SMS_ATTENDEE) {
|
||||
//as we do not have attendees phone number (user is notified about that when setting this action)
|
||||
bookingsForReminders.forEach(async (booking) => {
|
||||
const bookingInfo = {
|
||||
uid: booking.uid,
|
||||
attendees: booking.attendees.map((attendee) => {
|
||||
return { name: attendee.name, email: attendee.email, timeZone: attendee.timeZone };
|
||||
}),
|
||||
organizer: booking.user
|
||||
? {
|
||||
name: booking.user.name || "",
|
||||
email: booking.user.email,
|
||||
timeZone: booking.user.timeZone,
|
||||
}
|
||||
: { name: "", email: "", timeZone: "" },
|
||||
startTime: booking.startTime.toISOString(),
|
||||
title: booking.title,
|
||||
};
|
||||
if (
|
||||
step.action === WorkflowActions.EMAIL_HOST ||
|
||||
step.action === WorkflowActions.EMAIL_ATTENDEE
|
||||
) {
|
||||
const sendTo =
|
||||
step.action === WorkflowActions.EMAIL_HOST
|
||||
? bookingInfo.organizer?.email
|
||||
: bookingInfo.attendees[0].email;
|
||||
await scheduleEmailReminder(
|
||||
bookingInfo,
|
||||
WorkflowTriggerEvents.BEFORE_EVENT,
|
||||
step.action,
|
||||
{
|
||||
time,
|
||||
timeUnit,
|
||||
},
|
||||
sendTo,
|
||||
step.emailSubject || "",
|
||||
step.reminderBody || "",
|
||||
step.id,
|
||||
step.template
|
||||
);
|
||||
} else if (step.action === WorkflowActions.SMS_NUMBER) {
|
||||
await scheduleSMSReminder(
|
||||
bookingInfo,
|
||||
step.sendTo || "",
|
||||
WorkflowTriggerEvents.BEFORE_EVENT,
|
||||
step.action,
|
||||
{
|
||||
time,
|
||||
timeUnit,
|
||||
},
|
||||
step.reminderBody || "",
|
||||
step.id,
|
||||
step.template
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
//create all workflow - eventtypes relationships
|
||||
activeOn.forEach(async (eventTypeId) => {
|
||||
await ctx.prisma.workflowsOnEventTypes.createMany({
|
||||
data: {
|
||||
workflowId: id,
|
||||
eventTypeId,
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
userWorkflow.steps.map(async (oldStep) => {
|
||||
const newStep = steps.filter((s) => s.id === oldStep.id)[0];
|
||||
const remindersFromStep = await ctx.prisma.workflowReminder.findMany({
|
||||
where: {
|
||||
workflowStepId: oldStep.id,
|
||||
},
|
||||
include: {
|
||||
booking: true,
|
||||
},
|
||||
});
|
||||
//step was deleted
|
||||
if (!newStep) {
|
||||
//delete already scheduled reminders
|
||||
if (remindersFromStep.length > 0) {
|
||||
remindersFromStep.forEach((reminder) => {
|
||||
if (reminder.referenceId) {
|
||||
if (reminder.method === WorkflowMethods.EMAIL) {
|
||||
deleteScheduledEmailReminder(reminder.referenceId);
|
||||
} else if (reminder.method === WorkflowMethods.SMS) {
|
||||
deleteScheduledSMSReminder(reminder.referenceId);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
await ctx.prisma.workflowStep.delete({
|
||||
where: {
|
||||
id: oldStep.id,
|
||||
},
|
||||
});
|
||||
//step was edited
|
||||
} else if (JSON.stringify(oldStep) !== JSON.stringify(newStep)) {
|
||||
await ctx.prisma.workflowStep.update({
|
||||
where: {
|
||||
id: oldStep.id,
|
||||
},
|
||||
data: {
|
||||
action: newStep.action,
|
||||
sendTo: newStep.action === WorkflowActions.SMS_NUMBER ? newStep.sendTo : null,
|
||||
stepNumber: newStep.stepNumber,
|
||||
workflowId: newStep.workflowId,
|
||||
reminderBody: newStep.template === WorkflowTemplates.CUSTOM ? newStep.reminderBody : null,
|
||||
emailSubject: newStep.template === WorkflowTemplates.CUSTOM ? newStep.emailSubject : null,
|
||||
template: newStep.template,
|
||||
},
|
||||
});
|
||||
//cancel all reminders of step and create new ones (not for newEventTypes)
|
||||
const remindersToUpdate = remindersFromStep.filter((reminder) => {
|
||||
if (reminder.booking?.eventTypeId && !newEventTypes.includes(reminder.booking?.eventTypeId)) {
|
||||
return reminder;
|
||||
}
|
||||
});
|
||||
remindersToUpdate.forEach(async (reminder) => {
|
||||
if (reminder.referenceId) {
|
||||
if (reminder.method === WorkflowMethods.EMAIL) {
|
||||
deleteScheduledEmailReminder(reminder.referenceId);
|
||||
} else if (reminder.method === WorkflowMethods.SMS) {
|
||||
deleteScheduledSMSReminder(reminder.referenceId);
|
||||
}
|
||||
}
|
||||
await ctx.prisma.workflowReminder.deleteMany({
|
||||
where: {
|
||||
id: reminder.id,
|
||||
},
|
||||
});
|
||||
});
|
||||
const eventTypesToUpdateReminders = activeOn.filter((eventTypeId) => {
|
||||
if (!newEventTypes.includes(eventTypeId)) {
|
||||
return eventTypeId;
|
||||
}
|
||||
});
|
||||
if (eventTypesToUpdateReminders && trigger === WorkflowTriggerEvents.BEFORE_EVENT) {
|
||||
const bookingsOfEventTypes = await ctx.prisma.booking.findMany({
|
||||
where: {
|
||||
eventTypeId: {
|
||||
in: eventTypesToUpdateReminders,
|
||||
},
|
||||
status: BookingStatus.ACCEPTED,
|
||||
startTime: {
|
||||
gte: new Date(),
|
||||
},
|
||||
},
|
||||
include: {
|
||||
attendees: true,
|
||||
eventType: true,
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
bookingsOfEventTypes.forEach(async (booking) => {
|
||||
const bookingInfo = {
|
||||
uid: booking.uid,
|
||||
attendees: booking.attendees.map((attendee) => {
|
||||
return { name: attendee.name, email: attendee.email, timeZone: attendee.timeZone };
|
||||
}),
|
||||
organizer: booking.user
|
||||
? {
|
||||
name: booking.user.name || "",
|
||||
email: booking.user.email,
|
||||
timeZone: booking.user.timeZone,
|
||||
}
|
||||
: { name: "", email: "", timeZone: "" },
|
||||
startTime: booking.startTime.toISOString(),
|
||||
title: booking.title,
|
||||
};
|
||||
if (
|
||||
newStep.action === WorkflowActions.EMAIL_HOST ||
|
||||
newStep.action === WorkflowActions.EMAIL_ATTENDEE
|
||||
) {
|
||||
const sendTo =
|
||||
newStep.action === WorkflowActions.EMAIL_HOST
|
||||
? bookingInfo.organizer?.email
|
||||
: bookingInfo.attendees[0].email;
|
||||
await scheduleEmailReminder(
|
||||
bookingInfo,
|
||||
WorkflowTriggerEvents.BEFORE_EVENT,
|
||||
newStep.action,
|
||||
{
|
||||
time,
|
||||
timeUnit,
|
||||
},
|
||||
sendTo,
|
||||
newStep.emailSubject || "",
|
||||
newStep.reminderBody || "",
|
||||
newStep.id,
|
||||
newStep.template
|
||||
);
|
||||
} else if (newStep.action === WorkflowActions.SMS_NUMBER) {
|
||||
await scheduleSMSReminder(
|
||||
bookingInfo,
|
||||
newStep.sendTo || "",
|
||||
WorkflowTriggerEvents.BEFORE_EVENT,
|
||||
newStep.action,
|
||||
{
|
||||
time,
|
||||
timeUnit,
|
||||
},
|
||||
newStep.reminderBody || "",
|
||||
newStep.id || 0,
|
||||
newStep.template
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
//added steps
|
||||
const addedSteps = steps.map((s) => {
|
||||
if (s.id <= 0) {
|
||||
const { id, ...stepToAdd } = s;
|
||||
if (stepToAdd) {
|
||||
return stepToAdd;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (addedSteps) {
|
||||
const eventTypesToCreateReminders = activeOn.map((activeEventType) => {
|
||||
if (activeEventType && !newEventTypes.includes(activeEventType)) {
|
||||
return activeEventType;
|
||||
}
|
||||
});
|
||||
addedSteps.forEach(async (step) => {
|
||||
if (step) {
|
||||
const createdStep = await ctx.prisma.workflowStep.create({
|
||||
data: step,
|
||||
});
|
||||
if (
|
||||
trigger === WorkflowTriggerEvents.BEFORE_EVENT &&
|
||||
eventTypesToCreateReminders &&
|
||||
step.action !== WorkflowActions.SMS_ATTENDEE
|
||||
) {
|
||||
const bookingsForReminders = await ctx.prisma.booking.findMany({
|
||||
where: {
|
||||
eventTypeId: { in: eventTypesToCreateReminders as number[] },
|
||||
status: BookingStatus.ACCEPTED,
|
||||
startTime: {
|
||||
gte: new Date(),
|
||||
},
|
||||
},
|
||||
include: {
|
||||
attendees: true,
|
||||
eventType: true,
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
bookingsForReminders.forEach(async (booking) => {
|
||||
const bookingInfo = {
|
||||
uid: booking.uid,
|
||||
attendees: booking.attendees.map((attendee) => {
|
||||
return { name: attendee.name, email: attendee.email, timeZone: attendee.timeZone };
|
||||
}),
|
||||
organizer: booking.user
|
||||
? {
|
||||
name: booking.user.name || "",
|
||||
email: booking.user.email,
|
||||
timeZone: booking.user.timeZone,
|
||||
}
|
||||
: { name: "", email: "", timeZone: "" },
|
||||
startTime: booking.startTime.toISOString(),
|
||||
title: booking.title,
|
||||
};
|
||||
|
||||
if (
|
||||
step.action === WorkflowActions.EMAIL_ATTENDEE ||
|
||||
step.action === WorkflowActions.EMAIL_HOST
|
||||
) {
|
||||
const sendTo =
|
||||
step.action === WorkflowActions.EMAIL_HOST
|
||||
? bookingInfo.organizer?.email
|
||||
: bookingInfo.attendees[0].email;
|
||||
await scheduleEmailReminder(
|
||||
bookingInfo,
|
||||
trigger,
|
||||
step.action,
|
||||
{
|
||||
time,
|
||||
timeUnit,
|
||||
},
|
||||
sendTo,
|
||||
step.emailSubject || "",
|
||||
step.reminderBody || "",
|
||||
createdStep.id,
|
||||
step.template
|
||||
);
|
||||
} else if (step.action === WorkflowActions.SMS_NUMBER && step.sendTo) {
|
||||
await scheduleSMSReminder(
|
||||
bookingInfo,
|
||||
step.sendTo,
|
||||
WorkflowTriggerEvents.BEFORE_EVENT,
|
||||
step.action,
|
||||
{
|
||||
time,
|
||||
timeUnit,
|
||||
},
|
||||
step.reminderBody || "",
|
||||
createdStep.id,
|
||||
step.template
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
//update trigger, name, time, timeUnit
|
||||
await ctx.prisma.workflow.update({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
data: {
|
||||
name,
|
||||
trigger,
|
||||
time,
|
||||
timeUnit,
|
||||
},
|
||||
});
|
||||
|
||||
const workflow = await ctx.prisma.workflow.findFirst({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
include: {
|
||||
activeOn: {
|
||||
select: {
|
||||
eventType: true,
|
||||
},
|
||||
},
|
||||
steps: true,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
workflow,
|
||||
};
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user