Routing Forms (#2785)

* Add Routing logic to Query builder

* Make a working redirect

* Make it an app

* Move pages and components to App

* Integrate all pages in the app

* Integrate prisma everywhere

* Fix Routing Link

* Add routing preview

* Fixes

* Get deplouyed on preview with ts disabled

* Fix case

* add reordering for routes

* Move away from react DnD

* Add sidebar

* Add sidebar support and select support

* Various fixes and improvements

* Ignore eslint temporarly

* Route might be falsy

* Make CalNumber support required validation

* Loader improvements

* Add SSR support

* Fix few typescript issues

* More typesafety, download csv, bug fiees

* Add seo friendly link

* Avoid seding credebtials to frontend

* Self review fixes

* Improvements in app-store

* Cahnge Form layout

* Add scaffolding for app tests

* Add playwright tests and add user check in serving data

* Add CI tests

* Add route builder test

* Styling

* Apply suggestions from code review

Co-authored-by: Agusti Fernandez Pardo <[email protected]>

* Changes as per loom feedback

* Increase time for tests

* Fix PR suggestions

* Import CSS only in the module

* Fix codacy issues

* Move the codebbase to ee and add PRO and license check

* Add Badge

* Avoid lodash import

* Fix TS error

* Fix lint errors

* Fix bug to merge conflicts resolution - me query shouldnt cause the Shell to go in loading state

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Co-authored-by: zomars <[email protected]>
Co-authored-by: Agusti Fernandez Pardo <[email protected]>
This commit is contained in:
authored and GitHub committed 2022-07-14 12:40:53 +00:00
1 parent 7ec5f01647
commit 58d1c28e9d
80 files changed
+4223 -567

No files matched your search

+2 -1
View File
@@ -9,7 +9,8 @@
"build": "ts-node --transpile-only src/app-store.ts",
"cli": "ts-node --transpile-only src/cli.tsx",
"watch": "ts-node --transpile-only src/app-store.ts --watch",
"generate": "ts-node --transpile-only src/app-store.ts"
"generate": "ts-node --transpile-only src/app-store.ts",
"post-install": "yarn build"
},
"files": [
"dist/cli.js"
+63 -26
View File
@@ -1,19 +1,29 @@
const fs = require("fs");
const path = require("path");
import chokidar from "chokidar";
import fs from "fs";
import { debounce } from "lodash";
import path from "path";
let isInWatchMode = false;
if (process.argv[2] === "--watch") {
isInWatchMode = true;
}
const chokidar = require("chokidar");
const { debounce } = require("lodash");
const APP_STORE_PATH = path.join(__dirname, "..", "..", "app-store");
type App = {
name: string;
path: string;
};
function getAppName(candidatePath) {
function isValidAppName(candidatePath) {
if (!candidatePath.startsWith("_") && !candidatePath.includes("/") && !candidatePath.includes("\\")) {
if (
!candidatePath.startsWith("_") &&
candidatePath !== "ee" &&
!candidatePath.includes("/") &&
!candidatePath.includes("\\")
) {
return candidatePath;
}
}
if (isValidAppName(candidatePath)) {
// Already a dirname of an app
return candidatePath;
@@ -26,36 +36,63 @@ function getAppName(candidatePath) {
function generateFiles() {
const browserOutput = [`import dynamic from "next/dynamic"`];
const serverOutput = [];
const appDirs = [];
const appDirs: App[] = [];
fs.readdirSync(`${APP_STORE_PATH}`).forEach(function (dir) {
if (fs.statSync(`${APP_STORE_PATH}/${dir}`).isDirectory()) {
if (!getAppName(dir)) {
return;
if (dir === "ee") {
fs.readdirSync(path.join(APP_STORE_PATH, dir)).forEach(function (eeDir) {
if (fs.statSync(path.join(APP_STORE_PATH, dir, eeDir)).isDirectory()) {
if (!getAppName(path.resolve(eeDir))) {
appDirs.push({
name: eeDir,
path: path.join(dir, eeDir),
});
}
}
});
} else {
if (fs.statSync(path.join(APP_STORE_PATH, dir)).isDirectory()) {
if (!getAppName(dir)) {
return;
}
appDirs.push({
name: dir,
path: dir,
});
}
appDirs.push(dir);
}
});
function forEachAppDir(callback) {
function forEachAppDir(callback: (arg: App) => void) {
for (let i = 0; i < appDirs.length; i++) {
callback(appDirs[i]);
}
}
function getObjectExporter(objectName, { fileToBeImported, importBuilder, entryBuilder }) {
function getObjectExporter(
objectName,
{
fileToBeImported,
importBuilder,
entryBuilder,
}: {
fileToBeImported: string;
importBuilder: (arg: App) => string;
entryBuilder: (arg: App) => string;
}
) {
const output = [];
forEachAppDir((appName) => {
if (fs.existsSync(path.join(APP_STORE_PATH, appName, fileToBeImported))) {
output.push(importBuilder(appName));
forEachAppDir((app) => {
if (fs.existsSync(path.join(APP_STORE_PATH, app.path, fileToBeImported))) {
output.push(importBuilder(app));
}
});
output.push(`export const ${objectName} = {`);
forEachAppDir((dirName) => {
if (fs.existsSync(path.join(APP_STORE_PATH, dirName, fileToBeImported))) {
output.push(entryBuilder(dirName));
forEachAppDir((app) => {
if (fs.existsSync(path.join(APP_STORE_PATH, app.path, fileToBeImported))) {
output.push(entryBuilder(app));
}
});
@@ -66,25 +103,25 @@ function generateFiles() {
serverOutput.push(
...getObjectExporter("apiHandlers", {
fileToBeImported: "api/index.ts",
importBuilder: (appName) => `const ${appName}_api = import("./${appName}/api");`,
entryBuilder: (appName) => `${appName}:${appName}_api,`,
importBuilder: (app) => `const ${app.name}_api = import("./${app.path}/api");`,
entryBuilder: (app) => `${app.name}:${app.name}_api,`,
})
);
browserOutput.push(
...getObjectExporter("appStoreMetadata", {
fileToBeImported: "_metadata.ts",
importBuilder: (appName) => `import { metadata as ${appName}_meta } from "./${appName}/_metadata";`,
entryBuilder: (appName) => `${appName}:${appName}_meta,`,
importBuilder: (app) => `import { metadata as ${app.name}_meta } from "./${app.path}/_metadata";`,
entryBuilder: (app) => `${app.name}:${app.name}_meta,`,
})
);
browserOutput.push(
...getObjectExporter("InstallAppButtonMap", {
fileToBeImported: "components/InstallAppButton.tsx",
importBuilder: (appName) =>
`const ${appName}_installAppButton = dynamic(() =>import("./${appName}/components/InstallAppButton"));`,
entryBuilder: (appName) => `${appName}:${appName}_installAppButton,`,
importBuilder: (app) =>
`const ${app.name}_installAppButton = dynamic(() =>import("./${app.path}/components/InstallAppButton"));`,
entryBuilder: (app) => `${app.name}:${app.name}_installAppButton,`,
})
);
const banner = `/**
+8 -3
View File
@@ -6,13 +6,18 @@ export async function getAppWithMetadata(app: { dirName: string }) {
try {
appMetadata = (await import(`./${app.dirName}/_metadata`)).default as App;
} catch (error) {
if (error instanceof Error) {
console.error(`No metadata found for: "${app.dirName}". Message:`, error.message);
try {
appMetadata = (await import(`./ee/${app.dirName}/_metadata`)).default as App;
} catch (e) {
if (error instanceof Error) {
console.error(`No metadata found for: "${app.dirName}". Message:`, error.message);
}
return null;
}
return null;
}
if (!appMetadata) return null;
// Let's not leak api keys to the front end
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { key, ...metadata } = appMetadata;
return metadata;
}
@@ -0,0 +1,19 @@
import { Page } from "@playwright/test";
export async function loginAsUser(username: string, page: Page) {
// Skip if file exists
await page.goto(`${process.env.PLAYWRIGHT_TEST_BASE_URL}/auth/login`);
// Click input[name="email"]
await page.click('input[name="email"]');
// Fill input[name="email"]
await page.fill('input[name="email"]', `${username}@example.com`);
// Press Tab
await page.press('input[name="email"]', "Tab");
// Fill input[name="password"]
await page.fill('input[name="password"]', username);
// Press Enter
await page.press('input[name="password"]', "Enter");
await page.waitForSelector("[data-testid=dashboard-shell]");
// Save signed-in state to '${username}StorageState.json'.
await page.context().storageState({ path: `playwright/artifacts/${username}StorageState.json` });
}
@@ -0,0 +1,57 @@
import { PlaywrightTestConfig, devices } from "@playwright/test";
import { config as dotEnvConfig } from "dotenv";
import * as path from "path";
// TODO: May be derive it automatically, so that moving the file to another location doesn't require changing the code
dotEnvConfig({ path: "../../../../../.env" });
const DEFAULT_NAVIGATION_TIMEOUT = 15000;
// Paths are relative to main playwright config.
const outputDir = path.join("../results");
const testDir = path.join("../tests");
// Quick Mode has no retries to fail fast and quickly re-iterate
// Also, it runs the tests only one browser for the same reason
const quickMode = process.env.QUICK === "true";
const CI = process.env.CI;
export const config: PlaywrightTestConfig = {
forbidOnly: !!CI,
retries: quickMode && !CI ? 0 : 1,
workers: 1,
timeout: 60_000,
reporter: [
[CI ? "github" : "list"],
[
"html",
{
outputFolder: path.join(process.cwd(), "playwright", "reports", "playwright-html-report"),
open: "never",
},
],
["junit", { outputFile: path.join(process.cwd(), "playwright", "reports", "results.xml") }],
],
outputDir,
webServer: {
command: "NEXT_PUBLIC_IS_E2E=1 yarn workspace @calcom/web start -p 3000",
port: 3000,
timeout: 60_000,
reuseExistingServer: !process.env.CI,
},
use: {
baseURL: "http://localhost:3000",
locale: "en-US",
trace: "retain-on-failure",
headless: !!process.env.CI || !!process.env.PLAYWRIGHT_HEADLESS,
},
projects: [
{
name: "chromium",
testDir,
use: {
...devices["Desktop Chrome"],
/** If navigation takes more than this, then something's wrong, let's fail fast. */
navigationTimeout: DEFAULT_NAVIGATION_TIMEOUT,
},
},
],
};
@@ -0,0 +1 @@
export * from "../../../../apps/web/playwright/lib/testUtils";
-2
View File
@@ -1,10 +1,8 @@
import type { App } from "@calcom/types/App";
import config from "./config.json";
import _package from "./package.json";
export const metadata = {
description: _package.description,
category: "other",
// FIXME: Currently for an app to be shown as installed, it must have this variable set. Either hardcoded or if it depends on some env variable, that should be checked here
installed: true,
+11 -5
View File
@@ -4,19 +4,25 @@ import type { IntegrationOAuthCallbackState } from "@calcom/app-store/types";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { App } from "@calcom/types/App";
function useAddAppMutation(type: App["type"], options?: Parameters<typeof useMutation>[2]) {
const appName = type;
const mutation = useMutation(async () => {
function useAddAppMutation(_type: App["type"] | null, options?: Parameters<typeof useMutation>[2]) {
const mutation = useMutation<unknown, Error, { type?: App["type"] } | "">(async (variables) => {
let type: string | null | undefined;
if (variables === "") {
type = _type;
} else {
type = variables.type;
}
const state: IntegrationOAuthCallbackState = {
returnTo: WEBAPP_URL + "/apps/installed" + location.search,
};
const stateStr = encodeURIComponent(JSON.stringify(state));
const searchParams = `?state=${stateStr}`;
const res = await fetch(`/api/integrations/${appName}/add` + searchParams);
const res = await fetch(`/api/integrations/${type}/add` + searchParams);
if (!res.ok) {
throw new Error("Something went wrong");
const errorBody = await res.json();
throw new Error(errorBody.message || "Something went wrong");
}
const json = await res.json();
@@ -7,6 +7,7 @@ import { metadata as applecalendar_meta } from "./applecalendar/_metadata";
import { metadata as around_meta } from "./around/_metadata";
import { metadata as caldavcalendar_meta } from "./caldavcalendar/_metadata";
import { metadata as dailyvideo_meta } from "./dailyvideo/_metadata";
import { metadata as routing_forms_meta } from "./ee/routing_forms/_metadata";
import { metadata as exchange2013calendar_meta } from "./exchange2013calendar/_metadata";
import { metadata as exchange2016calendar_meta } from "./exchange2016calendar/_metadata";
import { metadata as giphy_meta } from "./giphy/_metadata";
@@ -32,6 +33,7 @@ applecalendar:applecalendar_meta,
around:around_meta,
caldavcalendar:caldavcalendar_meta,
dailyvideo:dailyvideo_meta,
routing_forms:routing_forms_meta,
exchange2013calendar:exchange2013calendar_meta,
exchange2016calendar:exchange2016calendar_meta,
giphy:giphy_meta,
@@ -5,6 +5,7 @@
const applecalendar_api = import("./applecalendar/api");
const around_api = import("./around/api");
const caldavcalendar_api = import("./caldavcalendar/api");
const routing_forms_api = import("./ee/routing_forms/api");
const exchange2013calendar_api = import("./exchange2013calendar/api");
const exchange2016calendar_api = import("./exchange2016calendar/api");
const giphy_api = import("./giphy/api");
@@ -28,6 +29,7 @@ export const apiHandlers = {
applecalendar:applecalendar_api,
around:around_api,
caldavcalendar:caldavcalendar_api,
routing_forms:routing_forms_api,
exchange2013calendar:exchange2013calendar_api,
exchange2016calendar:exchange2016calendar_api,
giphy:giphy_api,
+59 -21
View File
@@ -1,39 +1,77 @@
import { useSession } from "next-auth/react";
import { useRouter } from "next/router";
import { useState, useEffect, useRef } from "react";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { deriveAppDictKeyFromType } from "@calcom/lib/deriveAppDictKeyFromType";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { App } from "@calcom/types/App";
import Button from "@calcom/ui/Button";
import { trpc } from "@lib/trpc";
import { UpgradeToProDialog } from "@components/UpgradeToProDialog";
import { InstallAppButtonMap } from "./apps.browser.generated";
import { InstallAppButtonProps } from "./types";
export const InstallAppButton = (
function InstallAppButtonWithoutPlanCheck(
props: {
type: App["type"];
} & InstallAppButtonProps
) => {
const { status } = useSession();
const { t } = useLocale();
) {
const key = deriveAppDictKeyFromType(props.type, InstallAppButtonMap);
const InstallAppButtonComponent = InstallAppButtonMap[key as keyof typeof InstallAppButtonMap];
if (!InstallAppButtonComponent) return null;
if (status === "unauthenticated")
return (
<InstallAppButtonComponent
render={() => (
<Button
data-testid="install-app-button"
color="primary"
href={`${WEBAPP_URL}/auth/login?callbackUrl=${WEBAPP_URL + location.pathname + location.search}`}>
{t("install_app")}
</Button>
)}
onChanged={props.onChanged}
/>
);
if (!InstallAppButtonComponent) return <>{props.render({ useDefaultComponent: true })}</>;
return <InstallAppButtonComponent render={props.render} onChanged={props.onChanged} />;
}
export const InstallAppButton = (
props: {
isProOnly?: App["isProOnly"];
type: App["type"];
} & InstallAppButtonProps
) => {
const { isLoading, data: user } = trpc.useQuery(["viewer.me"]);
const { t } = useLocale();
const [modalOpen, setModalOpen] = useState(false);
const router = useRouter();
const proProtectionElementRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
const el = proProtectionElementRef.current;
if (!el) {
return;
}
el.addEventListener(
"click",
(e) => {
if (!user) {
router.push(
`${WEBAPP_URL}/auth/login?callbackUrl=${WEBAPP_URL + location.pathname + location.search}`
);
e.stopPropagation();
return;
}
if (user.plan === "FREE" && props.isProOnly) {
setModalOpen(true);
e.stopPropagation();
return;
}
},
true
);
}, [isLoading, user, router, props.isProOnly]);
if (isLoading) {
return null;
}
return (
<div ref={proProtectionElementRef}>
<InstallAppButtonWithoutPlanCheck {...props} />
<UpgradeToProDialog modalOpen={modalOpen} setModalOpen={setModalOpen}>
{t("app_upgrade_description")}
</UpgradeToProDialog>
</div>
);
};
export { AppConfiguration } from "./_components/AppConfiguration";
@@ -0,0 +1,18 @@
import type { App } from "@calcom/types/App";
import config from "./config.json";
export const metadata = {
category: "other",
// FIXME: Currently for an app to be shown as installed, it must have this variable set. Either hardcoded or if it depends on some env variable, that should be checked here
installed: true,
rating: 0,
reviews: 0,
trending: true,
verified: true,
licenseRequired: true,
isProOnly: true,
...config,
} as App;
export default metadata;
@@ -0,0 +1,25 @@
import prisma from "@calcom/prisma";
import { AppDeclarativeHandler } from "@calcom/types/AppHandler";
import appConfig from "../config.json";
const handler: AppDeclarativeHandler = {
// Instead of passing appType and slug from here, api/integrations/[..args] should be able to derive and pass these directly to createCredential
appType: appConfig.type,
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: async ({ user, appType, slug }) => {
return await prisma.credential.create({
data: {
type: appType,
key: {},
userId: user.id,
appId: slug,
},
});
},
redirectUrl: "/apps/routing_forms/forms",
};
export default handler;
@@ -0,0 +1,2 @@
export { default as add } from "./add";
export { default as responses } from "./responses/[formId]";
@@ -0,0 +1,68 @@
import type { NextApiRequest, NextApiResponse } from "next";
import prisma from "@calcom/prisma";
import { Response } from "../../pages/routing-link/[...appPages]";
function escapeCsvText(str: string) {
return str.replace(/,/, "%2C");
}
async function* getResponses(formId: string) {
let responses;
let skip = 0;
const take = 100;
while (
(responses = await prisma.app_RoutingForms_FormResponse.findMany({
where: {
formId,
},
take: take,
skip: skip,
})) &&
responses.length
) {
const csv: string[] = [];
// Because attributes can be added or removed at any time we can't have fixed columns.
// Because there can be huge amount of data we can't keep all that in memory to identify columns from all the data at once.
// TODO: So, for now add the field label in front of it. It certainly needs improvement.
// TODO: Email CSV when we need to scale it.
responses.forEach((response) => {
const fieldResponses = response.response as Response;
const csvLineColumns = [];
for (const [, fieldResponse] of Object.entries(fieldResponses)) {
const label = escapeCsvText(fieldResponse.label);
const value = fieldResponse.value;
let serializedValue = "";
if (value instanceof Array) {
serializedValue = value.map((val) => escapeCsvText(val)).join(" | ");
} else {
serializedValue = escapeCsvText(value);
}
csvLineColumns.push(`"Attribute Label :=> Value"`);
csvLineColumns.push(`"${label} :=> ${serializedValue}"`);
}
csv.push(csvLineColumns.join(","));
});
skip += take;
yield csv.join("\n");
}
return "";
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { args } = req.query;
if (!args) {
throw new Error("args must be set");
}
const formId = args[2];
if (!formId) {
throw new Error("formId must be provided");
}
res.setHeader("Content-Type", "text/csv; charset=UTF-8");
res.setHeader("Transfer-Encoding", "chunked");
const csvIterator = getResponses(formId);
for await (const partialCsv of csvIterator) {
res.write(partialCsv);
res.write("\n");
}
res.end();
}
@@ -0,0 +1,28 @@
import NavTabs from "@components/NavTabs";
import { getSerializableForm } from "../utils";
export default function RoutingNavBar({
form,
appUrl,
}: {
form: ReturnType<typeof getSerializableForm>;
appUrl: string;
}) {
const tabs = [
{
name: "Form",
href: `${appUrl}/form-edit/${form?.id}`,
},
{
name: "Routing",
href: `${appUrl}/route-builder/${form?.id}`,
className: "hidden lg:block",
},
];
return (
<div className="mb-4">
<NavTabs tabs={tabs} linkProps={{ shallow: true }} />
</div>
);
}
@@ -0,0 +1,33 @@
import { ReactNode } from "react";
import { Alert } from "@calcom/ui/Alert";
import Shell from "@components/Shell";
import RoutingNavBar from "../components/RoutingNavBar";
import { getSerializableForm } from "../utils";
const RoutingShell: React.FC<{
form: ReturnType<typeof getSerializableForm>;
heading: ReactNode;
appUrl: string;
children: ReactNode;
}> = function RoutingShell({ children, form, heading, appUrl }) {
return (
<Shell heading={heading} subtitle={form.description || ""}>
<div className="-mx-4 px-4 sm:px-6 md:-mx-8 md:px-8">
{!form.routes?.length ? (
<Alert severity="warning" title="No routes defined yet" message="" className="mb-4" />
) : null}
{!form.fields.length ? (
<Alert severity="warning" title="No attributes defined yet" message="" className="mb-4" />
) : null}
<div className="bg-gray-50">
<RoutingNavBar appUrl={appUrl} form={form} />
{children}
</div>
</div>
</Shell>
);
};
export default RoutingShell;
@@ -0,0 +1,105 @@
import { ExternalLinkIcon, LinkIcon, DownloadIcon, TrashIcon } from "@heroicons/react/solid";
import { useRouter } from "next/router";
import { CAL_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import showToast from "@calcom/lib/notification";
import { Switch } from "@calcom/ui";
import { DialogTrigger, Dialog } from "@calcom/ui/Dialog";
import { trpc } from "@calcom/web/lib/trpc";
import ConfirmationDialogContent from "@components/dialog/ConfirmationDialogContent";
import { getSerializableForm } from "../utils";
export default function SideBar({
form,
appUrl,
}: {
form: ReturnType<typeof getSerializableForm>;
appUrl: string;
}) {
const { t } = useLocale();
const utils = trpc.useContext();
const router = useRouter();
const mutation = trpc.useMutation("viewer.app_routing_forms.form", {
onSuccess() {
router.replace(router.asPath);
},
onError() {
showToast(`Something went wrong`, "error");
},
onSettled() {
utils.invalidateQueries(["viewer.app_routing_forms.form"]);
},
});
const deleteMutation = trpc.useMutation("viewer.app_routing_forms.deleteForm", {
onError() {
showToast(`Something went wrong`, "error");
},
onSuccess() {
router.push(`/${appUrl}/forms`);
},
});
const formLink = `${CAL_URL}/forms/${form.id}`;
return (
<div className="m-0 mt-1 mb-4 w-full lg:w-3/12 lg:px-2 lg:ltr:ml-2 lg:rtl:mr-2">
<div className="px-2">
<Switch
checked={!form.disabled}
onCheckedChange={(isChecked) => {
mutation.mutate({ ...form, disabled: !isChecked });
}}
label={!form.disabled ? t("Disable Form") : t("Enable Form")}
/>
</div>
<div className="mt-4 space-y-1.5">
<a
href={formLink}
target="_blank"
rel="noreferrer"
className="text-md inline-flex items-center rounded-sm px-2 py-1 text-sm font-medium text-neutral-700 hover:bg-gray-200 hover:text-gray-900">
<ExternalLinkIcon className="h-4 w-4 text-neutral-500 ltr:mr-2 rtl:ml-2" aria-hidden="true" />
{t("preview")}
</a>
<button
onClick={() => {
navigator.clipboard.writeText(formLink);
showToast("Link copied!", "success");
}}
type="button"
className="text-md flex items-center rounded-sm px-2 py-1 text-sm font-medium text-gray-700 hover:bg-gray-200 hover:text-gray-900">
<LinkIcon className="h-4 w-4 text-neutral-500 ltr:mr-2 rtl:ml-2" />
{t("Copy link to form")}
</button>
<a
href={"/api/integrations/routing_forms/responses/" + form.id}
download={`${form.name}-${form.id}.csv`}
className="text-md flex items-center rounded-sm px-2 py-1 text-sm font-medium text-gray-700 hover:bg-gray-200 hover:text-gray-900">
<DownloadIcon className="h-4 w-4 text-neutral-500 ltr:mr-2 rtl:ml-2" />
{t("Download responses (CSV)")}
</a>
<Dialog>
<DialogTrigger className="text-md flex items-center rounded-sm px-2 py-1 text-sm font-medium text-red-500 hover:bg-gray-200">
<TrashIcon className="h-4 w-4 text-red-500 ltr:mr-2 rtl:ml-2" />
{t("delete")}
</DialogTrigger>
<ConfirmationDialogContent
isLoading={deleteMutation.isLoading}
variety="danger"
title="Delete Form"
confirmBtnText="Yes, delete form"
onConfirm={() => {
deleteMutation.mutate({ id: form.id });
}}>
Are you sure you want to delete this form? Anyone who you&apos;ve shared the link with will no
longer be able to book using it.
</ConfirmationDialogContent>
</Dialog>
</div>
</div>
);
}
@@ -0,0 +1,2 @@
export { default as InstallAppButton } from "./InstallAppButton";
export { default as Icon } from "./icon";
@@ -0,0 +1,133 @@
import { Settings, Widgets, SelectWidgetProps } from "react-awesome-query-builder";
// Figure out why ee/routing_forms/env.d.ts doesn't work
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
import BasicConfig from "react-awesome-query-builder/lib/config/basic";
import widgetsComponents from "../widgets";
const {
TextWidget,
TextAreaWidget,
MultiSelectWidget,
SelectWidget,
NumberWidget,
FieldSelect,
Conjs,
Button,
ButtonGroup,
Provider,
} = widgetsComponents;
const renderComponent = function <T1>(props: T1 | undefined, Component: React.FC<T1>) {
if (!props) {
return <div />;
}
return <Component {...props} />;
};
const settings: Settings = {
...BasicConfig.settings,
renderField: (props) => renderComponent(props, FieldSelect),
renderOperator: (props) => renderComponent(props, FieldSelect),
renderFunc: (props) => renderComponent(props, FieldSelect),
renderConjs: (props) => renderComponent(props, Conjs),
renderButton: (props) => renderComponent(props, Button),
renderButtonGroup: (props) => renderComponent(props, ButtonGroup),
renderProvider: (props) => renderComponent(props, Provider),
groupActionsPosition: "bottomCenter",
// Disable groups
maxNesting: 1,
};
// react-query-builder types have missing type property on Widget
const widgets: Widgets & { [key in keyof Widgets]: Widgets[key] & { type: string } } = {
...BasicConfig.widgets,
text: {
...BasicConfig.widgets.text,
factory: (props) => renderComponent(props, TextWidget),
},
textarea: {
...BasicConfig.widgets.textarea,
factory: (props) => renderComponent(props, TextAreaWidget),
},
number: {
...BasicConfig.widgets.number,
factory: (props) => renderComponent(props, NumberWidget),
},
multiselect: {
...BasicConfig.widgets.multiselect,
factory: (
props: SelectWidgetProps & {
listValues: { title: string; value: string }[];
}
) => renderComponent(props, MultiSelectWidget),
},
select: {
...BasicConfig.widgets.select,
factory: (
props: SelectWidgetProps & {
listValues: { title: string; value: string }[];
}
) => renderComponent(props, SelectWidget),
},
phone: {
...BasicConfig.widgets.text,
factory: (props) => {
if (!props) {
return <div />;
}
return <TextWidget type="tel" {...props} />;
},
valuePlaceholder: "Enter Phone Number",
},
email: {
...BasicConfig.widgets.text,
factory: (props) => {
if (!props) {
return <div />;
}
return <TextWidget type="email" {...props} />;
},
},
};
const types = {
...BasicConfig.types,
phone: {
...BasicConfig.types.text,
widgets: {
...BasicConfig.types.text.widgets,
},
},
email: {
...BasicConfig.types.text,
widgets: {
...BasicConfig.types.text.widgets,
},
},
};
const operators = BasicConfig.operators;
operators.equal.label = operators.select_equals.label = "Equals";
operators.greater_or_equal.label = "Greater than or equal to";
operators.greater.label = "Greater than";
operators.less_or_equal.label = "Less than or equal to";
operators.less.label = "Less than";
operators.not_equal.label = operators.select_not_equals.label = "Does not equal";
operators.between.label = "Between";
delete operators.proximity;
delete operators.is_null;
delete operators.is_not_null;
const config = {
conjunctions: BasicConfig.conjunctions,
operators,
types,
widgets,
settings,
};
export default config;
@@ -0,0 +1,125 @@
.cal-query-builder .query-builder,
.cal-query-builder .qb-draggable,
.cal-query-builder .qb-drag-handler {
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* hide connectors */
.cal-query-builder .group-or-rule::before,
.cal-query-builder .group-or-rule::after {
/* !important to ensure that styles added by react-query-awesome-builder are overriden */
content: unset !important;
}
.cal-query-builder .group--children {
/* !important to ensure that styles added by react-query-awesome-builder are overriden */
padding-left: 0 !important;
}
/* Hide "and" for between numbers */
.cal-query-builder .widget--sep {
/* !important to ensure that styles added by react-query-awesome-builder are overriden */
display: none !important;
}
/* Layout of all fields- Distance b/w them, positioning, width */
.cal-query-builder .rule--body--wrapper {
flex: 1;
display: flex;
flex-direction: column;
}
.cal-query-builder .rule--body {
display: flex;
align-items: center;
}
.cal-query-builder .rule--field,
.cal-query-builder .rule--operator,
.cal-query-builder .rule--value {
display: flex;
flex-grow: 1;
}
.cal-query-builder .rule--widget {
display: "inline-block";
width: 100%;
}
.cal-query-builder .widget--widget,
.cal-query-builder .widget--widget,
.cal-query-builder .widget--widget > * {
width: 100%;
}
.cal-query-builder .rule--drag-handler,
.cal-query-builder .rule--header {
display: flex;
align-items: center;
margin-right: 8px;
/* !important to ensure that styles added by react-query-awesome-builder are overriden */
opacity: 1 !important;
}
.cal-query-builder .rule--func--wrapper,
.cal-query-builder .rule--func,
.cal-query-builder .rule--func--args,
.cal-query-builder .rule--func--arg,
.cal-query-builder .rule--func--arg-value,
.cal-query-builder .rule--func--bracket-before,
.cal-query-builder .rule--func--bracket-after,
.cal-query-builder .rule--func--arg-sep,
.cal-query-builder .rule--func--arg-label,
.cal-query-builder .rule--func--arg-label-sep {
display: inline-block;
}
.cal-query-builder .rule--field,
.cal-query-builder .group--field,
.cal-query-builder .rule--operator,
.cal-query-builder .rule--value,
.cal-query-builder .rule--operator-options,
.cal-query-builder .widget--widget,
.cal-query-builder .widget--valuesrc,
.cal-query-builder .operator--options--sep,
.cal-query-builder .rule--before-widget,
.cal-query-builder .rule--after-widget {
display: inline-block;
}
.cal-query-builder .rule--operator,
.cal-query-builder .widget--widget,
.cal-query-builder .widget--valuesrc,
.cal-query-builder .widget--sep {
margin-left: 10px;
}
.cal-query-builder .widget--valuesrc {
margin-right: -8px;
}
.cal-query-builder .group--header,
.cal-query-builder .group--footer {
padding-left: 10px;
padding-right: 10px;
margin-top: 10px;
margin-bottom: 10px;
}
.cal-query-builder .group-or-rule-container {
margin-top: 10px;
margin-bottom: 10px;
padding-right: 10px;
}
.cal-query-builder .rule {
background-color: white;
border: 1px solid transparent;
padding: 10px;
flex: 1;
display: flex;
}
@@ -0,0 +1,300 @@
import { TrashIcon } from "@heroicons/react/solid";
import { ChangeEvent } from "react";
import {
FieldProps,
ConjsProps,
ButtonProps,
ButtonGroupProps,
ProviderProps,
SelectWidgetProps,
NumberWidgetProps,
TextWidgetProps,
} from "react-awesome-query-builder";
import { Button as CalButton } from "@calcom/ui";
import { Input } from "@calcom/ui/form/fields";
// import { mapListValues } from "../../../../utils/stuff";
import { SelectWithValidation as Select } from "@components/ui/form/Select";
const TextAreaWidget = (props: TextWidgetProps) => {
const { value, setValue, readonly, placeholder, maxLength, customProps, ...remainingProps } = props;
const onChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
const val = e.target.value;
setValue(val);
};
const textValue = value || "";
return (
<textarea
value={textValue}
placeholder={placeholder}
disabled={readonly}
onChange={onChange}
maxLength={maxLength}
className="flex flex-grow border-gray-300 text-sm"
{...customProps}
{...remainingProps}
/>
);
};
const TextWidget = (props: TextWidgetProps & { type?: string }) => {
const { value, setValue, readonly, placeholder, customProps, ...remainingProps } = props;
let { type } = props;
type = type || "text";
const onChange = (e: ChangeEvent<HTMLInputElement>) => {
const val = e.target.value;
setValue(val);
};
const textValue = value || "";
return (
<input
type={type}
className="flex flex-grow border-gray-300 text-sm"
value={textValue}
placeholder={placeholder}
disabled={readonly}
onChange={onChange}
{...remainingProps}
{...customProps}
/>
);
};
function NumberWidget({ value, setValue, ...remainingProps }: NumberWidgetProps) {
return (
<Input
name="query-builder"
type="number"
className="mt-0"
value={value}
onChange={(e) => {
setValue(e.target.value);
}}
{...remainingProps}
/>
);
}
const MultiSelectWidget = ({
listValues,
setValue,
value,
...remainingProps
}: SelectWidgetProps & {
listValues: { title: string; value: string }[];
}) => {
//TODO: Use Select here.
//TODO: Let's set listValue itself as label and value instead of using title.
if (!listValues) {
return null;
}
const selectItems = listValues.map((item) => {
return {
label: item.title,
value: item.value,
};
});
const defaultValue = selectItems.filter((item) => value?.value?.includes(item.value));
return (
<Select
className="block w-full min-w-0 flex-1 rounded-none rounded-r-sm border-gray-300 sm:text-sm"
menuPosition="fixed"
onChange={(items) => {
setValue(items?.map((item) => item.value));
}}
defaultValue={defaultValue}
isMulti={true}
options={selectItems}
{...remainingProps}
/>
);
};
function SelectWidget({
listValues,
setValue,
value,
...remainingProps
}: SelectWidgetProps & {
listValues: { title: string; value: string }[];
}) {
if (!listValues) {
return null;
}
const selectItems = listValues.map((item) => {
return {
label: item.title,
value: item.value,
};
});
const defaultValue = selectItems.find((item) => item.value === value);
return (
<Select
className="data-testid-select block w-full min-w-0 flex-1 rounded-none rounded-r-sm border-gray-300 sm:text-sm"
menuPosition="fixed"
onChange={(item) => {
if (!item) {
return;
}
setValue(item.value);
}}
defaultValue={defaultValue}
options={selectItems}
{...remainingProps}
/>
);
}
function Button({ type, label, onClick, readonly }: ButtonProps) {
if (type === "delRule" || type == "delGroup") {
return (
<button className="ml-5">
<TrashIcon className="m-0 h-4 w-4 text-neutral-500" onClick={onClick} />
</button>
);
}
let dataTestId = "";
if (type === "addRule") {
label = "Add rule";
dataTestId = "add-rule";
} else if (type == "addGroup") {
label = "Add rule group";
dataTestId = "add-rule-group";
}
return (
<CalButton
data-testid={dataTestId}
type="button"
color="secondary"
size="sm"
disabled={readonly}
onClick={onClick}>
{label}
</CalButton>
);
}
function ButtonGroup({ children }: ButtonGroupProps) {
if (!(children instanceof Array)) {
return null;
}
return (
<>
{children.map((button) => {
if (!button) {
return null;
}
return button;
})}
</>
);
}
function Conjs({ not, setNot, config, conjunctionOptions, setConjunction, disabled }: ConjsProps) {
if (!config || !conjunctionOptions) {
return null;
}
const conjsCount = Object.keys(conjunctionOptions).length;
const lessThenTwo = disabled;
const { forceShowConj } = config.settings;
const showConj = forceShowConj || (conjsCount > 1 && !lessThenTwo);
const options = [
{ label: "All", value: "all" },
{ label: "Any", value: "any" },
{ label: "None", value: "none" },
];
const renderOptions = () => {
const { checked: andSelected } = conjunctionOptions["AND"];
const { checked: orSelected } = conjunctionOptions["OR"];
const notSelected = not;
// Default to All
let value = andSelected ? "all" : orSelected ? "any" : "all";
if (notSelected) {
// not of All -> None
// not of Any -> All
value = value == "any" ? "none" : "all";
}
const selectValue = options.find((option) => option.value === value);
return (
<div className="flex items-center text-sm">
<span>Rule group when</span>
<Select
className="flex px-2"
defaultValue={selectValue}
options={options}
onChange={(option) => {
if (!option) return;
if (option.value === "all") {
setConjunction("AND");
setNot(false);
} else if (option.value === "any") {
setConjunction("OR");
setNot(false);
} else if (option.value === "none") {
setConjunction("OR");
setNot(true);
}
}}
/>
<span>match</span>
</div>
);
};
return showConj ? renderOptions() : null;
}
const FieldSelect = function FieldSelect(props: FieldProps) {
const { items, setField, selectedKey } = props;
const selectItems = items.map((item) => {
return {
...item,
value: item.key,
};
});
const defaultValue = selectItems.find((item) => {
return item.value === selectedKey;
});
return (
<Select
className="data-testid-field-select"
menuPosition="fixed"
onChange={(item) => {
if (!item) {
return;
}
setField(item.value);
}}
defaultValue={defaultValue}
options={selectItems}
/>
);
};
const Provider = ({ children }: ProviderProps) => children;
const widgets = {
TextWidget,
TextAreaWidget,
SelectWidget,
NumberWidget,
MultiSelectWidget,
FieldSelect,
Button,
ButtonGroup,
Conjs,
Provider,
};
export default widgets;
@@ -0,0 +1,16 @@
{
"/*": "Don't modify slug - If required, do it using cli edit command",
"name": "Routing Forms",
"title": "Routing Forms",
"slug": "routing_forms",
"type": "routing_forms_other",
"imageSrc": "/api/app-store/ee/routing_forms/icon.svg",
"logo": "/api/app-store/ee/routing_forms/icon.svg",
"url": "https://cal.com/apps/routing_forms",
"variant": "other",
"categories": ["other"],
"publisher": "Cal.com",
"email": "[email protected]",
"description": "It would allow a booker to connect with the right person or choose the right event, faster. It would work by taking inputs from the booker and using that data to route to the correct booker/event as configured by Cal user",
"__createdUsingCli": true
}
+1
View File
@@ -0,0 +1 @@
declare module "react-awesome-query-builder/lib/config/basic";
@@ -0,0 +1,3 @@
export * as api from "./api";
export * as components from "./components";
export { metadata } from "./_metadata";
@@ -0,0 +1,23 @@
{
"$schema": "https://json.schemastore.org/package.json",
"private": true,
"name": "@calcom/routing_forms",
"version": "0.0.0",
"main": "./index.ts",
"description": "It would allow a booker to connect with the right person or choose the right event, faster. It would work by taking inputs from the booker and using that data to route to the correct booker/event as configured by Cal user ",
"scripts": {
"app-e2e": "yarn playwright test --config=playwright/config/playwright.config.ts",
"app-e2e-quick": "QUICK=true yarn app-e2e"
},
"dependencies": {
"@calcom/lib": "*",
"dotenv": "^16.0.1",
"json-logic-js": "^2.0.2",
"playwright": "^1.22.2",
"react-awesome-query-builder": "^5.1.2"
},
"devDependencies": {
"@calcom/types": "*",
"@types/json-logic-js": "^1.2.1"
}
}
@@ -0,0 +1,14 @@
//TODO: Generate this file automatically so that like in Next.js file based routing can work automatically
import * as formEdit from "./form-edit/[...appPages]";
import * as forms from "./forms/[...appPages]";
import * as RouteBuilder from "./route-builder/[...appPages]";
import * as RoutingLink from "./routing-link/[...appPages]";
const routingConfig = {
"form-edit": formEdit,
"route-builder": RouteBuilder,
forms: forms,
"routing-link": RoutingLink,
};
export default routingConfig;
@@ -0,0 +1,402 @@
import { TrashIcon, PlusIcon, ArrowUpIcon, CollectionIcon, ArrowDownIcon } from "@heroicons/react/solid";
import { useRouter } from "next/router";
import { useForm, UseFormReturn, useFieldArray, Controller } from "react-hook-form";
import { v4 as uuidv4 } from "uuid";
import classNames from "@calcom/lib/classNames";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import showToast from "@calcom/lib/notification";
import { AppGetServerSidePropsContext, AppPrisma, AppUser } from "@calcom/types/AppGetServerSideProps";
import { Button, Select, BooleanToggleGroup, EmptyScreen } from "@calcom/ui";
import { Form, TextArea } from "@calcom/ui/form/fields";
import { trpc } from "@calcom/web/lib/trpc";
import { inferSSRProps } from "@lib/types/inferSSRProps";
import PencilEdit from "@components/PencilEdit";
import RoutingShell from "../../components/RoutingShell";
import SideBar from "../../components/SideBar";
import { getSerializableForm } from "../../utils";
export const FieldTypes = [
{
label: "Short Text",
value: "text",
},
{
label: "Number",
value: "number",
},
{
label: "Long Text",
value: "textarea",
},
{
label: "Select",
value: "select",
},
{
label: "MultiSelect",
value: "multiselect",
},
{
label: "Phone",
value: "phone",
},
{
label: "Email",
value: "email",
},
];
function Field({
hookForm,
hookFieldNamespace,
deleteField,
moveUp,
moveDown,
}: {
hookForm: UseFormReturn<inferSSRProps<typeof getServerSideProps>["form"]>;
hookFieldNamespace: `fields.${number}`;
deleteField: {
check: () => boolean;
fn: () => void;
};
moveUp: {
check: () => boolean;
fn: () => void;
};
moveDown: {
check: () => boolean;
fn: () => void;
};
}) {
return (
<div
data-testid="attribute"
className="group mb-4 flex w-full items-center justify-between hover:bg-neutral-50 ltr:mr-2 rtl:ml-2">
{moveUp.check() ? (
<button
type="button"
className="invisible absolute left-1/2 -mt-4 mb-4 -ml-4 hidden h-7 w-7 scale-0 rounded-full border bg-white p-1 text-gray-400 transition-all hover:border-transparent hover:text-black hover:shadow group-hover:visible group-hover:scale-100 sm:left-[19px] sm:ml-0 sm:block"
onClick={() => moveUp.fn()}>
<ArrowUpIcon />
</button>
) : null}
{moveDown.check() ? (
<button
type="button"
className="invisible absolute left-1/2 mt-8 -ml-4 hidden h-7 w-7 scale-0 rounded-full border bg-white p-1 text-gray-400 transition-all hover:border-transparent hover:text-black hover:shadow group-hover:visible group-hover:scale-100 sm:left-[19px] sm:ml-0 sm:block"
onClick={() => moveDown.fn()}>
<ArrowDownIcon />
</button>
) : null}
<div className="-mx-4 flex flex-1 items-center rounded-sm border border-neutral-200 bg-white p-4 py-6 sm:mx-0 sm:px-8">
<div className="w-full">
<div className="mt-2 block items-center sm:flex">
<div className="min-w-48 mb-4 sm:mb-0">
<label htmlFor="label" className="mt-0 flex text-sm font-medium text-neutral-700">
Label
</label>
</div>
<div className="w-full">
<input
type="text"
required
{...hookForm.register(`${hookFieldNamespace}.label`)}
className="block w-full rounded-sm border-gray-300 text-sm"
/>
</div>
</div>
<div className="mt-2 block items-center sm:flex">
<div className="min-w-48 mb-4 sm:mb-0">
<label htmlFor="label" className="mt-0 flex text-sm font-medium text-neutral-700">
Type
</label>
</div>
<div className="w-full">
<Controller
name={`${hookFieldNamespace}.type`}
control={hookForm.control}
render={({ field: { value, onChange } }) => {
const defaultValue = FieldTypes.find((fieldType) => fieldType.value === value);
return (
<Select
className="data-testid-attribute-type"
options={FieldTypes}
onChange={(option) => {
if (!option) {
return;
}
onChange(option.value);
}}
defaultValue={defaultValue}
/>
);
}}
/>
</div>
</div>
{["select", "multiselect"].includes(hookForm.watch(`${hookFieldNamespace}.type`)) ? (
<div className="mt-2 block items-center sm:flex">
<div className="min-w-48 mb-4 sm:mb-0">
<label htmlFor="label" className="mt-0 flex text-sm font-medium text-neutral-700">
Options
</label>
</div>
<div className="w-full">
<TextArea
placeholder="Add 1 option per line"
{...hookForm.register(`${hookFieldNamespace}.selectText`)}
/>
</div>
</div>
) : null}
<div className="mt-2 block items-center sm:flex">
<div className="min-w-48 mb-4 sm:mb-0">
<label htmlFor="label" className="mt-0 flex text-sm font-medium text-neutral-700">
Required
</label>
</div>
<div className="w-full">
<Controller
name={`${hookFieldNamespace}.required`}
control={hookForm.control}
render={({ field: { value, onChange } }) => {
return <BooleanToggleGroup value={value} onValueChange={onChange} />;
}}
/>
</div>
</div>
</div>
{deleteField.check() ? (
<button
className="float-right ml-5"
onClick={() => {
deleteField.fn();
}}
color="secondary">
<TrashIcon className="h-4 w-4 text-gray-400" />
</button>
) : null}
</div>
</div>
);
}
export default function FormEdit({
form,
appUrl,
}: inferSSRProps<typeof getServerSideProps> & { appUrl: string }) {
const { t } = useLocale();
const utils = trpc.useContext();
const router = useRouter();
const mutation = trpc.useMutation("viewer.app_routing_forms.form", {
onError() {
showToast(`Something went wrong`, "error");
},
onSettled() {
utils.invalidateQueries([
"viewer.app_routing_forms.form",
{
id: form.id,
},
]);
},
onSuccess() {
showToast(`Form updated successfully.`, "success");
router.replace(router.asPath);
},
});
const fieldsNamespace = "fields";
const hookForm = useForm({
defaultValues: form,
});
const {
fields: hookFormFields,
append: appendHookFormField,
remove: removeHookFormField,
swap: swapHookFormField,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore https://github.com/react-hook-form/react-hook-form/issues/6679
} = useFieldArray({
control: hookForm.control,
name: fieldsNamespace,
});
// hookForm.reset(form);
if (!form.fields) {
form.fields = [];
}
const addAttribute = () => {
appendHookFormField({
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
id: uuidv4(),
// This is same type from react-awesome-query-builder
type: "text",
label: "",
});
};
return (
<RoutingShell
form={form}
appUrl={appUrl}
heading={
<PencilEdit
value={
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
hookForm.watch("name")
}
onChange={(value) => {
hookForm.setValue("name", value);
}}
/>
}>
{hookFormFields.length ? (
<div className="flex flex-col-reverse lg:flex-row">
<Form
className="w-full max-w-4xl ltr:mr-2 rtl:ml-2 md:w-9/12"
form={hookForm}
handleSubmit={(data) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
mutation.mutate({
...data,
});
}}>
<div className="mb-5">
<h3 className="mb-2 text-base font-medium leading-6 text-gray-900">Description</h3>
<div className="w-full">
<textarea
id="description"
data-testid="description"
className="block w-full rounded-sm border-gray-300 text-sm "
placeholder="Form Description"
{...hookForm.register("description")}
defaultValue={form.description || ""}
/>
</div>
</div>
<hr className="mb-5 border-neutral-200" />
<h3 className="mb-2 text-base font-medium leading-6 text-gray-900">Attributes</h3>
<div className="flex flex-col">
{hookFormFields.map((field, key) => {
return (
<Field
hookForm={hookForm}
hookFieldNamespace={`${fieldsNamespace}.${key}`}
deleteField={{
check: () => hookFormFields.length > 1,
fn: () => {
removeHookFormField(key);
},
}}
moveUp={{
check: () => key !== 0,
fn: () => {
swapHookFormField(key, key - 1);
},
}}
moveDown={{
check: () => key !== hookFormFields.length - 1,
fn: () => {
if (key === hookFormFields.length - 1) {
return;
}
swapHookFormField(key, key + 1);
},
}}
key={key}
/>
);
})}
</div>
{hookFormFields.length ? (
<div className={classNames("flex")}>
<Button
data-testid="add-attribute"
type="button"
StartIcon={PlusIcon}
color="secondary"
onClick={addAttribute}>
Add Attribute
</Button>
</div>
) : null}
{hookFormFields.length ? (
<div className="mt-4 flex justify-end space-x-2 rtl:space-x-reverse">
<Button href="/apps/routing_forms/forms" color="secondary" tabIndex={-1}>
{t("cancel")}
</Button>
<Button type="submit" data-testid="update-form" disabled={mutation.isLoading}>
{t("update")}
</Button>
</div>
) : null}
</Form>
<SideBar form={form} appUrl={appUrl} />
</div>
) : (
<button data-testid="add-attribute" onClick={addAttribute} className="w-full">
<EmptyScreen
Icon={CollectionIcon}
headline="Create your first attribute"
description="Attributes are the form fields that the booker would see."
/>
</button>
)}
</RoutingShell>
);
}
export const getServerSideProps = async function getServerSideProps(
context: AppGetServerSidePropsContext,
prisma: AppPrisma,
user: AppUser
) {
if (!user) {
return {
redirect: {
permanent: false,
destination: "/auth/login",
},
};
}
const { params } = context;
if (!params) {
return {
notFound: true,
};
}
const formId = params.appPages[0];
if (!formId || params.appPages.length > 1) {
return {
notFound: true,
};
}
const form = await prisma.app_RoutingForms_Form.findUnique({
where: {
id: formId,
},
});
if (!form) {
return {
notFound: true,
};
}
return {
props: {
form: getSerializableForm(form),
},
};
};
@@ -0,0 +1,267 @@
import {
TrashIcon,
DotsHorizontalIcon,
DuplicateIcon,
PencilIcon,
PlusIcon,
LinkIcon,
ExternalLinkIcon,
CollectionIcon,
} from "@heroicons/react/solid";
import Link from "next/link";
import { useRouter } from "next/router";
import { v4 as uuidv4 } from "uuid";
import classNames from "@calcom/lib/classNames";
import { CAL_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import showToast from "@calcom/lib/notification";
import { AppGetServerSidePropsContext, AppPrisma, AppUser } from "@calcom/types/AppGetServerSideProps";
import { Button, EmptyScreen, Tooltip } from "@calcom/ui";
import Dropdown, {
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@calcom/ui/Dropdown";
import { trpc } from "@calcom/web/lib/trpc";
import { inferSSRProps } from "@lib/types/inferSSRProps";
import Shell from "@components/Shell";
import { getSerializableForm } from "../../utils";
export default function RoutingForms({
forms,
appUrl,
}: inferSSRProps<typeof getServerSideProps> & { appUrl: string }) {
const router = useRouter();
const deleteMutation = trpc.useMutation("viewer.app_routing_forms.deleteForm", {
onSuccess: () => {
showToast("Form deleted", "success");
router.replace(router.asPath);
},
onSettled: () => {
utils.invalidateQueries(["viewer.app_routing_forms.forms"]);
},
onError: () => {
showToast("Something went wrong", "error");
},
});
const utils = trpc.useContext();
const { t } = useLocale();
const mutation = trpc.useMutation("viewer.app_routing_forms.form", {
onSuccess: (_data, variables) => {
utils.invalidateQueries("viewer.app_routing_forms.forms");
router.push(`${appUrl}/form-edit/${variables.id}`);
},
onError: () => {
showToast(`Something went wrong`, "error");
},
});
const formId = uuidv4();
return (
<Shell
heading="Routing Forms"
CTA={
<Button
onClick={() => {
const form = {
id: formId,
name: `Form-${formId.slice(0, 8)}`,
};
mutation.mutate(form);
}}
data-testid="new-routing-form"
StartIcon={PlusIcon}>
New Form
</Button>
}
subtitle="You can see all routing forms and create one here.">
<div className="-mx-4 md:-mx-8">
<div className="mb-10 w-full bg-gray-50 px-4 pb-2 sm:px-6 md:px-8">
{!forms.length ? (
<EmptyScreen
Icon={CollectionIcon}
headline="Create your first form"
description="Forms enable you to allow a booker to connect with the right person or choose the right event, faster. It would work by taking inputs from the booker and using that data to route to the correct booker/event as configured by Cal user"
/>
) : null}
{forms.length ? (
<div className="-mx-4 mb-16 overflow-hidden rounded-sm border border-gray-200 bg-white sm:mx-0">
<ul data-testid="routing-forms-list" className="divide-y divide-neutral-200">
{forms.map((form, index) => {
if (!form) {
return null;
}
const formLink = `${CAL_URL}/forms/${form.id}`;
const description = form.description || "";
const disabled = form.disabled;
form.routes = form.routes || [];
const fields = form.fields || [];
return (
<li key={index}>
<div
className={classNames(
"flex items-center justify-between hover:bg-neutral-50",
disabled ? "hover:bg-white" : ""
)}>
<div
className={classNames(
"group flex w-full items-center justify-between px-4 py-4 hover:bg-neutral-50 sm:px-6",
disabled ? "hover:bg-white" : ""
)}>
<Link href={appUrl + "/form-edit/" + form.id}>
<a
className={classNames(
"flex-grow truncate text-sm",
disabled ? "pointer-events-none cursor-not-allowed opacity-30" : ""
)}>
<div className="font-medium text-neutral-900 ltr:mr-1 rtl:ml-1">
{form.name}
</div>
<div className="text-neutral-500 dark:text-white">
<h2 className="max-w-[280px] overflow-hidden text-ellipsis pb-2 opacity-60 sm:max-w-[500px]">
{description.substring(0, 100)}
{description.length > 100 && "..."}
</h2>
<div className="mt-2 text-neutral-500 dark:text-white">
{fields.length} attributes, {form.routes.length} routes &{" "}
{form._count.responses} Responses
</div>
</div>
</a>
</Link>
<div className="mt-4 hidden flex-shrink-0 sm:mt-0 sm:ml-5 sm:flex">
<div
className={classNames(
"flex justify-between space-x-2 rtl:space-x-reverse ",
disabled && "pointer-events-none cursor-not-allowed"
)}>
<Tooltip content={t("preview") as string}>
<a
href={formLink}
target="_blank"
rel="noreferrer"
className={classNames(
"btn-icon appearance-none",
disabled && " opacity-30"
)}>
<ExternalLinkIcon
className={classNames("h-5 w-5", !disabled && "group-hover:text-black")}
/>
</a>
</Tooltip>
<Tooltip content={t("copy_link") as string}>
<button
onClick={() => {
showToast(t("link_copied"), "success");
navigator.clipboard.writeText(formLink);
}}
className={classNames("btn-icon", disabled && " opacity-30")}>
<LinkIcon
className={classNames("h-5 w-5", !disabled && "group-hover:text-black")}
/>
</button>
</Tooltip>
</div>
</div>
<Dropdown>
<DropdownMenuTrigger className="h-10 w-10 cursor-pointer rounded-sm border border-transparent text-neutral-500 hover:border-gray-300 hover:text-neutral-900 focus:border-gray-300">
<DotsHorizontalIcon className="h-5 w-5 group-hover:text-gray-800" />
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem>
<Link href={appUrl + "/form-edit/" + form.id} passHref={true}>
<Button
type="button"
size="sm"
color="minimal"
className={classNames("w-full rounded-none")}
StartIcon={PencilIcon}>
{t("edit")}
</Button>
</Link>
</DropdownMenuItem>
<DropdownMenuItem>
<Button
type="button"
color="minimal"
size="sm"
className={classNames("hidden w-full rounded-none")}
StartIcon={DuplicateIcon}>
{t("duplicate")}
</Button>
</DropdownMenuItem>
<DropdownMenuSeparator className="h-px bg-gray-200" />
<DropdownMenuItem>
<Button
onClick={() => {
deleteMutation.mutate({
id: form.id,
});
}}
color="warn"
size="sm"
StartIcon={TrashIcon}
className="w-full rounded-none">
{t("delete")}
</Button>
</DropdownMenuItem>
</DropdownMenuContent>
</Dropdown>
</div>
</div>
</li>
);
})}
</ul>
</div>
) : null}
</div>
</div>
</Shell>
);
}
export const getServerSideProps = async function getServerSideProps(
context: AppGetServerSidePropsContext,
prisma: AppPrisma,
user: AppUser
) {
if (!user) {
return {
redirect: {
permanent: false,
destination: "/auth/login",
},
};
}
const forms = await prisma.app_RoutingForms_Form.findMany({
where: {
userId: user.id,
},
orderBy: {
createdAt: "desc",
},
include: {
_count: {
select: {
responses: true,
},
},
},
});
const serializableForms = forms.map((form) => getSerializableForm(form));
return {
props: {
forms: serializableForms,
},
};
};
@@ -0,0 +1,518 @@
import { PlusIcon, TrashIcon, ArrowUpIcon, ArrowDownIcon } from "@heroicons/react/solid";
import { useRouter } from "next/router";
import React, { useState, useCallback } from "react";
import { Query, Config, Builder, Utils as QbUtils } from "react-awesome-query-builder";
// types
import { JsonTree, ImmutableTree, BuilderProps } from "react-awesome-query-builder";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import showToast from "@calcom/lib/notification";
import { AppGetServerSidePropsContext, AppPrisma, AppUser } from "@calcom/types/AppGetServerSideProps";
import { inferSSRProps } from "@calcom/types/inferSSRProps";
import { Button } from "@calcom/ui";
import { Label } from "@calcom/ui/form/fields";
import { trpc } from "@calcom/web/lib/trpc";
import PencilEdit from "@components/PencilEdit";
import { SelectWithValidation as Select } from "@components/ui/form/Select";
import RoutingShell from "../../components/RoutingShell";
import SideBar from "../../components/SideBar";
import QueryBuilderInitialConfig from "../../components/react-awesome-query-builder/config/config";
import "../../components/react-awesome-query-builder/styles.css";
import { getSerializableForm } from "../../utils";
import { FieldTypes } from "../form-edit/[...appPages]";
const InitialConfig = QueryBuilderInitialConfig;
type QueryBuilderUpdatedConfig = typeof QueryBuilderInitialConfig & { fields: Config["fields"] };
export function getQueryBuilderConfig(form: inferSSRProps<typeof getServerSideProps>["form"]) {
const fields: Record<string, any> = {};
form.fields?.forEach((field) => {
if (FieldTypes.map((f) => f.value).includes(field.type)) {
const optionValues = field.selectText?.trim().split("\n");
const options = optionValues?.map((value) => {
const title = value;
return {
value,
title,
};
});
const widget = InitialConfig.widgets[field.type];
const widgetType = widget.type;
fields[field.id] = {
label: field.label,
type: widgetType,
valueSources: ["value"],
fieldSettings: {
listValues: options,
},
// preferWidgets: field.type === "textarea" ? ["textarea"] : [],
};
} else {
throw new Error("Unsupported field type:" + field.type);
}
});
// You need to provide your own config. See below 'Config format'
const config: QueryBuilderUpdatedConfig = {
...InitialConfig,
fields: fields,
};
return config;
}
const getEmptyRoute = (): SerializableRoute => {
const uuid = QbUtils.uuid();
return {
id: uuid,
action: {
type: "eventTypeRedirectUrl",
value: "",
},
queryValue: { id: uuid, type: "group" },
};
};
const createFallbackRoute = (): SerializableRoute => {
const uuid = QbUtils.uuid();
return {
id: uuid,
isFallback: true,
action: {
type: "customPageMessage",
value: "Thank you for your interest! We will be in touch soon.",
},
queryValue: { id: uuid, type: "group" },
};
};
type Route = {
id: string;
isFallback?: boolean;
action: {
type: "customPageMessage" | "externalRedirectUrl" | "eventTypeRedirectUrl";
value: string;
};
// This is what's persisted
queryValue: JsonTree;
// `queryValue` is parsed to create state
state: {
tree: ImmutableTree;
config: QueryBuilderUpdatedConfig;
};
};
type SerializableRoute = Pick<Route, "id" | "action"> & {
queryValue: Route["queryValue"];
isFallback?: Route["isFallback"];
};
const Route = ({
route,
routes,
setRoute,
config,
setRoutes,
moveUp,
moveDown,
}: {
route: Route;
routes: Route[];
setRoute: (id: string, route: Partial<Route>) => void;
config: QueryBuilderUpdatedConfig;
setRoutes: React.Dispatch<React.SetStateAction<Route[]>>;
moveUp?: { fn: () => void; check: () => boolean } | null;
moveDown?: { fn: () => void; check: () => boolean } | null;
}) => {
const index = routes.indexOf(route);
const RoutingPages: { label: string; value: Route["action"]["type"] }[] = [
{
label: "Custom Page",
value: "customPageMessage",
},
{
label: "External Redirect",
value: "externalRedirectUrl",
},
{
label: "Event Redirect",
value: "eventTypeRedirectUrl",
},
];
const { data: eventTypesByGroup } = trpc.useQuery(["viewer.eventTypes"]);
const eventOptions: { label: string; value: string }[] = [];
eventTypesByGroup?.eventTypeGroups.forEach((group) => {
group.eventTypes.forEach((eventType) => {
const uniqueSlug = `${group.profile.slug}/${eventType.slug}`;
eventOptions.push({
label: uniqueSlug,
value: uniqueSlug,
});
});
});
const onChange = (route: Route, immutableTree: ImmutableTree, config: QueryBuilderUpdatedConfig) => {
const jsonTree = QbUtils.getTree(immutableTree);
setRoute(route.id, {
state: { tree: immutableTree, config: config },
queryValue: jsonTree,
});
};
const renderBuilder = useCallback(
(props: BuilderProps) => (
<div className="query-builder-container">
<div className="query-builder qb-lite">
<Builder {...props} />
</div>
</div>
),
[]
);
return (
<div className="group mb-4 flex w-full flex-row items-center justify-between hover:bg-neutral-50 ltr:mr-2 rtl:ml-2">
{!route.isFallback ? (
<>
{moveUp?.check() ? (
<button
type="button"
className="invisible absolute left-1/2 -mt-4 mb-4 -ml-4 hidden h-7 w-7 scale-0 rounded-full border bg-white p-1 text-gray-400 transition-all hover:border-transparent hover:text-black hover:shadow group-hover:visible group-hover:scale-100 sm:left-[19px] sm:ml-0 sm:block"
onClick={() => moveUp?.fn()}>
<ArrowUpIcon />
</button>
) : null}
{moveDown?.check() ? (
<button
type="button"
className="invisible absolute left-1/2 mt-8 -ml-4 hidden h-7 w-7 scale-0 rounded-full border bg-white p-1 text-gray-400 transition-all hover:border-transparent hover:text-black hover:shadow group-hover:visible group-hover:scale-100 sm:left-[19px] sm:ml-0 sm:block"
onClick={() => moveDown?.fn()}>
<ArrowDownIcon />
</button>
) : null}
</>
) : null}
<div className="-mx-4 mb-4 flex w-full items-center rounded-sm border border-neutral-200 bg-white sm:mx-0 xl:px-8">
<div className="cal-query-builder m-4 my-8 w-full ">
<div>
<div className="flex w-full items-center text-sm text-gray-900">
<div className="flex flex-grow-0 whitespace-nowrap">
<Label>{route.isFallback ? "Fallback Route" : `Route ${index + 1}`}</Label>
<span>: Send Booker to</span>
</div>
<Select
className="block w-full flex-grow px-2"
required
value={RoutingPages.find((page) => page.value === route.action.type)}
onChange={(item) => {
if (!item) {
return;
}
const action: Route["action"] = {
type: item.value,
value: "",
};
if (action.type === "customPageMessage") {
action.value = "We are not ready for you yet :(";
} else {
action.value = "";
}
setRoute(route.id, { action });
}}
options={RoutingPages}
/>
{route.action.type ? (
route.action.type === "customPageMessage" ? (
<textarea
required
className="flex w-full flex-grow border-gray-300"
value={route.action.value}
onChange={(e) => {
setRoute(route.id, { action: { ...route.action, value: e.target.value } });
}}
/>
) : route.action.type === "externalRedirectUrl" ? (
<input
className="flex w-full flex-grow border-gray-300 text-sm"
type="text"
required
value={route.action.value}
onChange={(e) => {
setRoute(route.id, { action: { ...route.action, value: e.target.value } });
}}
placeholder="Enter External Redirect URL"
/>
) : (
<div className="block w-full">
<Select
required
options={eventOptions}
onChange={(option) => {
if (!option) {
return;
}
setRoute(route.id, { action: { ...route.action, value: option.value } });
}}
value={eventOptions.find((eventOption) => eventOption.value === route.action.value)}
/>
</div>
)
) : null}
{routes.length !== 1 && !route.isFallback ? (
<button className="ml-5" type="button">
<TrashIcon
className="m-0 h-4 w-4 text-neutral-500"
onClick={() => {
const newRoutes = routes.filter((r) => r.id !== route.id);
setRoutes(newRoutes);
}}
/>
</button>
) : null}
</div>
<hr className="my-6 text-gray-200" />
<Query
{...config}
value={route.state.tree}
onChange={(immutableTree, config) => {
onChange(route, immutableTree, config as QueryBuilderUpdatedConfig);
}}
renderBuilder={renderBuilder}
/>
</div>
</div>
</div>
</div>
);
};
const deserializeRoute = (route: SerializableRoute, config: QueryBuilderUpdatedConfig): Route => {
return {
...route,
state: {
tree: QbUtils.checkTree(QbUtils.loadTree(route.queryValue), config),
config: config,
},
};
};
const Routes = ({
form,
appUrl,
}: {
form: inferSSRProps<typeof getServerSideProps>["form"];
appUrl: string;
}) => {
const { routes: serializedRoutes } = form;
const { t } = useLocale();
const router = useRouter();
const config = getQueryBuilderConfig(form);
const [routes, setRoutes] = useState(() => {
const transformRoutes = () => {
const _routes = serializedRoutes || [getEmptyRoute()];
_routes.forEach((r) => {
if (!r.queryValue?.id) {
r.queryValue = { id: QbUtils.uuid(), type: "group" };
}
});
return _routes;
};
return transformRoutes().map((route) => deserializeRoute(route, config));
});
const mutation = trpc.useMutation("viewer.app_routing_forms.form", {
onSuccess: () => {
showToast("Form routes saved successfully.", "success");
router.replace(router.asPath);
},
onError: () => {
showToast("Something went wrong", "error");
},
});
const mainRoutes = routes.filter((route) => !route.isFallback);
let fallbackRoute = routes.find((route) => route.isFallback);
if (!fallbackRoute) {
fallbackRoute = deserializeRoute(createFallbackRoute(), config);
setRoutes((routes) => {
// Even though it's obvious that fallbackRoute is defined here but TypeScript just can't figure it out.
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return [...routes, fallbackRoute!];
});
return null;
} else if (routes.indexOf(fallbackRoute) !== routes.length - 1) {
// Ensure fallback is last
setRoutes((routes) => {
// Even though it's obvious that fallbackRoute is defined here but TypeScript just can't figure it out.
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return [...routes.filter((route) => route.id !== fallbackRoute!.id), fallbackRoute!];
});
}
const setRoute = (id: string, route: Partial<Route>) => {
const index = routes.findIndex((route) => route.id === id);
const newRoutes = [...routes];
newRoutes[index] = { ...routes[index], ...route };
setRoutes(newRoutes);
};
const swap = (from: number, to: number) => {
setRoutes((routes) => {
const newRoutes = [...routes];
const routeToSwap = newRoutes[from];
newRoutes[from] = newRoutes[to];
newRoutes[to] = routeToSwap;
return newRoutes;
});
};
return (
<div className="flex flex-col-reverse md:flex-row">
<form
className="w-full max-w-4xl ltr:mr-2 rtl:ml-2 md:w-9/12"
onSubmit={(e) => {
const serializedRoutes: SerializableRoute[] = routes.map((route) => ({
id: route.id,
action: route.action,
isFallback: route.isFallback,
queryValue: route.queryValue,
}));
const updatedForm = {
...form,
routes: serializedRoutes,
};
mutation.mutate(updatedForm);
e.preventDefault();
}}>
{mainRoutes.map((route, key) => {
const jsonLogicQuery = QbUtils.jsonLogicFormat(route.state.tree, route.state.config);
console.log(`Route: ${JSON.stringify({ action: route.action, jsonLogicQuery })}`);
return (
<Route
key={key}
config={config}
route={route}
moveUp={{
check: () => key !== 0,
fn: () => {
swap(key, key - 1);
},
}}
moveDown={{
// routes.length - 1 is fallback route always. So, routes.length - 2 is the last item that can be moved down
check: () => key !== routes.length - 2,
fn: () => {
swap(key, key + 1);
},
}}
routes={routes}
setRoute={setRoute}
setRoutes={setRoutes}
/>
);
})}
<Button
type="button"
className="mb-8"
color="secondary"
StartIcon={PlusIcon}
size="sm"
onClick={() => {
const newEmptyRoute = getEmptyRoute();
const newRoutes = [
...routes,
{
...newEmptyRoute,
state: {
tree: QbUtils.checkTree(QbUtils.loadTree(newEmptyRoute.queryValue), config),
config,
},
},
];
setRoutes(newRoutes);
}}>
Add New Route
</Button>
<div>
<Route
config={config}
route={fallbackRoute}
routes={routes}
setRoute={setRoute}
setRoutes={setRoutes}
/>
</div>
<div className="mt-4 flex justify-end space-x-2 rtl:space-x-reverse">
<Button href="/apps/routing_forms/forms" color="secondary" tabIndex={-1}>
{t("cancel")}
</Button>
<Button type="submit" disabled={mutation.isLoading}>
{t("update")}
</Button>
</div>
</form>
<SideBar form={form} appUrl={appUrl} />
</div>
);
};
export default function RouteBuilder({
form,
appUrl,
}: inferSSRProps<typeof getServerSideProps> & { appUrl: string }) {
return (
<RoutingShell appUrl={appUrl} heading={<PencilEdit value={form?.name} readOnly={true} />} form={form}>
<div className="route-config">
<Routes form={form} appUrl={appUrl} />
</div>
</RoutingShell>
);
}
export const getServerSideProps = async function getServerSideProps(
context: AppGetServerSidePropsContext,
prisma: AppPrisma,
user: AppUser
) {
if (!user) {
return {
redirect: {
permanent: false,
destination: "/auth/login",
},
};
}
const { params } = context;
if (!params) {
return {
notFound: true,
};
}
const formId = params.appPages[0];
if (!formId || params.appPages.length > 1) {
return {
notFound: true,
};
}
const form = await prisma.app_RoutingForms_Form.findUnique({
where: {
id: formId,
},
});
if (!form) {
return {
notFound: true,
};
}
return {
props: {
form: getSerializableForm(form),
},
};
};
@@ -0,0 +1,266 @@
import jsonLogic from "json-logic-js";
import { useRouter } from "next/router";
import { useState, useRef, FormEvent } from "react";
import { Utils as QbUtils } from "react-awesome-query-builder";
import { Toaster } from "react-hot-toast";
import { v4 as uuidv4 } from "uuid";
import showToast from "@calcom/lib/notification";
import { AppGetServerSidePropsContext, AppPrisma } from "@calcom/types/AppGetServerSideProps";
import { inferSSRProps } from "@calcom/types/inferSSRProps";
import { Button } from "@calcom/ui";
import { trpc } from "@calcom/web/lib/trpc";
import { getSerializableForm } from "../../utils";
import { getQueryBuilderConfig } from "../route-builder/[...appPages]";
export type Response = Record<
string,
{
value: string | string[];
label: string;
}
>;
type Form = inferSSRProps<typeof getServerSideProps>["form"];
type Route = NonNullable<Form["routes"]>[0];
function RoutingForm({ form }: inferSSRProps<typeof getServerSideProps>) {
const [customPageMessage, setCustomPageMessage] = useState<Route["action"]["value"]>("");
const formFillerIdRef = useRef(uuidv4());
// TODO: We might want to prevent spam from a single user by having same formFillerId across pageviews
// But technically, a user can fill form multiple times due to any number of reasons and we currently can't differentiate b/w that.
// - like a network error
// - or he abandoned booking flow in between
const formFillerId = formFillerIdRef.current;
const decidedActionRef = useRef<Route["action"]>();
const router = useRouter();
const onSubmit = (response: Response) => {
const decidedAction = processRoute({ form, response });
if (!decidedAction) {
// FIXME: Make sure that when a form is created, there is always a fallback route and then remove this.
alert("Define atleast 1 route");
return;
}
responseMutation.mutate({
formId: form.id,
formFillerId,
response: response,
});
decidedActionRef.current = decidedAction;
};
const responseMutation = trpc.useMutation("viewer.app_routing_forms.response", {
onSuccess: () => {
const decidedAction = decidedActionRef.current;
if (!decidedAction) {
return;
}
//TODO: Maybe take action after successful mutation
if (decidedAction.type === "customPageMessage") {
setCustomPageMessage(decidedAction.value);
} else if (decidedAction.type === "eventTypeRedirectUrl") {
router.push(`/${decidedAction.value}`);
} else if (decidedAction.type === "externalRedirectUrl") {
window.location.href = decidedAction.value;
}
showToast("Form submitted successfully! Redirecting now ...", "success");
},
onError: (e) => {
if (e?.message) {
return void showToast(e?.message, "error");
}
if (e?.data?.code === "CONFLICT") {
return void showToast("Form already submitted", "error");
}
showToast("Something went wrong", "error");
},
});
const [response, setResponse] = useState<Response>({});
const queryBuilderConfig = getQueryBuilderConfig(form);
const handleOnSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
onSubmit(response);
};
return !customPageMessage ? (
<div className="mx-auto my-0 max-w-3xl md:my-24">
<div className="w-full max-w-4xl ltr:mr-2 rtl:ml-2">
<div className="mx-0 rounded-sm border border-neutral-200 bg-white p-4 py-6 sm:-mx-4 sm:px-8">
<Toaster position="bottom-right" />
<form onSubmit={handleOnSubmit}>
<div className="mb-8">
<h1 className="font-cal mb-1 text-xl font-bold capitalize tracking-wide text-gray-900">
{form.name}
</h1>
{form.description ? (
<p className="min-h-10 text-sm text-neutral-500 ltr:mr-4 rtl:ml-4">{form.description}</p>
) : null}
</div>
{form.fields?.map((field) => {
const widget = queryBuilderConfig.widgets[field.type];
if (!("factory" in widget)) {
return null;
}
const Component = widget.factory;
const optionValues = field.selectText?.trim().split("\n");
const options = optionValues?.map((value) => {
const title = value;
return {
value,
title,
};
});
return (
<div key={field.id} className="mb-4 block flex-col sm:flex ">
<div className="min-w-48 mb-2 flex-grow">
<label
id="slug-label"
htmlFor="slug"
className="flex text-sm font-medium text-neutral-700">
{field.label}
</label>
</div>
<div className="flex rounded-sm shadow-sm">
<Component
value={response[field.id]?.value}
// required property isn't accepted by query-builder types
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
/* @ts-ignore */
required={!!field.required}
listValues={options}
setValue={(value) => {
setResponse((response) => {
response = response || {};
return {
...response,
[field.id]: {
label: field.label,
value,
},
};
});
}}
/>
</div>
</div>
);
})}
<div className="mt-4 flex justify-end space-x-2 rtl:space-x-reverse">
<Button
loading={responseMutation.isLoading}
type="submit"
className="dark:text-darkmodebrandcontrast text-brandcontrast bg-brand dark:bg-darkmodebrand relative inline-flex items-center rounded-sm border border-transparent px-3 py-2 text-sm font-medium hover:bg-opacity-90 hover:shadow-md focus:outline-none focus:ring-2 focus:ring-neutral-900 focus:ring-offset-1">
Submit
</Button>
</div>
</form>
</div>
</div>
</div>
) : (
<div className="mx-auto my-0 max-w-3xl md:my-24">
<div className="w-full max-w-4xl ltr:mr-2 rtl:ml-2">
<div className="-mx-4 rounded-sm border border-neutral-200 bg-white p-4 py-6 sm:mx-0 sm:px-8">
<div>{customPageMessage}</div>
</div>
</div>
</div>
);
}
function processRoute({ form, response }: { form: Form; response: Response }) {
const queryBuilderConfig = getQueryBuilderConfig(form);
const routes = form.routes || [];
let decidedAction: Route["action"] | null = null;
const fallbackRoute = routes.find((route) => route.isFallback);
if (!fallbackRoute) {
throw new Error("Fallback route is missing");
}
const reorderedRoutes = routes.filter((route) => !route.isFallback).concat([fallbackRoute]);
reorderedRoutes.some((route) => {
if (!route) {
return false;
}
const state = {
tree: QbUtils.checkTree(QbUtils.loadTree(route.queryValue), queryBuilderConfig),
config: queryBuilderConfig,
};
const jsonLogicQuery = QbUtils.jsonLogicFormat(state.tree, state.config);
const logic = jsonLogicQuery.logic;
let result = false;
const responseValues: Record<string, string | string[]> = {};
for (const [uuid, { value }] of Object.entries(response)) {
responseValues[uuid] = value;
}
if (logic) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
result = jsonLogic.apply(logic as any, responseValues);
} else {
// If no logic is provided, then consider it a match
result = true;
}
if (result) {
decidedAction = route.action;
return true;
}
});
return decidedAction;
}
export default function RoutingLink({ form }: { form: Form }) {
return <RoutingForm form={form} />;
}
export const getServerSideProps = async function getServerSideProps(
context: AppGetServerSidePropsContext,
prisma: AppPrisma
) {
const { params } = context;
if (!params) {
return {
notFound: true,
};
}
const formId = params.appPages[0];
if (!formId || params.appPages.length > 1) {
return {
notFound: true,
};
}
const form = await prisma.app_RoutingForms_Form.findUnique({
where: {
id: formId,
},
});
if (!form || form.disabled) {
return {
notFound: true,
};
}
return {
props: {
form: getSerializableForm(form),
},
};
};
@@ -0,0 +1,45 @@
import { Page, chromium } from "@playwright/test";
// TODO: Import it in _playwright/config/globalSetup.ts and export it from there.
import { loginAsUser } from "@calcom/app-store/_apps-playwright/config/globalSetup";
import { hashPassword } from "@calcom/lib/auth";
import prisma from "@lib/prisma";
async function installApp(appName: string, redirectUrl: string, page: Page) {
await page.goto(`${process.env.PLAYWRIGHT_TEST_BASE_URL}/apps/${appName}`);
await page.click('[data-testid="install-app-button"]');
await page.waitForNavigation({
url: (url) => {
return url.pathname == redirectUrl;
},
});
}
async function createUser(userName: string) {
const email = `${userName}@example.com`;
await prisma.user.create({
data: {
username: userName,
email,
completedOnboarding: true,
password: await hashPassword(userName),
},
});
}
async function globalSetup(/* config: FullConfig */) {
const browser = await chromium.launch({
headless: true,
});
const page = await browser.newPage();
const appName = "routing_forms";
const userName = `${appName}-e2e-${Math.random()}`;
process.env.APP_USER_NAME = userName;
await createUser(userName);
await loginAsUser(userName, page);
await installApp(appName, `/apps/${appName}/forms`, page);
page.context().close();
}
export default globalSetup;
@@ -0,0 +1,18 @@
import prisma from "@lib/prisma";
async function deleteUser(userName: string) {
await prisma.user.deleteMany({
where: {
AND: {
username: {
contains: userName,
},
},
},
});
}
async function globalTeardown(/* config: FullConfig */) {
await deleteUser("routing_forms-e2e");
}
export default globalTeardown;
@@ -0,0 +1,12 @@
import { expect, Config } from "@playwright/test";
import { config as baseConfig } from "@calcom/app-store/_apps-playwright/config/playwright.config";
const config: Config = {
...baseConfig,
globalSetup: require.resolve("./globalSetup"),
globalTeardown: require.resolve("./globalTeardown"),
};
expect.extend({});
export default config;
@@ -0,0 +1,5 @@
import { test as base } from "@playwright/test";
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface Fixtures {}
export const test = base.extend<Fixtures>({});
@@ -0,0 +1,12 @@
import prisma from "@calcom/web/lib/prisma";
export * from "@calcom/app-store/_apps-playwright/lib/testUtils";
export async function cleanUpForms() {
await prisma.app_RoutingForms_Form.deleteMany({
where: {
user: {
username: process.env.APP_USER_NAME,
},
},
});
}
@@ -0,0 +1,111 @@
import { expect, Page } from "@playwright/test";
import { test } from "../fixtures/fixtures";
import { cleanUpForms, todo } from "../lib/testUtils";
async function addForm(page: Page) {
await page.click('[data-testid="new-routing-form"]');
await page.waitForSelector('[data-testid="add-attribute"]');
}
async function verifySelectOptions(
selector: { selector: string; nth: number },
expectedOptions: string[],
page: Page
) {
await page.locator(selector.selector).nth(selector.nth).click();
const selectOptions = await page
.locator(selector.selector)
.nth(selector.nth)
.locator('[id*="react-select-"][aria-disabled]')
.allInnerTexts();
const sortedSelectOptions = [...selectOptions].sort();
const sortedExpectedOptions = [...expectedOptions].sort();
expect(sortedSelectOptions).toEqual(sortedExpectedOptions);
return {
optionsInUi: selectOptions,
};
}
async function fillForm(
page: Page,
form: { description: string; field?: { typeIndex: number; label: string } }
) {
await page.click('[data-testid="add-attribute"]');
await page.fill('[data-testid="description"]', form.description);
// Verify all Options of SelectBox
const { optionsInUi: types } = await verifySelectOptions(
{ selector: ".data-testid-attribute-type", nth: 0 },
["Email", "Long Text", "MultiSelect", "Number", "Phone", "Select", "Short Text"],
page
);
if (form.field) {
await page.fill('[name="fields.0.label"]', form.field.label);
await page.click(".data-testid-attribute-type");
await page.locator('[id*="react-select-"][aria-disabled]').nth(form.field.typeIndex).click();
}
await page.click('[data-testid="update-form"]');
await page.waitForSelector(".data-testid-toast-success");
return {
types,
};
}
test.use({ storageState: `playwright/artifacts/${process.env.APP_USER_NAME}StorageState.json` });
test.describe("Forms", () => {
test("should be able to add a new form and see it in forms list", async ({ page }) => {
page.goto("/");
await page.click('[href="/apps/routing_forms/forms"]');
await page.waitForSelector('[data-testid="empty-screen"]');
await addForm(page);
await page.click('[href="/apps/routing_forms/forms"]');
await page.waitForSelector('[data-testid="routing-forms-list"]');
expect(await page.locator('[data-testid="routing-forms-list"] > li').count()).toBe(1);
});
test("should be able to edit the form", async ({ page }) => {
await page.goto("/apps/routing_forms/forms");
await addForm(page);
const description = "Test Description";
const field = {
label: "Test Label",
typeIndex: 1,
};
const { types } = await fillForm(page, {
description,
field: field,
});
await page.reload();
expect(await page.inputValue(`[data-testid="description"]`), description);
expect(await page.locator('[data-testid="attribute"]').count()).toBe(1);
expect(await page.inputValue('[name="fields.0.label"]')).toBe(field.label);
expect(await page.locator(".data-testid-attribute-type").first().innerText()).toBe(
types[field.typeIndex]
);
await page.click('[href*="/apps/routing_forms/route-builder/"]');
await page.click('[data-testid="add-rule"]');
await verifySelectOptions(
{
selector: ".rule-container .data-testid-field-select",
nth: 0,
},
[field.label],
page
);
});
todo("Test Routing Link");
test.afterAll(() => {
cleanUpForms();
});
});
@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
<path d="M7 3a1 1 0 000 2h6a1 1 0 100-2H7zM4 7a1 1 0 011-1h10a1 1 0 110 2H5a1 1 0 01-1-1zM2 11a2 2 0 012-2h12a2 2 0 012 2v4a2 2 0 01-2 2H4a2 2 0 01-2-2v-4z" />
</svg>

After

Width:  |  Height:  |  Size: 265 B

@@ -0,0 +1,182 @@
import { Prisma } from "@prisma/client";
import { z } from "zod";
import { createProtectedRouter } from "@server/createRouter";
import { TRPCError } from "@trpc/server";
import { zodFields, zodRoutes } from "./zod";
const app_RoutingForms = createProtectedRouter()
.query("forms", {
async resolve({ ctx: { user, prisma } }) {
return await prisma.app_RoutingForms_Form.findMany({
where: {
userId: user.id,
},
orderBy: {
createdAt: "asc",
},
});
},
})
.query("form", {
input: z.object({
id: z.string(),
}),
async resolve({ ctx: { prisma }, input }) {
const form = await prisma.app_RoutingForms_Form.findFirst({
where: {
id: input.id,
},
});
return form;
},
})
.mutation("form", {
input: z.object({
id: z.string(),
name: z.string(),
description: z.string().nullable().optional(),
disabled: z.boolean().optional(),
fields: zodFields,
routes: zodRoutes,
}),
async resolve({ ctx: { user, prisma }, input }) {
const { name, id, routes, description, disabled } = input;
let { fields } = input;
fields = fields || [];
return await prisma.app_RoutingForms_Form.upsert({
where: {
id: id,
},
create: {
user: {
connect: {
id: user.id,
},
},
fields: fields,
name: name,
description,
// Prisma doesn't allow setting null value directly for JSON. It recommends using JsonNull for that case.
routes: routes === null ? Prisma.JsonNull : routes,
id: id,
},
update: {
disabled: disabled,
fields: fields,
name: name,
description,
routes: routes === null ? Prisma.JsonNull : routes,
},
});
},
})
// TODO: Can't se use DELETE method on form?
.mutation("deleteForm", {
input: z.object({
id: z.string(),
}),
async resolve({ ctx, input }) {
return await ctx.prisma.app_RoutingForms_Form.delete({
where: {
id: input.id,
},
});
},
})
.mutation("response", {
input: z.object({
formId: z.string(),
formFillerId: z.string(),
response: z.record(
z.object({
label: z.string(),
value: z.union([z.string(), z.array(z.string())]),
})
),
}),
async resolve({ ctx: { prisma }, input }) {
try {
const { response, formId } = input;
const form = await prisma.app_RoutingForms_Form.findFirst({
where: {
id: formId,
},
});
if (!form) {
throw new TRPCError({
code: "NOT_FOUND",
});
}
const fieldsParsed = zodFields.safeParse(form.fields);
if (!fieldsParsed.success) {
// This should not be possible normally as before saving the form it is verified by zod
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
});
}
const fields = fieldsParsed.data;
if (!fields) {
// There is no point in submitting a form that doesn't have fields defined
throw new TRPCError({
code: "BAD_REQUEST",
});
}
const missingFields = fields
.filter((field) => !(field.required ? response[field.id]?.value : true))
.map((f) => f.label);
if (missingFields.length) {
throw new TRPCError({
code: "BAD_REQUEST",
message: `Missing required fields ${missingFields.join(", ")}`,
});
}
const invalidFields = fields
.filter((field) => {
const fieldValue = response[field.id]?.value;
// The field isn't required at this point. Validate only if it's set
if (!fieldValue) {
return false;
}
let schema;
if (field.type === "email") {
schema = z.string().email();
} else if (field.type === "phone") {
schema = z.any();
} else {
schema = z.any();
}
return !schema.safeParse(fieldValue).success;
})
.map((f) => ({ label: f.label, type: f.type }));
if (invalidFields.length) {
throw new TRPCError({
code: "BAD_REQUEST",
message: `Invalid fields ${invalidFields.map((f) => `${f.label}: ${f.type}`)}`,
});
}
return await prisma.app_RoutingForms_FormResponse.create({
data: input,
});
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
if (e.code === "P2002") {
throw new TRPCError({
code: "CONFLICT",
});
}
}
throw e;
}
},
});
export default app_RoutingForms;
@@ -0,0 +1,30 @@
import { App_RoutingForms_Form } from "@prisma/client";
import { zodFields, zodRoutes } from "./zod";
export function getSerializableForm<TForm extends App_RoutingForms_Form>(form: TForm) {
const routesParsed = zodRoutes.safeParse(form.routes);
if (!routesParsed.success) {
throw new Error("Error parsing routes");
}
const fieldsParsed = zodFields.safeParse(form.fields);
if (!fieldsParsed.success) {
throw new Error("Error parsing fields");
}
// Ideally we shouldb't have needed to explicitly type it but due to some reason it's not working reliably with VSCode TypeCheck
const serializableForm: Omit<TForm, "fields" | "routes" | "createdAt" | "updatedAt"> & {
fields: typeof fieldsParsed["data"];
routes: typeof routesParsed["data"];
createdAt: string;
updatedAt: string;
} = {
...form,
fields: fieldsParsed.data,
routes: routesParsed.data,
createdAt: form.createdAt.toString(),
updatedAt: form.updatedAt.toString(),
};
return serializableForm;
}
@@ -0,0 +1,39 @@
import { z } from "zod";
export const zodFields = z
.array(
z.object({
id: z.string(),
label: z.string(),
type: z.string(),
selectText: z.string().optional(),
required: z.boolean().optional(),
})
)
.optional();
export const zodRoutes = z
.union([
z.array(
z.object({
id: z.string(),
queryValue: z.object({
id: z.string().optional(),
type: z.union([z.literal("group"), z.literal("switch_group")]),
children1: z.any(),
properties: z.any(),
}),
isFallback: z.boolean().optional(),
action: z.object({
// TODO: Make it a union type of "customPageMessage" and ..
type: z.union([
z.literal("customPageMessage"),
z.literal("externalRedirectUrl"),
z.literal("eventTypeRedirectUrl"),
]),
value: z.string(),
}),
})
),
z.null(),
])
.optional();
+2
View File
@@ -5,6 +5,8 @@ import "./next-auth";
export declare module "next" {
interface NextApiRequest extends IncomingMessage {
// args is defined by /integrations/[...args] endpoint
query: Partial<{ [key: string]: string | string[] }> & { args: string[] };
session?: Session | null;
}
}
+4
View File
@@ -0,0 +1,4 @@
// TODO: Generate this file automatically. This supposed to contain trpc-routes from all the apps automatically imported here and then exported.
// Can't use this file right now as I am not able to figure out how to keep getting tRPC typesafety with merge calls done on already created router
// Till that time import routers from each app directly to core.
// import { Router } from "@trpc/server/dist/declarations/src/router";
+18 -2
View File
@@ -1,8 +1,24 @@
{
"extends": "@calcom/tsconfig/react-library.json",
"include": [".", "@calcom/types"],
"exclude": ["dist", "build", "node_modules"],
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@components/*": ["../../apps/web/components/*"],
"@lib/*": ["../../apps/web/lib/*"],
"@server/*": ["../../apps/web/server/*"],
"@prisma/client/*": ["@calcom/prisma/client/*"]
},
"resolveJsonModule": true
}
},
"include": [
"next-env.d.ts",
"@calcom/types",
"../../packages/types/*.d.ts",
"../../packages/types/next-auth.d.ts",
"**/*.ts",
"**/*.tsx",
"../../apps/web/server/**/*.ts",
"../../apps/web/server/**/*.tsx"
]
}
+7 -1
View File
@@ -5,6 +5,12 @@ export type IntegrationOAuthCallbackState = {
};
export interface InstallAppButtonProps {
render: (renderProps: ButtonBaseProps) => JSX.Element;
render: (
renderProps:
| ButtonBaseProps & {
/** Tells that the default render component should be used */
useDefaultComponent?: boolean;
}
) => JSX.Element;
onChanged?: () => unknown;
}
+1
View File
@@ -11,6 +11,7 @@ export default function showToast(message: string, variant: "success" | "warning
color: "#fff",
boxShadow: "none",
},
className: "data-testid-toast-success",
});
break;
case "error":
@@ -0,0 +1,33 @@
-- CreateTable
CREATE TABLE "App_RoutingForms_Form" (
"id" TEXT NOT NULL,
"description" TEXT,
"routes" JSONB,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
"name" TEXT NOT NULL,
"fields" JSONB,
"userId" INTEGER NOT NULL,
"disabled" BOOLEAN NOT NULL DEFAULT false,
CONSTRAINT "App_RoutingForms_Form_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "App_RoutingForms_FormResponse" (
"id" SERIAL NOT NULL,
"formFillerId" TEXT NOT NULL,
"formId" TEXT NOT NULL,
"response" JSONB NOT NULL,
CONSTRAINT "App_RoutingForms_FormResponse_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "App_RoutingForms_FormResponse_formFillerId_formId_key" ON "App_RoutingForms_FormResponse"("formFillerId", "formId");
-- AddForeignKey
ALTER TABLE "App_RoutingForms_Form" ADD CONSTRAINT "App_RoutingForms_Form_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "App_RoutingForms_FormResponse" ADD CONSTRAINT "App_RoutingForms_FormResponse_formId_fkey" FOREIGN KEY ("formId") REFERENCES "App_RoutingForms_Form"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+51 -25
View File
@@ -125,62 +125,64 @@ enum UserPermissionRole {
}
model User {
id Int @id @default(autoincrement())
username String? @unique
id Int @id @default(autoincrement())
username String? @unique
name String?
/// @zod.email()
email String @unique
email String @unique
emailVerified DateTime?
password String?
bio String?
avatar String?
timeZone String @default("Europe/London")
weekStart String @default("Sunday")
timeZone String @default("Europe/London")
weekStart String @default("Sunday")
// DEPRECATED - TO BE REMOVED
startTime Int @default(0)
endTime Int @default(1440)
startTime Int @default(0)
endTime Int @default(1440)
// </DEPRECATED>
bufferTime Int @default(0)
hideBranding Boolean @default(false)
bufferTime Int @default(0)
hideBranding Boolean @default(false)
theme String?
createdDate DateTime @default(now()) @map(name: "created")
createdDate DateTime @default(now()) @map(name: "created")
trialEndsAt DateTime?
eventTypes EventType[] @relation("user_eventtype")
eventTypes EventType[] @relation("user_eventtype")
credentials Credential[]
teams Membership[]
bookings Booking[]
schedules Schedule[]
defaultScheduleId Int?
selectedCalendars SelectedCalendar[]
completedOnboarding Boolean @default(false)
completedOnboarding Boolean @default(false)
locale String?
timeFormat Int? @default(12)
timeFormat Int? @default(12)
twoFactorSecret String?
twoFactorEnabled Boolean @default(false)
identityProvider IdentityProvider @default(CAL)
twoFactorEnabled Boolean @default(false)
identityProvider IdentityProvider @default(CAL)
identityProviderId String?
availability Availability[]
invitedTo Int?
plan UserPlan @default(TRIAL)
plan UserPlan @default(TRIAL)
webhooks Webhook[]
brandColor String @default("#292929")
darkBrandColor String @default("#fafafa")
brandColor String @default("#292929")
darkBrandColor String @default("#fafafa")
// the location where the events will end up
destinationCalendar DestinationCalendar?
away Boolean @default(false)
away Boolean @default(false)
// participate in dynamic group booking or not
allowDynamicBooking Boolean? @default(true)
allowDynamicBooking Boolean? @default(true)
/// @zod.custom(imports.userMetadata)
metadata Json?
verified Boolean? @default(false)
role UserPermissionRole @default(USER)
disableImpersonation Boolean @default(false)
impersonatedUsers Impersonations[] @relation("impersonated_user")
impersonatedBy Impersonations[] @relation("impersonated_by_user")
verified Boolean? @default(false)
role UserPermissionRole @default(USER)
disableImpersonation Boolean @default(false)
impersonatedUsers Impersonations[] @relation("impersonated_user")
impersonatedBy Impersonations[] @relation("impersonated_by_user")
apiKeys ApiKey[]
accounts Account[]
sessions Session[]
workflows Workflow[]
routingForms App_RoutingForms_Form[] @relation("routing-form")
Feedback Feedback[]
@@map(name: "users")
@@ -488,6 +490,30 @@ model App {
ApiKey ApiKey[]
}
model App_RoutingForms_Form {
id String @id @default(cuid())
description String?
routes Json?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
name String
fields Json?
user User @relation("routing-form", fields: [userId], references: [id], onDelete: Cascade)
userId Int
responses App_RoutingForms_FormResponse[]
disabled Boolean @default(false)
}
model App_RoutingForms_FormResponse {
id Int @id @default(autoincrement())
formFillerId String @default(cuid())
form App_RoutingForms_Form @relation(fields: [formId], references: [id], onDelete: Cascade)
formId String
response Json
@@unique([formFillerId, formId])
}
model Feedback {
id Int @id @default(autoincrement())
date DateTime
@@ -1,6 +1,12 @@
[
{
"/*": "This file is auto-generated and managed by `yarn app-store`. Don't edit manually but it is to be committed",
"dirName": "routing_forms",
"categories": ["other"],
"slug": "routing_forms",
"type": "routing_forms_other"
},
{
"dirName": "whereby",
"categories": ["video"],
"slug": "whereby",
+1
View File
@@ -108,6 +108,7 @@ async function main() {
invite_link: process.env.ZAPIER_INVITE_LINK,
});
}
// Web3 apps
await createApp("huddle01", "huddle01video", ["web3", "video"], "huddle01_video");
await createApp("metamask", "metamask", ["web3"], "metamask_web3");
+2
View File
@@ -73,4 +73,6 @@ export interface App {
price?: number;
/** only required for "usage-based" billing. % of commission for paid bookings */
commission?: number;
licenseRequired?: boolean;
isProOnly?: boolean;
}
+16
View File
@@ -0,0 +1,16 @@
import { GetServerSidePropsContext, GetServerSidePropsResult } from "next";
import { CalendsoSessionUser } from "next-auth";
import prisma from "@calcom/web/lib/prisma";
export type AppUser = CalendsoSessionUser | undefined;
export type AppPrisma = typeof prisma;
export type AppGetServerSidePropsContext = GetServerSidePropsContext<{
appPages: string[];
}>;
export type AppGetServerSideProps = (
context: AppGetServerSidePropsContext,
prisma: AppPrisma,
user: AppUser
) => GetServerSidePropsResult;
+15
View File
@@ -0,0 +1,15 @@
import { NextApiHandler } from "next";
import { Session } from "next-auth";
import { Credential } from "@calcom/prisma/client";
export type AppDeclarativeHandler = {
appType: string;
slug: string;
supportsMultipleInstalls: false;
handlerType: "add";
createCredential: (arg: { user: Session["user"]; appType: string; slug: string }) => Promise<Credential>;
supportsMultipleInstalls: boolean;
redirectUrl: string;
};
export type AppHandler = AppDeclarativeHandler | NextApiHandler;
+56
View File
@@ -0,0 +1,56 @@
import { Root as ToggleGroupPrimitive, Item as ToggleGroupItemPrimitive } from "@radix-ui/react-toggle-group";
import { useState } from "react";
import classNames from "@calcom/lib/classNames";
const boolean = (yesNo: "yes" | "no") => (yesNo === "yes" ? true : yesNo === "no" ? false : undefined);
const yesNo = (boolean?: boolean) => (boolean === true ? "yes" : boolean === false ? "no" : undefined);
export default function BooleanToggleGroup({
defaultValue = true,
value,
// eslint-disable-next-line @typescript-eslint/no-empty-function
onValueChange = () => {},
}: {
defaultValue?: boolean;
value?: boolean;
onValueChange?: (value?: boolean) => void;
}) {
// Maintain a state because it is not necessary that onValueChange the parent component would re-render. Think react-hook-form
// Also maintain a string as boolean isn't accepted as ToggleGroupPrimitive value
const [yesNoValue, setYesNoValue] = useState<"yes" | "no" | undefined>(yesNo(value));
if (!yesNoValue) {
setYesNoValue(yesNo(defaultValue));
onValueChange(defaultValue);
return null;
}
return (
<ToggleGroupPrimitive
value={yesNoValue}
type="single"
className="rounded-sm"
onValueChange={(yesNoValue: "yes" | "no") => {
setYesNoValue(yesNoValue);
onValueChange(boolean(yesNoValue));
}}>
<ToggleGroupItemPrimitive
className={classNames(
boolean(yesNoValue) ? "bg-gray-200" : "",
"border border-gray-300 py-2 px-3 text-sm"
)}
value="yes">
Yes
</ToggleGroupItemPrimitive>
<ToggleGroupItemPrimitive
className={classNames(
!boolean(yesNoValue) ? "bg-gray-200" : "",
"border border-l-0 border-gray-300 py-2 px-3 text-sm"
)}
value="no">
No
</ToggleGroupItemPrimitive>
</ToggleGroupPrimitive>
);
}
+3 -1
View File
@@ -13,7 +13,9 @@ export default function EmptyScreen({
}) {
return (
<>
<div className="min-h-80 my-6 flex flex-col items-center justify-center rounded-sm border border-dashed">
<div
data-testid="empty-screen"
className="min-h-80 my-6 flex flex-col items-center justify-center rounded-sm border border-dashed">
<div className="flex h-[72px] w-[72px] items-center justify-center rounded-full bg-gray-600 dark:bg-white">
<Icon className="inline-block h-10 w-10 text-white dark:bg-white dark:text-gray-600" />
</div>
+1
View File
@@ -5,3 +5,4 @@ export { default as Loader } from "./Loader";
export * from "./skeleton";
export { default as Switch } from "./Switch";
export { default as Tooltip } from "./Tooltip";
export { default as BooleanToggleGroup } from "./BooleanToggleGroup";