Refactors EE code (#3490)

* 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?

* WIP

* WIP

* Update index.ts

* Fixes

* Update workflow.tsx

* Moved queries to lib

* Moves QueryCell

* Migrates MultiSelectCheckboxes

* WIP

* CryptoSection type fixes

* WIP

* Import fixes

* Build fixes

* Update app-providers.tsx

* Build fixes

* Upgrades hookform zod resolvers

* Build fixes

* Cleanup

* Build fixes

* Relocates QueryCell to ui

* Moved List and SkeletonLoader

* Revert QueryCell migration

* Can't use QueryCell here

* oops

* CryptoSection cleanup

* Update app-providers.tsx

* Moved ee to features

* ee to features/ee

* Removes @calcom/ee

* Adds possible feature locations

* Build fixes

* Migrates stripe to app-store lib

* Colocates stripe imports

* Update subscription.ts

* Submodule sync

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
Omar Lópezandkodiakhq[bot] authored and GitHub committed 2022-07-28 13:58:26 -06:00
1 parent 84b4bb397f
commit 464343f5ab
257 files changed
+1000 -968

No files matched your search

+1
View File
@@ -0,0 +1 @@
# Auth-related code will live here
+4
View File
@@ -0,0 +1,4 @@
# Availability related code will live here
- [ ] Maybe migrate `getBusyTimes` here
- [ ] Maybe migrate `getUserAvailability` here (or into `users` feature)
+1
View File
@@ -0,0 +1 @@
# Bookings related code will live here
+4
View File
@@ -0,0 +1,4 @@
# Calendars related code will live here
- [ ] Maybe migrate `CalendarManager` here
- [ ] Maybe migrate `EventManager` here
+3
View File
@@ -0,0 +1,3 @@
# Conferencing related code will live here
- [ ] Maybe migrate `videoClient` here
+42
View File
@@ -0,0 +1,42 @@
The Cal.com Enterprise Edition (EE) license (the “EE License”)
Copyright (c) 2020-present Cal.com, Inc
With regard to the Cal.com Software:
This software and associated documentation files (the "Software") may only be
used in production, if you (and any entity that you represent) have agreed to,
and are in compliance with, the Cal.com Subscription Terms available
at https://cal.com/terms (the “EE Terms”), or other agreements governing
the use of the Software, as mutually agreed by you and Cal.com, Inc ("Cal.com"),
and otherwise have a valid Cal.com Enterprise Edition subscription ("EE Subscription")
for the correct number of hosts as defined in the EE Terms ("Hosts"). Subject to the foregoing sentence,
you are free to modify this Software and publish patches to the Software. You agree
that Cal.com and/or its licensors (as applicable) retain all right, title and interest in
and to all such modifications and/or patches, and all such modifications and/or
patches may only be used, copied, modified, displayed, distributed, or otherwise
exploited with a valid EE Subscription for the correct number of hosts.
Notwithstanding the foregoing, you may copy and modify the Software for development
and testing purposes, without requiring a subscription. You agree that Cal.com and/or
its licensors (as applicable) retain all right, title and interest in and to all such
modifications. You are not granted any other rights beyond what is expressly stated herein.
Subject to the foregoing, it is forbidden to copy, merge, publish, distribute, sublicense,
and/or sell the Software.
This EE License applies only to the part of this Software that is not distributed under
the AGPLv3 license. Any part of this Software distributed under the MIT license or which
is served client-side as an image, font, cascading stylesheet (CSS), file which produces
or is compiled, arranged, augmented, or combined into client-side JavaScript, in whole or
in part, is copyrighted under the AGPLv3 license. The full text of this EE License shall
be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
For all third party components incorporated into the Cal.com Software, those
components are licensed under the original license provided by the owner of the
applicable component.
+38
View File
@@ -0,0 +1,38 @@
<!-- PROJECT LOGO -->
<div align="center">
<a href="https://cal.com/enterprise">
<img src="https://user-images.githubusercontent.com/8019099/133430653-24422d2a-3c8d-4052-9ad6-0580597151ee.png" alt="Logo">
</a>
<a href="https://cal.com/enterprise">Get Started with Enterprise</a>
</div>
# Enterprise Edition
Welcome to the Enterprise Edition ("/ee") of Cal.com.
The [/ee](https://github.com/calcom/cal.com/tree/main/apps/web/ee) subfolder is the place for all the **Pro** features from our [hosted](https://cal.com/pricing) plan and [enterprise-grade](https://cal.com/enterprise) features such as SSO, SAML, ADFS, OIDC, SCIM, SIEM, HRIS and much more.
> _❗ WARNING: This repository is copyrighted (unlike our [main repo](https://github.com/calcom/cal.com)). You are not allowed to use this code to host your own version of app.cal.com without obtaining a proper [license](https://cal.com/enterprise) first❗_
## Setting up Stripe
1. Create a stripe account or use an existing one. For testing, you should use all stripe dashboard functions with the Test-Mode toggle in the top right activated.
2. Open [Stripe ApiKeys](https://dashboard.stripe.com/apikeys) save the token starting with `pk_...` to `NEXT_PUBLIC_STRIPE_PUBLIC_KEY` and `sk_...` to `STRIPE_PRIVATE_KEY` in the .env file.
3. Open [Stripe Connect Settings](https://dashboard.stripe.com/settings/connect) and activate OAuth for Standard Accounts
4. Add `<CALENDSO URL>/api/integrations/stripepayment/callback` as redirect URL.
5. Copy your client*id (`ca*...`) to `STRIPE_CLIENT_ID` in the .env file.
6. Open [Stripe Webhooks](https://dashboard.stripe.com/webhooks) and add `<CALENDSO URL>/api/integrations/stripepayment/webhook` as webhook for connected applications.
7. Select all `payment_intent` events for the webhook.
8. Copy the webhook secret (`whsec_...`) to `STRIPE_WEBHOOK_SECRET` in the .env file.
## Setting up SAML login
1. Set SAML_DATABASE_URL to a postgres database. Please use a different database than the main Cal instance since the migrations are separate for this database. For example `postgresql://postgres:@localhost:5450/cal-saml`
2. Set SAML_ADMINS to a comma separated list of admin emails from where the SAML metadata can be uploaded and configured.
3. Create a SAML application with your Identity Provider (IdP) using the instructions here - [SAML Setup](../../apps/web/docs/saml-setup.md)
4. Remember to configure access to the IdP SAML app for all your users (who need access to Cal).
5. You will need the XML metadata from your IdP later, so keep it accessible.
6. Log in to one of the admin accounts configured in SAML_ADMINS and then navigate to Settings -> Security.
7. You should see a SAML configuration section, copy and paste the XML metadata from step 5 and click on Save.
8. Your provisioned users can now log into Cal using SAML.
@@ -0,0 +1,150 @@
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import dayjs from "@calcom/dayjs";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import showToast from "@calcom/lib/notification";
import { trpc } from "@calcom/trpc/react";
import Button from "@calcom/ui/Button";
import { DialogFooter } from "@calcom/ui/Dialog";
import { ClipboardCopyIcon } from "@calcom/ui/Icon";
import Switch from "@calcom/ui/Switch";
import { Tooltip } from "@calcom/ui/Tooltip";
import { Form, TextField } from "@calcom/ui/form/fields";
import DatePicker from "@calcom/ui/v2/form/DatePicker";
import LicenseRequired from "../../common/components/LicenseRequired";
import type { TApiKeys } from "./ApiKeyListItem";
export default function ApiKeyDialogForm(props: {
title: string;
defaultValues?: Omit<TApiKeys, "userId" | "createdAt" | "lastUsedAt"> & { neverExpires?: boolean };
handleClose: () => void;
}) {
const { t } = useLocale();
const utils = trpc.useContext();
const {
defaultValues = {
note: "",
neverExpires: false,
expiresAt: dayjs().add(1, "month").toDate(),
},
} = props;
const [apiKey, setApiKey] = useState("");
const [successfulNewApiKeyModal, setSuccessfulNewApiKeyModal] = useState(false);
const [apiKeyDetails, setApiKeyDetails] = useState({
id: "",
hashedKey: "",
expiresAt: null as Date | null,
note: "" as string | null,
neverExpires: false,
});
const form = useForm({
defaultValues,
});
const watchNeverExpires = form.watch("neverExpires");
return (
<LicenseRequired>
{successfulNewApiKeyModal ? (
<>
<div className="mb-10">
<h2 className="font-semi-bold font-cal mb-2 text-xl tracking-wide text-gray-900">
{apiKeyDetails ? t("success_api_key_edited") : t("success_api_key_created")}
</h2>
<div className="text-sm text-gray-900">
<span className="font-semibold">{t("success_api_key_created_bold_tagline")}</span>{" "}
{t("you_will_only_view_it_once")}
</div>
</div>
<div>
<div className="flex">
<code className="my-2 mr-1 w-full truncate rounded-sm bg-gray-100 py-2 px-3 align-middle font-mono text-gray-800">
{apiKey}
</code>
<Tooltip side="top" content={t("copy_to_clipboard")}>
<Button
onClick={() => {
navigator.clipboard.writeText(apiKey);
showToast(t("api_key_copied"), "success");
}}
type="button"
className=" my-2 px-4 text-base">
<ClipboardCopyIcon className="mr-2 h-5 w-5 text-neutral-100" />
{t("copy")}
</Button>
</Tooltip>
</div>
<span className="text-sm text-gray-400">
{apiKeyDetails.neverExpires
? t("never_expire_key")
: `${t("expires")} ${apiKeyDetails?.expiresAt?.toLocaleDateString()}`}
</span>
</div>
<DialogFooter>
<Button type="button" color="secondary" onClick={props.handleClose} tabIndex={-1}>
{t("done")}
</Button>
</DialogFooter>
</>
) : (
<Form<Omit<TApiKeys, "userId" | "createdAt" | "lastUsedAt"> & { neverExpires?: boolean }>
form={form}
handleSubmit={async (event) => {
const apiKey = await utils.client.mutation("viewer.apiKeys.create", event);
setApiKey(apiKey);
setApiKeyDetails({ ...event, neverExpires: !!event.neverExpires });
await utils.invalidateQueries(["viewer.apiKeys.list"]);
setSuccessfulNewApiKeyModal(true);
}}
className="space-y-4">
<div className="mb-10 mt-1">
<h2 className="font-semi-bold font-cal text-xl tracking-wide text-gray-900">{props.title}</h2>
<p className="mt-1 mb-5 text-sm text-gray-500">{t("api_key_modal_subtitle")}</p>
</div>
<div>
<TextField
label={t("personal_note")}
placeholder={t("personal_note_placeholder")}
{...form.register("note")}
type="text"
/>
</div>
<div className="flex flex-col">
<div className="flex justify-between py-2">
<span className="block text-sm font-medium text-gray-700">{t("expire_date")}</span>
<Controller
name="neverExpires"
render={({ field: { onChange, value } }) => (
<Switch label={t("never_expire_key")} onCheckedChange={onChange} checked={value} />
)}
/>
</div>
<Controller
name="expiresAt"
render={({ field: { onChange, value } }) => (
<DatePicker
disabled={watchNeverExpires}
minDate={new Date()}
date={value}
onDatesChange={onChange}
/>
)}
/>
</div>
<DialogFooter>
<Button type="button" color="secondary" onClick={props.handleClose} tabIndex={-1}>
{t("cancel")}
</Button>
<Button type="submit" loading={form.formState.isSubmitting}>
{apiKeyDetails ? t("save") : t("create")}
</Button>
</DialogFooter>
</Form>
)}
</LicenseRequired>
);
}
@@ -0,0 +1,85 @@
import { useState } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import Button from "@calcom/ui/Button";
import { Dialog, DialogContent } from "@calcom/ui/Dialog";
import { Icon } from "@calcom/ui/Icon";
import { List } from "@calcom/ui/List";
import { ShellSubHeading } from "@calcom/ui/Shell";
import SkeletonLoader from "@calcom/ui/apps/SkeletonLoader";
import LicenseRequired from "../../common/components/LicenseRequired";
import ApiKeyDialogForm from "./ApiKeyDialogForm";
import ApiKeyListItem, { TApiKeys } from "./ApiKeyListItem";
function ApiKeyListContainer() {
const { t } = useLocale();
const query = trpc.useQuery(["viewer.apiKeys.list"]);
const data = query.data;
const [newApiKeyModal, setNewApiKeyModal] = useState(false);
const [editModalOpen, setEditModalOpen] = useState(false);
const [apiKeyToEdit, setApiKeyToEdit] = useState<(TApiKeys & { neverExpires?: boolean }) | null>(null);
return (
<div className="border-b border-gray-200 py-8 pl-2 pr-1">
<ShellSubHeading
className="mt-2"
title={t("api_keys")}
subtitle={t("api_keys_subtitle")}
actions={
<Button color="minimal" size="icon" StartIcon={Icon.Plus} onClick={() => setNewApiKeyModal(true)} />
}
/>
<LicenseRequired>
{(() => {
if (query.isLoading) return <SkeletonLoader />;
if (!data) return null;
return (
<>
{data.length > 0 && (
<List className="mt-6">
{data.map((item) => (
<ApiKeyListItem
key={item.id}
apiKey={item}
onEditApiKey={() => {
setApiKeyToEdit(item);
setEditModalOpen(true);
}}
/>
))}
</List>
)}
{/* New api key dialog */}
<Dialog open={newApiKeyModal} onOpenChange={(isOpen) => !isOpen && setNewApiKeyModal(false)}>
<DialogContent>
<ApiKeyDialogForm
title={t("create_api_key")}
handleClose={() => setNewApiKeyModal(false)}
/>
</DialogContent>
</Dialog>
{/* Edit api key dialog */}
<Dialog open={editModalOpen} onOpenChange={(isOpen) => !isOpen && setEditModalOpen(false)}>
<DialogContent>
{apiKeyToEdit && (
<ApiKeyDialogForm
title={t("edit_api_key")}
key={apiKeyToEdit.id}
handleClose={() => setEditModalOpen(false)}
defaultValues={apiKeyToEdit}
/>
)}
</DialogContent>
</Dialog>
</>
);
})()}
</LicenseRequired>
</div>
);
}
export default ApiKeyListContainer;
@@ -0,0 +1,99 @@
import dayjs from "@calcom/dayjs";
import classNames from "@calcom/lib/classNames";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { inferQueryOutput, trpc } from "@calcom/trpc/react";
import Badge from "@calcom/ui/Badge";
import Button from "@calcom/ui/Button";
import ConfirmationDialogContent from "@calcom/ui/ConfirmationDialogContent";
import { Dialog, DialogTrigger } from "@calcom/ui/Dialog";
import { Icon } from "@calcom/ui/Icon";
import { ListItem } from "@calcom/ui/List";
import { Tooltip } from "@calcom/ui/Tooltip";
export type TApiKeys = inferQueryOutput<"viewer.apiKeys.list">[number];
export default function ApiKeyListItem(props: { apiKey: TApiKeys; onEditApiKey: () => void }) {
const { t } = useLocale();
const utils = trpc.useContext();
const isExpired = props?.apiKey?.expiresAt ? props.apiKey.expiresAt < new Date() : null;
const neverExpires = props?.apiKey?.expiresAt === null;
const deleteApiKey = trpc.useMutation("viewer.apiKeys.delete", {
async onSuccess() {
await utils.invalidateQueries(["viewer.apiKeys.list"]);
},
});
return (
<ListItem className="flex w-full p-4">
<div className="flex w-full justify-between">
<div className="flex max-w-full flex-col truncate">
<div className="flex space-x-2">
<span className="text-gray-900">
{props?.apiKey?.note ? props.apiKey.note : t("api_key_no_note")}
</span>
{!neverExpires && isExpired && (
<Badge className="-p-2" variant="default">
{t("expired")}
</Badge>
)}
</div>
<div className="mt-2 flex">
<span
className={classNames(
"flex flex-col space-x-2 space-y-1 text-xs sm:flex-row sm:space-y-0 sm:rtl:space-x-reverse",
isExpired ? "text-red-600" : "text-gray-500",
neverExpires ? "text-yellow-600" : ""
)}>
{neverExpires ? (
<div className="flex flex-row space-x-3 text-gray-500">
<Icon.AlertTriangle className="w-4" />
{t("api_key_never_expires")}
</div>
) : (
`${isExpired ? t("expired") : t("expires")} ${dayjs(
props?.apiKey?.expiresAt?.toString()
).fromNow()}`
)}
</span>
</div>
</div>
<div className="flex">
<Tooltip side="top" content={t("edit_api_key")}>
<Button
onClick={() => props.onEditApiKey()}
color="minimal"
size="icon"
StartIcon={Icon.Edit2}
className="ml-4 w-full self-center p-2"
/>
</Tooltip>
<Dialog>
<Tooltip side="top" content={t("delete_api_key")}>
<DialogTrigger asChild>
<Button
onClick={(e) => {
e.stopPropagation();
}}
color="minimal"
size="icon"
className="ml-2 w-full self-center p-2"
/>
</DialogTrigger>
</Tooltip>
<ConfirmationDialogContent
variety="danger"
title={t("confirm_delete_api_key")}
confirmBtnText={t("revoke_api_key")}
cancelBtnText={t("cancel")}
onConfirm={() =>
deleteApiKey.mutate({
id: props.apiKey.id,
})
}>
{t("delete_api_key_confirm_title")}
</ConfirmationDialogContent>
</Dialog>
</div>
</div>
</ListItem>
);
}
@@ -0,0 +1,10 @@
import { randomBytes, createHash } from "crypto";
// Hash the API key to check against when veriying it. so we don't have to store the key in plain text.
export const hashAPIKey = (apiKey: string): string => createHash("sha256").update(apiKey).digest("hex");
// Generate a random API key. Prisma already makes sure it's unique. So no need to add salts like with passwords.
export const generateUniqueAPIKey = (apiKey = randomBytes(16).toString("hex")) => [
hashAPIKey(apiKey),
apiKey,
];
@@ -0,0 +1,32 @@
import { hashAPIKey } from "@calcom/features/ee/api-keys/lib/apiKeys";
import prisma from "@calcom/prisma";
const findValidApiKey = async (apiKey: string, appId?: string) => {
const hashedKey = hashAPIKey(apiKey.substring(process.env.API_KEY_PREFIX?.length || 0));
const validKey = await prisma.apiKey.findFirst({
where: {
AND: [
{
hashedKey,
},
{
appId,
},
],
OR: [
{
expiresAt: {
gte: new Date(Date.now()),
},
},
{
expiresAt: null,
},
],
},
});
return validKey;
};
export default findValidApiKey;
@@ -0,0 +1,99 @@
import { Trans } from "react-i18next";
import ConfirmationDialogContent from "@calcom/ui/ConfirmationDialogContent";
import { Dialog, DialogTrigger } from "@calcom/ui/Dialog";
import { Icon, BadgeCheckIcon } from "@calcom/ui/Icon";
import { useLocale } from "@lib/hooks/useLocale";
export default function LicenseBanner() {
const { t } = useLocale();
/*
Set this value to 'agree' to accept our license:
LICENSE: https://github.com/calcom/cal.com/blob/main/LICENSE
Summary of terms:
- The codebase has to stay open source, whether it was modified or not
- You can not repackage or sell the codebase
- Acquire a commercial license to remove these terms by visiting: cal.com/sales
NEXT_PUBLIC_LICENSE_CONSENT=''
*/
if (process.env.NEXT_PUBLIC_LICENSE_CONSENT === "agree" || process.env.NEXT_PUBLIC_IS_E2E) {
return null;
}
return (
<div className="fixed inset-x-0 bottom-0 left-0 pb-2 sm:pb-5 md:left-56">
<div className="mx-auto max-w-7xl px-2 sm:px-8">
<div className="rounded-sm bg-green-600 p-2 shadow-lg sm:p-3">
<div className="flex flex-wrap items-center justify-between">
<div className="flex w-0 flex-1 items-center">
<span className="flex rounded-sm bg-green-800 p-2">
<BadgeCheckIcon className="h-6 w-6 text-white" aria-hidden="true" />
</span>
<p className="ml-3 truncate font-medium text-white">
<span className="inline">
<Trans i18nKey="accept_our_license" values={{ agree: "agree" }}>
Accept our license by changing the .env variable
<span className="bg-gray-50 bg-opacity-20 px-1">NEXT_PUBLIC_LICENSE_CONSENT</span> to
&apos;agree&apos;.
</Trans>
</span>
</p>
</div>
<div className="order-3 mt-2 w-full flex-shrink-0 sm:order-2 sm:mt-0 sm:w-auto">
<Dialog>
<DialogTrigger asChild>
<button className="flex w-full items-center justify-center rounded-sm border border-transparent bg-white px-4 py-2 text-sm font-medium text-green-600 hover:bg-green-50">
{t("accept_license")}
</button>
</DialogTrigger>
<DialogContent />
</Dialog>
</div>
<div className="order-2 flex-shrink-0 sm:order-3 sm:ml-2">
<Dialog>
<DialogTrigger asChild>
<button className="-mr-1 flex rounded-sm p-2 hover:bg-green-500 focus:outline-none focus:ring-2 focus:ring-white">
<span className="sr-only">{t("dismiss")}</span>
<Icon.X className="h-6 w-6 text-white" aria-hidden="true" />
</button>
</DialogTrigger>
<DialogContent />
</Dialog>
</div>
</div>
</div>
</div>
</div>
);
function DialogContent() {
return (
<ConfirmationDialogContent
variety="success"
title={t("open_env")}
confirmBtnText={t("env_changed")}
cancelBtnText={t("cancel")}>
<Trans i18nKey="remove_banner_instructions" values={{ agree: "agree" }}>
To remove this banner, please open your .env file and change the
<span className="bg-green-400 bg-opacity-20 p-[2px] text-green-500">
NEXT_PUBLIC_LICENSE_CONSENT
</span>
variable to &apos;agreeapos;.
</Trans>
<h2 className="font-cal mt-8 mb-2 text-black">{t("terms_summary")}:</h2>
<ul className="ml-5 list-disc">
<li>{t("codebase_has_to_stay_opensource")}</li>
<li>{t("cannot_repackage_codebase")}</li>
<li>
{t("acquire_license")}:{" "}
<a className="text-blue-500 underline" href="https://cal.com/sales">
cal.com/sales
</a>
</li>
</ul>
</ConfirmationDialogContent>
);
}
}
@@ -0,0 +1,60 @@
import { useSession } from "next-auth/react";
import React, { AriaRole, ComponentType, Fragment } from "react";
import { CONSOLE_URL } from "@calcom/lib/constants";
import EmptyScreen from "@calcom/ui/EmptyScreen";
import { Icon } from "@calcom/ui/Icon";
type LicenseRequiredProps = {
as?: keyof JSX.IntrinsicElements | "";
className?: string;
role?: AriaRole | undefined;
children: React.ReactNode;
};
/**
* This component will only render it's children if the installation has a valid
* license.
*/
const LicenseRequired = ({ children, as = "", ...rest }: LicenseRequiredProps) => {
const session = useSession();
const Component = as || Fragment;
return (
<Component {...rest}>
{session.data?.hasValidLicense ? (
children
) : (
<EmptyScreen
Icon={Icon.AlertTriangle}
headline="This is an enterprise feature"
description={
<>
To enable this feature, get a deployment key at{" "}
<a href={CONSOLE_URL} target="_blank" rel="noopener noreferrer" className="underline">
Cal.com console
</a>{" "}
and add it to your .env as <code>CALCOM_LICENSE_KEY</code>. If your team already has a license,
please contact{" "}
<a href="mailto:[email protected]" className="underline">
peer@cal.com
</a>{" "}
for help.
</>
}
/>
)}
</Component>
);
};
export const withLicenseRequired =
<T,>(Component: ComponentType<T>) =>
// eslint-disable-next-line react/display-name
(hocProps: T) =>
(
<LicenseRequired>
<Component {...hocProps} />
</LicenseRequired>
);
export default LicenseRequired;
@@ -0,0 +1,164 @@
import React, { useEffect, useRef, useState } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import showToast from "@calcom/lib/notification";
import { collectPageParameters, telemetryEventTypes, useTelemetry } from "@calcom/lib/telemetry";
import { trpc } from "@calcom/trpc/react";
import { Alert } from "@calcom/ui/Alert";
import Badge from "@calcom/ui/Badge";
import Button from "@calcom/ui/Button";
import ConfirmationDialogContent from "@calcom/ui/ConfirmationDialogContent";
import { Dialog, DialogTrigger } from "@calcom/ui/Dialog";
import { TextArea } from "@calcom/ui/form/fields";
import LicenseRequired from "./LicenseRequired";
export default function SAMLConfiguration({
teamsView,
teamId,
}: {
teamsView: boolean;
teamId: null | undefined | number;
}) {
const [isSAMLLoginEnabled, setIsSAMLLoginEnabled] = useState(false);
const [samlConfig, setSAMLConfig] = useState<string | null>(null);
const query = trpc.useQuery(["viewer.showSAMLView", { teamsView, teamId }]);
const telemetry = useTelemetry();
useEffect(() => {
const data = query.data;
setIsSAMLLoginEnabled(data?.isSAMLLoginEnabled ?? false);
setSAMLConfig(data?.provider ?? null);
}, [query.data]);
const mutation = trpc.useMutation("viewer.updateSAMLConfig", {
onSuccess: (data: { provider: string | undefined }) => {
showToast(t("saml_config_updated_successfully"), "success");
setHasErrors(false); // dismiss any open errors
setSAMLConfig(data?.provider ?? null);
samlConfigRef.current.value = "";
},
onError: () => {
setHasErrors(true);
setErrorMessage(t("saml_configuration_update_failed"));
document?.getElementsByTagName("main")[0]?.scrollTo({ top: 0, behavior: "smooth" });
},
});
const deleteMutation = trpc.useMutation("viewer.deleteSAMLConfig", {
onSuccess: () => {
showToast(t("saml_config_deleted_successfully"), "success");
setHasErrors(false); // dismiss any open errors
setSAMLConfig(null);
samlConfigRef.current.value = "";
},
onError: () => {
setHasErrors(true);
setErrorMessage(t("saml_configuration_delete_failed"));
document?.getElementsByTagName("main")[0]?.scrollTo({ top: 0, behavior: "smooth" });
},
});
const samlConfigRef = useRef<HTMLTextAreaElement>() as React.MutableRefObject<HTMLTextAreaElement>;
const [hasErrors, setHasErrors] = useState(false);
const [errorMessage, setErrorMessage] = useState("");
async function updateSAMLConfigHandler(event: React.FormEvent<HTMLElement>) {
event.preventDefault();
const rawMetadata = samlConfigRef.current.value;
// track Google logins. Without personal data/payload
telemetry.event(telemetryEventTypes.samlConfig, collectPageParameters());
mutation.mutate({
encodedRawMetadata: Buffer.from(rawMetadata).toString("base64"),
teamId,
});
}
async function deleteSAMLConfigHandler(event: React.MouseEvent<HTMLElement, MouseEvent>) {
event.preventDefault();
deleteMutation.mutate({
teamId,
});
}
const { t } = useLocale();
return (
<>
{isSAMLLoginEnabled ? (
<LicenseRequired>
<hr className="mt-8" />
<div className="mt-6">
<h2 className="font-cal text-lg font-medium leading-6 text-gray-900">
{t("saml_configuration")}
<Badge className="ml-2 text-xs" variant={samlConfig ? "success" : "gray"}>
{samlConfig ? t("enabled") : t("disabled")}
</Badge>
{samlConfig ? (
<>
<Badge className="ml-2 text-xs" variant="success">
{samlConfig ? samlConfig : ""}
</Badge>
</>
) : null}
</h2>
</div>
{samlConfig ? (
<div className="mt-2 flex">
<Dialog>
<DialogTrigger asChild>
<Button
color="warn"
type="button"
onClick={(e) => {
e.stopPropagation();
}}>
{t("delete_saml_configuration")}
</Button>
</DialogTrigger>
<ConfirmationDialogContent
variety="danger"
title={t("delete_saml_configuration")}
confirmBtnText={t("confirm_delete_saml_configuration")}
cancelBtnText={t("cancel")}
onConfirm={deleteSAMLConfigHandler}>
{t("delete_saml_configuration_confirmation_message")}
</ConfirmationDialogContent>
</Dialog>
</div>
) : (
<p className="mt-1 text-sm text-gray-500">{!samlConfig ? t("saml_not_configured_yet") : ""}</p>
)}
<p className="mt-1 text-sm text-gray-500">{t("saml_configuration_description")}</p>
<form className="mt-3 divide-y divide-gray-200 lg:col-span-9" onSubmit={updateSAMLConfigHandler}>
{hasErrors && <Alert severity="error" title={errorMessage} />}
<TextArea
data-testid="saml_config"
ref={samlConfigRef}
name="saml_config"
id="saml_config"
required={true}
rows={10}
placeholder={t("saml_configuration_placeholder")}
/>
<div className="flex justify-end py-8">
<Button type="submit">{t("save")}</Button>
</div>
<hr className="mt-4" />
</form>
</LicenseRequired>
) : null}
</>
);
}
@@ -0,0 +1,40 @@
import dayjs from "@calcom/dayjs";
import Button from "@calcom/ui/Button";
import { TRIAL_LIMIT_DAYS } from "@lib/config/constants";
import { useLocale } from "@lib/hooks/useLocale";
import useMeQuery from "@lib/hooks/useMeQuery";
const TrialBanner = () => {
const { t } = useLocale();
const query = useMeQuery();
const user = query.data;
if (!user || user.plan !== "TRIAL") return null;
const trialDaysLeft = user.trialEndsAt
? dayjs(user.trialEndsAt).add(1, "day").diff(dayjs(), "day")
: dayjs(user.createdDate)
.add(TRIAL_LIMIT_DAYS + 1, "day")
.diff(dayjs(), "day");
return (
<div
className="m-4 hidden rounded-md bg-yellow-200 p-4 text-center text-sm font-medium text-gray-600 lg:block"
data-testid="trial-banner">
<div className="mb-2 text-left">
{trialDaysLeft > 0 ? t("trial_days_left", { days: trialDaysLeft }) : t("trial_expired")}
</div>
<Button
href="/api/upgrade"
color="minimal"
prefetch={false}
className="w-full justify-center border-2 border-gray-600 hover:bg-yellow-100">
{t("upgrade_now")}
</Button>
</div>
);
};
export default TrialBanner;
@@ -0,0 +1,25 @@
import { WEBSITE_URL } from "@calcom/lib/constants";
import slugify from "@calcom/lib/slugify";
interface ResponseUsernameApi {
available: boolean;
premium: boolean;
message?: string;
suggestion?: string;
}
export async function checkPremiumUsername(_username: string): Promise<ResponseUsernameApi> {
const username = slugify(_username);
const response = await fetch(`${WEBSITE_URL}/api/username`, {
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ username }),
method: "POST",
mode: "cors",
});
const json = await response.json();
return json;
}
@@ -0,0 +1,25 @@
import cache from "memory-cache";
import { CONSOLE_URL } from "@calcom/lib/constants";
const CACHING_TIME = 86400000; // 24 hours in milliseconds
async function checkLicense(license: string): Promise<boolean> {
if (!!process.env.NEXT_PUBLIC_IS_E2E) return true;
const url = `${CONSOLE_URL}/api/license?key=${license}`;
const cachedResponse = cache.get(url);
if (cachedResponse) {
return cachedResponse;
} else {
try {
const response = await fetch(url, { mode: "cors" });
const data = await response.json();
cache.put(url, data.valid, CACHING_TIME);
return data.valid;
} catch (error) {
return false;
}
}
}
export default checkLicense;
@@ -0,0 +1,32 @@
import { useSession } from "next-auth/react";
import { Trans } from "next-i18next";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Alert } from "@calcom/ui/Alert";
function ImpersonatingBanner() {
const { t } = useLocale();
const { data } = useSession();
if (!data?.user.impersonatedByUID) return null;
return (
<Alert
severity="warning"
title={
<>
{t("impersonating_user_warning", { user: data.user.username })}{" "}
<Trans i18nKey="impersonating_stop_instructions">
<a href="/auth/logout" className="underline">
Click Here To stop
</a>
.
</Trans>
</>
}
className="mx-4 mb-2 sm:mx-6 md:mx-8"
/>
);
}
export default ImpersonatingBanner;
@@ -0,0 +1,138 @@
import { User } from "@prisma/client";
import CredentialsProvider from "next-auth/providers/credentials";
import { getSession } from "next-auth/react";
import prisma from "@calcom/prisma";
import { asNumberOrThrow } from "@lib/asStringOrNull";
const auditAndReturnNextUser = async (
impersonatedUser: Pick<User, "id" | "username" | "email" | "name" | "role">,
impersonatedByUID: number
) => {
// Log impersonations for audit purposes
await prisma.impersonations.create({
data: {
impersonatedBy: {
connect: {
id: impersonatedByUID,
},
},
impersonatedUser: {
connect: {
id: impersonatedUser.id,
},
},
},
});
const obj = {
id: impersonatedUser.id,
username: impersonatedUser.username,
email: impersonatedUser.email,
name: impersonatedUser.name,
role: impersonatedUser.role,
impersonatedByUID,
};
return obj;
};
const ImpersonationProvider = CredentialsProvider({
id: "impersonation-auth",
name: "Impersonation",
type: "credentials",
credentials: {
username: { type: "text" },
teamId: { type: "text" },
},
async authorize(creds, req) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore need to figure out how to correctly type this
const session = await getSession({ req });
const teamId = creds?.teamId ? asNumberOrThrow(creds.teamId) : undefined;
if (session?.user.username === creds?.username) {
throw new Error("You cannot impersonate yourself.");
}
if (!creds?.username) throw new Error("Username must be present");
// If you are an ADMIN we return way before team impersonation logic is executed, so NEXT_PUBLIC_TEAM_IMPERSONATION certainly true
if (session?.user.role !== "ADMIN" && process.env.NEXT_PUBLIC_TEAM_IMPERSONATION === "false") {
throw new Error("You do not have permission to do this.");
}
// Get user who is being impersonated
const impersonatedUser = await prisma.user.findUnique({
where: {
username: creds?.username,
},
select: {
id: true,
username: true,
role: true,
name: true,
email: true,
disableImpersonation: true,
teams: {
where: {
disableImpersonation: false, // Ensure they have impersonation enabled
accepted: true, // Ensure they are apart of the team and not just invited.
team: {
id: teamId, // Bring back only the right team
},
},
select: {
teamId: true,
disableImpersonation: true,
},
},
},
});
// Check if impersonating is allowed for this user
if (!impersonatedUser) {
throw new Error("This user does not exist");
}
if (session?.user.role === "ADMIN") {
if (impersonatedUser.disableImpersonation) {
throw new Error("This user has disabled Impersonation.");
}
return auditAndReturnNextUser(impersonatedUser, session?.user.id as number);
}
// Check session
const sessionUserFromDb = await prisma.user.findUnique({
where: {
id: session?.user.id,
},
include: {
teams: {
where: {
AND: [
{
role: {
in: ["ADMIN", "OWNER"],
},
},
{
team: {
id: teamId,
},
},
],
},
},
},
});
if (sessionUserFromDb?.teams.length === 0 || impersonatedUser.teams.length === 0) {
throw new Error("You do not have permission to do this.");
}
return auditAndReturnNextUser(impersonatedUser, session?.user.id as number);
},
});
export default ImpersonationProvider;
+1
View File
@@ -0,0 +1 @@
export { default } from "./common/server/checkLicense";
+21
View File
@@ -0,0 +1,21 @@
{
"name": "@calcom/ee",
"description": "Cal.com Enterprise Edition features",
"version": "0.0.0",
"private": true,
"license": "See license in LICENSE",
"main": "./index.ts",
"dependencies": {
"@calcom/lib": "*",
"@calcom/ui": "*",
"@hookform/error-message": "^2.0.0",
"@hookform/resolvers": "^2.9.7",
"@sendgrid/client": "^7.6.2",
"@sendgrid/mail": "^7.6.2",
"twilio": "^3.75.1",
"zod": "^3.16.0"
},
"devDependencies": {
"@calcom/tsconfig": "*"
}
}
@@ -0,0 +1,216 @@
import { BookingStatus, Prisma } from "@prisma/client";
import { buffer } from "micro";
import type { NextApiRequest, NextApiResponse } from "next";
import Stripe from "stripe";
import stripe from "@calcom/app-store/stripepayment/lib/server";
import EventManager from "@calcom/core/EventManager";
import { sendScheduledEmails } from "@calcom/emails";
import { isPrismaObjOrUndefined, parseRecurringEvent } from "@calcom/lib";
import { getErrorFromUnknown } from "@calcom/lib/errors";
import prisma, { bookingMinimalSelect } from "@calcom/prisma";
import type { CalendarEvent } from "@calcom/types/Calendar";
import { IS_PRODUCTION } from "@lib/config/constants";
import { HttpError as HttpCode } from "@lib/core/http/error";
import { getTranslation } from "@server/lib/i18n";
export const config = {
api: {
bodyParser: false,
},
};
async function handlePaymentSuccess(event: Stripe.Event) {
const paymentIntent = event.data.object as Stripe.PaymentIntent;
const payment = await prisma.payment.findFirst({
where: {
externalId: paymentIntent.id,
},
select: {
id: true,
bookingId: true,
},
});
if (!payment?.bookingId) {
console.log(JSON.stringify(paymentIntent), JSON.stringify(payment));
}
if (!payment?.bookingId) throw new HttpCode({ statusCode: 204, message: "Payment not found" });
const booking = await prisma.booking.findUnique({
where: {
id: payment.bookingId,
},
select: {
...bookingMinimalSelect,
location: true,
eventTypeId: true,
userId: true,
uid: true,
paid: true,
destinationCalendar: true,
status: true,
user: {
select: {
id: true,
credentials: true,
timeZone: true,
email: true,
name: true,
locale: true,
destinationCalendar: true,
},
},
},
});
if (!booking) throw new HttpCode({ statusCode: 204, message: "No booking found" });
const eventTypeSelect = Prisma.validator<Prisma.EventTypeSelect>()({ recurringEvent: true });
const eventTypeData = Prisma.validator<Prisma.EventTypeArgs>()({ select: eventTypeSelect });
type EventTypeRaw = Prisma.EventTypeGetPayload<typeof eventTypeData>;
let eventTypeRaw: EventTypeRaw | null = null;
if (booking.eventTypeId) {
eventTypeRaw = await prisma.eventType.findUnique({
where: {
id: booking.eventTypeId,
},
select: eventTypeSelect,
});
}
const { user } = booking;
if (!user) throw new HttpCode({ statusCode: 204, message: "No user found" });
const t = await getTranslation(user.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 = {
type: booking.title,
title: booking.title,
description: booking.description || undefined,
startTime: booking.startTime.toISOString(),
endTime: booking.endTime.toISOString(),
customInputs: isPrismaObjOrUndefined(booking.customInputs),
organizer: {
email: user.email,
name: user.name!,
timeZone: user.timeZone,
language: { translate: t, locale: user.locale ?? "en" },
},
attendees: attendeesList,
uid: booking.uid,
destinationCalendar: booking.destinationCalendar || user.destinationCalendar,
recurringEvent: parseRecurringEvent(eventTypeRaw?.recurringEvent),
};
if (booking.location) evt.location = booking.location;
const bookingData: Prisma.BookingUpdateInput = {
paid: true,
status: BookingStatus.ACCEPTED,
};
const isConfirmed = booking.status === BookingStatus.ACCEPTED;
if (isConfirmed) {
const eventManager = new EventManager(user);
const scheduleResult = await eventManager.create(evt);
bookingData.references = { create: scheduleResult.referencesToCreate };
}
const paymentUpdate = prisma.payment.update({
where: {
id: payment.id,
},
data: {
success: true,
},
});
const bookingUpdate = prisma.booking.update({
where: {
id: booking.id,
},
data: bookingData,
});
await prisma.$transaction([paymentUpdate, bookingUpdate]);
await sendScheduledEmails({ ...evt });
throw new HttpCode({
statusCode: 200,
message: `Booking with id '${booking.id}' was paid and confirmed.`,
});
}
type WebhookHandler = (event: Stripe.Event) => Promise<void>;
const webhookHandlers: Record<string, WebhookHandler | undefined> = {
"payment_intent.succeeded": handlePaymentSuccess,
};
/**
* @deprecated
* We need to create a PaymentManager in `@calcom/core`
* to prevent circular dependencies on App Store migration
*/
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
if (req.method !== "POST") {
throw new HttpCode({ statusCode: 405, message: "Method Not Allowed" });
}
const sig = req.headers["stripe-signature"];
if (!sig) {
throw new HttpCode({ statusCode: 400, message: "Missing stripe-signature" });
}
if (!process.env.STRIPE_WEBHOOK_SECRET) {
throw new HttpCode({ statusCode: 500, message: "Missing process.env.STRIPE_WEBHOOK_SECRET" });
}
const requestBuffer = await buffer(req);
const payload = requestBuffer.toString();
const event = stripe.webhooks.constructEvent(payload, sig, process.env.STRIPE_WEBHOOK_SECRET);
if (!event.account) {
throw new HttpCode({ statusCode: 202, message: "Incoming connected account" });
}
const handler = webhookHandlers[event.type];
if (handler) {
await handler(event);
} else {
/** Not really an error, just letting Stripe know that the webhook was received but unhandled */
throw new HttpCode({
statusCode: 202,
message: `Unhandled Stripe Webhook event type ${event.type}`,
});
}
} catch (_err) {
const err = getErrorFromUnknown(_err);
console.error(`Webhook Error: ${err.message}`);
res.status(err.statusCode ?? 500).send({
message: err.message,
stack: IS_PRODUCTION ? undefined : err.stack,
});
return;
}
// Return a response to acknowledge receipt of the event
res.json({ received: true });
}
@@ -0,0 +1,129 @@
import { CardElement, useElements, useStripe } from "@stripe/react-stripe-js";
import stripejs, { StripeCardElementChangeEvent, StripeElementLocale } from "@stripe/stripe-js";
import { useRouter } from "next/router";
import { stringify } from "querystring";
import React, { SyntheticEvent, useEffect, useState } from "react";
import { PaymentData } from "@calcom/app-store/stripepayment/lib/server";
import Button from "@calcom/ui/Button";
import { useLocale } from "@lib/hooks/useLocale";
const CARD_OPTIONS: stripejs.StripeCardElementOptions = {
iconStyle: "solid" as const,
classes: {
base: "block p-2 w-full border-solid border-2 border-gray-300 rounded-md dark:bg-black dark:text-white dark:border-black focus-within:ring-black focus-within:border-black text-sm",
},
style: {
base: {
color: "#666",
iconColor: "#666",
fontFamily: "ui-sans-serif, system-ui",
fontSmoothing: "antialiased",
fontSize: "16px",
"::placeholder": {
color: "#888888",
},
},
},
} as const;
type Props = {
payment: {
data: PaymentData;
};
eventType: { id: number };
user: { username: string | null };
location?: string | null;
bookingId: number;
};
type States =
| { status: "idle" }
| { status: "processing" }
| { status: "error"; error: Error }
| { status: "ok" };
export default function PaymentComponent(props: Props) {
const { t, i18n } = useLocale();
const router = useRouter();
const { email, name, date } = router.query;
const [state, setState] = useState<States>({ status: "idle" });
const stripe = useStripe();
const elements = useElements();
useEffect(() => {
elements?.update({ locale: i18n.language as StripeElementLocale });
}, [elements, i18n.language]);
const handleChange = async (event: StripeCardElementChangeEvent) => {
// Listen for changes in the CardElement
// and display any errors as the customer types their card details
setState({ status: "idle" });
if (event.error)
setState({ status: "error", error: new Error(event.error?.message || t("missing_card_fields")) });
};
const handleSubmit = async (ev: SyntheticEvent) => {
ev.preventDefault();
if (!stripe || !elements) return;
const card = elements.getElement(CardElement);
if (!card) return;
setState({ status: "processing" });
const payload = await stripe.confirmCardPayment(props.payment.data.client_secret!, {
payment_method: {
card,
},
});
if (payload.error) {
setState({
status: "error",
error: new Error(`Payment failed: ${payload.error.message}`),
});
} else {
const params: { [k: string]: any } = {
date,
type: props.eventType.id,
user: props.user.username,
email,
name,
bookingId: props.bookingId,
};
if (props.location) {
if (props.location.includes("integration")) {
params.location = t("web_conferencing_details_to_follow");
} else {
params.location = props.location;
}
}
const query = stringify(params);
const successUrl = `/success?${query}`;
await router.push(successUrl);
}
};
return (
<form id="payment-form" className="mt-4" onSubmit={handleSubmit}>
<CardElement id="card-element" options={CARD_OPTIONS} onChange={handleChange} />
<div className="mt-2 flex justify-center">
<Button
type="submit"
disabled={["processing", "error"].includes(state.status)}
loading={state.status === "processing"}
id="submit">
<span id="button-text">
{state.status === "processing" ? <div className="spinner" id="spinner" /> : t("pay_now")}
</span>
</Button>
</div>
{state.status === "error" && (
<div className="mt-4 text-center text-gray-700 dark:text-gray-300" role="alert">
{state.error.message}
</div>
)}
</form>
);
}
@@ -0,0 +1,156 @@
import { Elements } from "@stripe/react-stripe-js";
import classNames from "classnames";
import Head from "next/head";
import { FC, useEffect, useState } from "react";
import { FormattedNumber, IntlProvider } from "react-intl";
import { LocationOptionsToString } from "@calcom/app-store/locations";
import getStripe from "@calcom/app-store/stripepayment/lib/client";
import dayjs from "@calcom/dayjs";
import { sdkActionManager, useIsEmbed } from "@calcom/embed-core/embed-iframe";
import { WEBSITE_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import useTheme from "@calcom/lib/hooks/useTheme";
import { isBrowserLocale24h } from "@calcom/lib/timeFormat";
import { Icon } from "@calcom/ui/Icon";
import type { PaymentPageProps } from "../pages/payment";
import PaymentComponent from "./Payment";
const PaymentPage: FC<PaymentPageProps> = (props) => {
const { t } = useLocale();
const [is24h, setIs24h] = useState(isBrowserLocale24h());
const [date, setDate] = useState(dayjs.utc(props.booking.startTime));
useTheme(props.profile.theme);
const isEmbed = useIsEmbed();
useEffect(() => {
let embedIframeWidth = 0;
setDate(date.tz(localStorage.getItem("timeOption.preferredTimeZone") || dayjs.tz.guess()));
setIs24h(!!localStorage.getItem("timeOption.is24hClock"));
if (isEmbed) {
requestAnimationFrame(function fixStripeIframe() {
// HACK: Look for stripe iframe and center position it just above the embed content
const stripeIframeWrapper = document.querySelector(
'iframe[src*="https://js.stripe.com/v3/authorize-with-url-inner"]'
)?.parentElement;
if (stripeIframeWrapper) {
stripeIframeWrapper.style.margin = "0 auto";
stripeIframeWrapper.style.width = embedIframeWidth + "px";
}
requestAnimationFrame(fixStripeIframe);
});
sdkActionManager?.on("__dimensionChanged", (e) => {
embedIframeWidth = e.detail.data.iframeWidth as number;
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isEmbed]);
const eventName = props.booking.title;
return (
<div className="h-screen">
<Head>
<title>
{t("payment")} | {eventName} | Cal.com
</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main className="mx-auto max-w-3xl py-24">
<div className="fixed inset-0 z-50 overflow-y-auto">
<div className="flex min-h-screen items-end justify-center px-4 pt-4 pb-20 text-center sm:block sm:p-0">
<div className="fixed inset-0 my-4 transition-opacity sm:my-0" aria-hidden="true">
<span className="hidden sm:inline-block sm:h-screen sm:align-middle" aria-hidden="true">
&#8203;
</span>
<div
className={classNames(
"main inline-block transform overflow-hidden rounded-lg border border-neutral-200 bg-white px-8 pt-5 pb-4 text-left align-bottom transition-all dark:border-neutral-700 dark:bg-gray-800 sm:w-full sm:max-w-lg sm:py-6 sm:align-middle",
isEmbed ? "" : "sm:my-8"
)}
role="dialog"
aria-modal="true"
aria-labelledby="modal-headline">
<div>
<div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-green-100">
<Icon.CreditCard className="h-8 w-8 text-green-600" />
</div>
<div className="mt-3 text-center sm:mt-5">
<h3
className="text-2xl font-semibold leading-6 text-neutral-900 dark:text-white"
id="modal-headline">
{t("payment")}
</h3>
<div className="mt-3">
<p className="text-sm text-neutral-600 dark:text-gray-300">
{t("pay_later_instructions")}
</p>
</div>
<div className="mt-4 grid grid-cols-3 border-t border-b py-4 text-left text-gray-700 dark:border-gray-900 dark:text-gray-300">
<div className="font-medium">{t("what")}</div>
<div className="col-span-2 mb-6">{eventName}</div>
<div className="font-medium">{t("when")}</div>
<div className="col-span-2 mb-6">
{date.format("dddd, DD MMMM YYYY")}
<br />
{date.format(is24h ? "H:mm" : "h:mma")} - {props.eventType.length} mins{" "}
<span className="text-gray-500">
({localStorage.getItem("timeOption.preferredTimeZone") || dayjs.tz.guess()})
</span>
</div>
{props.booking.location && (
<>
<div className="font-medium">{t("where")}</div>
<div className="col-span-2 mb-6">
{LocationOptionsToString(props.booking.location, t)}
</div>
</>
)}
<div className="font-medium">{t("price")}</div>
<div className="col-span-2 mb-6">
<IntlProvider locale="en">
<FormattedNumber
value={props.eventType.price / 100.0}
style="currency"
currency={props.eventType.currency.toUpperCase()}
/>
</IntlProvider>
</div>
</div>
</div>
</div>
<div>
{props.payment.success && !props.payment.refunded && (
<div className="mt-4 text-center text-gray-700 dark:text-gray-300">{t("paid")}</div>
)}
{!props.payment.success && (
<Elements stripe={getStripe(props.payment.data.stripe_publishable_key)}>
<PaymentComponent
payment={props.payment}
eventType={props.eventType}
user={props.user}
location={props.booking.location}
bookingId={props.booking.id}
/>
</Elements>
)}
{props.payment.refunded && (
<div className="mt-4 text-center text-gray-700 dark:text-gray-300">{t("refunded")}</div>
)}
</div>
{!props.profile.hideBranding && (
<div className="mt-4 border-t pt-4 text-center text-xs text-gray-400 dark:border-gray-900 dark:text-white">
<a href={`${WEBSITE_URL}/signup`}>{t("create_booking_link_with_calcom")}</a>
</div>
)}
</div>
</div>
</div>
</div>
</main>
</div>
);
};
export default PaymentPage;
@@ -0,0 +1,109 @@
import { GetServerSidePropsContext } from "next";
import { z } from "zod";
import { PaymentData } from "@calcom/app-store/stripepayment/lib/server";
import prisma from "@calcom/prisma";
import type { inferSSRProps } from "@calcom/types/inferSSRProps";
export type PaymentPageProps = inferSSRProps<typeof getServerSideProps>;
const querySchema = z.object({
uid: z.string(),
});
export const getServerSideProps = async (context: GetServerSidePropsContext) => {
const { uid } = querySchema.parse(context.query);
const rawPayment = await prisma.payment.findFirst({
where: {
uid,
},
select: {
data: true,
success: true,
uid: true,
refunded: true,
bookingId: true,
booking: {
select: {
id: true,
description: true,
title: true,
startTime: true,
attendees: {
select: {
email: true,
name: true,
},
},
eventTypeId: true,
location: true,
eventType: {
select: {
id: true,
title: true,
description: true,
length: true,
eventName: true,
requiresConfirmation: true,
userId: true,
users: {
select: {
name: true,
username: true,
hideBranding: true,
plan: true,
theme: true,
},
},
team: {
select: {
name: true,
hideBranding: true,
},
},
price: true,
currency: true,
},
},
},
},
},
});
if (!rawPayment) return { notFound: true };
const { data, booking: _booking, ...restPayment } = rawPayment;
const payment = {
...restPayment,
data: data as unknown as PaymentData,
};
if (!_booking) return { notFound: true };
const { startTime, eventType, ...restBooking } = _booking;
const booking = {
...restBooking,
startTime: startTime.toString(),
};
if (!eventType) return { notFound: true };
const [user] = eventType.users;
if (!user) return { notFound: true };
const profile = {
name: eventType.team?.name || user?.name || null,
theme: (!eventType.team?.name && user?.theme) || null,
hideBranding: eventType.team?.hideBranding || user?.hideBranding || null,
};
return {
props: {
user,
eventType,
booking,
payment,
profile,
},
};
};
@@ -0,0 +1,13 @@
import HelpscoutMenuItem from "../lib/helpscout/HelpscoutMenuItem";
import IntercomMenuItem from "../lib/intercom/IntercomMenuItem";
import ZendeskMenuItem from "../lib/zendesk/ZendeskMenuItem";
export default function HelpMenuItem() {
return (
<>
<IntercomMenuItem />
<ZendeskMenuItem />
<HelpscoutMenuItem />
</>
);
}
@@ -0,0 +1,224 @@
import { useState } from "react";
import { useChat } from "react-live-chat-loader";
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 Button from "@calcom/ui/Button";
import { Icon } from "@calcom/ui/Icon";
import ContactMenuItem from "./ContactMenuItem";
interface HelpMenuItemProps {
onHelpItemSelect: () => void;
}
export default function HelpMenuItem({ onHelpItemSelect }: HelpMenuItemProps) {
const [rating, setRating] = useState<null | string>(null);
const [comment, setComment] = useState("");
const [disableSubmit, setDisableSubmit] = useState(true);
const [active, setActive] = useState(false);
const [, loadChat] = useChat();
const { t } = useLocale();
const mutation = trpc.useMutation("viewer.submitFeedback", {
onSuccess: () => {
setDisableSubmit(true);
showToast("Thank you, feedback submitted", "success");
onHelpItemSelect();
},
});
const onRatingClick = (value: string) => {
setRating(value);
setDisableSubmit(false);
};
const sendFeedback = async (rating: string, comment: string) => {
mutation.mutate({ rating: rating, comment: comment });
};
return (
<div className="w-full border-gray-300 bg-white">
<div className="w-full py-5">
<p className="mb-1 px-5 text-neutral-500">{t("resources").toUpperCase()}</p>
<a
onClick={() => onHelpItemSelect()}
href="https://docs.cal.com/"
target="_blank"
className="flex w-full px-5 py-2 pr-4 text-sm font-medium text-gray-700 hover:bg-gray-100 hover:text-gray-900"
rel="noreferrer">
{t("support_documentation")}
<Icon.ExternalLink
className={classNames(
"text-neutral-400 group-hover:text-neutral-500",
"ml-1 h-5 w-5 flex-shrink-0 ltr:mr-3"
)}
/>
</a>
<a
onClick={() => onHelpItemSelect()}
href="https://developer.cal.com/"
target="_blank"
className="flex w-full px-5 py-2 pr-4 text-sm font-medium text-gray-700 hover:bg-gray-100 hover:text-gray-900"
rel="noreferrer">
{t("developer_documentation")}
<Icon.ExternalLink
className={classNames(
"text-neutral-400 group-hover:text-neutral-500",
"ml-1 h-5 w-5 flex-shrink-0 ltr:mr-3"
)}
/>
</a>
<div onClick={() => onHelpItemSelect()}>
<ContactMenuItem />
</div>
</div>
<hr className=" bg-gray-200" />
<div className="w-full p-5">
<p className="mb-1 text-neutral-500">{t("feedback").toUpperCase()}</p>
<p className="flex w-full py-2 text-sm font-medium text-gray-700">{t("comments")}</p>
<textarea
id="comment"
name="comment"
rows={3}
onChange={(event) => setComment(event.target.value)}
className="my-1 block w-full rounded-sm border-gray-300 py-2 pb-2 text-sm"
/>
<div className="my-3 flex justify-end">
<button
className={classNames(
"m-1 items-center justify-center p-1.5 grayscale hover:opacity-100 hover:grayscale-0",
rating === "Extremely unsatisfied" ? "grayscale-0" : "opacity-50"
)}
onClick={() => onRatingClick("Extremely unsatisfied")}>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" width="1.5em" height="1.5em">
<path
fill="#FFCC4D"
d="M36 18c0 9.941-8.059 18-18 18S0 27.941 0 18 8.059 0 18 0s18 8.059 18 18"
/>
<path
fill="#664500"
d="M22 27c0 2.763-1.791 3-4 3-2.21 0-4-.237-4-3 0-2.761 1.79-6 4-6 2.209 0 4 3.239 4 6zm8-12c-.124 0-.25-.023-.371-.072-5.229-2.091-7.372-5.241-7.461-5.374-.307-.46-.183-1.081.277-1.387.459-.306 1.077-.184 1.385.274.019.027 1.93 2.785 6.541 4.629.513.206.763.787.558 1.3-.157.392-.533.63-.929.63zM6 15c-.397 0-.772-.238-.929-.629-.205-.513.044-1.095.557-1.3 4.612-1.844 6.523-4.602 6.542-4.629.308-.456.929-.577 1.387-.27.457.308.581.925.275 1.383-.089.133-2.232 3.283-7.46 5.374C6.25 14.977 6.124 15 6 15z"
/>
<path fill="#5DADEC" d="M24 16h4v19l-4-.046V16zM8 35l4-.046V16H8v19z" />
<path
fill="#664500"
d="M14.999 18c-.15 0-.303-.034-.446-.105-3.512-1.756-7.07-.018-7.105 0-.495.249-1.095.046-1.342-.447-.247-.494-.047-1.095.447-1.342.182-.09 4.498-2.197 8.895 0 .494.247.694.848.447 1.342-.176.35-.529.552-.896.552zm14 0c-.15 0-.303-.034-.446-.105-3.513-1.756-7.07-.018-7.105 0-.494.248-1.094.047-1.342-.447-.247-.494-.047-1.095.447-1.342.182-.09 4.501-2.196 8.895 0 .494.247.694.848.447 1.342-.176.35-.529.552-.896.552z"
/>
<ellipse fill="#5DADEC" cx="18" cy="34" rx="18" ry="2" />
<ellipse fill="#E75A70" cx="18" cy="27" rx="3" ry="2" />
</svg>
</button>
<button
className={classNames(
"m-1 items-center justify-center p-1.5 grayscale hover:opacity-100 hover:grayscale-0",
rating === "Unsatisfied" ? "grayscale-0" : "opacity-50"
)}
onClick={() => onRatingClick("Unsatisfied")}>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" width="1.5em" height="1.5em">
<path
fill="#FFCC4D"
d="M36 18c0 9.941-8.059 18-18 18-9.94 0-18-8.059-18-18C0 8.06 8.06 0 18 0c9.941 0 18 8.06 18 18"
/>
<ellipse fill="#664500" cx="11.5" cy="14.5" rx="2.5" ry="3.5" />
<ellipse fill="#664500" cx="24.5" cy="14.5" rx="2.5" ry="3.5" />
<path
fill="#664500"
d="M8.665 27.871c.178.161.444.171.635.029.039-.029 3.922-2.9 8.7-2.9 4.766 0 8.662 2.871 8.7 2.9.191.142.457.13.635-.029.177-.16.217-.424.094-.628C27.3 27.029 24.212 22 18 22s-9.301 5.028-9.429 5.243c-.123.205-.084.468.094.628z"
/>
</svg>
</button>
<button
className={classNames(
"m-1 items-center justify-center p-1.5 grayscale hover:opacity-100 hover:grayscale-0",
rating === "Satisfied" ? "grayscale-0" : "opacity-50"
)}
onClick={() => onRatingClick("Satisfied")}>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" width="1.5em" height="1.5em">
<path
fill="#FFCC4D"
d="M36 18c0 9.941-8.059 18-18 18-9.94 0-18-8.059-18-18C0 8.06 8.06 0 18 0c9.941 0 18 8.06 18 18"
/>
<path
fill="#664500"
d="M28.457 17.797c-.06-.135-1.499-3.297-4.457-3.297-2.957 0-4.397 3.162-4.457 3.297-.092.207-.032.449.145.591.175.142.426.147.61.014.012-.009 1.262-.902 3.702-.902 2.426 0 3.674.881 3.702.901.088.066.194.099.298.099.11 0 .221-.037.312-.109.177-.142.238-.386.145-.594zm-12 0c-.06-.135-1.499-3.297-4.457-3.297-2.957 0-4.397 3.162-4.457 3.297-.092.207-.032.449.144.591.176.142.427.147.61.014.013-.009 1.262-.902 3.703-.902 2.426 0 3.674.881 3.702.901.088.066.194.099.298.099.11 0 .221-.037.312-.109.178-.142.237-.386.145-.594zM18 22c-3.623 0-6.027-.422-9-1-.679-.131-2 0-2 2 0 4 4.595 9 11 9 6.404 0 11-5 11-9 0-2-1.321-2.132-2-2-2.973.578-5.377 1-9 1z"
/>
<path fill="#FFF" d="M9 23s3 1 9 1 9-1 9-1-2 4-9 4-9-4-9-4z" />
</svg>
</button>
<button
className={classNames(
"m-1 items-center justify-center p-1.5 grayscale hover:opacity-100 hover:grayscale-0",
rating === "Extremely satisfied" ? "grayscale-0" : "opacity-50"
)}
onClick={() => onRatingClick("Extremely satisfied")}>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" width="1.5em" height="1.5em">
<path
fill="#FFCC4D"
d="M36 18c0 9.941-8.059 18-18 18S0 27.941 0 18 8.059 0 18 0s18 8.059 18 18"
/>
<path
fill="#664500"
d="M18 21c-3.623 0-6.027-.422-9-1-.679-.131-2 0-2 2 0 4 4.595 9 11 9 6.404 0 11-5 11-9 0-2-1.321-2.132-2-2-2.973.578-5.377 1-9 1z"
/>
<path fill="#FFF" d="M9 22s3 1 9 1 9-1 9-1-2 4-9 4-9-4-9-4z" />
<path
fill="#E95F28"
d="M15.682 4.413l-4.542.801L8.8.961C8.542.492 8.012.241 7.488.333c-.527.093-.937.511-1.019 1.039l-.745 4.797-4.542.801c-.535.094-.948.525-1.021 1.064s.211 1.063.703 1.297l4.07 1.932-.748 4.812c-.083.536.189 1.064.673 1.309.179.09.371.133.562.133.327 0 .65-.128.891-.372l3.512-3.561 4.518 2.145c.49.232 1.074.123 1.446-.272.372-.395.446-.984.185-1.459L13.625 9.73l3.165-3.208c.382-.387.469-.977.217-1.459-.254-.482-.793-.743-1.325-.65zm4.636 0l4.542.801L27.2.961c.258-.469.788-.72 1.312-.628.526.093.936.511 1.018 1.039l.745 4.797 4.542.801c.536.094.949.524 1.021 1.063s-.211 1.063-.703 1.297l-4.07 1.932.748 4.812c.083.536-.189 1.064-.673 1.309-.179.09-.371.133-.562.133-.327 0-.65-.128-.891-.372l-3.512-3.561-4.518 2.145c-.49.232-1.074.123-1.446-.272-.372-.395-.446-.984-.185-1.459l2.348-4.267-3.165-3.208c-.382-.387-.469-.977-.217-1.459.255-.482.794-.743 1.326-.65z"
/>
</svg>
</button>
</div>
<div className="my-2 flex justify-end">
<Button
disabled={disableSubmit}
loading={mutation.isLoading}
onClick={async () => {
if (rating && comment) {
await sendFeedback(rating, comment);
}
}}>
{t("submit")}
</Button>
</div>
{mutation.isError && (
<div className="mb-4 flex bg-red-100 p-4 text-sm text-red-700">
<div className="flex-shrink-0">
<Icon.AlertTriangle className="h-5 w-5" />
</div>
<div className="ml-3 flex-grow">
<p className="font-medium">{t("feedback_error")}</p>
<p>{t("please_try_again")}</p>
</div>
</div>
)}
</div>
<div className="w-full bg-neutral-50 p-5 text-neutral-500">
<p className="">{t("specific_issue")}</p>
<button
className="font-medium underline hover:text-neutral-700"
onClick={() => {
setActive(true);
loadChat({ open: true });
onHelpItemSelect();
}}>
{t("contact_support")}
</button>
<span> {t("or").toLowerCase()} </span>
<a
onClick={() => onHelpItemSelect()}
className="font-medium underline hover:text-neutral-700"
href="https://docs.cal.com/"
target="_blank"
rel="noreferrer">
{t("browse_our_docs")}
</a>
.
</div>
</div>
);
}
@@ -0,0 +1,30 @@
import { useState } from "react";
import { HelpScout, useChat } from "react-live-chat-loader";
import { useLocale } from "@calcom/lib/hooks/useLocale";
export default function HelpscoutMenuItem() {
const { t } = useLocale();
const [active, setActive] = useState(false);
const [, loadChat] = useChat();
function handleClick() {
setActive(true);
loadChat({ open: true });
}
if (!process.env.NEXT_PUBLIC_HELPSCOUT_KEY) return null;
else
return (
<>
<button
onClick={handleClick}
className="flex w-full px-5 py-2 pr-4 text-sm font-medium text-gray-700 hover:bg-gray-100 hover:text-gray-900">
{t("contact_support")}
</button>
{active && <HelpScout color="#292929" icon="message" horizontalPosition="right" zIndex="1" />}
</>
);
}
@@ -0,0 +1,10 @@
import { FC } from "react";
import { LiveChatLoaderProvider } from "react-live-chat-loader";
const Provider: FC<{ children: React.ReactNode }> = ({ children }) => (
<LiveChatLoaderProvider providerKey={process.env.NEXT_PUBLIC_HELPSCOUT_KEY || ""} provider="helpScout">
<>{children}</>
</LiveChatLoaderProvider>
);
export default Provider;
@@ -0,0 +1,8 @@
import dynamic from "next/dynamic";
import { Fragment } from "react";
const DynamicHelpscoutProvider = process.env.NEXT_PUBLIC_HELPSCOUT_KEY
? dynamic(() => import("./provider"))
: Fragment;
export default DynamicHelpscoutProvider;
@@ -0,0 +1,20 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { useIntercom } from "./useIntercom";
export default function IntercomMenuItem() {
const { t } = useLocale();
const { boot, show } = useIntercom();
if (!process.env.NEXT_PUBLIC_INTERCOM_APP_ID) return null;
else
return (
<button
onClick={() => {
boot();
show();
}}
className="flex w-full px-5 py-2 pr-4 text-sm font-medium text-gray-700 hover:bg-gray-100 hover:text-gray-900">
{t("contact_support")}
</button>
);
}
@@ -0,0 +1,8 @@
import { FC } from "react";
import { IntercomProvider } from "react-use-intercom";
const Provider: FC<{ children: React.ReactNode }> = ({ children }) => (
<IntercomProvider appId={process.env.NEXT_PUBLIC_INTERCOM_APP_ID || ""}>{children}</IntercomProvider>
);
export default Provider;
@@ -0,0 +1,8 @@
import dynamic from "next/dynamic";
import { Fragment } from "react";
const DynamicIntercomProvider = process.env.NEXT_PUBLIC_INTERCOM_APP_ID
? dynamic(() => import("./provider"))
: Fragment;
export default DynamicIntercomProvider;
@@ -0,0 +1,12 @@
import noop from "lodash/noop";
import { useIntercom as _useIntercom } from "react-use-intercom";
export const useIntercom =
typeof window !== "undefined" && !!process.env.NEXT_PUBLIC_INTERCOM_APP_ID
? _useIntercom
: () => ({
boot: noop,
show: noop,
});
export default useIntercom;
@@ -0,0 +1,26 @@
import Script from "next/script";
import { useState } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
const ZENDESK_KEY = process.env.NEXT_PUBLIC_ZENDESK_KEY;
export default function ZendeskMenuItem() {
const [active, setActive] = useState(false);
const { t } = useLocale();
if (!process.env.NEXT_PUBLIC_ZENDESK_KEY) return null;
else
return (
<>
<button
onClick={() => setActive(true)}
className="flex w-full px-5 py-2 pr-4 text-sm font-medium text-gray-700 hover:bg-gray-100 hover:text-gray-900">
{t("contact_support")}
</button>
{active && (
<Script id="ze-snippet" src={"https://static.zdassets.com/ekr/snippet.js?key=" + ZENDESK_KEY} />
)}
</>
);
}
+20
View File
@@ -0,0 +1,20 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { upgradeTeam } from "@calcom/app-store/stripepayment/lib/team-billing";
import { getSession } from "@calcom/lib/auth";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === "GET") {
const session = await getSession({ req });
if (!session) {
res.status(401).json({ message: "You must be logged in to do this" });
return;
}
await upgradeTeam(session.user.id, Number(req.query.team));
// redirect to team screen
res.redirect(302, `${process.env.NEXT_PUBLIC_WEBAPP_URL}/settings/teams/${req.query.team}?upgraded=true`);
}
}
@@ -0,0 +1,95 @@
import React, { useState, useEffect } from "react";
import dayjs from "@calcom/dayjs";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { inferQueryOutput, trpc } from "@calcom/trpc/react";
import Select from "@calcom/ui/form/Select";
import TimezoneSelect, { ITimezone } from "@calcom/ui/form/TimezoneSelect";
import { Avatar } from "@calcom/ui/v2";
import DatePicker from "@calcom/ui/v2/form/DatePicker";
import LicenseRequired from "../../common/components/LicenseRequired";
import TeamAvailabilityTimes from "./TeamAvailabilityTimes";
interface Props {
team?: inferQueryOutput<"viewer.teams.get">;
member?: inferQueryOutput<"viewer.teams.get">["members"][number];
}
export default function TeamAvailabilityModal(props: Props) {
const utils = trpc.useContext();
const [selectedDate, setSelectedDate] = useState(dayjs());
const [selectedTimeZone, setSelectedTimeZone] = useState<ITimezone>(
localStorage.getItem("timeOption.preferredTimeZone") || dayjs.tz.guess()
);
const [frequency, setFrequency] = useState<15 | 30 | 60>(30);
useEffect(() => {
utils.invalidateQueries(["viewer.teams.getMemberAvailability"]);
}, [utils, selectedTimeZone, selectedDate]);
return (
<LicenseRequired>
<div className="flex max-h-[500px] min-h-[500px] flex-row space-x-8 rtl:space-x-reverse">
<div className="min-w-64 w-64 space-y-5 p-5 pr-0">
<div className="flex">
<Avatar
size="sm"
imageSrc={WEBAPP_URL + "/" + props.member?.username + "/avatar.png"}
alt={props.member?.name || ""}
className="h-14 w-14 rounded-full"
/>
<div className="ml-3 inline-block pt-1">
<span className="text-lg font-bold text-neutral-700">{props.member?.name}</span>
<span className="-mt-1 block text-sm text-gray-400">{props.member?.email}</span>
</div>
</div>
<div className="flex flex-col">
<span className="font-bold text-gray-600">Date</span>
<DatePicker
date={selectedDate.toDate()}
onDatesChange={(newDate) => {
setSelectedDate(dayjs(newDate));
}}
/>
</div>
<div>
<span className="font-bold text-gray-600">Timezone</span>
<TimezoneSelect
id="timeZone"
value={selectedTimeZone}
onChange={(timezone) => setSelectedTimeZone(timezone.value)}
classNamePrefix="react-select"
className="react-select-container mt-1 block w-full rounded-sm border border-gray-300 text-sm focus:border-neutral-800 focus:ring-neutral-800"
/>
</div>
<div>
<span className="font-bold text-gray-600">Slot Length</span>
<Select
options={[
{ value: 15, label: "15 minutes" },
{ value: 30, label: "30 minutes" },
{ value: 60, label: "60 minutes" },
]}
isSearchable={false}
classNamePrefix="react-select"
className="react-select-container focus:ring-primary-500 focus:border-primary-500 block w-full min-w-0 flex-1 rounded-sm border border-gray-300 text-sm"
value={{ value: frequency, label: `${frequency} minutes` }}
onChange={(newFrequency) => setFrequency(newFrequency?.value ?? 30)}
/>
</div>
</div>
{props.team && props.member && (
<TeamAvailabilityTimes
className="overflow-scroll"
teamId={props.team.id}
memberId={props.member.id}
frequency={frequency}
selectedDate={selectedDate}
selectedTimeZone={selectedTimeZone}
/>
)}
</div>
</LicenseRequired>
);
}
@@ -0,0 +1,118 @@
import React, { useState, useEffect, CSSProperties } from "react";
import AutoSizer from "react-virtualized-auto-sizer";
import { FixedSizeList as List } from "react-window";
import dayjs from "@calcom/dayjs";
import { CAL_URL } from "@calcom/lib/constants";
import { inferQueryOutput, trpc } from "@calcom/trpc/react";
import Select from "@calcom/ui/form/Select";
import TimezoneSelect, { ITimezone } from "@calcom/ui/form/TimezoneSelect";
import Avatar from "@calcom/ui/v2/Avatar";
import DatePicker from "@calcom/ui/v2/form/DatePicker";
import TeamAvailabilityTimes from "./TeamAvailabilityTimes";
interface Props {
team?: inferQueryOutput<"viewer.teams.get">;
}
export default function TeamAvailabilityScreen(props: Props) {
const utils = trpc.useContext();
const [selectedDate, setSelectedDate] = useState(dayjs());
const [selectedTimeZone, setSelectedTimeZone] = useState<ITimezone>(
localStorage.getItem("timeOption.preferredTimeZone") || dayjs.tz.guess()
);
const [frequency, setFrequency] = useState<15 | 30 | 60>(30);
useEffect(() => {
utils.invalidateQueries(["viewer.teams.getMemberAvailability"]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedTimeZone, selectedDate]);
const Item = ({ index, style }: { index: number; style: CSSProperties }) => {
const member = props.team?.members?.[index];
if (!member) return <></>;
return (
<div key={member.id} style={style} className="flex border-r border-gray-200 pl-4 ">
<TeamAvailabilityTimes
teamId={props.team?.id as number}
memberId={member.id}
frequency={frequency}
selectedDate={selectedDate}
selectedTimeZone={selectedTimeZone}
HeaderComponent={
<div className="mb-6 flex items-center">
<Avatar
size="sm"
imageSrc={CAL_URL + "/" + member.username + "/avatar.png"}
alt={member?.name || ""}
className="min-w-10 min-h-10 mt-1 h-10 w-10 rounded-full"
/>
<div className="ml-3 inline-block overflow-hidden pt-1">
<span className="truncate text-lg font-bold text-neutral-700">{member?.name}</span>
<span className="-mt-1 block truncate text-sm text-gray-400">{member?.email}</span>
</div>
</div>
}
/>
</div>
);
};
return (
<div className="flex flex-1 flex-col rounded-sm border border-neutral-200 bg-white">
<div className="flex w-full space-x-5 border-b border-gray-200 p-4 rtl:space-x-reverse">
<div className="flex flex-col">
<span className="text-sm font-medium text-neutral-700">Date</span>
<DatePicker
date={selectedDate.toDate()}
className="p-1.5"
onDatesChange={(newDate) => {
setSelectedDate(dayjs(newDate));
}}
/>
</div>
<div className="flex flex-col">
<span className="text-sm font-medium text-neutral-700">Timezone</span>
<TimezoneSelect
id="timeZone"
value={selectedTimeZone}
onChange={(timezone) => setSelectedTimeZone(timezone.value)}
classNamePrefix="react-select"
className="react-select-container w-full rounded-sm border border-gray-300 text-sm"
/>
</div>
<div className="hidden sm:block">
<span className="text-sm font-medium text-neutral-700">Slot Length</span>
<Select
options={[
{ value: 15, label: "15 minutes" },
{ value: 30, label: "30 minutes" },
{ value: 60, label: "60 minutes" },
]}
isSearchable={false}
className="block w-full min-w-0 flex-1 rounded-sm border border-gray-300 text-sm"
value={{ value: frequency, label: `${frequency} minutes` }}
onChange={(newFrequency) => setFrequency(newFrequency?.value ?? 30)}
/>
</div>
</div>
<div className="flex h-full flex-1">
<AutoSizer>
{({ height, width }) => (
<List
itemSize={240}
itemCount={props.team?.members?.length ?? 0}
className="List"
height={height}
layout="horizontal"
width={width}>
{Item}
</List>
)}
</AutoSizer>
</div>
</div>
);
}
@@ -0,0 +1,67 @@
import classNames from "classnames";
import React from "react";
import { ITimezone } from "react-timezone-select";
import { Dayjs } from "@calcom/dayjs";
import getSlots from "@calcom/lib/slots";
import { trpc } from "@calcom/trpc/react";
import Loader from "@calcom/ui/Loader";
interface Props {
teamId: number;
memberId: number;
selectedDate: Dayjs;
selectedTimeZone: ITimezone;
frequency: number;
HeaderComponent?: React.ReactNode;
className?: string;
}
export default function TeamAvailabilityTimes(props: Props) {
const { data, isLoading } = trpc.useQuery(
[
"viewer.teams.getMemberAvailability",
{
teamId: props.teamId,
memberId: props.memberId,
dateFrom: props.selectedDate.toString(),
dateTo: props.selectedDate.add(1, "day").toString(),
timezone: `${props.selectedTimeZone.toString()}`,
},
],
{
refetchOnWindowFocus: false,
}
);
const times = !isLoading
? getSlots({
frequency: props.frequency,
inviteeDate: props.selectedDate,
workingHours: data?.workingHours || [],
minimumBookingNotice: 0,
eventLength: props.frequency,
})
: [];
return (
<div className={classNames("min-w-60 flex-grow p-5 pl-0", props.className)}>
{props.HeaderComponent}
{isLoading && times.length === 0 && <Loader />}
{!isLoading && times.length === 0 && (
<div className="flex flex-col items-center justify-center pt-4">
<span className="text-sm text-gray-500">No Available Slots</span>
</div>
)}
{times.map((time) => (
<div key={time.format()} className="flex flex-row items-center">
<a
className="min-w-48 border-brand text-bookingdarker hover:bg-brand hover:text-brandcontrast dark:hover:bg-darkmodebrand dark:hover:text-darkmodebrandcontrast mb-2 mr-3 block flex-grow rounded-sm border bg-white py-2 text-center font-medium dark:border-transparent dark:bg-gray-600 dark:text-neutral-200 dark:hover:border-black dark:hover:bg-black dark:hover:text-white"
data-testid="time">
{time.format("HH:mm")}
</a>
</div>
))}
</div>
);
}
@@ -0,0 +1,67 @@
import { useRouter } from "next/router";
import { useMemo, useState } from "react";
import { getPlaceholderAvatar } from "@calcom/lib/getPlaceholderAvatar";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
import { Alert } from "@calcom/ui/Alert";
import Loader from "@calcom/ui/Loader";
import Shell from "@calcom/ui/Shell";
import { Avatar } from "@calcom/ui/v2";
import LicenseRequired from "../../common/components/LicenseRequired";
import TeamAvailabilityScreen from "../components/TeamAvailabilityScreen";
export function TeamAvailabilityPage() {
const { t } = useLocale();
const router = useRouter();
const [errorMessage, setErrorMessage] = useState("");
const me = useMeQuery();
const isFreeUser = me.data?.plan === "FREE";
const { data: team, isLoading } = trpc.useQuery(["viewer.teams.get", { teamId: Number(router.query.id) }], {
refetchOnWindowFocus: false,
onError: (e) => {
setErrorMessage(e.message);
},
});
// prevent unnecessary re-renders due to shell queries
const TeamAvailability = useMemo(() => {
return <TeamAvailabilityScreen team={team} />;
}, [team]);
return (
<Shell
backPath={!errorMessage ? `/settings/teams/${team?.id}` : undefined}
heading={!isFreeUser && team?.name}
flexChildrenContainer
subtitle={team && !isFreeUser && "Your team's availability at a glance"}
HeadingLeftIcon={
team &&
!isFreeUser && (
<Avatar
size="sm"
imageSrc={getPlaceholderAvatar(team?.logo, team?.name as string)}
alt="Team Logo"
className="mt-1"
/>
)
}>
<LicenseRequired>
{!!errorMessage && <Alert className="-mt-24 border" severity="error" title={errorMessage} />}
{isLoading && <Loader />}
{isFreeUser ? (
<Alert className="-mt-24 border" severity="warning" title={t("pro_feature_teams")} />
) : (
TeamAvailability
)}
</LicenseRequired>
</Shell>
);
}
export default TeamAvailabilityPage;
@@ -0,0 +1,9 @@
[
{
"inputs": [{ "internalType": "address", "name": "owner", "type": "address" }],
"name": "balanceOf",
"outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
"stateMutability": "view",
"type": "function"
}
]
@@ -0,0 +1,143 @@
import Router from "next/router";
import React, { useCallback, useMemo, useState } from "react";
import Web3 from "web3";
import type { AbstractProvider } from "web3-core";
import { AbiItem } from "web3-utils";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import showToast from "@calcom/lib/notification";
import { Button } from "@calcom/ui/Button";
import { withLicenseRequired } from "../../common/components/LicenseRequired";
import genericAbi from "../abis/abiWithGetBalance.json";
import { useContracts } from "../contexts/contractsContext";
import verifyAccount, { AUTH_MESSAGE } from "../utils/verifyAccount";
interface Window {
ethereum: AbstractProvider & { selectedAddress: string };
web3: Web3;
}
interface EvtsToVerify {
[eventId: string]: boolean;
}
declare const window: Window;
export interface CryptoSectionProps {
id: number | string;
pathname: string;
smartContractAddress: string;
/** When set to true, there will be only 1 button which will both connect Metamask and verify the user's wallet. Otherwise, it will be in 2 steps with 2 buttons. */
oneStep: boolean;
verified: boolean | undefined;
setEvtsToVerify: React.Dispatch<React.SetStateAction<Record<number | string, boolean>>>;
}
const CryptoSection = (props: CryptoSectionProps) => {
// Crypto section which should be shown on booking page if event type requires a smart contract token.
const [ethEnabled, toggleEthEnabled] = useState<boolean>(false);
const { addContract } = useContracts();
const { t } = useLocale();
const connectMetamask = useCallback(async () => {
if (window.ethereum && typeof window.ethereum.request === "function") {
await window.ethereum.request({ method: "eth_requestAccounts" });
window.web3 = new Web3(window.ethereum);
toggleEthEnabled(true);
} else {
toggleEthEnabled(false);
}
}, []);
const verifyWallet = useCallback(async () => {
try {
if (!window.web3) throw new Error("MetaMask browser extension is not installed");
const contract = new window.web3.eth.Contract(genericAbi as AbiItem[], props.smartContractAddress);
const balance = await contract.methods.balanceOf(window.ethereum.selectedAddress).call();
const hasToken = balance > 0;
if (!hasToken)
throw new Error("Specified wallet does not own any tokens belonging to this smart contract");
const [account] = await window.web3.eth.getAccounts();
const signature = await window.web3.eth.personal.sign(AUTH_MESSAGE, account, "");
addContract({ address: props.smartContractAddress, signature });
await verifyAccount(signature, account);
props.setEvtsToVerify((prevState: EvtsToVerify) => ({ ...prevState, [props.id]: hasToken }));
} catch (err) {
const message = err instanceof Error ? err.message : "An error has occurred";
showToast(message, "error");
}
}, [props, addContract]);
// @TODO: Show error on either of buttons if fails. Yup schema already contains the error message.
const successButton = useMemo(() => {
if (props.verified) {
Router.push(props.pathname);
}
return <div />;
}, [props.pathname, props.verified]);
const verifyButton = useMemo(() => {
return (
<Button color="secondary" onClick={verifyWallet} type="button" id="hasToken">
<img className="mr-1 h-5" src="/api/app-store/metamask/icon.svg" alt="MetaMask" />
{t("verify_wallet")}
</Button>
);
}, [verifyWallet, t]);
const connectButton = useMemo(() => {
return (
<Button color="secondary" onClick={connectMetamask} type="button">
{
// eslint-disable-next-line @next/next/no-img-element
<img className="mr-1 h-5" src="/api/app-store/metamask/icon.svg" alt="MetaMask" />
}
{t("connect_metamask")}
</Button>
);
}, [connectMetamask, t]);
const oneStepButton = useMemo(() => {
return (
<Button
color="secondary"
type="button"
onClick={async () => {
await connectMetamask();
await verifyWallet();
}}>
{
// eslint-disable-next-line @next/next/no-img-element
<img className="mr-1 h-5" src="/api/app-store/metamask/icon.svg" alt="MetaMask" />
}
{t("verify_wallet")}
</Button>
);
}, [connectMetamask, verifyWallet, t]);
const determineButton = useCallback(() => {
// Did it in an extra function for some added readability, but this can be done in a ternary depending on preference
if (props.oneStep) {
return props.verified ? successButton : oneStepButton;
} else {
if (ethEnabled) {
return props.verified ? successButton : verifyButton;
} else {
return connectButton;
}
}
}, [props.verified, successButton, oneStepButton, connectButton, ethEnabled, props.oneStep, verifyButton]);
return (
<div
className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 transform opacity-0 transition-opacity group-hover:opacity-100 dark:bg-gray-900"
id={`crypto-${props.id}`}>
{determineButton()}
</div>
);
};
export default withLicenseRequired(CryptoSection);
@@ -0,0 +1,48 @@
import noop from "lodash/noop";
import { createContext, ReactNode, useContext } from "react";
import { localStorage } from "@calcom/lib/webstorage";
type contractsContextType = {
contracts: Record<string, string>;
addContract: (payload: addContractsPayload) => void;
};
const contractsContextDefaultValue: contractsContextType = {
contracts: {},
addContract: noop,
};
const ContractsContext = createContext<contractsContextType>(contractsContextDefaultValue);
export function useContracts() {
return useContext(ContractsContext);
}
type Props = {
children: ReactNode;
};
interface addContractsPayload {
address: string;
signature: string;
}
export function ContractsProvider({ children }: Props) {
const addContract = (payload: addContractsPayload) => {
localStorage.setItem(
"contracts",
JSON.stringify({
...JSON.parse(localStorage.getItem("contracts") || "{}"),
[payload.address]: payload.signature,
})
);
};
const value = {
contracts: typeof window !== "undefined" ? JSON.parse(localStorage.getItem("contracts") || "{}") : {},
addContract,
};
return <ContractsContext.Provider value={value}>{children}</ContractsContext.Provider>;
}
@@ -0,0 +1,12 @@
import Web3 from "web3";
export const AUTH_MESSAGE =
"I authorize the use of my Ethereum address for the purposes of this application.";
const verifyAccount = async (signature: string, address: string) => {
const web3 = new Web3();
const signingAddress = await web3.eth.accounts.recover(AUTH_MESSAGE, signature);
if (!(address.toLowerCase() === signingAddress.toLowerCase())) throw new Error("Failed to verify address");
};
export default verifyAccount;
@@ -0,0 +1,138 @@
/* Schedule any workflow reminder that falls within 72 hours for email */
import { WorkflowActions, WorkflowMethods, WorkflowTemplates } from "@prisma/client";
import client from "@sendgrid/client";
import sgMail from "@sendgrid/mail";
import type { NextApiRequest, NextApiResponse } from "next";
import dayjs from "@calcom/dayjs";
import { defaultHandler } from "@calcom/lib/server";
import prisma from "@calcom/prisma";
import emailReminderTemplate from "../lib/reminders/templates/emailReminderTemplate";
const sendgridAPIKey = process.env.SENDGRID_API_KEY as string;
const senderEmail = process.env.SENDGRID_EMAIL as string;
sgMail.setApiKey(sendgridAPIKey);
async function handler(req: NextApiRequest, res: NextApiResponse) {
const apiKey = req.headers.authorization || req.query.apiKey;
if (process.env.CRON_API_KEY !== apiKey) {
res.status(401).json({ message: "Not authenticated" });
return;
}
if (!process.env.SENDGRID_API_KEY || !process.env.SENDGRID_EMAIL) {
res.status(405).json({ message: "No SendGrid API key or email" });
return;
}
const batchIdResponse = await client.request({
url: "/v3/mail/batch",
method: "POST",
});
//delete all scheduled email reminders where scheduled is past current date
await prisma.workflowReminder.deleteMany({
where: {
method: WorkflowMethods.EMAIL,
scheduledDate: {
lte: dayjs().toISOString(),
},
},
});
//find all unscheduled Email reminders
const unscheduledReminders = await prisma.workflowReminder.findMany({
where: {
method: WorkflowMethods.EMAIL,
scheduled: false,
},
include: {
workflowStep: true,
booking: {
include: {
eventType: true,
user: true,
attendees: true,
},
},
},
});
if (!unscheduledReminders.length) res.json({ ok: true });
const dateInSeventyTwoHours = dayjs().add(72, "hour");
unscheduledReminders.forEach(async (reminder) => {
if (dayjs(reminder.scheduledDate).isBefore(dateInSeventyTwoHours)) {
try {
const sendTo =
reminder.workflowStep.action === WorkflowActions.EMAIL_HOST
? reminder.booking?.user?.email
: reminder.booking?.attendees[0].email;
const name =
reminder.workflowStep.action === WorkflowActions.EMAIL_ATTENDEE
? reminder.booking?.attendees[0].name
: reminder.booking?.user?.name;
const attendeeName =
reminder.workflowStep.action === WorkflowActions.EMAIL_ATTENDEE
? reminder.booking?.user?.name
: reminder.booking?.attendees[0].name;
const timeZone =
reminder.workflowStep.action === WorkflowActions.EMAIL_ATTENDEE
? reminder.booking?.attendees[0].timeZone
: reminder.booking?.user?.timeZone;
let emailContent = {
emailSubject: reminder.workflowStep.emailSubject || "",
emailBody: {
text: reminder.workflowStep.reminderBody || "",
html: `<body style="white-space: pre-wrap;">${reminder.workflowStep.reminderBody || ""}</body>`,
},
};
switch (reminder.workflowStep.template) {
case WorkflowTemplates.REMINDER:
emailContent = emailReminderTemplate(
reminder.booking?.startTime.toISOString() || "",
reminder.booking?.eventType?.title || "",
timeZone || "",
attendeeName || "",
name || ""
);
break;
}
if (emailContent.emailSubject.length > 0 && emailContent.emailBody.text.length > 0 && sendTo) {
await sgMail.send({
to: sendTo,
from: senderEmail,
subject: emailContent.emailSubject,
text: emailContent.emailBody.text,
html: emailContent.emailBody.html,
batchId: batchIdResponse[1].batch_id,
sendAt: dayjs(reminder.scheduledDate).unix(),
});
}
await prisma.workflowReminder.updateMany({
where: {
id: reminder.id,
},
data: {
scheduled: true,
referenceId: batchIdResponse[1].batch_id,
},
});
} catch (error) {
console.log(`Error scheduling Email with error ${error}`);
}
}
});
}
export default defaultHandler({
POST: Promise.resolve({ default: handler }),
});
@@ -0,0 +1,108 @@
/* Schedule any workflow reminder that falls within 7 days for SMS */
import { WorkflowActions, WorkflowMethods, WorkflowTemplates } from "@prisma/client";
import type { NextApiRequest, NextApiResponse } from "next";
import dayjs from "@calcom/dayjs";
import { defaultHandler } from "@calcom/lib/server";
import prisma from "@calcom/prisma";
import * as twilio from "../lib/reminders/smsProviders/twilioProvider";
import smsReminderTemplate from "../lib/reminders/templates/smsReminderTemplate";
async function handler(req: NextApiRequest, res: NextApiResponse) {
const apiKey = req.headers.authorization || req.query.apiKey;
if (process.env.CRON_API_KEY !== apiKey) {
res.status(401).json({ message: "Not authenticated" });
return;
}
//delete all scheduled sms reminders where scheduled date is past current date
await prisma.workflowReminder.deleteMany({
where: {
method: WorkflowMethods.SMS,
scheduledDate: {
lte: dayjs().toISOString(),
},
},
});
//find all unscheduled SMS reminders
const unscheduledReminders = await prisma.workflowReminder.findMany({
where: {
method: WorkflowMethods.SMS,
scheduled: false,
},
include: {
workflowStep: true,
booking: {
include: {
eventType: true,
user: true,
attendees: true,
},
},
},
});
if (!unscheduledReminders.length) res.json({ ok: true });
const dateInSevenDays = dayjs().add(7, "day");
unscheduledReminders.forEach(async (reminder) => {
if (dayjs(reminder.scheduledDate).isBefore(dateInSevenDays)) {
try {
const sendTo =
reminder.workflowStep.action === WorkflowActions.SMS_NUMBER
? reminder.workflowStep.sendTo
: reminder.booking?.smsReminderNumber;
const userName =
reminder.workflowStep.action === WorkflowActions.SMS_ATTENDEE
? reminder.booking?.attendees[0].name
: "";
const attendeeName =
reminder.workflowStep.action === WorkflowActions.SMS_ATTENDEE
? reminder.booking?.user?.name
: reminder.booking?.attendees[0].name;
const timeZone =
reminder.workflowStep.action === WorkflowActions.SMS_ATTENDEE
? reminder.booking?.attendees[0].timeZone
: reminder.booking?.user?.timeZone;
let message: string | null = reminder.workflowStep.reminderBody;
switch (reminder.workflowStep.template) {
case WorkflowTemplates.REMINDER:
message = smsReminderTemplate(
reminder.booking?.startTime.toISOString() || "",
reminder.booking?.eventType?.title || "",
timeZone || "",
attendeeName || "",
userName
);
break;
}
if (message?.length && message?.length > 0 && sendTo) {
const scheduledSMS = await twilio.scheduleSMS(sendTo, message, reminder.scheduledDate);
await prisma.workflowReminder.updateMany({
where: {
id: reminder.id,
},
data: {
scheduled: true,
referenceId: scheduledSMS.sid,
},
});
}
} catch (error) {
console.log(`Error scheduling SMS with error ${error}`);
}
}
});
}
export default defaultHandler({
POST: Promise.resolve({ default: handler }),
});
@@ -0,0 +1,140 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { WorkflowActions } from "@prisma/client";
import { isValidPhoneNumber } from "libphonenumber-js";
import { Dispatch, SetStateAction, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { z } from "zod";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import Button from "@calcom/ui/Button";
import { Dialog, DialogClose, DialogContent, DialogFooter, DialogHeader } from "@calcom/ui/Dialog";
import PhoneInput from "@calcom/ui/form/PhoneInputLazy";
import Select from "@calcom/ui/form/Select";
import { Form } from "@calcom/ui/form/fields";
import { WORKFLOW_ACTIONS } from "../lib/constants";
import { getWorkflowActionOptions } from "../lib/getOptions";
interface IAddActionDialog {
isOpenDialog: boolean;
setIsOpenDialog: Dispatch<SetStateAction<boolean>>;
addAction: (action: WorkflowActions, sendTo?: string) => void;
}
type AddActionFormValues = {
action: WorkflowActions;
sendTo?: string;
};
export const AddActionDialog = (props: IAddActionDialog) => {
const { t } = useLocale();
const { isOpenDialog, setIsOpenDialog, addAction } = props;
const [isPhoneNumberNeeded, setIsPhoneNumberNeeded] = useState(false);
const actionOptions = getWorkflowActionOptions(t);
const formSchema = z.object({
action: z.enum(WORKFLOW_ACTIONS),
sendTo: z
.string()
.refine((val) => isValidPhoneNumber(val))
.optional(),
});
const form = useForm<AddActionFormValues>({
mode: "onSubmit",
defaultValues: {
action: WorkflowActions.EMAIL_HOST,
},
resolver: zodResolver(formSchema),
});
return (
<Dialog open={isOpenDialog} onOpenChange={setIsOpenDialog}>
<DialogContent>
<div className="space-x-3 ">
<div className="pt-1">
<DialogHeader title={t("add_action")} />
<Form
form={form}
handleSubmit={(values) => {
addAction(values.action, values.sendTo);
form.unregister("sendTo");
form.unregister("action");
setIsOpenDialog(false);
setIsPhoneNumberNeeded(false);
}}>
<div className="space-y-1">
<label htmlFor="label" className="mt-5 block text-sm font-medium text-gray-700">
{t("action")}:
</label>
<Controller
name="action"
control={form.control}
render={() => {
return (
<Select
isSearchable={false}
className="block w-full min-w-0 flex-1 rounded-sm text-sm"
defaultValue={actionOptions[0]}
onChange={(val) => {
if (val) {
form.setValue("action", val.value);
if (val.value === WorkflowActions.SMS_NUMBER) {
setIsPhoneNumberNeeded(true);
} else {
setIsPhoneNumberNeeded(false);
form.unregister("sendTo");
}
form.clearErrors("action");
}
}}
options={actionOptions}
/>
);
}}
/>
{form.formState.errors.action && (
<p className="mt-1 text-sm text-red-500">{form.formState.errors.action.message}</p>
)}
</div>
{isPhoneNumberNeeded && (
<div className="mt-5 space-y-1">
<label htmlFor="sendTo" className="block text-sm font-medium text-gray-700 dark:text-white">
{t("phone_number")}
</label>
<div className="mt-1">
<PhoneInput<AddActionFormValues>
control={form.control}
name="sendTo"
placeholder={t("enter_phone_number")}
id="sendTo"
required
/>
{form.formState.errors.sendTo && (
<p className="mt-1 text-sm text-red-500">{form.formState.errors.sendTo.message}</p>
)}
</div>
</div>
)}
<DialogFooter>
<DialogClose asChild>
<Button
color="secondary"
onClick={() => {
setIsOpenDialog(false);
form.unregister("sendTo");
form.unregister("action");
setIsPhoneNumberNeeded(false);
}}>
{t("cancel")}
</Button>
</DialogClose>
<Button type="submit">{t("add")}</Button>
</DialogFooter>
</Form>
</div>
</div>
</DialogContent>
</Dialog>
);
};
@@ -0,0 +1,253 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { TimeUnit, WorkflowActions, WorkflowTriggerEvents } from "@prisma/client";
import { isValidPhoneNumber } from "libphonenumber-js";
import { useRouter } from "next/router";
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { z } from "zod";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { HttpError } from "@calcom/lib/http-error";
import showToast from "@calcom/lib/notification";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui";
import { Dialog, DialogClose, DialogContent, DialogTrigger } from "@calcom/ui/Dialog";
import { Icon } from "@calcom/ui/Icon";
import PhoneInput from "@calcom/ui/form/PhoneInputLazy";
import Select from "@calcom/ui/form/Select";
import { Form, TextField } from "@calcom/ui/form/fields";
import { TIME_UNIT, WORKFLOW_ACTIONS, WORKFLOW_TRIGGER_EVENTS } from "../lib/constants";
import {
getWorkflowActionOptions,
getWorkflowTimeUnitOptions,
getWorkflowTriggerOptions,
} from "../lib/getOptions";
type WorkflowFormValues = {
name: string;
trigger: WorkflowTriggerEvents;
action: WorkflowActions;
time?: number;
timeUnit?: TimeUnit;
sendTo?: string;
};
export function NewWorkflowButton() {
const { t } = useLocale();
const router = useRouter();
const [showTimeSection, setShowTimeSection] = useState(false);
const [isPhoneNumberNeeded, setIsPhoneNumberNeeded] = useState(false);
const triggerOptions = getWorkflowTriggerOptions(t);
const actionOptions = getWorkflowActionOptions(t);
const timeUnitOptions = getWorkflowTimeUnitOptions(t);
const formSchema = z.object({
name: z.string().nonempty(),
trigger: z.enum(WORKFLOW_TRIGGER_EVENTS),
action: z.enum(WORKFLOW_ACTIONS),
time: z.number().min(1).optional(),
timeUnit: z.enum(TIME_UNIT).optional(),
sendTo: z
.string()
.refine((val) => isValidPhoneNumber(val))
.optional(),
});
const form = useForm<WorkflowFormValues>({
defaultValues: {
timeUnit: TimeUnit.HOUR,
},
mode: "onSubmit",
resolver: zodResolver(formSchema),
});
const createMutation = trpc.useMutation("viewer.workflows.create", {
onSuccess: async ({ workflow }) => {
await router.replace("/workflows/" + workflow.id);
setIsPhoneNumberNeeded(false);
setShowTimeSection(false);
showToast(t("workflow_created_successfully", { workflowName: workflow.name }), "success");
},
onError: (err) => {
if (err instanceof HttpError) {
const message = `${err.statusCode}: ${err.message}`;
showToast(message, "error");
}
if (err.data?.code === "UNAUTHORIZED") {
const message = `${err.data.code}: You are not able to create this event`;
showToast(message, "error");
}
},
});
return (
<Dialog name="new-workflow">
<DialogTrigger asChild>
<Button StartIcon={Icon.Plus}>{t("new_workflow_btn")}</Button>
</DialogTrigger>
<DialogContent>
<div className="mb-4">
<h3 className="text-lg font-bold leading-6 text-gray-900" id="modal-title">
{t("add_new_workflow")}
</h3>
</div>
<Form
form={form}
handleSubmit={(values) => {
form.clearErrors();
createMutation.mutate(values);
}}>
<>
<div className="mt-9">
<TextField
label={t("workflow_name")}
placeholder={t("custom_workflow")}
{...form.register("name")}
/>
</div>
<div className="mt-5 space-y-1">
<label htmlFor="label" className="mt-5 block text-sm font-medium text-gray-700">
{t("trigger")}:
</label>
<Controller
name="trigger"
control={form.control}
render={() => {
return (
<Select
isSearchable={false}
className="block w-full min-w-0 flex-1 rounded-sm text-sm"
onChange={(val) => {
if (val) {
form.setValue("trigger", val.value);
form.clearErrors("trigger");
if (val.value === WorkflowTriggerEvents.BEFORE_EVENT) {
setShowTimeSection(true);
} else {
setShowTimeSection(false);
form.unregister("time");
form.unregister("timeUnit");
}
}
}}
options={triggerOptions}
/>
);
}}
/>
{form.formState.errors.trigger && (
<p className="mt-1 text-sm text-red-500">{form.formState.errors.trigger.message}</p>
)}
</div>
{showTimeSection && (
<div className="mt-5 mb-4 space-y-1">
<label htmlFor="label" className="mb-2 block text-sm font-medium text-gray-700">
{t("how_long_before")}
</label>
<div className="flex">
<input
type="number"
min="1"
defaultValue={24}
className="mr-5 block w-32 rounded-sm border-gray-300 px-3 py-2 text-sm marker:border focus:border-neutral-800 focus:outline-none focus:ring-1 focus:ring-neutral-800"
{...form.register("time", { valueAsNumber: true })}
/>
<div className="w-28">
<Controller
name="timeUnit"
control={form.control}
render={() => {
return (
<Select
isSearchable={false}
className="block min-w-0 flex-1 rounded-sm text-sm"
onChange={(val) => {
if (val) {
form.setValue("timeUnit", val.value);
}
}}
defaultValue={timeUnitOptions[1]}
options={timeUnitOptions}
/>
);
}}
/>
</div>
</div>
</div>
)}
<div className="mt-5 space-y-1">
<label htmlFor="label" className="block text-sm font-medium text-gray-700">
{t("action")}:
</label>
<Controller
name="action"
control={form.control}
render={() => {
return (
<Select
isSearchable={false}
className="block w-full min-w-0 flex-1 rounded-sm text-sm"
onChange={(val) => {
if (val) {
form.setValue("action", val.value);
form.clearErrors("action");
if (val.value === WorkflowActions.SMS_NUMBER) {
setIsPhoneNumberNeeded(true);
} else {
setIsPhoneNumberNeeded(false);
form.unregister("sendTo");
}
}
}}
options={actionOptions}
/>
);
}}
/>
{form.formState.errors.action && (
<p className="mt-1 text-sm text-red-500">{form.formState.errors.action.message}</p>
)}
</div>
{isPhoneNumberNeeded && (
<div className="mt-5 space-y-1">
<label htmlFor="sendTo" className="block text-sm font-medium text-gray-700 dark:text-white">
{t("phone_number")}
</label>
<div className="mt-1">
<PhoneInput<WorkflowFormValues>
control={form.control}
name="sendTo"
placeholder={t("enter_phone_number")}
id="sendTo"
required
/>
</div>
{form.formState.errors.sendTo && (
<p className="mt-1 text-sm text-red-500">{form.formState.errors.sendTo.message}</p>
)}
</div>
)}
</>
<div className="mt-8 flex flex-row-reverse gap-x-2">
<Button type="submit">{t("continue")}</Button>
<DialogClose asChild>
<Button
color="secondary"
onClick={() => {
setShowTimeSection(false);
setIsPhoneNumberNeeded(false);
form.clearErrors();
form.setValue("name", "");
}}>
{t("cancel")}
</Button>
</DialogClose>
</div>
</Form>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,192 @@
import { WorkflowActions, WorkflowTemplates } from "@prisma/client";
import { useRouter } from "next/router";
import { Dispatch, SetStateAction, useMemo, useState } from "react";
import { Controller, UseFormReturn } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { HttpError } from "@calcom/lib/http-error";
import showToast from "@calcom/lib/notification";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui";
import MultiSelectCheckboxes, { Option } from "@calcom/ui/form/MultiSelectCheckboxes";
import { Form } from "@calcom/ui/form/fields";
import type { FormValues } from "../pages/workflow";
import { AddActionDialog } from "./AddActionDialog";
import WorkflowStepContainer from "./WorkflowStepContainer";
interface Props {
form: UseFormReturn<FormValues>;
workflowId: number;
selectedEventTypes: Option[];
setSelectedEventTypes: Dispatch<SetStateAction<Option[]>>;
}
export default function WorkflowDetailsPage(props: Props) {
const { form, workflowId, selectedEventTypes, setSelectedEventTypes } = props;
const { t } = useLocale();
const router = useRouter();
const utils = trpc.useContext();
const [isAddActionDialogOpen, setIsAddActionDialogOpen] = useState(false);
const [reload, setReload] = useState(false);
const [editCounter, setEditCounter] = useState(0);
const { data, isLoading } = trpc.useQuery(["viewer.eventTypes"]);
const eventTypeOptions = useMemo(
() =>
data?.eventTypeGroups.reduce(
(options, group) => [
...options,
...group.eventTypes.map((eventType) => ({
value: String(eventType.id),
label: eventType.title,
})),
],
[] as Option[]
) || [],
[data]
);
const updateMutation = trpc.useMutation("viewer.workflows.update", {
onSuccess: async ({ workflow }) => {
if (workflow) {
utils.setQueryData(["viewer.workflows.get", { id: +workflow.id }], workflow);
showToast(
t("workflow_updated_successfully", {
workflowName: workflow.name,
}),
"success"
);
}
await router.push("/workflows");
},
onError: (err) => {
if (err instanceof HttpError) {
const message = `${err.statusCode}: ${err.message}`;
showToast(message, "error");
}
},
});
const addAction = (action: WorkflowActions, sendTo?: string) => {
const steps = form.getValues("steps");
const id =
steps?.length > 0
? steps.sort((a, b) => {
return a.id - b.id;
})[0].id - 1
: 0;
const step = {
id: id > 0 ? 0 : id, //id of new steps always <= 0
action,
stepNumber:
steps && steps.length > 0
? steps.sort((a, b) => {
return a.stepNumber - b.stepNumber;
})[steps.length - 1].stepNumber + 1
: 1,
sendTo: sendTo || null,
workflowId: workflowId,
reminderBody: null,
emailSubject: null,
template: WorkflowTemplates.REMINDER,
};
steps?.push(step);
form.setValue("steps", steps);
};
return (
<div>
<Form
form={form}
handleSubmit={async (values) => {
let activeOnEventTypeIds: number[] = [];
if (values.activeOn) {
activeOnEventTypeIds = values.activeOn.map((option) => {
return parseInt(option.value, 10);
});
}
updateMutation.mutate({
id: parseInt(router.query.workflow as string, 10),
name: values.name,
activeOn: activeOnEventTypeIds,
steps: values.steps,
trigger: values.trigger,
time: values.time || null,
timeUnit: values.timeUnit || null,
});
}}>
<div className="-mt-7 space-y-1">
<label htmlFor="label" className="blocktext-sm mb-2 font-medium text-gray-700">
{t("active_on")}:
</label>
<Controller
name="activeOn"
control={form.control}
render={() => {
return (
<MultiSelectCheckboxes
options={eventTypeOptions}
isLoading={isLoading}
setSelected={setSelectedEventTypes}
selected={selectedEventTypes}
setValue={(s: Option[]) => {
form.setValue("activeOn", s);
}}
/>
);
}}
/>
</div>
{/* Workflow Trigger Event & Steps */}
<div className="mt-5 px-5 pt-10 pb-5">
{form.getValues("trigger") && (
<div>
<WorkflowStepContainer form={form} setEditCounter={setEditCounter} editCounter={editCounter} />
</div>
)}
{form.getValues("steps") && (
<>
{form.getValues("steps")?.map((step) => {
return (
<WorkflowStepContainer
key={step.id}
form={form}
step={step}
reload={reload}
setReload={setReload}
setEditCounter={setEditCounter}
editCounter={editCounter}
/>
);
})}
</>
)}
<div className="flex justify-center">
<div className="h-10 border-l-2 border-gray-400" />
</div>
<div className="flex justify-center">
<Button type="button" onClick={() => setIsAddActionDialogOpen(true)} color="secondary">
{t("add_action")}
</Button>
</div>
<div className="rtl:space-x-reverse; mt-10 flex justify-end space-x-2">
<Button type="submit" disabled={updateMutation.isLoading || editCounter > 0}>
{t("save")}
</Button>
</div>
</div>
</Form>
<AddActionDialog
isOpenDialog={isAddActionDialogOpen}
setIsOpenDialog={setIsAddActionDialogOpen}
addAction={addAction}
/>
</div>
);
}
@@ -0,0 +1,168 @@
import Link from "next/link";
import { useState } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { HttpError } from "@calcom/lib/http-error";
import showToast from "@calcom/lib/notification";
import { EventType, Workflow, WorkflowsOnEventTypes } from "@calcom/prisma/client";
import { trpc } from "@calcom/trpc/react";
import { Button, Tooltip } from "@calcom/ui";
import ConfirmationDialogContent from "@calcom/ui/ConfirmationDialogContent";
import { Dialog } from "@calcom/ui/Dialog";
import Dropdown, { DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@calcom/ui/Dropdown";
import EmptyScreen from "@calcom/ui/EmptyScreen";
import { Icon } from "@calcom/ui/Icon";
const CreateFirstWorkflowView = () => {
const { t } = useLocale();
return (
<EmptyScreen
Icon={Icon.Zap}
headline={t("new_workflow_heading")}
description={t("new_workflow_description")}
/>
);
};
interface Props {
workflows:
| (Workflow & {
activeOn: (WorkflowsOnEventTypes & { eventType: EventType })[];
})[]
| undefined;
}
export default function WorkflowListPage({ workflows }: Props) {
const { t } = useLocale();
const utils = trpc.useContext();
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [deleteDialogTypeId, setDeleteDialogTypeId] = useState(0);
const query = trpc.useQuery(["viewer.workflows.list"]);
const deleteMutation = trpc.useMutation("viewer.workflows.delete", {
onSuccess: async () => {
await utils.invalidateQueries(["viewer.workflows.list"]);
showToast(t("workflow_deleted_successfully"), "success");
setDeleteDialogOpen(false);
},
onError: (err) => {
if (err instanceof HttpError) {
const message = `${err.statusCode}: ${err.message}`;
showToast(message, "error");
setDeleteDialogOpen(false);
}
},
});
async function deleteWorkflowHandler(id: number) {
const payload = { id };
deleteMutation.mutate(payload);
}
return (
<>
{workflows && workflows.length > 0 ? (
<div className="-mx-4 mb-16 overflow-hidden rounded-sm border border-gray-200 bg-white sm:mx-0">
<ul className="divide-y divide-neutral-200">
{workflows.map((workflow) => (
<li key={workflow.id}>
<div className="first-line:group flex w-full items-center justify-between px-4 py-4 hover:bg-neutral-50 sm:px-6">
<Link href={"/workflows/" + workflow.id}>
<a className="flex-grow cursor-pointer">
<div className="rtl:space-x-reverse">
<div className="max-w-56 truncate text-sm font-medium leading-6 text-neutral-900 md:max-w-max">
{workflow.name}
</div>
<ul className="mt-2 flex flex-wrap text-sm text-neutral-500 sm:flex-nowrap">
<li className="mb-1 mr-4 flex min-w-[265px] items-center truncate whitespace-nowrap">
<span className="mr-1">{t("triggers")}</span>
{workflow.timeUnit && workflow.time && (
<span className="mr-1">
{t(`${workflow.timeUnit.toLowerCase()}`, { count: workflow.time })}
</span>
)}
<span>{t(`${workflow.trigger.toLowerCase()}_trigger`)}</span>
</li>
<li className="mb-1 mr-4 flex min-w-[11rem] items-center whitespace-nowrap">
<Icon.Link
className="mr-1.5 inline h-4 w-4 text-neutral-400"
aria-hidden="true"
/>
{workflow.activeOn && workflow.activeOn.length > 0 ? (
<Tooltip
content={workflow.activeOn.map((activeOn, key) => (
<p key={key}>{activeOn.eventType.title}</p>
))}>
<span>{t("active_on_event_types", { count: workflow.activeOn.length })}</span>
</Tooltip>
) : (
<span>{t("no_active_event_types")}</span>
)}
</li>
</ul>
</div>
</a>
</Link>
<div className="flex flex-shrink-0">
<div className="flex justify-between space-x-2 rtl:space-x-reverse">
<Dropdown>
<DropdownMenuTrigger asChild>
<Button type="button" color="minimal" size="icon" StartIcon={Icon.MoreHorizontal} />
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem>
<Link href={"/workflows/" + workflow.id} passHref={true}>
<Button
type="button"
size="sm"
color="minimal"
className="w-full rounded-none"
StartIcon={Icon.Edit2}>
{t("edit")}
</Button>
</Link>
</DropdownMenuItem>
<DropdownMenuItem>
<Button
onClick={() => {
setDeleteDialogOpen(true);
setDeleteDialogTypeId(workflow.id);
}}
color="warn"
size="sm"
StartIcon={Icon.Trash}
className="w-full rounded-none">
{t("delete")}
</Button>
</DropdownMenuItem>
</DropdownMenuContent>
</Dropdown>
</div>
</div>
</div>
</li>
))}
</ul>
<Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<ConfirmationDialogContent
isLoading={deleteMutation.isLoading}
variety="danger"
title={t("delete_workflow")}
confirmBtnText={t("confirm_delete_workflow")}
loadingText={t("confirm_delete_workflow")}
onConfirm={(e) => {
e.preventDefault();
deleteWorkflowHandler(deleteDialogTypeId);
}}>
{t("delete_workflow_description")}
</ConfirmationDialogContent>
</Dialog>
</div>
) : (
<CreateFirstWorkflowView />
)}
</>
);
}
@@ -0,0 +1,438 @@
import {
TimeUnit,
WorkflowActions,
WorkflowStep,
WorkflowTemplates,
WorkflowTriggerEvents,
} from "@prisma/client";
import { isValidPhoneNumber } from "libphonenumber-js";
import { Dispatch, SetStateAction, useState } from "react";
import { Controller, UseFormReturn } from "react-hook-form";
import PhoneInput from "react-phone-number-input";
import classNames from "@calcom/lib/classNames";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui";
import Dropdown, { DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@calcom/ui/Dropdown";
import { Icon } from "@calcom/ui/Icon";
import Select from "@calcom/ui/form/Select";
import { TextArea, TextField } from "@calcom/ui/form/fields";
import {
getWorkflowActionOptions,
getWorkflowTemplateOptions,
getWorkflowTimeUnitOptions,
getWorkflowTriggerOptions,
} from "../lib/getOptions";
import type { FormValues } from "../pages/workflow";
type WorkflowStepProps = {
step?: WorkflowStep;
form: UseFormReturn<FormValues>;
reload?: boolean;
setReload?: Dispatch<SetStateAction<boolean>>;
editCounter: number;
setEditCounter: Dispatch<SetStateAction<number>>;
};
export default function WorkflowStepContainer(props: WorkflowStepProps) {
const { t } = useLocale();
const { step, form, reload, setReload, editCounter, setEditCounter } = props;
const [editNumberMode, setEditNumberMode] = useState(
step?.action === WorkflowActions.SMS_NUMBER && !step?.sendTo ? true : false
);
const [editEmailBodyMode, setEditEmailBodyMode] = useState(false);
const [sendTo, setSendTo] = useState(step?.sendTo || "");
const [errorMessageNumber, setErrorMessageNumber] = useState("");
const [errorMessageCustomInput, setErrorMessageCustomInput] = useState("");
const [isPhoneNumberNeeded, setIsPhoneNumberNeeded] = useState(
step?.action === WorkflowActions.SMS_NUMBER ? true : false
);
const [isCustomReminderBodyNeeded, setIsCustomReminderBodyNeeded] = useState(
step?.template === WorkflowTemplates.CUSTOM ? true : false
);
const [isEmailSubjectNeeded, setIsEmailSubjectNeeded] = useState(
step?.action === WorkflowActions.EMAIL_ATTENDEE || step?.action === WorkflowActions.EMAIL_HOST
? true
: false
);
const [showTimeSection, setShowTimeSection] = useState(
form.getValues("trigger") === WorkflowTriggerEvents.BEFORE_EVENT ? true : false
);
const actionOptions = getWorkflowActionOptions(t);
const triggerOptions = getWorkflowTriggerOptions(t);
const timeUnitOptions = getWorkflowTimeUnitOptions(t);
const templateOptions = getWorkflowTemplateOptions(t);
//trigger
if (!step) {
const trigger = form.getValues("trigger");
const timeUnit = form.getValues("timeUnit");
const selectedTrigger = { label: t(`${trigger.toLowerCase()}_trigger`), value: trigger };
const selectedTimeUnit = timeUnit
? { label: t(`${timeUnit.toLowerCase()}_timeUnit`), value: timeUnit }
: undefined;
return (
<>
<div className="flex justify-center">
<div className=" min-w-80 w-[50rem] rounded border-2 border-gray-400 bg-gray-50 px-10 pb-9 pt-5">
<div className="font-bold">{t("triggers")}:</div>
<Controller
name="trigger"
control={form.control}
render={() => {
return (
<Select
isSearchable={false}
className="mt-3 block w-full min-w-0 flex-1 rounded-sm text-sm"
onChange={(val) => {
if (val) {
form.setValue("trigger", val.value);
if (val.value === WorkflowTriggerEvents.BEFORE_EVENT) {
setShowTimeSection(true);
form.setValue("time", 24);
form.setValue("timeUnit", TimeUnit.HOUR);
} else {
setShowTimeSection(false);
form.unregister("time");
form.unregister("timeUnit");
}
}
}}
defaultValue={selectedTrigger}
options={triggerOptions}
/>
);
}}
/>
{showTimeSection && (
<div className="mt-5 space-y-1">
<label htmlFor="label" className="mb-2 block text-sm font-medium text-gray-700">
{t("how_long_before")}
</label>
<div className="flex">
<input
type="number"
min="1"
defaultValue={form.getValues("time") || 24}
className="mr-5 block w-20 rounded-sm border-gray-300 px-3 py-2 text-sm marker:border focus:border-neutral-800 focus:outline-none focus:ring-1 focus:ring-neutral-800"
{...form.register("time", { valueAsNumber: true })}
/>
<div className="w-28">
<Controller
name="timeUnit"
control={form.control}
render={() => {
return (
<Select
isSearchable={false}
className="block min-w-0 flex-1 rounded-sm text-sm"
onChange={(val) => {
if (val) {
form.setValue("timeUnit", val.value);
}
}}
defaultValue={selectedTimeUnit || timeUnitOptions[1]}
options={timeUnitOptions}
/>
);
}}
/>
</div>
</div>
</div>
)}
</div>
</div>
</>
);
}
if (step && step.action) {
const selectedAction = { label: t(`${step.action.toLowerCase()}_action`), value: step.action };
const selectedTemplate = { label: t(`${step.template.toLowerCase()}`), value: step.template };
return (
<>
<div className="flex justify-center">
<div className="h-10 border-l-2 border-gray-400" />
</div>
<div className="flex justify-center">
<div className="min-w-80 flex w-[50rem] rounded border-2 border-gray-400 bg-gray-50 pl-10 pb-9 ">
<div className="w-full pt-5">
<div className="font-bold">{t("action")}:</div>
<div>
<Controller
name={`steps.${step.stepNumber - 1}.action`}
control={form.control}
render={() => {
return (
<Select
isSearchable={false}
className="mt-3 block w-full min-w-0 flex-1 rounded-sm text-sm"
onChange={(val) => {
if (val) {
let counter = 0;
if (val.value === WorkflowActions.SMS_NUMBER) {
setIsPhoneNumberNeeded(true);
setEditNumberMode(true);
counter = counter + 1;
} else {
setIsPhoneNumberNeeded(false);
setEditNumberMode(false);
}
if (
form.getValues(`steps.${step.stepNumber - 1}.template`) ===
WorkflowTemplates.CUSTOM
) {
setEditEmailBodyMode(true);
counter = counter + 1;
}
if (
val.value === WorkflowActions.EMAIL_ATTENDEE ||
val.value === WorkflowActions.EMAIL_HOST
) {
setIsEmailSubjectNeeded(true);
} else {
setIsEmailSubjectNeeded(false);
}
setEditCounter(counter);
form.setValue(`steps.${step.stepNumber - 1}.action`, val.value);
setErrorMessageNumber("");
setErrorMessageCustomInput("");
}
}}
defaultValue={selectedAction}
options={actionOptions}
/>
);
}}
/>
{form.getValues(`steps.${step.stepNumber - 1}.action`) === WorkflowActions.SMS_ATTENDEE && (
<p className="mt-2 ml-1 text-sm text-gray-500">{t("not_triggering_existing_bookings")}</p>
)}
</div>
{isPhoneNumberNeeded && (
<>
<label
htmlFor="sendTo"
className="mt-5 block text-sm font-medium text-gray-700 dark:text-white">
{t("phone_number")}
</label>
<div className="flex space-y-1">
<div className="mt-1 ">
<PhoneInput
international
value={sendTo}
onChange={(newValue) => {
if (newValue) {
setSendTo(newValue);
setErrorMessageNumber("");
}
}}
placeholder={t("enter_phone_number")}
id="sendTo"
disabled={!editNumberMode}
required
countrySelectProps={{ className: "text-black" }}
numberInputProps={{ className: "border-0 text-sm focus:ring-0 dark:bg-gray-700" }}
className={classNames(
"border-1 focus-within:border-brand block w-full rounded-sm border border-gray-300 py-px pl-3 ring-black focus-within:ring-1 disabled:text-gray-500 disabled:opacity-50 dark:border-gray-900 dark:bg-gray-700 dark:text-white dark:selection:bg-green-500 disabled:dark:text-gray-500",
!editNumberMode ? "text-gray-500 dark:text-gray-500" : ""
)}
/>
</div>
{!editNumberMode ? (
<Button
type="button"
color="secondary"
onClick={() => {
setEditNumberMode(true);
setEditCounter(editCounter + 1);
}}>
{t("edit")}
</Button>
) : (
<Button
type="button"
color="primary"
onClick={async () => {
if (sendTo) {
form.setValue(`steps.${step.stepNumber - 1}.sendTo`, sendTo);
if (isValidPhoneNumber(sendTo)) {
setEditNumberMode(false);
setEditCounter(editCounter - 1);
} else {
setErrorMessageNumber(t("invalid_input"));
}
}
}}>
{t("save")}
</Button>
)}
</div>
{errorMessageNumber && <p className="mt-1 text-sm text-red-500">{errorMessageNumber}</p>}
</>
)}
<div className="mt-5">
<label htmlFor="label" className="mt-5 block text-sm font-medium text-gray-700">
{t("choose_template")}
</label>
<Controller
name={`steps.${step.stepNumber - 1}.template`}
control={form.control}
render={() => {
return (
<Select
isSearchable={false}
className="mt-3 block w-full min-w-0 flex-1 rounded-sm text-sm"
onChange={(val) => {
if (val) {
form.setValue(`steps.${step.stepNumber - 1}.template`, val.value);
const isCustomTemplate = val.value === WorkflowTemplates.CUSTOM;
setIsCustomReminderBodyNeeded(isCustomTemplate);
if (isCustomTemplate) {
setEditEmailBodyMode(true);
setEditCounter(editCounter + 1);
} else if (editEmailBodyMode) {
setEditEmailBodyMode(false);
setEditCounter(editCounter - 1);
}
setErrorMessageCustomInput("");
}
}}
defaultValue={selectedTemplate}
options={templateOptions}
/>
);
}}
/>
</div>
{isCustomReminderBodyNeeded && (
<>
{isEmailSubjectNeeded && (
<div className="mt-5 mb-2">
<TextField
label={t("subject")}
type="text"
disabled={!editEmailBodyMode}
className={classNames(
"border-1 focus-within:border-brand block w-full rounded-sm border border-gray-300 px-2 font-sans text-sm ring-black focus-within:ring-1 dark:border-black dark:bg-black dark:text-white",
!editEmailBodyMode ? "text-gray-500 dark:text-gray-500" : ""
)}
{...form.register(`steps.${step.stepNumber - 1}.emailSubject`)}
/>
</div>
)}
<label className="mt-3 mb-1 block text-sm font-medium text-gray-700 dark:text-white">
{isEmailSubjectNeeded ? t("email_body") : t("text_message")}
</label>
<TextArea
className={classNames(
"border-1 focus-within:border-brand mb-2 block w-full rounded-sm border border-gray-300 p-2 text-sm ring-black focus-within:ring-1 dark:border-black dark:bg-black dark:text-white",
!editEmailBodyMode ? "text-gray-500 dark:text-gray-500" : ""
)}
rows={5}
disabled={!editEmailBodyMode}
{...form.register(`steps.${step.stepNumber - 1}.reminderBody`)}
/>
{errorMessageCustomInput && (
<p className="mb-3 text-sm text-red-500">{errorMessageCustomInput}</p>
)}
{!editEmailBodyMode ? (
<Button
type="button"
color="secondary"
onClick={() => {
setEditEmailBodyMode(true);
setEditCounter(editCounter + 1);
}}>
{t("edit")}
</Button>
) : (
<Button
type="button"
color="primary"
onClick={async () => {
const reminderBody = form.getValues(`steps.${step.stepNumber - 1}.reminderBody`);
const emailSubject = form.getValues(`steps.${step.stepNumber - 1}.emailSubject`);
let isEmpty = false;
let errorMessage = "";
if (isEmailSubjectNeeded) {
if (!reminderBody || !emailSubject) {
isEmpty = true;
errorMessage = "Email body or subject is empty";
}
} else if (!reminderBody) {
isEmpty = true;
errorMessage = "Text message is empty";
}
if (!isEmpty) {
setEditEmailBodyMode(false);
setEditCounter(editCounter - 1);
}
setErrorMessageCustomInput(errorMessage);
}}>
{t("save")}
</Button>
)}
</>
)}
</div>
<div>
<Dropdown>
<DropdownMenuTrigger asChild>
<Button type="button" color="minimal" size="icon" StartIcon={Icon.MoreHorizontal} />
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem>
<Button
onClick={() => {
const steps = form.getValues("steps");
const updatedSteps = steps
?.filter((currStep) => currStep.id !== step.id)
.map((s) => {
const updatedStep = s;
if (step.stepNumber < updatedStep.stepNumber) {
updatedStep.stepNumber = updatedStep.stepNumber - 1;
}
return updatedStep;
});
form.setValue("steps", updatedSteps);
if (setReload) {
setReload(!reload);
}
}}
color="warn"
size="sm"
StartIcon={Icon.Trash}
className="w-full rounded-none">
{t("delete")}
</Button>
</DropdownMenuItem>
</DropdownMenuContent>
</Dropdown>
</div>
</div>
</div>
</>
);
}
return <></>;
}
@@ -0,0 +1,18 @@
import { TimeUnit, WorkflowActions, WorkflowTemplates, WorkflowTriggerEvents } from "@prisma/client";
export const WORKFLOW_TRIGGER_EVENTS = [
WorkflowTriggerEvents.BEFORE_EVENT,
WorkflowTriggerEvents.EVENT_CANCELLED,
WorkflowTriggerEvents.NEW_EVENT,
] as const;
export const WORKFLOW_ACTIONS = [
WorkflowActions.EMAIL_HOST,
WorkflowActions.EMAIL_ATTENDEE,
WorkflowActions.SMS_ATTENDEE,
WorkflowActions.SMS_NUMBER,
] as const;
export const TIME_UNIT = [TimeUnit.DAY, TimeUnit.HOUR, TimeUnit.MINUTE] as const;
export const WORKFLOW_TEMPLATES = [WorkflowTemplates.CUSTOM, WorkflowTemplates.REMINDER] as const;
@@ -0,0 +1,27 @@
import { TFunction } from "next-i18next";
import { TIME_UNIT, WORKFLOW_ACTIONS, WORKFLOW_TEMPLATES, WORKFLOW_TRIGGER_EVENTS } from "./constants";
export function getWorkflowActionOptions(t: TFunction) {
return WORKFLOW_ACTIONS.map((action) => {
return { label: t(`${action.toLowerCase()}_action`), value: action };
});
}
export function getWorkflowTriggerOptions(t: TFunction) {
return WORKFLOW_TRIGGER_EVENTS.map((triggerEvent) => {
return { label: t(`${triggerEvent.toLowerCase()}_trigger`), value: triggerEvent };
});
}
export function getWorkflowTimeUnitOptions(t: TFunction) {
return TIME_UNIT.map((timeUnit) => {
return { label: t(`${timeUnit.toLowerCase()}_timeUnit`), value: timeUnit };
});
}
export function getWorkflowTemplateOptions(t: TFunction) {
return WORKFLOW_TEMPLATES.map((template) => {
return { label: t(`${template.toLowerCase()}`), value: template };
});
}
@@ -0,0 +1,152 @@
import {
TimeUnit,
WorkflowTriggerEvents,
WorkflowTemplates,
WorkflowActions,
WorkflowMethods,
} from "@prisma/client";
import client from "@sendgrid/client";
import sgMail from "@sendgrid/mail";
import dayjs from "@calcom/dayjs";
import prisma from "@calcom/prisma";
import { BookingInfo, timeUnitLowerCase } from "./smsReminderManager";
import emailReminderTemplate from "./templates/emailReminderTemplate";
let sendgridAPIKey, senderEmail: string;
if (process.env.SENDGRID_API_KEY) {
sendgridAPIKey = process.env.SENDGRID_API_KEY as string;
senderEmail = process.env.SENDGRID_EMAIL as string;
sgMail.setApiKey(sendgridAPIKey);
client.setApiKey(sendgridAPIKey);
}
export const scheduleEmailReminder = async (
evt: BookingInfo,
triggerEvent: WorkflowTriggerEvents,
action: WorkflowActions,
timeBefore: {
time: number | null;
timeUnit: TimeUnit | null;
},
sendTo: string,
emailSubject: string,
emailBody: string,
workflowStepId: number,
template: WorkflowTemplates
) => {
const { startTime } = evt;
const uid = evt.uid as string;
const currentDate = dayjs();
const timeUnit: timeUnitLowerCase | undefined =
timeBefore.timeUnit?.toLocaleLowerCase() as timeUnitLowerCase;
const scheduledDate =
timeBefore.time && timeUnit ? dayjs(startTime).subtract(timeBefore.time, timeUnit) : null;
if (!process.env.SENDGRID_API_KEY || !process.env.SENDGRID_EMAIL) {
console.error("Sendgrid credentials are missing from the .env file");
return;
}
const batchIdResponse = await client.request({
url: "/v3/mail/batch",
method: "POST",
});
const name = action === WorkflowActions.EMAIL_HOST ? evt.organizer.name : evt.attendees[0].name;
const attendeeName = action === WorkflowActions.EMAIL_HOST ? evt.attendees[0].name : evt.organizer.name;
const timeZone = action === WorkflowActions.EMAIL_HOST ? evt.organizer.timeZone : evt.attendees[0].timeZone;
let emailContent = {
emailSubject,
emailBody: {
text: emailBody,
html: `<body style="white-space: pre-wrap;">${emailBody}</body>`,
},
};
switch (template) {
case WorkflowTemplates.REMINDER:
emailContent = emailReminderTemplate(startTime, evt.title, timeZone, attendeeName, name);
break;
}
if (
triggerEvent === WorkflowTriggerEvents.NEW_EVENT ||
triggerEvent === WorkflowTriggerEvents.EVENT_CANCELLED
) {
try {
await sgMail.send({
to: sendTo,
from: senderEmail,
subject: emailContent.emailSubject,
text: emailContent.emailBody.text,
html: emailContent.emailBody.html,
batchId: batchIdResponse[1].batch_id,
});
} catch (error) {
console.log("Error sending Email");
}
} else if (triggerEvent === WorkflowTriggerEvents.BEFORE_EVENT && scheduledDate) {
// Sendgrid to schedule emails
// Can only schedule at least 60 minutes and at most 72 hours in advance
if (
currentDate.isBefore(scheduledDate.subtract(1, "hour")) &&
!scheduledDate.isAfter(currentDate.add(72, "hour"))
) {
try {
await sgMail.send({
to: sendTo,
from: senderEmail,
subject: emailContent.emailSubject,
text: emailContent.emailBody.text,
html: emailContent.emailBody.html,
batchId: batchIdResponse[1].batch_id,
sendAt: scheduledDate.unix(),
});
await prisma.workflowReminder.create({
data: {
bookingUid: uid,
workflowStepId: workflowStepId,
method: WorkflowMethods.EMAIL,
scheduledDate: scheduledDate.toDate(),
scheduled: true,
referenceId: batchIdResponse[1].batch_id,
},
});
} catch (error) {
console.log(`Error scheduling email with error ${error}`);
}
} else if (scheduledDate.isAfter(currentDate.add(72, "hour"))) {
// Write to DB and send to CRON if scheduled reminder date is past 72 hours
await prisma.workflowReminder.create({
data: {
bookingUid: uid,
workflowStepId: workflowStepId,
method: WorkflowMethods.EMAIL,
scheduledDate: scheduledDate.toDate(),
scheduled: false,
},
});
}
}
};
export const deleteScheduledEmailReminder = async (referenceId: string) => {
try {
await client.request({
url: "/v3/user/scheduled_sends",
method: "POST",
body: {
batch_id: referenceId,
status: "cancel",
},
});
} catch (error) {
console.log(`Error canceling reminder with error ${error}`);
}
};
@@ -0,0 +1,130 @@
import {
Workflow,
WorkflowActions,
WorkflowsOnEventTypes,
WorkflowStep,
WorkflowTriggerEvents,
} from "@prisma/client";
import type { CalendarEvent } from "@calcom/types/Calendar";
import { scheduleEmailReminder } from "./emailReminderManager";
import { scheduleSMSReminder } from "./smsReminderManager";
export const scheduleWorkflowReminders = async (
workflows: (WorkflowsOnEventTypes & {
workflow: Workflow & {
steps: WorkflowStep[];
};
})[],
smsReminderNumber: string | null,
evt: CalendarEvent,
needsConfirmation: boolean
) => {
if (workflows.length > 0 && !needsConfirmation) {
workflows.forEach((workflowReference) => {
if (workflowReference.workflow.steps.length > 0) {
const workflow = workflowReference.workflow;
if (
workflow.trigger === WorkflowTriggerEvents.BEFORE_EVENT ||
workflow.trigger === WorkflowTriggerEvents.NEW_EVENT
) {
workflow.steps.forEach(async (step) => {
if (step.action === WorkflowActions.SMS_ATTENDEE || step.action === WorkflowActions.SMS_NUMBER) {
const sendTo = step.action === WorkflowActions.SMS_ATTENDEE ? smsReminderNumber : step.sendTo;
await scheduleSMSReminder(
evt,
sendTo,
workflow.trigger,
step.action,
{
time: workflow.time,
timeUnit: workflow.timeUnit,
},
step.reminderBody || "",
step.id,
step.template
);
} else if (
step.action === WorkflowActions.EMAIL_ATTENDEE ||
step.action === WorkflowActions.EMAIL_HOST
) {
const sendTo =
step.action === WorkflowActions.EMAIL_HOST ? evt.organizer.email : evt.attendees[0].email;
scheduleEmailReminder(
evt,
workflow.trigger,
step.action,
{
time: workflow.time,
timeUnit: workflow.timeUnit,
},
sendTo,
step.emailSubject || "",
step.reminderBody || "",
step.id,
step.template
);
}
});
}
}
});
}
};
export const sendCancelledReminders = async (
workflows: (WorkflowsOnEventTypes & {
workflow: Workflow & {
steps: WorkflowStep[];
};
})[],
smsReminderNumber: string | null,
evt: CalendarEvent
) => {
if (workflows.length > 0) {
workflows
.filter((workflowRef) => workflowRef.workflow.trigger === WorkflowTriggerEvents.EVENT_CANCELLED)
.forEach((workflowRef) => {
const workflow = workflowRef.workflow;
workflow.steps.forEach(async (step) => {
if (step.action === WorkflowActions.SMS_ATTENDEE || step.action === WorkflowActions.SMS_NUMBER) {
const sendTo = step.action === WorkflowActions.SMS_ATTENDEE ? smsReminderNumber : step.sendTo;
await scheduleSMSReminder(
evt,
sendTo,
workflow.trigger,
step.action,
{
time: workflow.time,
timeUnit: workflow.timeUnit,
},
step.reminderBody || "",
step.id,
step.template
);
} else if (
step.action === WorkflowActions.EMAIL_ATTENDEE ||
step.action === WorkflowActions.EMAIL_HOST
) {
const sendTo =
step.action === WorkflowActions.EMAIL_HOST ? evt.organizer.email : evt.attendees[0].email;
scheduleEmailReminder(
evt,
workflow.trigger,
step.action,
{
time: workflow.time,
timeUnit: workflow.timeUnit,
},
sendTo,
step.emailSubject || "",
step.reminderBody || "",
step.id,
step.template
);
}
});
});
}
};
@@ -0,0 +1,39 @@
import twilio from "twilio";
let TWILIO_SID, TWILIO_TOKEN, TWILIO_MESSAGING_SID: string, client: twilio.Twilio;
// Only assign the API keys if they exist in .env
if (process.env.TWILIO_SID && process.env.TWILIO_TOKEN && process.env.TWILIO_MESSAGING_SID) {
TWILIO_SID = process.env.TWILIO_SID;
TWILIO_TOKEN = process.env.TWILIO_TOKEN;
TWILIO_MESSAGING_SID = process.env.TWILIO_MESSAGING_SID;
client = twilio(TWILIO_SID, TWILIO_TOKEN);
} else {
console.error("Twilio credentials are missing from the .env file");
}
export const sendSMS = async (phoneNumber: string, body: string) => {
const response = await client.messages.create({
body: body,
messagingServiceSid: TWILIO_MESSAGING_SID,
to: phoneNumber,
});
return response;
};
export const scheduleSMS = async (phoneNumber: string, body: string, scheduledDate: Date) => {
const response = await client.messages.create({
body: body,
messagingServiceSid: TWILIO_MESSAGING_SID,
to: phoneNumber,
scheduleType: "fixed",
sendAt: scheduledDate,
});
return response;
};
export const cancelSMS = async (referenceId: string) => {
await client.messages(referenceId).update({ status: "canceled" });
};
@@ -0,0 +1,116 @@
import {
WorkflowTriggerEvents,
TimeUnit,
WorkflowTemplates,
WorkflowActions,
WorkflowMethods,
} from "@prisma/client";
import dayjs from "@calcom/dayjs";
import prisma from "@calcom/prisma";
import * as twilio from "./smsProviders/twilioProvider";
import smsReminderTemplate from "./templates/smsReminderTemplate";
export enum timeUnitLowerCase {
DAY = "day",
MINUTE = "minute",
YEAR = "year",
}
export type BookingInfo = {
uid?: string | null;
attendees: { name: string; email: string; timeZone: string }[];
organizer: { name: string; email: string; timeZone: string };
startTime: string;
title: string;
};
export const scheduleSMSReminder = async (
evt: BookingInfo,
reminderPhone: string | null,
triggerEvent: WorkflowTriggerEvents,
action: WorkflowActions,
timeBefore: {
time: number | null;
timeUnit: TimeUnit | null;
},
message: string,
workflowStepId: number,
template: WorkflowTemplates
) => {
const { startTime } = evt;
const uid = evt.uid as string;
const currentDate = dayjs();
const timeUnit: timeUnitLowerCase | undefined =
timeBefore.timeUnit?.toLocaleLowerCase() as timeUnitLowerCase;
const scheduledDate =
timeBefore.time && timeUnit ? dayjs(startTime).subtract(timeBefore.time, timeUnit) : null;
const name = action === WorkflowActions.SMS_ATTENDEE ? evt.attendees[0].name : "";
const attendeeName = action === WorkflowActions.SMS_ATTENDEE ? evt.organizer.name : evt.attendees[0].name;
const timeZone =
action === WorkflowActions.SMS_ATTENDEE ? evt.attendees[0].timeZone : evt.organizer.timeZone;
switch (template) {
case WorkflowTemplates.REMINDER:
message = smsReminderTemplate(evt.startTime, evt.title, timeZone, attendeeName, name) || message;
break;
}
if (message.length > 0 && reminderPhone) {
//send SMS when event is booked/cancelled
if (
triggerEvent === WorkflowTriggerEvents.NEW_EVENT ||
triggerEvent === WorkflowTriggerEvents.EVENT_CANCELLED
) {
try {
await twilio.sendSMS(reminderPhone, message);
} catch (error) {
console.log(`Error sending SMS with error ${error}`);
}
} else if (triggerEvent === WorkflowTriggerEvents.BEFORE_EVENT && scheduledDate) {
// Can only schedule at least 60 minutes in advance and at most 7 days in advance
if (
currentDate.isBefore(scheduledDate.subtract(1, "hour")) &&
!scheduledDate.isAfter(currentDate.add(7, "day"))
) {
try {
const scheduledSMS = await twilio.scheduleSMS(reminderPhone, message, scheduledDate.toDate());
await prisma.workflowReminder.create({
data: {
bookingUid: uid,
workflowStepId: workflowStepId,
method: WorkflowMethods.SMS,
scheduledDate: scheduledDate.toDate(),
scheduled: true,
referenceId: scheduledSMS.sid,
},
});
} catch (error) {
console.log(`Error scheduling SMS with error ${error}`);
}
} else if (scheduledDate.isAfter(currentDate.add(7, "day"))) {
// Write to DB and send to CRON if scheduled reminder date is past 7 days
await prisma.workflowReminder.create({
data: {
bookingUid: uid,
workflowStepId: workflowStepId,
method: WorkflowMethods.SMS,
scheduledDate: scheduledDate.toDate(),
scheduled: false,
},
});
}
}
}
};
export const deleteScheduledSMSReminder = async (referenceId: string) => {
try {
await twilio.cancelSMS(referenceId);
} catch (error) {
console.log(`Error canceling reminder with error ${error}`);
}
};
@@ -0,0 +1,31 @@
import dayjs from "@calcom/dayjs";
const emailReminderTemplate = (
startTime: string,
eventName: string,
timeZone: string,
attendee: string,
name: string
) => {
const emailSubject = `Reminder: ${eventName} on ${dayjs(startTime)
.tz(timeZone)
.format("YYYY MMM D")} at ${dayjs(startTime).tz(timeZone).format("h:mmA")} ${timeZone}.`;
const templateBodyText = `Hi ${name}, this is a reminder that your meeting (${eventName}) with ${attendee} is on ${dayjs(
startTime
)
.tz(timeZone)
.format("YYYY MMM D")} at ${dayjs(startTime).tz(timeZone).format("h:mmA")} ${timeZone}.`;
const templateBodyHtml = `<body>Hi ${name},<br><br>This is a reminder that your meeting (${eventName}) with ${attendee} is on ${dayjs(
startTime
)
.tz(timeZone)
.format("YYYY MMM D")} at ${dayjs(startTime).tz(timeZone).format("h:mmA")} ${timeZone}.<body>`;
const emailBody = { text: templateBodyText, html: templateBodyHtml };
return { emailSubject, emailBody };
};
export default emailReminderTemplate;
@@ -0,0 +1,28 @@
import dayjs from "@calcom/dayjs";
const smsReminderTemplate = (
startTime: string,
eventName: string,
timeZone: string,
attendee: string,
name?: string
) => {
const templateOne = `Hi${name ? ` ${name}` : ``}, this is a reminder that your meeting (${eventName}) with
${attendee} is on ${dayjs(startTime).tz(timeZone).format("MMM D")} at ${dayjs(startTime)
.tz(timeZone)
.format("h:mmA")} ${timeZone}`;
//Twilio recomments message to be no longer than 320 characters
if (templateOne.length <= 320) return templateOne;
const templateTwo = `Hi, this is a reminder that your meeting with ${attendee} is on ${dayjs(startTime)
.tz(timeZone)
.format("MMM D")} at ${dayjs(startTime).tz(timeZone).format("h:mmA")} ${timeZone}`;
//Twilio supports up to 1600 characters
if (templateTwo.length <= 1600) return templateTwo;
return null;
};
export default smsReminderTemplate;
@@ -0,0 +1,46 @@
import { useSession } from "next-auth/react";
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
import { Alert } from "@calcom/ui/Alert";
import Loader from "@calcom/ui/Loader";
import Shell from "@calcom/ui/Shell";
import { NewWorkflowButton } from "../components/NewWorkflowButton";
import WorkflowList from "../components/WorkflowListPage";
function WorkflowsPage() {
const { t } = useLocale();
const session = useSession();
const me = useMeQuery();
const isFreeUser = me.data?.plan === "FREE";
const { data, isLoading } = trpc.useQuery(["viewer.workflows.list"]);
return (
<Shell
heading={t("workflows")}
subtitle={t("workflows_to_automate_notifications")}
CTA={session.data?.hasValidLicense && !isFreeUser ? <NewWorkflowButton /> : <></>}>
<LicenseRequired>
{isLoading ? (
<Loader />
) : (
<>
{isFreeUser ? (
<Alert className="border " severity="warning" title={t("pro_feature_workflows")} />
) : (
<WorkflowList workflows={data?.workflows} />
)}
</>
)}
</LicenseRequired>
</Shell>
);
}
export default WorkflowsPage;
@@ -0,0 +1,181 @@
import { zodResolver } from "@hookform/resolvers/zod";
import {
TimeUnit,
WorkflowActions,
WorkflowStep,
WorkflowTemplates,
WorkflowTriggerEvents,
} from "@prisma/client";
import { isValidPhoneNumber } from "libphonenumber-js";
import { useSession } from "next-auth/react";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { stringOrNumber } from "@calcom/prisma/zod-utils";
import { trpc } from "@calcom/trpc/react";
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
import { Alert } from "@calcom/ui/Alert";
import { Icon } from "@calcom/ui/Icon";
import Loader from "@calcom/ui/Loader";
import Shell from "@calcom/ui/Shell";
import { Option } from "@calcom/ui/form/MultiSelectCheckboxes";
import LicenseRequired from "../../common/components/LicenseRequired";
import WorkflowDetailsPage from "../components/WorkflowDetailsPage";
export type FormValues = {
name: string;
activeOn: Option[];
steps: WorkflowStep[];
trigger: WorkflowTriggerEvents;
time?: number;
timeUnit?: TimeUnit;
};
const formSchema = z.object({
name: z.string(),
activeOn: z.object({ value: z.string(), label: z.string() }).array(),
trigger: z.nativeEnum(WorkflowTriggerEvents),
time: z.number().gte(0).optional(),
timeUnit: z.nativeEnum(TimeUnit).optional(),
steps: z
.object({
id: z.number(),
stepNumber: z.number(),
action: z.nativeEnum(WorkflowActions),
workflowId: z.number(),
reminderBody: z.string().nullable(),
emailSubject: z.string().nullable(),
template: z.nativeEnum(WorkflowTemplates),
sendTo: z
.string()
.refine((val) => isValidPhoneNumber(val))
.nullable(),
})
.array(),
});
const querySchema = z.object({
workflow: stringOrNumber,
});
function WorkflowPage() {
const { t } = useLocale();
const session = useSession();
const router = useRouter();
const me = useMeQuery();
const isFreeUser = me.data?.plan === "FREE";
const [editIcon, setEditIcon] = useState(true);
const [selectedEventTypes, setSelectedEventTypes] = useState<Option[]>([]);
const [isAllDataLoaded, setIsAllDataLoaded] = useState(false);
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
});
const { workflow: workflowId } = router.isReady ? querySchema.parse(router.query) : { workflow: -1 };
const {
data: workflow,
isError,
error,
dataUpdatedAt,
} = trpc.useQuery(["viewer.workflows.get", { id: +workflowId }], {
enabled: router.isReady && !!workflowId,
});
useEffect(() => {
if (workflow) {
setSelectedEventTypes(
workflow.activeOn.map((active) => ({
value: String(active.eventType.id),
label: active.eventType.title,
})) || []
);
const activeOn = workflow.activeOn
? workflow.activeOn.map((active) => ({
value: active.eventType.id.toString(),
label: active.eventType.slug,
}))
: undefined;
form.setValue("name", workflow.name);
form.setValue("steps", workflow.steps);
form.setValue("trigger", workflow.trigger);
form.setValue("time", workflow.time || undefined);
form.setValue("timeUnit", workflow.timeUnit || undefined);
form.setValue("activeOn", activeOn || []);
setIsAllDataLoaded(true);
}
}, [dataUpdatedAt]);
return (
<Shell
title="Title"
heading={
session.data?.hasValidLicense &&
isAllDataLoaded && (
<div className="group relative cursor-pointer" onClick={() => setEditIcon(false)}>
{editIcon ? (
<>
<h1
style={{ fontSize: 22, letterSpacing: "-0.0009em" }}
className="inline pl-0 text-gray-900 focus:text-black group-hover:text-gray-500">
{form.getValues("name") && form.getValues("name") !== ""
? form.getValues("name")
: workflow?.name}
</h1>
<Icon.Edit2 className="ml-1 -mt-1 inline h-4 w-4 text-gray-700 group-hover:text-gray-500" />
</>
) : (
<div style={{ marginBottom: -11 }}>
<input
type="text"
autoFocus
style={{ top: -6, fontSize: 22 }}
required
className="relative h-10 w-full cursor-pointer border-none bg-transparent pl-0 text-gray-900 hover:text-gray-700 focus:text-black focus:outline-none focus:ring-0"
placeholder={t("Custom workflow")}
{...form.register("name")}
defaultValue={workflow?.name}
onBlur={() => {
setEditIcon(true);
form.getValues("name") === "" && form.setValue("name", workflow?.name || "");
}}
/>
</div>
)}
</div>
)
}>
<LicenseRequired>
{isFreeUser ? (
<Alert className="border " severity="warning" title={t("pro_feature_workflows")} />
) : (
<>
{!isError ? (
<>
{isAllDataLoaded ? (
<WorkflowDetailsPage
form={form}
workflowId={+workflowId}
selectedEventTypes={selectedEventTypes}
setSelectedEventTypes={setSelectedEventTypes}
/>
) : (
<Loader />
)}
</>
) : (
<Alert severity="error" title="Something went wrong" message={error.message} />
)}
</>
)}
</LicenseRequired>
</Shell>
);
}
export default WorkflowPage;
+1
View File
@@ -0,0 +1 @@
export * as ee from "./ee";
+3
View File
@@ -0,0 +1,3 @@
# Event types will become Links…
…and this is where the feature will live.
+8
View File
@@ -0,0 +1,8 @@
{
"name": "@calcom/features",
"description": "Cal.com's main collocation of features",
"authors": "Cal.com, Inc.",
"version": "1.0.0",
"main": "index.ts",
"dependencies": {}
}
+12
View File
@@ -0,0 +1,12 @@
{
"extends": "@calcom/tsconfig/react-library.json",
"compilerOptions": {
"baseUrl": ".",
"paths": {
"~/*": ["/*"]
},
"resolveJsonModule": true
},
"include": [".", "../types/next-auth.d.ts"],
"exclude": ["dist", "build", "node_modules"]
}
+1
View File
@@ -0,0 +1 @@
# User-centric related code will live here