feat: Custom Fields OR Add-Ons with a fee associated (#19997)

* feat: Addons to bookings

* Add tests

* Add tests

* Fix price field not shown immediately after enabling payment for an event

* Add support for all currencies in addons and fix type errors

* Address review comments

* Add tests to cover all input types

* Address cubic-dev-ai comments

* Remove openapi.json from git tracking

* Revert changes

* Revert unrelated linter/formatter changes

* Address cubic-dev-ai comments

* Addres cubic-dev-ai comment

* Update to use test id instead of hardcoded label

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Address coderabbits review comments

* Fix failing unit test

* some fixes...

* Fix tests

* Fix import

* Move handlePayment test file to appropriate location

* Fix test

---------

Co-authored-by: Omar López <[email protected]>
Co-authored-by: amrit <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Kartik Saini <[email protected]>
Co-authored-by: Anik Dhabal Babu <[email protected]>
Co-authored-by: Devanshu Sharma <[email protected]>
Co-authored-by: Benny Joo <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: Volnei Munhoz <[email protected]>
This commit is contained in:
14 files changed
+822 -40

No files matched your search

@@ -167,4 +167,108 @@ describe("FormBuilder", () => {
expect(pageObject.dialog.isFieldShowingAsRequired({ dialog })).toBe(true);
});
});
describe("Addon Fields Tests", () => {
beforeEach(() => {
renderComponent({
formBuilderProps: {
...mockProps,
showPriceField: true,
},
formDefaultValues: {},
});
});
it("Should add number field with price", async () => {
const identifier = "quantity-addon";
const price = 10;
await verifier.verifyFieldAddition({
fieldType: "number",
identifier,
label: "Quantity",
price,
});
pageObject.openEditFieldDialog({ identifier });
await expectScenario.toHavePriceField({ identifier, price });
});
it("Should add boolean field with price", async () => {
const identifier = "extra-service-addon";
const price = 15;
await verifier.verifyFieldAddition({
fieldType: "boolean",
identifier,
label: "Extra Service",
price,
});
pageObject.openEditFieldDialog({ identifier });
await expectScenario.toHavePriceField({ identifier, price });
});
it("Should add select field with price and options", async () => {
const identifier = "meal-selection";
await verifier.verifyFieldAddition({
fieldType: "select",
identifier,
label: "Meal Selection",
options: [
{ label: "Vegetarian", value: "veg", price: 20 },
{ label: "Non-Vegetarian", value: "non-veg", price: 25 },
],
});
verifier.verifyOptionPrices({ identifier, prices: [20, 25] });
});
it("Should add multiselect field with price and options", async () => {
const identifier = "add-ons";
await verifier.verifyFieldAddition({
fieldType: "multiselect",
identifier,
label: "Add-ons",
options: [
{ label: "WiFi", value: "wifi", price: 10 },
{ label: "Breakfast", value: "breakfast", price: 15 },
{ label: "Parking", value: "parking", price: 20 },
],
});
verifier.verifyOptionPrices({ identifier, prices: [10, 15, 20] });
});
it("Should add checkbox group field with price and options", async () => {
const identifier = "amenities";
await verifier.verifyFieldAddition({
fieldType: "checkbox",
identifier,
label: "Amenities",
options: [
{ label: "Pool Access", value: "pool", price: 15 },
{ label: "Gym Access", value: "gym", price: 20 },
{ label: "Spa Access", value: "spa", price: 25 },
],
});
verifier.verifyOptionPrices({ identifier, prices: [15, 20, 25] });
});
it("Should add radio group field with price and options", async () => {
const identifier = "room-type";
await verifier.verifyFieldAddition({
fieldType: "radio",
identifier,
label: "Room Type",
options: [
{ label: "Standard", value: "standard", price: 50 },
{ label: "Deluxe", value: "deluxe", price: 75 },
{ label: "Suite", value: "suite", price: 100 },
],
});
verifier.verifyOptionPrices({ identifier, prices: [50, 75, 100] });
});
});
});
+90 -26
View File
@@ -5,6 +5,7 @@ import { Controller, useFieldArray, useForm, useFormContext } from "react-hook-f
import type { z } from "zod";
import { ZodError } from "zod";
import { getCurrencySymbol } from "@calcom/app-store/_utils/payments/currencyConversions";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { md } from "@calcom/lib/markdownIt";
@@ -79,6 +80,8 @@ export const FormBuilder = function FormBuilder({
LockedIcon,
dataStore,
shouldConsiderRequired,
showPriceField,
paymentCurrency = "USD",
showPhoneAndEmailToggle = false,
}: {
formProp: string;
@@ -97,6 +100,8 @@ export const FormBuilder = function FormBuilder({
* e.g. Location field has a default value at backend so API can send no location but formBuilder in UI doesn't allow it.
*/
shouldConsiderRequired?: (field: RhfFormField) => boolean | undefined;
showPriceField?: boolean;
paymentCurrency?: string;
}) {
// I would have liked to give Form Builder it's own Form but nested Forms aren't something that browsers support.
// So, this would reuse the same Form as the parent form.
@@ -402,6 +407,8 @@ export const FormBuilder = function FormBuilder({
});
}}
shouldConsiderRequired={shouldConsiderRequired}
showPriceField={showPriceField}
paymentCurrency={paymentCurrency}
/>
)}
</div>
@@ -415,13 +422,19 @@ function Options({
onChange = () => {},
className = "",
readOnly = false,
showPrice = false,
paymentCurrency,
}: {
label?: string;
value: { label: string; value: string }[];
onChange?: (value: { label: string; value: string }[]) => void;
value: { label: string; value: string; price?: number }[];
onChange?: (value: { label: string; value: string; price?: number }[]) => void;
className?: string;
readOnly?: boolean;
showPrice?: boolean;
paymentCurrency: string;
}) {
const { t } = useLocale();
const [animationRef] = useAutoAnimate<HTMLUListElement>();
if (!value) {
onChange([
@@ -438,26 +451,52 @@ function Options({
return (
<div className={className}>
<Label>{label}</Label>
<div className="bg-muted rounded-md p-4">
<div className="bg-muted rounded-md p-4" data-testid="options-container">
<ul ref={animationRef} className="flex flex-col gap-1">
{value?.map((option, index) => (
<li key={index}>
<div className="flex items-center">
<Input
required
value={option.label}
onChange={(e) => {
// Right now we use label of the option as the value of the option. It allows us to not separately lookup the optionId to know the optionValue
// It has the same drawback that if the label is changed, the value of the option will change. It is not a big deal for now.
value.splice(index, 1, {
label: e.target.value,
value: e.target.value.trim(),
});
onChange(value);
}}
readOnly={readOnly}
placeholder={`Enter Option ${index + 1}`}
/>
<div className="flex items-center gap-2">
<div className="flex-grow">
<Input
required
value={option.label}
onChange={(e) => {
// Right now we use label of the option as the value of the option. It allows use to not separately lookup the optionId to know the optionValue
// It has the same drawback that if the label is changed, the value of the option will change. It is not a big deal for now.
const newOptions = [...(value || [])];
newOptions.splice(index, 1, {
label: e.target.value,
value: e.target.value.trim(),
});
onChange(newOptions);
}}
readOnly={readOnly}
placeholder={t("enter_option", { index: index + 1 })}
/>
</div>
{showPrice && (
<div className="w-24">
<InputField
type="number"
min={0}
step="0.01"
value={option.price}
onChange={(e) => {
const val = e.target.value;
const numValue = val === "" ? undefined : Number(val);
const updatedOptions = [...(value || [])];
updatedOptions[index] = {
...option,
price: numValue,
};
onChange(updatedOptions);
}}
readOnly={readOnly}
placeholder="0"
addOnLeading={getCurrencySymbol(paymentCurrency)}
/>
</div>
)}
{value.length > 2 && !readOnly && (
<Button
type="button"
@@ -466,10 +505,8 @@ function Options({
color="minimal"
StartIcon="x"
onClick={() => {
if (!value) {
return;
}
const newOptions = [...value];
if (!value) return;
const newOptions = [...(value || [])];
newOptions.splice(index, 1);
onChange(newOptions);
}}
@@ -482,9 +519,11 @@ function Options({
{!readOnly && (
<Button
color="minimal"
data-testid="add-option"
onClick={() => {
value.push({ label: "", value: "" });
onChange(value);
const newOptions = [...(value || [])];
newOptions.push({ label: "", value: "", price: 0 });
onChange(newOptions);
}}
StartIcon="plus">
Add an Option
@@ -521,11 +560,15 @@ function FieldEditDialog({
onOpenChange,
handleSubmit,
shouldConsiderRequired,
showPriceField,
paymentCurrency,
}: {
dialog: { isOpen: boolean; fieldIndex: number; data: RhfFormField | null };
onOpenChange: (isOpen: boolean) => void;
handleSubmit: SubmitHandler<RhfFormField>;
shouldConsiderRequired?: (field: RhfFormField) => boolean | undefined;
showPriceField?: boolean;
paymentCurrency: string;
}) {
const { t } = useLocale();
const fieldForm = useForm<RhfFormField>({
@@ -633,7 +676,15 @@ function FieldEditDialog({
<Controller
name="options"
render={({ field: { value, onChange } }) => {
return <Options onChange={onChange} value={value} className="mt-6" />;
return (
<Options
onChange={onChange}
value={value}
className="mt-6"
showPrice={showPriceField && fieldType.optionsSupportPricing}
paymentCurrency={paymentCurrency}
/>
);
}}
/>
) : null}
@@ -684,6 +735,19 @@ function FieldEditDialog({
/>
)}
{/* Add price field only for fields that support pricing */}
{showPriceField && fieldType.supportsPricing && (
<InputField
{...fieldForm.register("price")}
containerClassName="mt-6"
label={t("price")}
type="number"
min={0}
placeholder="0"
addOnLeading={getCurrencySymbol(paymentCurrency)}
/>
)}
<div className="mt-6">
<Controller
name="required"
@@ -99,6 +99,7 @@ const configMap: Record<FieldType, Omit<z.infer<typeof fieldTypeConfigSchema>, "
label: "Number",
value: "number",
isTextType: true,
supportsPricing: true,
},
textarea: {
label: "Long Text",
@@ -114,12 +115,14 @@ const configMap: Record<FieldType, Omit<z.infer<typeof fieldTypeConfigSchema>, "
value: "select",
needsOptions: true,
isTextType: true,
optionsSupportPricing: true,
},
multiselect: {
label: "MultiSelect",
value: "multiselect",
needsOptions: true,
isTextType: false,
optionsSupportPricing: true,
},
multiemail: {
label: "Multiple Emails",
@@ -140,17 +143,20 @@ const configMap: Record<FieldType, Omit<z.infer<typeof fieldTypeConfigSchema>, "
value: "checkbox",
needsOptions: true,
isTextType: false,
optionsSupportPricing: true,
},
radio: {
label: "Radio Group",
value: "radio",
needsOptions: true,
isTextType: false,
optionsSupportPricing: true,
},
boolean: {
label: "Checkbox",
value: "boolean",
isTextType: false,
supportsPricing: true,
},
url: {
label: "URL",
+13 -1
View File
@@ -82,7 +82,15 @@ const baseFieldSchema = z.object({
* It is the list of options that is valid for a certain type of fields.
*
*/
options: z.array(z.object({ label: z.string(), value: z.string() })).optional(),
options: z
.array(
z.object({
label: z.string(),
value: z.string(),
price: z.coerce.number().min(0).optional(),
})
)
.optional(),
/**
* This is an alternate way to specify options when the options are stored elsewhere. Form Builder expects options to be present at `dataStore[getOptionsAt]`
* This allows keeping a single source of truth in DB.
@@ -124,6 +132,8 @@ const baseFieldSchema = z.object({
excludeEmails: excludeOrRequireEmailSchema.optional(),
// Emails that need to be required
requireEmails: excludeOrRequireEmailSchema.optional(),
// Price associated with the field which works like addons which users can add to the booking
price: z.coerce.number().min(0).optional(),
});
export const variantsConfigSchema = z.object({
@@ -162,6 +172,8 @@ export const fieldTypeConfigSchema = z
maxLength: z.number(),
})
.optional(),
supportsPricing: z.boolean().default(false).optional(),
optionsSupportPricing: z.boolean().default(false).optional(),
propsType: z.enum([
"text",
"textList",
@@ -9,6 +9,8 @@ export interface FieldProps {
fieldType: string;
identifier: string;
label: string;
price?: number;
options?: { label: string; value: string; price?: number }[];
}
type FormBuilderProps = React.ComponentProps<typeof FormBuilder>;
@@ -22,6 +24,7 @@ export const mockProps: FormBuilderProps = {
LockedIcon: false,
dataStore: { options: {} },
};
export const getLocationBookingField = () => {
const bookingFields = getBookingFieldsWithSystemFields({
bookingFields: [],
@@ -163,6 +166,46 @@ export const pageObject = {
fireEvent.change(dialog.getAllByRole("textbox")[1], { target: { value: label } });
}
},
fillInPrice: ({ dialog, price }: { dialog: TestingLibraryElement; price: number }) => {
// The price input is rendered with an Input component with a $ suffix
const priceInput = dialog.getByRole("spinbutton");
fireEvent.change(priceInput, { target: { value: price.toString() } });
},
addOption: ({ dialog }: { dialog: TestingLibraryElement }) => {
fireEvent.click(dialog.getByTestId("add-option"));
},
fillInOption: async ({
dialog,
index,
label,
price,
}: {
dialog: TestingLibraryElement;
index: number;
label: string;
price?: number;
}) => {
pageObject.dialog.addOption({ dialog });
const optionInputs = dialog.getByTestId("options-container");
await waitFor(() => {
const listItems = optionInputs.querySelectorAll("li");
expect(listItems.length).toBeGreaterThan(index);
const optionInput = within(listItems[index]).getByRole("textbox");
expect(optionInput).toBeInTheDocument();
fireEvent.change(optionInput, { target: { value: label } });
});
if (price !== undefined) {
await waitFor(() => {
const listItems = optionInputs.querySelectorAll("li");
expect(listItems.length).toBeGreaterThan(index);
const priceInput = within(listItems[index]).getByRole("spinbutton");
expect(priceInput).toBeInTheDocument();
fireEvent.change(priceInput, { target: { value: price.toString() } });
});
}
},
close: ({ dialog }: { dialog: TestingLibraryElement }) => {
fireEvent.click(dialog.getByTestId("dialog-rejection"));
},
@@ -199,6 +242,23 @@ export const verifier = {
pageObject.dialog.selectFieldType({ dialog, fieldType: props.fieldType });
pageObject.dialog.fillInFieldIdentifier({ dialog, identifier: props.identifier });
pageObject.dialog.fillInFieldLabel({ dialog, label: props.label, fieldType: props.fieldType });
if (props.price !== undefined) {
pageObject.dialog.fillInPrice({ dialog, price: props.price });
}
if (props.options) {
for (let index = 0; index < props.options.length; index++) {
const option = props.options[index];
await pageObject.dialog.fillInOption({
dialog,
index,
label: option.label,
price: option.price,
});
}
}
pageObject.dialog.saveField({ dialog: getEditDialogForm() });
await waitFor(() => {
@@ -239,6 +299,16 @@ export const verifier = {
expect(screen.getByTestId("optional")).toBeInTheDocument();
});
},
verifyOptionPrices: ({ identifier, prices }: { identifier: string; prices: number[] }) => {
const dialog = pageObject.openEditFieldDialog({ identifier });
const optionsContainer = dialog.getByTestId("options-container");
const optionPriceInputs = within(optionsContainer).getAllByRole("spinbutton");
expect(optionPriceInputs).toHaveLength(prices.length);
prices.forEach((price, index) => {
expect(optionPriceInputs[index]).toHaveValue(price);
});
},
};
export const expectScenario = {
@@ -279,4 +349,14 @@ export const expectScenario = {
const field = getFieldInTheList({ identifier });
expect(field.getByText("required")).not.toBeNull();
},
toHavePriceField: async ({ identifier, price }: { identifier: string; price: number }) => {
const dialog = pageObject.openEditFieldDialog({ identifier });
await waitFor(() => {
// Find the spinbutton input with $ suffix
const priceInput = dialog.getByRole("spinbutton");
expect(priceInput).toBeInTheDocument();
// Verify the price value is set
expect(priceInput).toHaveValue(price);
});
},
};