Feature/ Manage Booking Questions (#6560)

* WIP

* Create Booking Questions builder

* Renaming things

* wip

* wip

* Implement Add Guests and other fixes

* Fixes after testing

* Fix wrong status code 404

* Fixes

* Lint fixes

* Self review comments addressed

* More self review comments addressed

* Feedback from zomars

* BugFixes after testing

* More fixes discovered during review

* Update packages/lib/hooks/useHasPaidPlan.ts

Co-authored-by: Omar López <zomars@me.com>

* More fixes discovered during review

* Update packages/ui/components/form/inputs/Input.tsx

Co-authored-by: Omar López <zomars@me.com>

* More fixes discovered during review

* Update packages/features/bookings/lib/getBookingFields.ts

Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>

* More PR review fixes

* Hide label using labelSrOnly

* Fix Carinas feedback and implement 2 workflows thingy

* Misc fixes

* Fixes from Loom comments and PR

* Fix a lint errr

* Fix cancellation reason

* Fix regression in edit due to name conflict check

* Update packages/features/form-builder/FormBuilder.tsx

Co-authored-by: Carina Wollendorfer <30310907+CarinaWolli@users.noreply.github.com>

* Fix options not set when default value is used

* Restoring reqBody to avoid uneeded conflicts with main

* Type fix

* Update apps/web/components/booking/pages/BookingPage.tsx

Co-authored-by: Omar López <zomars@me.com>

* Update packages/features/form-builder/FormBuilder.tsx

Co-authored-by: Omar López <zomars@me.com>

* Update apps/web/components/booking/pages/BookingPage.tsx

Co-authored-by: Omar López <zomars@me.com>

* Apply suggestions from code review

Co-authored-by: Omar López <zomars@me.com>

* Show fields but mark them disabled

* Apply suggestions from code review

Co-authored-by: Omar López <zomars@me.com>

* More comments

* Fix booking success page crash when a booking doesnt have newly added required fields response

* Dark theme asterisk not visible

* Make location required in zodSchema as was there in production

* Linting

* Remove _metadata.ts files for apps that have config.json

* Revert "Remove _metadata.ts files for apps that have config.json"

This reverts commit d79bdd336cf312a30a8943af94c059947bd91ccd.

* Fix lint error

* Fix missing condition for samlSPConfig

* Delete unexpectedly added file

* yarn.lock change not required

* fix types

* Make checkboxes rounded

* Fix defaultLabel being stored as label due to SSR rendering

* Shaved 16kb from booking page

* Explicit types for profile

* Show payment value only if price is greater than 0

* Fix type error

* Add back inferred types as they are failing

* Fix duplicate label on number

---------

Co-authored-by: zomars <zomars@me.com>
Co-authored-by: sean-brydon <55134778+sean-brydon@users.noreply.github.com>
Co-authored-by: Carina Wollendorfer <30310907+CarinaWolli@users.noreply.github.com>
Co-authored-by: Efraín Rochín <roae.85@gmail.com>
This commit is contained in:
Hariom Balhara
2023-03-02 11:15:28 -07:00
committed by GitHub
co-authored by Omar López sean-brydon Carina Wollendorfer Efraín Rochín
parent 51bf613621
commit 517cfde5b8
58 changed files with 2921 additions and 1463 deletions
@@ -0,0 +1,24 @@
import { FormattedNumber, IntlProvider } from "react-intl";
import getPaymentAppData from "@calcom/lib/getPaymentAppData";
import { FiCreditCard } from "@calcom/ui/components/icon";
const BookingDescriptionPayment = (props: { eventType: Parameters<typeof getPaymentAppData>[0] }) => {
const paymentAppData = getPaymentAppData(props.eventType);
if (!paymentAppData || paymentAppData.price <= 0) return null;
return (
<p className="text-bookinglight -ml-2 px-2 text-sm ">
<FiCreditCard className="ml-[2px] -mt-1 inline-block h-4 w-4 ltr:mr-[10px] rtl:ml-[10px]" />
<IntlProvider locale="en">
<FormattedNumber
value={paymentAppData.price / 100.0}
style="currency"
currency={paymentAppData.currency?.toUpperCase()}
/>
</IntlProvider>
</p>
);
};
export default BookingDescriptionPayment;
File diff suppressed because it is too large Load Diff
@@ -4,7 +4,7 @@ import { isValidPhoneNumber } from "libphonenumber-js";
import { Trans } from "next-i18next";
import Link from "next/link";
import { useEffect } from "react";
import { Controller, useForm, useWatch } from "react-hook-form";
import { Controller, useForm, useWatch, useFormContext } from "react-hook-form";
import { z } from "zod";
import type { EventLocationType, LocationObject } from "@calcom/app-store/locations";
@@ -49,16 +49,19 @@ const LocationInput = (props: {
defaultValue?: string;
}): JSX.Element | null => {
const { eventLocationType, locationFormMethods, ...remainingProps } = props;
const { control } = useFormContext() as typeof locationFormMethods;
if (eventLocationType?.organizerInputType === "text") {
return (
<input {...locationFormMethods.register(eventLocationType.variable)} type="text" {...remainingProps} />
);
} else if (eventLocationType?.organizerInputType === "phone") {
return (
<PhoneInput
<Controller
name={eventLocationType.variable}
control={locationFormMethods.control}
{...remainingProps}
control={control}
render={({ field: { onChange, value } }) => {
return <PhoneInput onChange={onChange} value={value} {...remainingProps} />;
}}
/>
);
}
@@ -1,214 +0,0 @@
import { useAutoAnimate } from "@formkit/auto-animate/react";
import { EventTypeCustomInputType } from "@prisma/client";
import type { CustomInputParsed } from "pages/event-types/[type]";
import type { FC } from "react";
import type { Control, UseFormRegister } from "react-hook-form";
import { Controller, useFieldArray, useForm, useWatch } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button, Label, Select, TextField } from "@calcom/ui";
import { FiPlus, FiX } from "@calcom/ui/components/icon";
interface OptionTypeBase {
label: string;
value: EventTypeCustomInputType;
options?: { label: string; type: string }[];
}
interface Props {
onSubmit: (output: CustomInputParsed) => void;
onCancel: () => void;
selectedCustomInput?: CustomInputParsed;
}
type IFormInput = CustomInputParsed;
/**
* Getting a random ID gives us the option to know WHICH field is changed
* when the user edits a custom field.
* This UUID is only used to check for changes in the UI and not the ID we use in the DB
* There is very very very slim chance that this will cause a collision
* */
const randomId = () => Math.floor(Math.random() * 1000000 + new Date().getTime());
const CustomInputTypeForm: FC<Props> = (props) => {
const { t } = useLocale();
const inputOptions: OptionTypeBase[] = [
{ value: EventTypeCustomInputType.TEXT, label: t("text") },
{ value: EventTypeCustomInputType.TEXTLONG, label: t("multiline_text") },
{ value: EventTypeCustomInputType.NUMBER, label: t("number") },
{ value: EventTypeCustomInputType.BOOL, label: t("checkbox") },
{
value: EventTypeCustomInputType.RADIO,
label: t("radio"),
},
{ value: EventTypeCustomInputType.PHONE, label: t("phone_number") },
];
const { selectedCustomInput } = props;
const defaultValues = selectedCustomInput
? { ...selectedCustomInput, id: selectedCustomInput?.id || randomId() }
: {
id: randomId(),
type: EventTypeCustomInputType.TEXT,
};
const { register, control, getValues } = useForm<IFormInput>({
defaultValues,
});
const selectedInputType = useWatch({ name: "type", control });
const selectedInputOption = inputOptions.find((e) => selectedInputType === e.value);
const onCancel = () => {
props.onCancel();
};
return (
<div className="flex flex-col space-y-4">
<div>
<label htmlFor="type" className="block text-sm font-medium text-gray-700">
{t("input_type")}
</label>
<Controller
name="type"
control={control}
render={({ field }) => (
<Select
id="type"
defaultValue={selectedInputOption}
options={inputOptions}
isSearchable={false}
className="mt-1 mb-2 block w-full min-w-0 flex-1 text-sm"
onChange={(option) => option && field.onChange(option.value)}
value={selectedInputOption}
onBlur={field.onBlur}
name={field.name}
/>
)}
/>
</div>
<TextField
label={t("label")}
type="text"
id="label"
required
className="block w-full rounded-sm border-gray-300 text-sm"
defaultValue={selectedCustomInput?.label}
{...register("label", { required: true })}
/>
{(selectedInputType === EventTypeCustomInputType.TEXT ||
selectedInputType === EventTypeCustomInputType.TEXTLONG) && (
<TextField
label={t("placeholder")}
type="text"
id="placeholder"
className="block w-full rounded-sm border-gray-300 text-sm"
defaultValue={selectedCustomInput?.placeholder}
{...register("placeholder")}
/>
)}
{selectedInputType === EventTypeCustomInputType.RADIO && (
<RadioInputHandler control={control} register={register} />
)}
<div className="flex h-5 items-center">
<input
id="required"
type="checkbox"
className="text-primary-600 focus:ring-primary-500 h-4 w-4 rounded border-gray-300 ltr:mr-2 rtl:ml-2"
defaultChecked={selectedCustomInput?.required ?? true}
{...register("required")}
/>
<label htmlFor="required" className="block text-sm font-medium text-gray-700">
{t("is_required")}
</label>
</div>
<input
type="hidden"
id="eventTypeId"
value={selectedCustomInput?.eventTypeId || -1}
{...register("eventTypeId", { valueAsNumber: true })}
/>
<input
type="hidden"
id="id"
value={selectedCustomInput?.id || -1}
{...register("id", { valueAsNumber: true })}
/>
<div className="mt-5 flex justify-end space-x-2 rtl:space-x-reverse sm:mt-4">
<Button onClick={onCancel} type="button" color="secondary" className="ltr:mr-2 rtl:ml-2">
{t("cancel")}
</Button>
<Button
type="button"
onClick={() => {
props.onSubmit(getValues());
}}>
{t("save")}
</Button>
</div>
</div>
);
};
function RadioInputHandler({
register,
control,
}: {
register: UseFormRegister<IFormInput>;
control: Control<IFormInput>;
}) {
const { t } = useLocale();
const { fields, append, remove } = useFieldArray<IFormInput>({
control,
name: "options",
shouldUnregister: true,
});
const [animateRef] = useAutoAnimate<HTMLUListElement>();
return (
<div className="flex flex-col ">
<Label htmlFor="radio_options">{t("options")}</Label>
<ul
className="flex max-h-80 w-full flex-col space-y-1 overflow-y-scroll rounded-md bg-gray-50 p-4"
ref={animateRef}>
<>
{fields.map((option, index) => (
<li key={`${option.id}`}>
<TextField
id={option.id}
placeholder={t("enter_option", { index: index + 1 })}
addOnFilled={false}
label={t("option", { index: index + 1 })}
labelSrOnly
{...register(`options.${index}.label` as const, { required: true })}
addOnSuffix={
<Button
variant="icon"
color="minimal"
StartIcon={FiX}
onClick={() => {
remove(index);
}}
/>
}
/>
</li>
))}
<Button
color="minimal"
StartIcon={FiPlus}
className="!text-sm !font-medium"
onClick={() => {
append({ label: "", type: "text" });
}}>
{t("add_an_option")}
</Button>
</>
</ul>
</div>
);
}
export default CustomInputTypeForm;
@@ -1,5 +1,5 @@
import Link from "next/link";
import type { CustomInputParsed, EventTypeSetupProps, FormValues } from "pages/event-types/[type]";
import type { EventTypeSetupProps, FormValues } from "pages/event-types/[type]";
import { useEffect, useState } from "react";
import { Controller, useFormContext } from "react-hook-form";
import short from "short-uuid";
@@ -8,7 +8,7 @@ import { v5 as uuidv5 } from "uuid";
import type { EventNameObjectType } from "@calcom/core/event";
import { getEventName } from "@calcom/core/event";
import DestinationCalendarSelector from "@calcom/features/calendars/DestinationCalendarSelector";
import CustomInputItem from "@calcom/features/eventtypes/components/CustomInputItem";
import { FormBuilder } from "@calcom/features/form-builder/FormBuilder";
import { APP_NAME, CAL_URL, IS_SELF_HOSTED } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
@@ -26,9 +26,7 @@ import {
TextField,
Tooltip,
} from "@calcom/ui";
import { FiEdit, FiCopy, FiPlus } from "@calcom/ui/components/icon";
import CustomInputTypeForm from "@components/eventtype/CustomInputTypeForm";
import { FiEdit, FiCopy } from "@calcom/ui/components/icon";
import RequiresConfirmationController from "./RequiresConfirmationController";
@@ -39,22 +37,11 @@ const generateHashedLink = (id: number) => {
return uid;
};
const getRandomId = (length = 8) => {
return (
-1 *
parseInt(
Math.ceil(Math.random() * Date.now())
.toPrecision(length)
.toString()
.replace(".", "")
)
);
};
export const EventAdvancedTab = ({ eventType, team }: Pick<EventTypeSetupProps, "eventType" | "team">) => {
const connectedCalendarsQuery = trpc.viewer.connectedCalendars.useQuery();
const formMethods = useFormContext<FormValues>();
const { t } = useLocale();
const [showEventNameTip, setShowEventNameTip] = useState(false);
const [hashedLinkVisible, setHashedLinkVisible] = useState(!!eventType.hashedLink);
const [redirectUrlVisible, setRedirectUrlVisible] = useState(!!eventType.successRedirectUrl);
@@ -67,21 +54,10 @@ export const EventAdvancedTab = ({ eventType, team }: Pick<EventTypeSetupProps,
t,
};
const [previewText, setPreviewText] = useState(getEventName(eventNameObject));
const [customInputs, setCustomInputs] = useState<CustomInputParsed[]>(
eventType.customInputs.sort((a, b) => a.id - b.id) || []
);
const [selectedCustomInput, setSelectedCustomInput] = useState<CustomInputParsed | undefined>(undefined);
const [selectedCustomInputModalOpen, setSelectedCustomInputModalOpen] = useState(false);
const [requiresConfirmation, setRequiresConfirmation] = useState(eventType.requiresConfirmation);
const placeholderHashedLink = `${CAL_URL}/d/${hashedUrl}/${eventType.slug}`;
const seatsEnabled = formMethods.watch("seatsPerTimeSlotEnabled");
const removeCustom = (index: number) => {
formMethods.getValues("customInputs").splice(index, 1);
customInputs.splice(index, 1);
setCustomInputs([...customInputs]);
};
const replaceEventNamePlaceholder = (eventNameObject: EventNameObjectType, previewEventName: string) =>
previewEventName
.replace("{Event type title}", eventNameObject.eventType)
@@ -96,11 +72,21 @@ export const EventAdvancedTab = ({ eventType, team }: Pick<EventTypeSetupProps,
!hashedUrl && setHashedUrl(generateHashedLink(eventType.users[0]?.id ?? team?.id));
}, [eventType.users, hashedUrl, team?.id]);
useEffect(() => {
if (eventType.customInputs) {
setCustomInputs(eventType.customInputs.sort((a, b) => a.id - b.id));
}
}, [eventType.customInputs]);
const toggleGuests = (enabled: boolean) => {
const bookingFields = formMethods.getValues("bookingFields");
formMethods.setValue(
"bookingFields",
bookingFields.map((field) => {
if (field.name === "guests") {
return {
...field,
hidden: !enabled,
};
}
return field;
})
);
};
const eventNamePlaceholder = replaceEventNamePlaceholder(eventNameObject, t("meeting_with_user"));
@@ -167,48 +153,12 @@ export const EventAdvancedTab = ({ eventType, team }: Pick<EventTypeSetupProps,
/>
</div>
<hr />
<div className="">
<SettingsToggle
title={t("additional_inputs")}
description={t("additional_input_description")}
checked={customInputs.length > 0}
onCheckedChange={(e) => {
if (e && customInputs.length === 0) {
// Push a placeholders
setSelectedCustomInputModalOpen(true);
} else if (!e) {
formMethods.setValue("customInputs", []);
}
}}>
<ul className="my-4 rounded-md border">
{customInputs.map((customInput, idx) => (
<CustomInputItem
key={idx}
question={customInput.label}
type={customInput.type}
required={customInput.required}
editOnClick={() => {
setSelectedCustomInput(customInput);
setSelectedCustomInputModalOpen(true);
}}
deleteOnClick={() => removeCustom(idx)}
/>
))}
</ul>
{customInputs.length > 0 && (
<Button
StartIcon={FiPlus}
color="minimal"
type="button"
onClick={() => {
setSelectedCustomInput(undefined);
setSelectedCustomInputModalOpen(true);
}}>
{t("add_input")}
</Button>
)}
</SettingsToggle>
</div>
<FormBuilder
title={t("booking_questions_title")}
description={t("booking_questions_description")}
addFieldLabel={t("add_a_booking_question")}
formProp="bookingFields"
/>
<hr />
<RequiresConfirmationController
seatsEnabled={seatsEnabled}
@@ -216,22 +166,6 @@ export const EventAdvancedTab = ({ eventType, team }: Pick<EventTypeSetupProps,
requiresConfirmation={requiresConfirmation}
onRequiresConfirmation={setRequiresConfirmation}
/>
<hr />
<Controller
name="disableGuests"
control={formMethods.control}
defaultValue={eventType.disableGuests}
render={({ field: { value, onChange } }) => (
<SettingsToggle
title={t("disable_guests")}
description={t("disable_guests_description")}
checked={value}
onCheckedChange={(e) => onChange(e)}
disabled={seatsEnabled}
/>
)}
/>
<hr />
<Controller
name="hideCalendarNotes"
@@ -247,22 +181,6 @@ export const EventAdvancedTab = ({ eventType, team }: Pick<EventTypeSetupProps,
)}
/>
<hr />
<Controller
name="metadata.additionalNotesRequired"
control={formMethods.control}
defaultValue={!!eventType.metadata.additionalNotesRequired}
render={({ field: { value, onChange } }) => (
<div className="flex space-x-3 ">
<SettingsToggle
title={t("require_additional_notes")}
description={t("require_additional_notes_description")}
checked={!!value}
onCheckedChange={(e) => onChange(e)}
/>
</div>
)}
/>
<hr />
<Controller
name="successRedirectUrl"
control={formMethods.control}
@@ -363,13 +281,13 @@ export const EventAdvancedTab = ({ eventType, team }: Pick<EventTypeSetupProps,
onCheckedChange={(e) => {
// Enabling seats will disable guests and requiring confirmation until fully supported
if (e) {
formMethods.setValue("disableGuests", true);
toggleGuests(false);
formMethods.setValue("requiresConfirmation", false);
setRequiresConfirmation(false);
formMethods.setValue("seatsPerTimeSlot", 2);
} else {
formMethods.setValue("seatsPerTimeSlot", null);
formMethods.setValue("disableGuests", false);
toggleGuests(true);
}
onChange(e);
}}>
@@ -475,62 +393,6 @@ export const EventAdvancedTab = ({ eventType, team }: Pick<EventTypeSetupProps,
</DialogContent>
</Dialog>
)}
<Controller
name="customInputs"
control={formMethods.control}
defaultValue={customInputs}
render={() => (
<Dialog open={selectedCustomInputModalOpen} onOpenChange={setSelectedCustomInputModalOpen}>
<DialogContent
type="creation"
Icon={FiPlus}
title={t("add_new_custom_input_field")}
description={t("this_input_will_shown_booking_this_event")}>
<CustomInputTypeForm
selectedCustomInput={selectedCustomInput}
onSubmit={(values) => {
const customInput: CustomInputParsed = {
id: getRandomId(),
eventTypeId: -1,
label: values.label,
placeholder: values.placeholder,
required: values.required,
type: values.type,
options: values.options,
hasToBeCreated: true,
};
if (selectedCustomInput) {
selectedCustomInput.label = customInput.label;
selectedCustomInput.placeholder = customInput.placeholder;
selectedCustomInput.required = customInput.required;
selectedCustomInput.type = customInput.type;
selectedCustomInput.options = customInput.options || undefined;
selectedCustomInput.hasToBeCreated = false;
// Update by id
const inputIndex = customInputs.findIndex((input) => input.id === values.id);
customInputs[inputIndex] = selectedCustomInput;
setCustomInputs(customInputs);
formMethods.setValue("customInputs", customInputs);
} else {
const concatted = customInputs.concat({
...customInput,
options: customInput.options,
});
console.log(concatted);
setCustomInputs(concatted);
formMethods.setValue("customInputs", concatted);
}
setSelectedCustomInputModalOpen(false);
}}
onCancel={() => {
setSelectedCustomInputModalOpen(false);
}}
/>
</DialogContent>
</Dialog>
)}
/>
</div>
);
};
+78 -2
View File
@@ -1,7 +1,55 @@
import type { Prisma, PrismaClient } from "@prisma/client";
import type { z } from "zod";
async function getBooking(prisma: PrismaClient, uid: string) {
const booking = await prisma.booking.findFirst({
import { getBookingResponsesPartialSchema } from "@calcom/features/bookings/lib/getBookingResponsesSchema";
import slugify from "@calcom/lib/slugify";
import type { eventTypeBookingFields } from "@calcom/prisma/zod-utils";
type BookingSelect = {
description: true;
customInputs: true;
attendees: {
select: {
email: true;
name: true;
};
};
location: true;
smsReminderNumber: true;
};
// Backward Compatibility for booking created before we had managed booking questions
function getResponsesFromOldBooking(
rawBooking: Prisma.BookingGetPayload<{
select: BookingSelect;
}>
) {
const customInputs = rawBooking.customInputs || {};
const responses = Object.keys(customInputs).reduce((acc, label) => {
acc[slugify(label) as keyof typeof acc] = customInputs[label as keyof typeof customInputs];
return acc;
}, {});
return {
name: rawBooking.attendees[0].name,
email: rawBooking.attendees[0].email,
guests: rawBooking.attendees.slice(1).map((attendee) => {
return attendee.email;
}),
notes: rawBooking.description || "",
location: {
value: rawBooking.location || "",
optionValue: rawBooking.location || "",
},
...responses,
};
}
async function getBooking(
prisma: PrismaClient,
uid: string,
bookingFields: z.infer<typeof eventTypeBookingFields> & z.BRAND<"HAS_SYSTEM_FIELDS">
) {
const rawBooking = await prisma.booking.findFirst({
where: {
uid,
},
@@ -9,6 +57,7 @@ async function getBooking(prisma: PrismaClient, uid: string) {
startTime: true,
description: true,
customInputs: true,
responses: true,
smsReminderNumber: true,
location: true,
attendees: {
@@ -20,6 +69,14 @@ async function getBooking(prisma: PrismaClient, uid: string) {
},
});
if (!rawBooking) {
return rawBooking;
}
const booking = getBookingWithResponses(rawBooking, {
bookingFields,
});
if (booking) {
// @NOTE: had to do this because Server side cant return [Object objects]
// probably fixable with json.stringify -> json.parse
@@ -31,4 +88,23 @@ async function getBooking(prisma: PrismaClient, uid: string) {
export type GetBookingType = Prisma.PromiseReturnType<typeof getBooking>;
export const getBookingWithResponses = <
T extends Prisma.BookingGetPayload<{
select: BookingSelect & {
responses: true;
};
}>
>(
booking: T,
eventType: {
bookingFields: z.infer<typeof eventTypeBookingFields> & z.BRAND<"HAS_SYSTEM_FIELDS">;
}
) => {
return {
...booking,
responses: getBookingResponsesPartialSchema({
bookingFields: eventType.bookingFields,
}).parse(booking.responses || getResponsesFromOldBooking(booking)),
};
};
export default getBooking;
@@ -1,8 +1,11 @@
import * as fetch from "@lib/core/http/fetch-wrapper";
import type { BookingCreateBody, BookingResponse } from "@lib/types/booking";
import type { BookingCreateBody } from "@calcom/prisma/zod-utils";
const createBooking = async (data: BookingCreateBody) => {
const response = await fetch.post<BookingCreateBody, BookingResponse>("/api/book/event", data);
import * as fetch from "@lib/core/http/fetch-wrapper";
import type { BookingResponse } from "@lib/types/booking";
type BookingCreateBodyForMutation = Omit<BookingCreateBody, "location">;
const createBooking = async (data: BookingCreateBodyForMutation) => {
const response = await fetch.post<BookingCreateBodyForMutation, BookingResponse>("/api/book/event", data);
return response;
};
@@ -1,7 +1,8 @@
import type { BookingCreateBody } from "@calcom/prisma/zod-utils";
import type { AppsStatus } from "@calcom/types/Calendar";
import * as fetch from "@lib/core/http/fetch-wrapper";
import type { BookingCreateBody, BookingResponse } from "@lib/types/booking";
import type { BookingResponse } from "@lib/types/booking";
type ExtendedBookingCreateBody = BookingCreateBody & {
noEmail?: boolean;
-30
View File
@@ -2,36 +2,6 @@ import type { Attendee, Booking } from "@prisma/client";
import type { AppsStatus } from "@calcom/types/Calendar";
export type BookingCreateBody = {
email: string;
end: string;
web3Details?: {
userWallet: string;
userSignature: unknown;
};
eventTypeId: number;
eventTypeSlug: string;
guests?: string[];
location: string;
name: string;
notes?: string;
rescheduleUid?: string;
recurringEventId?: string;
start: string;
timeZone: string;
user?: string | string[];
language: string;
bookingUid?: string;
customInputs: { label: string; value: string | boolean }[];
metadata: {
[key: string]: string;
};
hasHashedBookingLink: boolean;
hashedLink?: string | null;
smsReminderNumber?: string;
ethSignature?: string;
};
export type BookingResponse = Booking & {
paymentUid?: string;
attendees: Attendee[];
+4 -2
View File
@@ -3,6 +3,7 @@ import type { GetServerSidePropsContext } from "next";
import type { LocationObject } from "@calcom/app-store/locations";
import { privacyFilteredLocations } from "@calcom/app-store/locations";
import { getAppFromSlug } from "@calcom/app-store/utils";
import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/getBookingFields";
import { parseRecurringEvent } from "@calcom/lib";
import {
getDefaultEvent,
@@ -118,10 +119,10 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {
});
if (!eventTypeRaw) return { notFound: true };
const eventType = {
...eventTypeRaw,
metadata: EventTypeMetaDataSchema.parse(eventTypeRaw.metadata || {}),
bookingFields: getBookingFieldsWithSystemFields(eventTypeRaw),
recurringEvent: parseRecurringEvent(eventTypeRaw.recurringEvent),
};
@@ -183,7 +184,8 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {
prisma,
context.query.rescheduleUid
? (context.query.rescheduleUid as string)
: (context.query.bookingUid as string)
: (context.query.bookingUid as string),
eventTypeObject.bookingFields
);
}
+3 -1
View File
@@ -8,7 +8,9 @@ async function handler(req: NextApiRequest & { userId?: number }) {
const session = await getSession({ req });
/* To mimic API behavior and comply with types */
req.userId = session?.user?.id || -1;
const booking = await handleNewBooking(req);
const booking = await handleNewBooking(req, {
isNotAnApiCall: true,
});
return booking;
}
+46 -78
View File
@@ -1,4 +1,4 @@
import { BookingStatus, WorkflowActions } from "@prisma/client";
import { BookingStatus } from "@prisma/client";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@radix-ui/react-collapsible";
import classNames from "classnames";
import { createEvent } from "ics";
@@ -23,6 +23,10 @@ import {
useIsBackgroundTransparent,
useIsEmbed,
} from "@calcom/embed-core/embed-iframe";
import {
SystemField,
getBookingFieldsWithSystemFields,
} from "@calcom/features/bookings/lib/getBookingFields";
import { parseRecurringEvent } from "@calcom/lib";
import CustomBranding from "@calcom/lib/CustomBranding";
import { APP_NAME } from "@calcom/lib/constants";
@@ -42,10 +46,11 @@ import prisma from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { bookingMetadataSchema } from "@calcom/prisma/zod-utils";
import { customInputSchema, EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import { Button, EmailInput, HeadSeo } from "@calcom/ui";
import { Button, EmailInput, HeadSeo, Label } from "@calcom/ui";
import { FiX, FiExternalLink, FiChevronLeft, FiCheck, FiCalendar } from "@calcom/ui/components/icon";
import { timeZone } from "@lib/clock";
import { getBookingWithResponses } from "@lib/getBooking";
import type { inferSSRProps } from "@lib/types/inferSSRProps";
import CancelBooking from "@components/booking/CancelBooking";
@@ -195,10 +200,7 @@ export default function Success(props: SuccessProps) {
window.scrollTo(0, document.body.scrollHeight);
}
const location: ReturnType<typeof getEventLocationValue> = props.bookingInfo.location
? props.bookingInfo.location
: // If there is no location set then we default to Cal Video
"integrations:daily";
const location = props.bookingInfo.location as ReturnType<typeof getEventLocationValue>;
const locationVideoCallUrl: string | undefined = bookingMetadataSchema.parse(
props?.bookingInfo?.metadata || {}
@@ -335,12 +337,12 @@ export default function Success(props: SuccessProps) {
}
return t("emailed_you_and_attendees" + titleSuffix);
}
const userIsOwner = !!(session?.user?.id && eventType.owner?.id === session.user.id);
useTheme(isSuccessBookingPage ? props.profile.theme : "light");
const title = t(
`booking_${needsConfirmation ? "submitted" : "confirmed"}${props.recurringBookings ? "_recurring" : ""}`
);
const customInputs = bookingInfo?.customInputs;
const locationToDisplay = getSuccessPageLocationMessage(
locationVideoCallUrl ? locationVideoCallUrl : location,
@@ -348,10 +350,6 @@ export default function Success(props: SuccessProps) {
bookingInfo.status
);
const hasSMSAttendeeAction =
eventType.workflows.find((workflowEventType) =>
workflowEventType.workflow.steps.find((step) => step.action === WorkflowActions.SMS_ATTENDEE)
) !== undefined;
const providerName = guessEventLocationType(location)?.label;
return (
@@ -541,63 +539,27 @@ export default function Success(props: SuccessProps) {
</div>
</>
)}
{customInputs &&
Object.keys(customInputs).map((key) => {
// This breaks if you have two label that are the same.
// TODO: Fix this in another PR
const customInput = customInputs[key as keyof typeof customInputs];
const eventTypeCustomFound = eventType.customInputs?.find((ci) => ci.label === key);
return (
<>
{eventTypeCustomFound?.type === "RADIO" && (
<>
<div className="border-bookinglightest dark:border-darkgray-300 col-span-3 mt-8 border-t pt-8 pr-3 font-medium">
{eventTypeCustomFound.label}
</div>
<div className="col-span-3 mt-1 mb-2">
{eventTypeCustomFound.options &&
eventTypeCustomFound.options.map((option) => {
const selected = option.label == customInput;
return (
<div
key={option.label}
className={classNames(
"flex space-x-1",
!selected && "text-gray-500"
)}>
<p>{option.label}</p>
<span>{option.label === customInput && "✅"}</span>
</div>
);
})}
</div>
</>
)}
{eventTypeCustomFound?.type !== "RADIO" && customInput !== "" && (
<>
<div className="border-bookinglightest dark:border-darkgray-300 col-span-3 mt-8 border-t pt-8 pr-3 font-medium">
{key}
</div>
<div className="col-span-3 mt-2 mb-2">
{typeof customInput === "boolean" ? (
<p>{customInput ? "true" : "false"}</p>
) : (
<p>{customInput}</p>
)}
</div>
</>
)}
</>
);
})}
{bookingInfo?.smsReminderNumber && hasSMSAttendeeAction && (
<>
<div className="mt-9 font-medium">{t("number_sms_notifications")}</div>
<div className="col-span-2 mb-2 mt-9">
<p>{bookingInfo.smsReminderNumber}</p>
</div>
</>
)}
{Object.entries(bookingInfo.responses).map(([name, response]) => {
const field = eventType.bookingFields.find((field) => field.name === name);
// We show location in the "where" section
// We show Booker Name, Emails and guests in Who section
// We show notes in additional notes section
// We show rescheduleReason at the top
if (!field) return null;
const isSystemField = SystemField.safeParse(field.name);
if (isSystemField.success) return null;
const label = field.label || t(field.defaultLabel || "");
return (
<>
<Label className="col-span-3 mt-8 border-t pt-8 pr-3 font-medium">{label}</Label>
{/* Might be a good idea to use the readonly variant of respective components here */}
<div className="col-span-3 mt-1 mb-2">{response.toString()}</div>
</>
);
})}
</div>
</div>
{(!needsConfirmation || !userIsOwner) &&
@@ -927,6 +889,8 @@ const getEventTypesFromDB = async (id: number) => {
locations: true,
price: true,
currency: true,
bookingFields: true,
disableGuests: true,
owner: {
select: userSelect,
},
@@ -951,6 +915,7 @@ const getEventTypesFromDB = async (id: number) => {
select: {
workflow: {
select: {
id: true,
steps: true,
},
},
@@ -973,6 +938,7 @@ const getEventTypesFromDB = async (id: number) => {
return {
isDynamic: false,
...eventType,
bookingFields: getBookingFieldsWithSystemFields(eventType),
metadata,
};
};
@@ -1017,7 +983,7 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {
if (!parsedQuery.success) return { notFound: true };
const { uid, email, eventTypeSlug, cancel } = parsedQuery.data;
const bookingInfo = await prisma.booking.findFirst({
const bookingInfoRaw = await prisma.booking.findFirst({
where: {
uid,
},
@@ -1035,6 +1001,7 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {
status: true,
metadata: true,
cancellationReason: true,
responses: true,
rejectionReason: true,
user: {
select: {
@@ -1059,27 +1026,28 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {
},
},
});
if (!bookingInfo) {
if (!bookingInfoRaw) {
return {
notFound: true,
};
}
// @NOTE: had to do this because Server side cant return [Object objects]
// probably fixable with json.stringify -> json.parse
bookingInfo["startTime"] = (bookingInfo?.startTime as Date)?.toISOString() as unknown as Date;
bookingInfo["endTime"] = (bookingInfo?.endTime as Date)?.toISOString() as unknown as Date;
const eventTypeRaw = !bookingInfo.eventTypeId
const eventTypeRaw = !bookingInfoRaw.eventTypeId
? getDefaultEvent(eventTypeSlug || "")
: await getEventTypesFromDB(bookingInfo.eventTypeId);
: await getEventTypesFromDB(bookingInfoRaw.eventTypeId);
if (!eventTypeRaw) {
return {
notFound: true,
};
}
const bookingInfo = getBookingWithResponses(bookingInfoRaw, eventTypeRaw);
// @NOTE: had to do this because Server side cant return [Object objects]
// probably fixable with json.stringify -> json.parse
bookingInfo["startTime"] = (bookingInfo?.startTime as Date)?.toISOString() as unknown as Date;
bookingInfo["endTime"] = (bookingInfo?.endTime as Date)?.toISOString() as unknown as Date;
eventTypeRaw.users = !!eventTypeRaw.hosts?.length
? eventTypeRaw.hosts.map((host) => host.user)
: eventTypeRaw.users;
+2 -1
View File
@@ -3,7 +3,7 @@ import type { GetServerSidePropsContext } from "next";
import { parseRecurringEvent } from "@calcom/lib";
import prisma from "@calcom/prisma";
import { bookEventTypeSelect } from "@calcom/prisma/selects";
import { customInputSchema, EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import { customInputSchema, eventTypeBookingFields, EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import { asStringOrNull, asStringOrThrow } from "@lib/asStringOrNull";
import type { inferSSRProps } from "@lib/types/inferSSRProps";
@@ -71,6 +71,7 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {
...eventTypeRaw,
metadata: EventTypeMetaDataSchema.parse(eventTypeRaw.metadata || {}),
recurringEvent: parseRecurringEvent(eventTypeRaw.recurringEvent),
bookingFields: eventTypeBookingFields.parse(eventTypeRaw.bookingFields || []),
};
const eventTypeObject = [eventType].map((e) => {
+45 -40
View File
@@ -4,7 +4,7 @@ import { zodResolver } from "@hookform/resolvers/zod";
import type { PeriodType } from "@prisma/client";
import { SchedulingType } from "@prisma/client";
import type { GetServerSidePropsContext } from "next";
import { useState } from "react";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
@@ -16,6 +16,7 @@ import { useLocale } from "@calcom/lib/hooks/useLocale";
import { useTypedQuery } from "@calcom/lib/hooks/useTypedQuery";
import { HttpError } from "@calcom/lib/http-error";
import prisma from "@calcom/prisma";
import { eventTypeBookingFields } from "@calcom/prisma/zod-utils";
import type { customInputSchema, EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
@@ -86,6 +87,7 @@ export type FormValues = {
bookingLimits?: BookingLimit;
hosts: { userId: number }[];
hostsFixed: { userId: number }[];
bookingFields: z.infer<typeof eventTypeBookingFields>;
};
export type CustomInputParsed = typeof customInputSchema._output;
@@ -178,48 +180,59 @@ const EventTypePage = (props: EventTypeSetupProps) => {
delete metadata.config?.useHostSchedulesForTeamEvent;
}
const formMethods = useForm<FormValues>({
defaultValues: {
title: eventType.title,
locations: eventType.locations || [],
recurringEvent: eventType.recurringEvent || null,
description: eventType.description ?? undefined,
schedule: eventType.schedule || undefined,
bookingLimits: eventType.bookingLimits || undefined,
length: eventType.length,
hidden: eventType.hidden,
periodDates: {
startDate: periodDates.startDate,
endDate: periodDates.endDate,
},
periodType: eventType.periodType,
periodCountCalendarDays: eventType.periodCountCalendarDays ? "1" : "0",
schedulingType: eventType.schedulingType,
minimumBookingNotice: eventType.minimumBookingNotice,
metadata,
hosts: !!eventType.hosts?.length
? eventType.hosts.filter((host) => !host.isFixed)
: eventType.users
.filter(() => eventType.schedulingType === SchedulingType.ROUND_ROBIN)
.map((user) => ({ userId: user.id })),
hostsFixed: !!eventType.hosts?.length
? eventType.hosts.filter((host) => host.isFixed)
: eventType.users
.filter(() => eventType.schedulingType === SchedulingType.COLLECTIVE)
.map((user) => ({ userId: user.id })),
const defaultValues = {
title: eventType.title,
locations: eventType.locations || [],
recurringEvent: eventType.recurringEvent || null,
description: eventType.description ?? undefined,
schedule: eventType.schedule || undefined,
bookingLimits: eventType.bookingLimits || undefined,
length: eventType.length,
hidden: eventType.hidden,
periodDates: {
startDate: periodDates.startDate,
endDate: periodDates.endDate,
},
bookingFields: eventType.bookingFields,
periodType: eventType.periodType,
periodCountCalendarDays: eventType.periodCountCalendarDays ? "1" : "0",
schedulingType: eventType.schedulingType,
minimumBookingNotice: eventType.minimumBookingNotice,
metadata,
hosts: !!eventType.hosts?.length
? eventType.hosts.filter((host) => !host.isFixed)
: eventType.users
.filter(() => eventType.schedulingType === SchedulingType.ROUND_ROBIN)
.map((user) => ({ userId: user.id })),
hostsFixed: !!eventType.hosts?.length
? eventType.hosts.filter((host) => host.isFixed)
: eventType.users
.filter(() => eventType.schedulingType === SchedulingType.COLLECTIVE)
.map((user) => ({ userId: user.id })),
} as const;
const formMethods = useForm<FormValues>({
defaultValues,
resolver: zodResolver(
z
.object({
// Length if string, is converted to a number or it can be a number
// Make it optional because it's not submitted from all tabs of the page
length: z.union([z.string().transform((val) => +val), z.number()]).optional(),
bookingFields: eventTypeBookingFields,
})
// TODO: Add schema for other fields later.
.passthrough()
),
});
useEffect(() => {
if (!formMethods.formState.isDirty) {
//TODO: What's the best way to sync the form with backend
formMethods.setValue("bookingFields", defaultValues.bookingFields);
}
}, [defaultValues]);
const appsMetadata = formMethods.getValues("metadata")?.apps;
const numberOfInstalledApps = eventTypeApps?.filter((app) => app.isInstalled).length || 0;
let numberOfActiveApps = 0;
@@ -342,13 +355,7 @@ const EventTypePage = (props: EventTypeSetupProps) => {
};
const EventTypePageWrapper = (props: inferSSRProps<typeof getServerSideProps>) => {
const { data, isLoading } = trpc.viewer.eventTypes.get.useQuery(
{ id: props.type },
{
initialData: props.initialData,
}
);
const { data, isLoading } = trpc.viewer.eventTypes.get.useQuery({ id: props.type });
if (isLoading || !data) return null;
return <EventTypePage {...data} />;
};
@@ -391,9 +398,7 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
},
};
} catch (err) {
return {
notFound: true,
};
throw err;
}
};
+15 -1
View File
@@ -2,6 +2,7 @@ import type { GetServerSidePropsContext } from "next";
import type { LocationObject } from "@calcom/core/location";
import { privacyFilteredLocations } from "@calcom/core/location";
import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/getBookingFields";
import { parseRecurringEvent } from "@calcom/lib";
import { getWorkingHours } from "@calcom/lib/availability";
import prisma from "@calcom/prisma";
@@ -78,6 +79,7 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
availability: true,
description: true,
length: true,
disableGuests: true,
schedulingType: true,
periodType: true,
periodStartDate: true,
@@ -96,12 +98,24 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
slotInterval: true,
metadata: true,
seatsPerTimeSlot: true,
bookingFields: true,
customInputs: true,
schedule: {
select: {
timeZone: true,
availability: true,
},
},
workflows: {
select: {
workflow: {
select: {
id: true,
steps: true,
},
},
},
},
team: {
select: {
members: {
@@ -163,7 +177,7 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
let booking: GetBookingType | null = null;
if (rescheduleUid) {
booking = await getBooking(prisma, rescheduleUid);
booking = await getBooking(prisma, rescheduleUid, getBookingFieldsWithSystemFields(eventTypeObject));
}
const weekStart = eventType.team?.members?.[0]?.user?.weekStart;
+11 -4
View File
@@ -2,9 +2,10 @@ import type { GetServerSidePropsContext } from "next";
import type { LocationObject } from "@calcom/app-store/locations";
import { privacyFilteredLocations } from "@calcom/app-store/locations";
import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/getBookingFields";
import { parseRecurringEvent } from "@calcom/lib";
import prisma from "@calcom/prisma";
import { customInputSchema, EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import { customInputSchema, eventTypeBookingFields, EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import { asStringOrNull, asStringOrThrow } from "@lib/asStringOrNull";
import type { GetBookingType } from "@lib/getBooking";
@@ -13,6 +14,8 @@ import type { inferSSRProps } from "@lib/types/inferSSRProps";
import BookingPage from "@components/booking/pages/BookingPage";
import { ssrInit } from "@server/lib/ssr";
export type TeamBookingPageProps = inferSSRProps<typeof getServerSideProps>;
export default function TeamBookingPage(props: TeamBookingPageProps) {
@@ -22,6 +25,7 @@ export default function TeamBookingPage(props: TeamBookingPageProps) {
TeamBookingPage.isThemeSupported = true;
export async function getServerSideProps(context: GetServerSidePropsContext) {
const ssr = await ssrInit(context);
const eventTypeId = parseInt(asStringOrThrow(context.query.type));
const recurringEventCountQuery = asStringOrNull(context.query.count);
if (typeof eventTypeId !== "number" || eventTypeId % 1 !== 0) {
@@ -55,6 +59,7 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {
metadata: true,
seatsPerTimeSlot: true,
schedulingType: true,
bookingFields: true,
workflows: {
include: {
workflow: {
@@ -92,12 +97,13 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {
//TODO: Use zodSchema to verify it instead of using Type Assertion
locations: privacyFilteredLocations((eventTypeRaw.locations || []) as LocationObject[]),
recurringEvent: parseRecurringEvent(eventTypeRaw.recurringEvent),
bookingFields: eventTypeBookingFields.parse(eventTypeRaw.bookingFields || []),
};
const eventTypeObject = [eventType].map((e) => {
return {
...e,
metadata: EventTypeMetaDataSchema.parse(eventType.metadata || {}),
metadata: EventTypeMetaDataSchema.parse(e.metadata || {}),
bookingFields: getBookingFieldsWithSystemFields(eventType),
periodStartDate: e.periodStartDate?.toString() ?? null,
periodEndDate: e.periodEndDate?.toString() ?? null,
customInputs: customInputSchema.array().parse(e.customInputs || []),
@@ -114,7 +120,7 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {
let booking: GetBookingType | null = null;
if (context.query.rescheduleUid) {
booking = await getBooking(prisma, context.query.rescheduleUid as string);
booking = await getBooking(prisma, context.query.rescheduleUid as string, eventTypeObject.bookingFields);
}
// Checking if number of recurring event ocurrances is valid against event type configuration
@@ -128,6 +134,7 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {
return {
props: {
trpcState: ssr.dehydrate(),
profile: {
...eventTypeObject.team,
// FIXME: This slug is used as username on success page which is wrong. This is correctly set as username for user booking.
+2
View File
@@ -90,6 +90,8 @@ test("add webhook & test that creating an event triggers a webhook call", async
timeZone: "[redacted/dynamic]",
language: "[redacted/dynamic]",
},
responses: { email: "test@example.com", name: "Test Testson" },
userFieldsResponses: {},
attendees: [
{
email: "test@example.com",
@@ -1599,10 +1599,18 @@
"under_maintenance": "Down for maintenance",
"under_maintenance_description": "The {{appName}} team are performing scheduled maintenance. If you have any questions, please contact support.",
"event_type_seats": "{{numberOfSeats}} seats",
"booking_questions_title": "Booking questions",
"booking_questions_description": "Customize the questions asked on the booking page",
"add_a_booking_question": "Add a question",
"duplicate_email": "Email is duplicate",
"booking_with_payment_cancelled": "Paying for this event is no longer possible",
"booking_with_payment_cancelled_already_paid": "A refund for this booking payment it's on the way.",
"booking_with_payment_cancelled_refunded": "This booking payment has been refunded.",
"booking_confirmation_failed": "Booking confirmation failed",
"form_builder_field_already_exists": "A field with this name already exists",
"form_builder_field_add_subtitle": "Customize the questions asked on the booking page",
"form_builder_system_field_cant_delete": "This system field can't be removed.",
"form_builder_system_field_cant_toggle": "This system field can't be toggled.",
"get_started_zapier_templates": "Get started with Zapier templates",
"team_member": "Team member",
"a_routing_form": "A Routing Form",