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:
authored and GitHub committed 2023-03-02 11:15:28 -07:00
1 parent 51bf613621
commit 517cfde5b8
58 files changed
+2921 -1463

No files matched your search

@@ -0,0 +1,332 @@
import type { EventTypeCustomInput, EventType, Prisma, Workflow } from "@prisma/client";
import { z } from "zod";
import slugify from "@calcom/lib/slugify";
import {
BookingFieldType,
customInputSchema,
eventTypeBookingFields,
EventTypeMetaDataSchema,
} from "@calcom/prisma/zod-utils";
export const SMS_REMINDER_NUMBER_FIELD = "smsReminderNumber";
export const getSmsReminderNumberField = () =>
({
name: SMS_REMINDER_NUMBER_FIELD,
type: "phone",
defaultLabel: "number_sms_notifications",
defaultPlaceholder: "enter_phone_number",
editable: "system",
} as const);
export const getSmsReminderNumberSource = ({
workflowId,
isSmsReminderNumberRequired,
}: {
workflowId: Workflow["id"];
isSmsReminderNumberRequired: boolean;
}) => ({
id: "" + workflowId,
type: "workflow",
label: "Workflow",
fieldRequired: isSmsReminderNumberRequired,
editUrl: `/workflows/${workflowId}`,
});
type Fields = z.infer<typeof eventTypeBookingFields>;
const EventTypeCustomInputType = {
TEXT: "TEXT",
TEXTLONG: "TEXTLONG",
NUMBER: "NUMBER",
BOOL: "BOOL",
RADIO: "RADIO",
PHONE: "PHONE",
} as const;
export const SystemField = z.enum([
"name",
"email",
"location",
"notes",
"guests",
"rescheduleReason",
"smsReminderNumber",
]);
export const SystemFieldsEditability: Record<z.infer<typeof SystemField>, Fields[number]["editable"]> = {
name: "system",
email: "system",
location: "system",
notes: "system-but-optional",
guests: "system-but-optional",
rescheduleReason: "system",
smsReminderNumber: "system",
};
/**
* This fn is the key to ensure on the fly mapping of customInputs to bookingFields and ensuring that all the systems fields are present and correctly ordered in bookingFields
*/
export const getBookingFieldsWithSystemFields = ({
bookingFields,
disableGuests,
customInputs,
metadata,
workflows,
}: {
bookingFields: Fields | EventType["bookingFields"];
disableGuests: boolean;
customInputs: EventTypeCustomInput[] | z.infer<typeof customInputSchema>[];
metadata: EventType["metadata"] | z.infer<typeof EventTypeMetaDataSchema>;
workflows: Prisma.EventTypeGetPayload<{
select: {
workflows: {
select: {
workflow: {
select: {
id: true;
steps: true;
};
};
};
};
};
}>["workflows"];
}) => {
const parsedMetaData = EventTypeMetaDataSchema.parse(metadata || {});
const parsedBookingFields = eventTypeBookingFields.parse(bookingFields || []);
const parsedCustomInputs = customInputSchema.array().parse(customInputs || []);
workflows = workflows || [];
return ensureBookingInputsHaveSystemFields({
bookingFields: parsedBookingFields,
disableGuests,
additionalNotesRequired: parsedMetaData?.additionalNotesRequired || false,
customInputs: parsedCustomInputs,
workflows,
});
};
export const ensureBookingInputsHaveSystemFields = ({
bookingFields,
disableGuests,
additionalNotesRequired,
customInputs,
workflows,
}: {
bookingFields: Fields;
disableGuests: boolean;
additionalNotesRequired: boolean;
customInputs: z.infer<typeof customInputSchema>[];
workflows: Prisma.EventTypeGetPayload<{
select: {
workflows: {
select: {
workflow: {
select: {
id: true;
steps: true;
};
};
};
};
};
}>["workflows"];
}) => {
// If bookingFields is set already, the migration is done.
const handleMigration = !bookingFields.length;
const CustomInputTypeToFieldType = {
[EventTypeCustomInputType.TEXT]: BookingFieldType.text,
[EventTypeCustomInputType.TEXTLONG]: BookingFieldType.textarea,
[EventTypeCustomInputType.NUMBER]: BookingFieldType.number,
[EventTypeCustomInputType.BOOL]: BookingFieldType.boolean,
[EventTypeCustomInputType.RADIO]: BookingFieldType.radio,
[EventTypeCustomInputType.PHONE]: BookingFieldType.phone,
};
const smsNumberSources = [] as NonNullable<(typeof bookingFields)[number]["sources"]>;
workflows.forEach((workflow) => {
workflow.workflow.steps.forEach((step) => {
if (step.action === "SMS_ATTENDEE") {
const workflowId = workflow.workflow.id;
smsNumberSources.push(
getSmsReminderNumberSource({
workflowId,
isSmsReminderNumberRequired: !!step.numberRequired,
})
);
}
});
});
// These fields should be added before other user fields
const systemBeforeFields: typeof bookingFields = [
{
defaultLabel: "your_name",
defaultPlaceholder: "example_name",
type: "name",
name: "name",
required: true,
sources: [
{
label: "Default",
id: "default",
type: "default",
},
],
},
{
defaultLabel: "email_address",
defaultPlaceholder: "you@example.com",
type: "email",
name: "email",
required: true,
sources: [
{
label: "Default",
id: "default",
type: "default",
},
],
},
{
defaultLabel: "location",
type: "radioInput",
name: "location",
required: false,
// Populated on the fly from locations. I don't want to duplicate storing locations and instead would like to be able to refer to locations in eventType.
// options: `eventType.locations`
optionsInputs: {
attendeeInPerson: {
type: "address",
required: true,
placeholder: "",
},
phone: {
type: "phone",
required: true,
placeholder: "",
},
},
sources: [
{
label: "Default",
id: "default",
type: "default",
},
],
},
];
// Backward Compatibility for SMS Reminder Number
if (smsNumberSources.length) {
systemBeforeFields.push({
...getSmsReminderNumberField(),
sources: smsNumberSources,
});
}
// These fields should be added after other user fields
const systemAfterFields: typeof bookingFields = [
{
defaultLabel: "additional_notes",
type: "textarea",
name: "notes",
required: additionalNotesRequired,
defaultPlaceholder: "share_additional_notes",
sources: [
{
label: "Default",
id: "default",
type: "default",
},
],
},
{
defaultLabel: "additional_guests",
type: "multiemail",
name: "guests",
required: false,
hidden: disableGuests,
sources: [
{
label: "Default",
id: "default",
type: "default",
},
],
},
{
defaultLabel: "reschedule_reason",
type: "textarea",
name: "rescheduleReason",
defaultPlaceholder: "reschedule_placeholder",
required: false,
sources: [
{
label: "Default",
id: "default",
type: "default",
},
],
},
];
const missingSystemBeforeFields = [];
for (const field of systemBeforeFields) {
// Only do a push, we must not update existing system fields as user could have modified any property in it,
if (!bookingFields.find((f) => f.name === field.name)) {
missingSystemBeforeFields.push(field);
}
}
bookingFields = missingSystemBeforeFields.concat(bookingFields);
// Backward Compatibility: If we are migrating from old system, we need to map `customInputs` to `bookingFields`
if (handleMigration) {
customInputs.forEach((input) => {
bookingFields.push({
label: input.label,
editable: "user",
// Custom Input's slugified label was being used as query param for prefilling. So, make that the name of the field
name: slugify(input.label),
placeholder: input.placeholder,
type: CustomInputTypeToFieldType[input.type],
required: input.required,
options: input.options
? input.options.map((o) => {
return {
...o,
// Send the label as the value without any trimming or lowercase as this is what customInput are doing. It maintains backward compatibility
value: o.label,
};
})
: [],
});
});
}
const missingSystemAfterFields = [];
for (const field of systemAfterFields) {
// Only do a push, we must not update existing system fields as user could have modified any property in it,
if (!bookingFields.find((f) => f.name === field.name)) {
missingSystemAfterFields.push(field);
}
}
bookingFields = bookingFields.concat(missingSystemAfterFields);
bookingFields = bookingFields.map((field) => {
const foundEditableMap = SystemFieldsEditability[field.name as keyof typeof SystemFieldsEditability];
if (!foundEditableMap) {
return field;
}
// Ensure that system fields editability, even if modified to something else in DB(accidentally), get's reset to what's in the code.
return {
...field,
editable: foundEditableMap,
};
});
return eventTypeBookingFields.brand<"HAS_SYSTEM_FIELDS">().parse(bookingFields);
};
@@ -0,0 +1,188 @@
import { isValidPhoneNumber } from "libphonenumber-js";
import z from "zod";
import type { eventTypeBookingFields } from "@calcom/prisma/zod-utils";
import { bookingResponses } from "@calcom/prisma/zod-utils";
type EventType = Parameters<typeof preprocess>[0]["eventType"];
export const getBookingResponsesPartialSchema = (eventType: EventType) => {
const schema = bookingResponses.unwrap().partial().and(z.record(z.any()));
return preprocess({ schema, eventType, isPartialSchema: true });
};
// Should be used when we know that not all fields responses are present
// - Can happen when we are parsing the prefill query string
// - Can happen when we are parsing a booking's responses (which was created before we added a new required field)
export default function getBookingResponsesSchema(eventType: EventType) {
const schema = bookingResponses.and(z.record(z.any()));
return preprocess({ schema, eventType, isPartialSchema: false });
}
// TODO: Move preprocess of `booking.responses` to FormBuilder schema as that is going to parse the fields supported by FormBuilder
// It allows anyone using FormBuilder to get the same preprocessing automatically
function preprocess<T extends z.ZodType>({
schema,
eventType,
isPartialSchema,
}: {
schema: T;
isPartialSchema: boolean;
eventType: {
bookingFields: z.infer<typeof eventTypeBookingFields> & z.BRAND<"HAS_SYSTEM_FIELDS">;
};
}): z.ZodType<z.infer<T>, z.infer<T>, z.infer<T>> {
const preprocessed = z.preprocess(
(responses) => {
const parsedResponses = z.record(z.any()).nullable().parse(responses) || {};
const newResponses = {} as typeof parsedResponses;
eventType.bookingFields.forEach((field) => {
const value = parsedResponses[field.name];
if (value === undefined) {
// If there is no response for the field, then we don't need to do any processing
return;
}
// Turn a boolean in string to a real boolean
if (field.type === "boolean") {
newResponses[field.name] = value === "true" || value === true;
}
// Make sure that the value is an array
else if (field.type === "multiemail" || field.type === "checkbox" || field.type === "multiselect") {
newResponses[field.name] = value instanceof Array ? value : [value];
}
// Parse JSON
else if (field.type === "radioInput" && typeof value === "string") {
let parsedValue = {
optionValue: "",
value: "",
};
try {
parsedValue = JSON.parse(value);
} catch (e) {}
newResponses[field.name] = parsedValue;
} else {
newResponses[field.name] = value;
}
});
return newResponses;
},
schema.superRefine((responses, ctx) => {
eventType.bookingFields.forEach((bookingField) => {
const value = responses[bookingField.name];
const stringSchema = z.string();
const emailSchema = isPartialSchema ? z.string() : z.string().email();
const phoneSchema = isPartialSchema
? z.string()
: z.string().refine((val) => isValidPhoneNumber(val));
// Tag the message with the input name so that the message can be shown at appropriate place
const m = (message: string) => `{${bookingField.name}}${message}`;
const isRequired = bookingField.required;
if ((isPartialSchema || !isRequired) && value === undefined) {
return;
}
if (isRequired && !isPartialSchema && !value)
ctx.addIssue({ code: z.ZodIssueCode.custom, message: m(`error_required_field`) });
if (bookingField.type === "email") {
// Email RegExp to validate if the input is a valid email
if (!emailSchema.safeParse(value).success) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: m("email_validation_error"),
});
}
return;
}
if (bookingField.type === "multiemail") {
const emailsParsed = emailSchema.array().safeParse(value);
if (!emailsParsed.success) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: m("email_validation_error"),
});
return;
}
const emails = emailsParsed.data;
emails.sort().some((item, i) => {
if (item === emails[i + 1]) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: m("duplicate_email") });
return true;
}
});
return;
}
if (bookingField.type === "checkbox" || bookingField.type === "multiselect") {
if (!stringSchema.array().safeParse(value).success) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: m("Invalid array of strings") });
}
return;
}
if (bookingField.type === "phone") {
if (!phoneSchema.safeParse(value).success) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: m("invalid_number") });
}
return;
}
if (bookingField.type === "boolean") {
const schema = z.boolean();
if (!schema.safeParse(value).success) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: m("Invalid Boolean") });
}
return;
}
if (bookingField.type === "radioInput") {
if (bookingField.optionsInputs) {
const optionValue = value?.optionValue;
const optionField = bookingField.optionsInputs[value?.value];
const typeOfOptionInput = optionField?.type;
if (
// Either the field is required or there is a radio selected, we need to check if the optionInput is required or not.
(isRequired || value?.value) &&
optionField?.required &&
!optionValue
) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: m("error_required_field") });
}
if (optionValue) {
// `typeOfOptionInput` can be any of the main types. So, we the same validations should run for `optionValue`
if (typeOfOptionInput === "phone") {
if (!phoneSchema.safeParse(optionValue).success) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: m("invalid_number") });
}
}
}
}
return;
}
if (
["address", "text", "select", "name", "number", "radio", "textarea"].includes(bookingField.type)
) {
const schema = stringSchema;
if (!schema.safeParse(value).success) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: m("Invalid string") });
}
return;
}
throw new Error(`Can't parse unknown booking field type: ${bookingField.type}`);
});
})
);
if (isPartialSchema) {
// Query Params can be completely invalid, try to preprocess as much of it in correct format but in worst case simply don't prefill instead of crashing
return preprocessed.catch(() => {
console.error("Failed to preprocess query params, prefilling will be skipped");
return {};
});
}
return preprocessed;
}
@@ -1,5 +1,5 @@
import type { App, Credential, EventTypeCustomInput, Prisma } from "@prisma/client";
import { BookingStatus, SchedulingType, WebhookTriggerEvents, WorkflowMethods } from "@prisma/client";
import type { App, Credential, EventTypeCustomInput } from "@prisma/client";
import { BookingStatus, SchedulingType, WebhookTriggerEvents, WorkflowMethods, Prisma } from "@prisma/client";
import async from "async";
import { isValidPhoneNumber } from "libphonenumber-js";
import { cloneDeep } from "lodash";
@@ -28,6 +28,7 @@ import {
sendScheduledEmails,
sendScheduledSeatsEmails,
} from "@calcom/emails";
import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/getBookingFields";
import { deleteScheduledEmailReminder } from "@calcom/features/ee/workflows/lib/reminders/emailReminderManager";
import { scheduleWorkflowReminders } from "@calcom/features/ee/workflows/lib/reminders/reminderScheduler";
import { deleteScheduledSMSReminder } from "@calcom/features/ee/workflows/lib/reminders/smsReminderManager";
@@ -43,9 +44,12 @@ import logger from "@calcom/lib/logger";
import { handlePayment } from "@calcom/lib/payment/handlePayment";
import { checkBookingLimits, getLuckyUser } from "@calcom/lib/server";
import { getTranslation } from "@calcom/lib/server/i18n";
import { slugify } from "@calcom/lib/slugify";
import { updateWebUser as syncServicesUpdateWebUser } from "@calcom/lib/sync/SyncServiceManager";
import prisma, { userSelect } from "@calcom/prisma";
import type { bookingCreateSchemaLegacyPropsForApi } from "@calcom/prisma/zod-utils";
import {
bookingCreateBodySchemaForApi,
customInputSchema,
EventTypeMetaDataSchema,
extendedBookingCreateBody,
@@ -58,6 +62,7 @@ import type { WorkingHours } from "@calcom/types/schedule";
import type { EventTypeInfo } from "../../webhooks/lib/sendPayload";
import sendPayload from "../../webhooks/lib/sendPayload";
import getBookingResponsesSchema from "./getBookingResponsesSchema";
const translator = short();
const log = logger.getChildLogger({ prefix: ["[api] book:user"] });
@@ -162,6 +167,7 @@ const getEventTypesFromDB = async (eventTypeId: number) => {
select: {
id: true,
customInputs: true,
disableGuests: true,
users: userSelect,
team: {
select: {
@@ -169,6 +175,7 @@ const getEventTypesFromDB = async (eventTypeId: number) => {
name: true,
},
},
bookingFields: true,
title: true,
length: true,
eventName: true,
@@ -228,8 +235,9 @@ const getEventTypesFromDB = async (eventTypeId: number) => {
...eventType,
metadata: EventTypeMetaDataSchema.parse(eventType.metadata),
recurringEvent: parseRecurringEvent(eventType.recurringEvent),
customInputs: customInputSchema.array().parse(eventType.customInputs),
customInputs: customInputSchema.array().parse(eventType.customInputs || []),
locations: (eventType.locations ?? []) as LocationObject[],
bookingFields: getBookingFieldsWithSystemFields(eventType),
};
};
@@ -306,33 +314,146 @@ async function ensureAvailableUsers(
return availableUsers;
}
async function handler(req: NextApiRequest & { userId?: number | undefined }) {
function getBookingData({
req,
isNotAnApiCall,
eventType,
}: {
req: NextApiRequest;
isNotAnApiCall: boolean;
eventType: Awaited<ReturnType<typeof getEventTypesFromDB>>;
}) {
const bookingDataSchema = isNotAnApiCall
? extendedBookingCreateBody.merge(
z.object({
responses: getBookingResponsesSchema({
bookingFields: eventType.bookingFields,
}),
})
)
: bookingCreateBodySchemaForApi;
const reqBody = bookingDataSchema.parse(req.body);
if ("responses" in reqBody) {
const responses = reqBody.responses;
const userFieldsResponses = {} as typeof responses;
eventType.bookingFields.forEach((field) => {
if (field.editable === "user" || field.editable === "user-readonly") {
userFieldsResponses[field.name] = responses[field.name];
}
});
return {
...reqBody,
name: responses.name,
email: responses.email,
guests: responses.guests ? responses.guests : [],
location: responses.location?.optionValue || responses.location?.value || "",
smsReminderNumber: responses.smsReminderNumber,
notes: responses.notes || "",
userFieldsResponses,
rescheduleReason: responses.rescheduleReason,
};
} else {
// Check if required custom inputs exist
handleCustomInputs(eventType.customInputs as EventTypeCustomInput[], reqBody.customInputs);
return {
...reqBody,
name: reqBody.name,
email: reqBody.email,
guests: reqBody.guests,
location: reqBody.location || "",
smsReminderNumber: reqBody.smsReminderNumber,
notes: reqBody.notes,
rescheduleReason: reqBody.rescheduleReason,
};
}
}
function getCustomInputsResponses(
reqBody: {
responses?: Record<string, any>;
customInputs?: z.infer<typeof bookingCreateSchemaLegacyPropsForApi>["customInputs"];
},
eventTypeCustomInputs: Awaited<ReturnType<typeof getEventTypesFromDB>>["customInputs"]
) {
const customInputsResponses = {} as NonNullable<CalendarEvent["customInputs"]>;
if ("customInputs" in reqBody) {
const reqCustomInputsResponses = reqBody.customInputs || [];
if (reqCustomInputsResponses?.length > 0) {
reqCustomInputsResponses.forEach(({ label, value }) => {
customInputsResponses[label] = value;
});
}
} else {
const responses = reqBody.responses || {};
// Backward Compatibility: Map new `responses` to old `customInputs` format so that webhooks can still receive same values.
for (const [fieldName, fieldValue] of Object.entries(responses)) {
const foundACustomInputForTheResponse = eventTypeCustomInputs.find(
(input) => slugify(input.label) === fieldName
);
if (foundACustomInputForTheResponse) {
customInputsResponses[foundACustomInputForTheResponse.label] = fieldValue;
}
}
}
return customInputsResponses;
}
async function handler(
req: NextApiRequest & { userId?: number | undefined },
{
isNotAnApiCall = false,
}: {
isNotAnApiCall?: boolean;
} = {
isNotAnApiCall: false,
}
) {
const { userId } = req;
// handle dynamic user
let eventType =
!req.body.eventTypeId && !!req.body.eventTypeSlug
? getDefaultEvent(req.body.eventTypeSlug)
: await getEventTypesFromDB(req.body.eventTypeId);
eventType = {
...eventType,
bookingFields: getBookingFieldsWithSystemFields(eventType),
};
const {
recurringCount,
allRecurringDates,
currentRecurringIndex,
noEmail,
eventTypeSlug,
eventTypeId,
eventTypeSlug,
hasHashedBookingLink,
language,
appsStatus: reqAppsStatus,
name: bookerName,
email: bookerEmail,
guests: reqGuests,
location,
notes: additionalNotes,
smsReminderNumber,
rescheduleReason,
...reqBody
} = extendedBookingCreateBody.parse(req.body);
} = getBookingData({
req,
isNotAnApiCall,
eventType,
});
// handle dynamic user
const dynamicUserList = Array.isArray(reqBody.user)
? getGroupName(reqBody.user)
: getUsernameList(reqBody.user);
const tAttendees = await getTranslation(language ?? "en", "common");
const tGuests = await getTranslation("en", "common");
log.debug(`Booking eventType ${eventTypeId} started`);
const eventType =
!eventTypeId && !!eventTypeSlug ? getDefaultEvent(eventTypeSlug) : await getEventTypesFromDB(eventTypeId);
const dynamicUserList = Array.isArray(reqBody.user)
? getGroupName(reqBody.user)
: getUsernameList(reqBody.user);
if (!eventType) throw new HttpError({ statusCode: 404, message: "eventType.notFound" });
const isTeamEventType =
@@ -341,9 +462,6 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
const paymentAppData = getPaymentAppData(eventType);
// Check if required custom inputs exist
handleCustomInputs(eventType.customInputs as EventTypeCustomInput[], reqBody.customInputs);
let timeOutOfBounds = false;
try {
timeOutOfBounds = isOutOfBounds(reqBody.start, {
@@ -493,14 +611,14 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
const invitee = [
{
email: reqBody.email,
name: reqBody.name,
email: bookerEmail,
name: bookerName,
timeZone: reqBody.timeZone,
language: { translate: tAttendees, locale: language ?? "en" },
},
];
const guests = (reqBody.guests || []).reduce((guestArray, guest) => {
const guests = (reqGuests || []).reduce((guestArray, guest) => {
// If it's a team event, remove the team member from guests
if (isTeamEventType) {
if (users.some((user) => user.email === guest)) {
@@ -520,7 +638,7 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
const seed = `${organizerUser.username}:${dayjs(reqBody.start).utc().format()}:${new Date().getTime()}`;
const uid = translator.fromUUID(uuidv5(seed, uuidv5.URL));
let locationBodyString = reqBody.location;
let locationBodyString = location;
let defaultLocationUrl = undefined;
if (dynamicUserList.length > 1) {
users = users.sort((a, b) => {
@@ -535,8 +653,7 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
}
const bookingLocation = getLocationValueForDB(locationBodyString, eventType.locations);
const customInputs = {} as NonNullable<CalendarEvent["customInputs"]>;
const customInputs = getCustomInputsResponses(reqBody, eventType.customInputs);
const teamMemberPromises =
users.length > 1
? users.slice(1).map(async function (user) {
@@ -557,16 +674,16 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
const attendeesList = [...invitee, ...guests];
const eventNameObject = {
attendeeName: reqBody.name || "Nameless",
//TODO: Can we have an unnamed attendee? If not, I would really like to throw an error here.
attendeeName: bookerName || "Nameless",
eventType: eventType.title,
eventName: eventType.eventName,
// TODO: Can we have an unnamed organizer? If not, I would really like to throw an error here.
host: organizerUser.name || "Nameless",
location: bookingLocation,
t: tOrganizer,
};
const additionalNotes = reqBody.notes;
let requiresConfirmation = eventType?.requiresConfirmation;
const rcThreshold = eventType?.metadata?.requiresConfirmationThreshold;
if (rcThreshold) {
@@ -575,6 +692,8 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
}
}
const responses = "responses" in reqBody ? reqBody.responses : null;
const userFieldsResponses = "userFieldsResponses" in reqBody ? reqBody.userFieldsResponses : null;
let evt: CalendarEvent = {
type: eventType.title,
title: getEventName(eventNameObject), //this needs to be either forced in english, or fetched for each attendee and organizer separately
@@ -590,6 +709,8 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
timeZone: organizerUser.timeZone,
language: { translate: tOrganizer, locale: organizerUser.locale ?? "en" },
},
responses,
userFieldsResponses,
attendees: attendeesList,
location: bookingLocation, // Will be processed by the EventManager later.
/** For team events & dynamic collective events, we will need to handle each member destinationCalendar eventually */
@@ -729,12 +850,6 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
return booking;
}
if (reqBody.customInputs.length > 0) {
reqBody.customInputs.forEach(({ label, value }) => {
customInputs[label] = value;
});
}
if (isTeamEventType) {
evt.team = {
members: teamMembers,
@@ -782,6 +897,7 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
},
});
}
type BookingType = Prisma.PromiseReturnType<typeof getOriginalRescheduledBooking>;
let originalRescheduledBooking: BookingType = null;
if (rescheduleUid) {
@@ -813,6 +929,7 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
const newBookingData: Prisma.BookingCreateInput = {
uid,
responses: responses === null ? Prisma.JsonNull : responses,
title: evt.title,
startTime: dayjs.utc(evt.startTime).toDate(),
endTime: dayjs.utc(evt.endTime).toDate(),
@@ -821,7 +938,7 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
status: isConfirmedByDefault ? BookingStatus.ACCEPTED : BookingStatus.PENDING,
location: evt.location,
eventType: eventTypeRel,
smsReminderNumber: reqBody.smsReminderNumber,
smsReminderNumber,
metadata: reqBody.metadata,
attendees: {
createMany: {
@@ -981,7 +1098,6 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
}
let videoCallUrl;
if (originalRescheduledBooking?.uid) {
try {
// cancel workflow reminders from previous rescheduled booking
@@ -1001,7 +1117,7 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
evt,
originalRescheduledBooking.uid,
booking?.id,
reqBody.rescheduleReason
rescheduleReason
);
// This gets overridden when updating the event - to check if notes have been hidden or not. We just reset this back
// to the default description when we are sending the emails.
@@ -1037,7 +1153,7 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
...evt,
additionalInformation: metadata,
additionalNotes, // Resets back to the additionalNote input and not the override value
cancellationReason: "$RCH$" + reqBody.rescheduleReason, // Removable code prefix to differentiate cancellation from rescheduling for email
cancellationReason: "$RCH$" + rescheduleReason, // Removable code prefix to differentiate cancellation from rescheduling for email
});
}
}
@@ -1295,7 +1411,7 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
try {
await scheduleWorkflowReminders(
eventType.workflows,
reqBody.smsReminderNumber as string | null,
smsReminderNumber || null,
{ ...evt, ...{ metadata } },
evt.requiresConfirmation || false,
rescheduleUid ? true : false,
+3 -3
View File
@@ -1,14 +1,14 @@
import jackson from "@boxyhq/saml-jackson";
import type {
IConnectionAPIController,
IOAuthController,
JacksonOption,
ISPSAMLConfig,
} from "@boxyhq/saml-jackson";
import jackson from "@boxyhq/saml-jackson";
import { WEBAPP_URL } from "@calcom/lib/constants";
import {WEBAPP_URL} from "@calcom/lib/constants";
import { samlDatabaseUrl, samlAudience, samlPath, oidcPath } from "./saml";
import {samlDatabaseUrl, samlAudience, samlPath, oidcPath} from "./saml";
// Set the required options. Refer to https://github.com/boxyhq/jackson#configuration for the full list
const opts: JacksonOption = {
+1 -1
View File
@@ -1,5 +1,5 @@
import type { NextApiRequest, NextApiResponse } from "next";
import Stripe from "stripe";
import type Stripe from "stripe";
import { z } from "zod";
import { getRequestedSlugError } from "@calcom/app-store/stripepayment/lib/team-billing";
@@ -166,13 +166,19 @@ export const AddActionDialog = (props: IAddActionDialog) => {
<div className="mt-5 space-y-1">
<Label htmlFor="sendTo">{t("phone_number")}</Label>
<div className="mt-1 mb-5">
<PhoneInput<AddActionFormValues>
<Controller
control={form.control}
name="sendTo"
className="rounded-md"
placeholder={t("enter_phone_number")}
id="sendTo"
required
render={({ field: { value, onChange } }) => (
<PhoneInput
className="rounded-md"
placeholder={t("enter_phone_number")}
id="sendTo"
required
value={value}
onChange={onChange}
/>
)}
/>
{form.formState.errors.sendTo && (
<p className="mt-1 text-sm text-red-500">{form.formState.errors.sendTo.message}</p>
@@ -36,6 +36,7 @@ const WorkflowListItem = (props: ItemProps) => {
);
const isActive = activeEventTypeIds.includes(eventType.id);
const utils = trpc.useContext();
const activateEventTypeMutation = trpc.viewer.workflows.activateEventType.useMutation({
onSuccess: async () => {
@@ -52,6 +53,7 @@ const WorkflowListItem = (props: ItemProps) => {
setActiveEventTypeIds(newActiveEventTypeIds);
offOn = "on";
}
await utils.viewer.eventTypes.get.invalidate({ id: eventType.id });
showToast(
t("workflow_turned_on_successfully", {
workflowName: workflow.name,
@@ -397,19 +397,26 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
<div className="mt-2 rounded-md bg-gray-50 p-4 pt-0">
<Label className="pt-4">{t("custom_phone_number")}</Label>
<div className="block sm:flex">
<PhoneInput<FormValues>
control={form.control}
<Controller
name={`steps.${step.stepNumber - 1}.sendTo`}
placeholder={t("phone_number")}
id={`steps.${step.stepNumber - 1}.sendTo`}
className="min-w-fit sm:rounded-tl-md sm:rounded-bl-md sm:border-r-transparent"
required
onChange={() => {
const isAlreadyVerified = !!verifiedNumbers
?.concat([])
.find((number) => number === form.getValues(`steps.${step.stepNumber - 1}.sendTo`));
setNumberVerified(isAlreadyVerified);
}}
render={({ field: { value, onChange } }) => (
<PhoneInput
placeholder={t("phone_number")}
id={`steps.${step.stepNumber - 1}.sendTo`}
className="min-w-fit sm:rounded-tl-md sm:rounded-bl-md sm:border-r-transparent"
required
value={value}
onChange={(val) => {
const isAlreadyVerified = !!verifiedNumbers
?.concat([])
.find(
(number) => number === form.getValues(`steps.${step.stepNumber - 1}.sendTo`)
);
setNumberVerified(isAlreadyVerified);
onChange(val);
}}
/>
)}
/>
<Button
color="secondary"
@@ -1,42 +0,0 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Badge, Button, ButtonGroup } from "@calcom/ui";
import { FiTrash } from "@calcom/ui/components/icon";
type Props = {
required?: boolean;
question?: string;
type?: string;
editOnClick: () => void;
deleteOnClick: () => void;
};
function CustomInputItem({ required, deleteOnClick, editOnClick, type, question }: Props) {
const { t } = useLocale();
return (
<li className="flex rounded-b-md border-t border-gray-200 bg-white px-6 py-4 first:rounded-t-md first:border-0">
<div className="flex flex-col">
<div className="flex items-center">
<span className="pr-2 text-sm font-semibold leading-none text-black">{question}</span>
<Badge variant="default" color="gray" withDot={false}>
{required ? t("required") : t("optional")}
</Badge>
</div>
<p className="text-sm leading-normal text-gray-600">{type}</p>
</div>
<ButtonGroup containerProps={{ className: "ml-auto" }}>
<Button color="secondary" onClick={editOnClick}>
{t("edit")}
</Button>
<Button
StartIcon={FiTrash}
variant="icon"
color="destructive"
onClick={deleteOnClick}
className="h-[36px] border border-gray-200"
/>
</ButtonGroup>
</li>
);
}
export default CustomInputItem;
@@ -1,7 +1,6 @@
import dynamic from "next/dynamic";
export { default as CheckedTeamSelect } from "./CheckedTeamSelect";
export { default as CustomInputItem } from "./CustomInputItem";
export { default as CreateEventTypeDialog } from "./CreateEventTypeDialog";
export { default as EventTypeDescription } from "./EventTypeDescription";
export const EventTypeDescriptionLazy = dynamic(() => import("./EventTypeDescription"));
@@ -0,0 +1,141 @@
import { z } from "zod";
import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/getBookingFields";
import { prisma } from "@calcom/prisma";
import { EventType } from "@calcom/prisma/client";
import { eventTypeBookingFields } from "@calcom/prisma/zod-utils";
type Field = z.infer<typeof eventTypeBookingFields>[number];
async function getEventType(eventTypeId: EventType["id"]) {
const rawEventType = await prisma.eventType.findUnique({
where: {
id: eventTypeId,
},
include: {
customInputs: true,
workflows: {
select: {
workflow: {
select: {
id: true,
steps: true,
},
},
},
},
},
});
if (!rawEventType) {
throw new Error(`EventType:${eventTypeId} not found`);
}
const eventType = {
...rawEventType,
bookingFields: getBookingFieldsWithSystemFields(rawEventType),
};
return eventType;
}
/**
*
* @param fieldToAdd Field to add
* @param source Source of the field to be shown in UI
* @param eventTypeId
*/
export async function upsertBookingField(
fieldToAdd: Omit<Field, "required">,
source: NonNullable<Field["sources"]>[number],
eventTypeId: EventType["id"]
) {
const eventType = await getEventType(eventTypeId);
let fieldFound = false;
const newFields = eventType.bookingFields.map((f) => {
if (f.name === fieldToAdd.name) {
fieldFound = true;
const currentSources = f.sources ? f.sources : ([] as NonNullable<typeof f.sources>[]);
let sourceFound = false;
let newSources = currentSources.map((s) => {
if (s.id !== source.id) {
// If the source is not found, nothing to update
return s;
}
sourceFound = true;
return {
...s,
...source,
};
});
if (!sourceFound) {
newSources = [...newSources, source];
}
const newField = {
...f,
// If any source requires the field, mark the field required
required: newSources.some((s) => s.fieldRequired),
sources: newSources,
};
return newField;
}
return f;
});
if (!fieldFound) {
newFields.push({
...fieldToAdd,
required: source.fieldRequired,
sources: [source],
});
}
await prisma.eventType.update({
where: {
id: eventTypeId,
},
data: {
bookingFields: newFields,
},
});
}
export async function removeBookingField(
fieldToRemove: Pick<Field, "name">,
source: Pick<NonNullable<Field["sources"]>[number], "id" | "type">,
eventTypeId: EventType["id"]
) {
const eventType = await getEventType(eventTypeId);
const newFields = eventType.bookingFields
.map((f) => {
if (f.name === fieldToRemove.name) {
const currentSources = f.sources ? f.sources : ([] as NonNullable<typeof f.sources>[]);
if (!currentSources.find((s) => s.id === source.id)) {
// No need to remove the source - It doesn't exist already
return f;
}
const newSources = currentSources.filter((s) => s.id !== source.id);
const newField = {
...f,
required: newSources.some((s) => s.fieldRequired),
sources: newSources,
};
if (newField.sources.length === 0) {
return null;
}
return newField;
}
return f;
})
.filter((f): f is Field => !!f);
await prisma.eventType.update({
where: {
id: eventTypeId,
},
data: {
bookingFields: newFields,
},
});
}
@@ -0,0 +1,384 @@
import { useEffect } from "react";
import type { z } from "zod";
import type {
TextLikeComponentProps,
SelectLikeComponentProps,
} from "@calcom/app-store/ee/routing-forms/components/react-awesome-query-builder/widgets";
import Widgets from "@calcom/app-store/ee/routing-forms/components/react-awesome-query-builder/widgets";
import { classNames } from "@calcom/lib";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { BookingFieldType } from "@calcom/prisma/zod-utils";
import { PhoneInput, AddressInput, Button, Label, Group, RadioField, EmailField, Tooltip } from "@calcom/ui";
import { FiUserPlus, FiX } from "@calcom/ui/components/icon";
import { ComponentForField } from "./FormBuilder";
import type { fieldsSchema } from "./FormBuilderFieldsSchema";
type Component =
| {
propsType: "text";
factory: <TProps extends TextLikeComponentProps>(props: TProps) => JSX.Element;
}
| {
propsType: "textList";
factory: <TProps extends TextLikeComponentProps<string[]>>(props: TProps) => JSX.Element;
}
| {
propsType: "select";
factory: <TProps extends SelectLikeComponentProps>(props: TProps) => JSX.Element;
}
| {
propsType: "boolean";
factory: <TProps extends TextLikeComponentProps<boolean>>(props: TProps) => JSX.Element;
}
| {
propsType: "multiselect";
factory: <TProps extends SelectLikeComponentProps<string[]>>(props: TProps) => JSX.Element;
}
| {
// Objective type question with option having a possible input
propsType: "objectiveWithInput";
factory: <
TProps extends SelectLikeComponentProps<{
value: string;
optionValue: string;
}> & {
optionsInputs: NonNullable<z.infer<typeof fieldsSchema>[number]["optionsInputs"]>;
value: { value: string; optionValue: string };
} & {
name?: string;
}
>(
props: TProps
) => JSX.Element;
};
// TODO: Share FormBuilder components across react-query-awesome-builder(for Routing Forms) widgets.
// There are certain differences b/w two. Routing Forms expect label to be provided by the widget itself and FormBuilder adds label itself and expect no label to be added by component.
// Routing Form approach is better as it provides more flexibility to show the label in complex components. But that can't be done right now because labels are missing consistent asterisk required support across different components
export const Components: Record<BookingFieldType, Component> = {
text: {
propsType: "text",
factory: (props) => <Widgets.TextWidget noLabel={true} {...props} />,
},
textarea: {
propsType: "text",
// TODO: Make rows configurable in the form builder
factory: (props) => <Widgets.TextAreaWidget rows={3} {...props} />,
},
number: {
propsType: "text",
factory: (props) => <Widgets.NumberWidget noLabel={true} {...props} />,
},
name: {
propsType: "text",
// Keep special "name" type field and later build split(FirstName and LastName) variant of it.
factory: (props) => <Widgets.TextWidget noLabel={true} {...props} />,
},
phone: {
propsType: "text",
factory: ({ setValue, readOnly, ...props }) => {
if (!props) {
return <div />;
}
return (
<PhoneInput
disabled={readOnly}
onChange={(val: string) => {
setValue(val);
}}
{...props}
/>
);
},
},
email: {
propsType: "text",
factory: (props) => {
if (!props) {
return <div />;
}
return <Widgets.TextWidget type="email" noLabel={true} {...props} />;
},
},
address: {
propsType: "text",
factory: (props) => {
return (
<AddressInput
onChange={(val) => {
props.setValue(val);
}}
{...props}
/>
);
},
},
multiemail: {
propsType: "textList",
//TODO: Make it a ui component
factory: function MultiEmail({ value, readOnly, label, setValue, ...props }) {
const placeholder = props.placeholder;
const { t } = useLocale();
value = value || [];
const inputClassName =
"dark:placeholder:text-darkgray-600 focus:border-brand dark:border-darkgray-300 dark:text-darkgray-900 block w-full rounded-md border-gray-300 text-sm focus:ring-black disabled:bg-gray-200 disabled:hover:cursor-not-allowed dark:bg-transparent dark:selection:bg-green-500 disabled:dark:text-gray-500";
return (
<>
{value.length ? (
<div>
<label
htmlFor="guests"
className="mb-1 block text-sm font-medium text-gray-700 dark:text-white">
{label}
</label>
<ul>
{value.map((field, index) => (
<li key={index}>
<EmailField
disabled={readOnly}
value={value[index]}
onChange={(e) => {
value[index] = e.target.value;
setValue(value);
}}
className={classNames(inputClassName, "border-r-0")}
addOnClassname={classNames(
"border-gray-300 border block border-l-0 disabled:bg-gray-200 disabled:hover:cursor-not-allowed bg-transparent disabled:text-gray-500 dark:border-darkgray-300 "
)}
placeholder={placeholder}
label={<></>}
required
addOnSuffix={
!readOnly ? (
<Tooltip content="Remove email">
<button
className="m-1 disabled:hover:cursor-not-allowed"
type="button"
onClick={() => {
value.splice(index, 1);
setValue(value);
}}>
<FiX className="text-gray-600" />
</button>
</Tooltip>
) : null
}
/>
</li>
))}
</ul>
{!readOnly && (
<Button
type="button"
color="minimal"
StartIcon={FiUserPlus}
className="my-2.5"
onClick={() => {
value.push("");
setValue(value);
}}>
{t("add_another")}
</Button>
)}
</div>
) : (
<></>
)}
{!value.length && !readOnly && (
<Button
color="minimal"
variant="button"
StartIcon={FiUserPlus}
onClick={() => {
value.push("");
setValue(value);
}}
className="mr-auto">
{label}
</Button>
)}
</>
);
},
},
multiselect: {
propsType: "multiselect",
factory: (props) => {
const newProps = {
...props,
listValues: props.options.map((o) => ({ title: o.label, value: o.value })),
};
return <Widgets.MultiSelectWidget {...newProps} />;
},
},
select: {
propsType: "select",
factory: (props) => {
const newProps = {
...props,
listValues: props.options.map((o) => ({ title: o.label, value: o.value })),
};
return <Widgets.SelectWidget {...newProps} />;
},
},
checkbox: {
propsType: "multiselect",
factory: ({ options, readOnly, setValue, value }) => {
value = value || [];
return (
<div>
{options.map((option, i) => {
return (
<label key={i} className="block">
<input
type="checkbox"
disabled={readOnly}
onChange={(e) => {
const newValue = value.filter((v) => v !== option.value);
if (e.target.checked) {
newValue.push(option.value);
}
setValue(newValue);
}}
className="dark:bg-darkgray-300 dark:border-darkgray-300 h-4 w-4 rounded border-gray-300 text-black focus:ring-black ltr:mr-2 rtl:ml-2"
value={option.value}
checked={value.includes(option.value)}
/>
<span className="text-sm ltr:ml-2 ltr:mr-2 rtl:ml-2 dark:text-white">
{option.label ?? ""}
</span>
</label>
);
})}
</div>
);
},
},
radio: {
propsType: "select",
factory: ({ setValue, value, options }) => {
return (
<Group
value={value}
onValueChange={(e) => {
setValue(e);
}}>
<>
{options.map((option, i) => (
<RadioField
label={option.label}
key={`option.${i}.radio`}
value={option.label}
id={`option.${i}.radio`}
/>
))}
</>
</Group>
);
},
},
radioInput: {
propsType: "objectiveWithInput",
factory: function RadioInputWithLabel({ name, options, optionsInputs, value, setValue, readOnly }) {
useEffect(() => {
if (!value) {
setValue({
value: options[0]?.value,
optionValue: "",
});
}
}, [options, setValue, value]);
return (
<div>
<div>
<div className="mb-2">
{options.length > 1 ? (
options.map((option, i) => {
return (
<label key={i} className="block">
<input
type="radio"
disabled={readOnly}
name={name}
className="dark:bg-darkgray-300 dark:border-darkgray-300 h-4 w-4 border-gray-300 text-black focus:ring-black ltr:mr-2 rtl:ml-2"
value={option.value}
onChange={(e) => {
setValue({
value: e.target.value,
optionValue: "",
});
}}
checked={value?.value === option.value}
/>
<span className="text-sm ltr:ml-2 ltr:mr-2 rtl:ml-2 dark:text-white">
{option.label ?? ""}
</span>
</label>
);
})
) : (
// Show option itself as label because there is just one option
// TODO: Support asterisk for required fields
<Label>{options[0].label}</Label>
)}
</div>
</div>
{(() => {
const optionField = optionsInputs[value?.value];
if (!optionField) {
return null;
}
return (
<div>
<ComponentForField
readOnly={!!readOnly}
field={{
...optionField,
name: "optionField",
}}
value={value?.optionValue}
setValue={(val: string) => {
setValue({
value: value?.value,
optionValue: val,
});
}}
/>
</div>
);
})()}
</div>
);
},
},
boolean: {
propsType: "boolean",
factory: ({ readOnly, label, value, setValue }) => {
return (
<div className="flex">
<input
type="checkbox"
onChange={(e) => {
if (e.target.checked) {
setValue(true);
} else {
setValue(false);
}
}}
className="h-4 w-4 rounded border-gray-300 text-black focus:ring-black disabled:bg-gray-200 ltr:mr-2 rtl:ml-2 disabled:dark:text-gray-500"
placeholder=""
checked={value}
disabled={readOnly}
/>
<Label className="-mt-px block text-sm font-medium text-gray-700 dark:text-white">{label}</Label>
</div>
);
},
},
} as const;
// Should use `statisfies` to check if the `type` is from supported types. But satisfies doesn't work with Next.js config
@@ -0,0 +1,733 @@
import { useAutoAnimate } from "@formkit/auto-animate/react";
import { ErrorMessage } from "@hookform/error-message";
import { useState } from "react";
import { Controller, useFieldArray, useForm, useFormContext } from "react-hook-form";
import type { z } from "zod";
import { classNames } from "@calcom/lib";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import {
Label,
Badge,
Button,
Dialog,
DialogClose,
DialogContent,
DialogHeader,
DialogFooter,
Form,
BooleanToggleGroupField,
SelectField,
InputField,
Input,
showToast,
} from "@calcom/ui";
import { Switch } from "@calcom/ui";
import { FiArrowDown, FiArrowUp, FiX, FiPlus, FiTrash2, FiInfo } from "@calcom/ui/components/icon";
import { Components } from "./Components";
import type { fieldsSchema } from "./FormBuilderFieldsSchema";
type RhfForm = {
fields: z.infer<typeof fieldsSchema>;
};
type RhfFormFields = RhfForm["fields"];
type RhfFormField = RhfFormFields[number];
/**
* It works with a react-hook-form only.
* `formProp` specifies the name of the property in the react-hook-form that has the fields. This is where fields would be updated.
*/
export const FormBuilder = function FormBuilder({
title,
description,
addFieldLabel,
formProp,
}: {
formProp: string;
title: string;
description: string;
addFieldLabel: string;
}) {
const FieldTypesMap: Record<
string,
{
value: RhfForm["fields"][number]["type"];
label: string;
needsOptions?: boolean;
systemOnly?: boolean;
isTextType?: boolean;
}
> = {
name: {
label: "Name",
value: "name",
isTextType: true,
},
email: {
label: "Email",
value: "email",
isTextType: true,
},
phone: {
label: "Phone",
value: "phone",
isTextType: true,
},
text: {
label: "Short Text",
value: "text",
isTextType: true,
},
number: {
label: "Number",
value: "number",
isTextType: true,
},
textarea: {
label: "Long Text",
value: "textarea",
isTextType: true,
},
select: {
label: "Select",
value: "select",
needsOptions: true,
isTextType: true,
},
multiselect: {
label: "MultiSelect",
value: "multiselect",
needsOptions: true,
isTextType: false,
},
multiemail: {
label: "Multiple Emails",
value: "multiemail",
isTextType: true,
},
radioInput: {
label: "Radio Input",
value: "radioInput",
isTextType: false,
systemOnly: true,
},
checkbox: {
label: "Checkbox Group",
value: "checkbox",
needsOptions: true,
isTextType: false,
},
radio: {
label: "Radio Group",
value: "radio",
needsOptions: true,
isTextType: false,
},
boolean: {
label: "Checkbox",
value: "boolean",
isTextType: false,
},
};
const FieldTypes = Object.values(FieldTypesMap);
// 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.
const fieldsForm = useFormContext<RhfForm>();
const { t } = useLocale();
const fieldForm = useForm<RhfFormField>();
const { fields, swap, remove, update, append } = useFieldArray({
control: fieldsForm.control,
// HACK: It allows any property name to be used for instead of `fields` property name
name: formProp as unknown as "fields",
});
function OptionsField({
label = "Options",
value,
onChange,
className = "",
readOnly = false,
}: {
label?: string;
value: { label: string; value: string }[];
onChange: (value: { label: string; value: string }[]) => void;
className?: string;
readOnly?: boolean;
}) {
const [animationRef] = useAutoAnimate<HTMLUListElement>();
if (!value) {
onChange([
{
label: "Option 1",
value: "Option 1",
},
{
label: "Option 2",
value: "Option 2",
},
]);
}
return (
<div className={className}>
<Label>{label}</Label>
<div className="rounded-md bg-gray-50 p-4">
<ul ref={animationRef}>
{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.toLowerCase().trim(),
});
onChange(value);
}}
readOnly={readOnly}
placeholder={`Enter Option ${index + 1}`}
/>
{value.length > 2 && !readOnly && (
<Button
type="button"
className="mb-2 -ml-8 hover:!bg-transparent focus:!bg-transparent focus:!outline-none focus:!ring-0"
size="sm"
color="minimal"
StartIcon={FiX}
onClick={() => {
if (!value) {
return;
}
const newOptions = [...value];
newOptions.splice(index, 1);
onChange(newOptions);
}}
/>
)}
</div>
</li>
))}
</ul>
{!readOnly && (
<Button
color="minimal"
onClick={() => {
value.push({ label: "", value: "" });
onChange(value);
}}
StartIcon={FiPlus}>
Add an Option
</Button>
)}
</div>
</div>
);
}
const [fieldDialog, setFieldDialog] = useState({
isOpen: false,
fieldIndex: -1,
});
const addField = () => {
fieldForm.reset({});
setFieldDialog({
isOpen: true,
fieldIndex: -1,
});
};
const editField = (index: number, data: RhfFormField) => {
fieldForm.reset(data);
setFieldDialog({
isOpen: true,
fieldIndex: index,
});
};
const removeField = (index: number) => {
remove(index);
};
const fieldType = FieldTypesMap[fieldForm.watch("type")];
const isFieldEditMode = fieldDialog.fieldIndex !== -1;
return (
<div>
<div>
<div className="text-sm font-semibold text-gray-700 ltr:mr-1 rtl:ml-1">{title}</div>
<p className="max-w-[280px] break-words py-1 text-sm text-gray-500 sm:max-w-[500px]">{description}</p>
<ul className="mt-2 rounded-md border">
{fields.map((field, index) => {
const fieldType = FieldTypesMap[field.type];
// Hidden fields can't be required
const isRequired = field.required && !field.hidden;
if (!fieldType) {
throw new Error(`Invalid field type - ${field.type}`);
}
const sources = field.sources || [];
const groupedBySourceLabel = sources.reduce((groupBy, source) => {
const item = groupBy[source.label] || [];
if (source.type === "user" || source.type === "default") {
return groupBy;
}
item.push(source);
groupBy[source.label] = item;
return groupBy;
}, {} as Record<string, NonNullable<(typeof field)["sources"]>>);
return (
<li
key={index}
className="group relative flex items-center justify-between border-b p-4 last:border-b-0">
<button
type="button"
className="invisible absolute -left-[12px] -mt-4 mb-4 -ml-4 hidden h-6 w-6 scale-0 items-center justify-center rounded-md border bg-white p-1 text-gray-400 transition-all hover:border-transparent hover:text-black hover:shadow disabled:hover:border-inherit disabled:hover:text-gray-400 disabled:hover:shadow-none group-hover:visible group-hover:scale-100 sm:ml-0 sm:flex"
onClick={() => swap(index, index - 1)}>
<FiArrowUp className="h-5 w-5" />
</button>
<button
type="button"
className="invisible absolute -left-[12px] mt-8 -ml-4 hidden h-6 w-6 scale-0 items-center justify-center rounded-md border bg-white p-1 text-gray-400 transition-all hover:border-transparent hover:text-black hover:shadow disabled:hover:border-inherit disabled:hover:text-gray-400 disabled:hover:shadow-none group-hover:visible group-hover:scale-100 sm:ml-0 sm:flex"
onClick={() => swap(index, index + 1)}>
<FiArrowDown className="h-5 w-5" />
</button>
<div>
<div className="flex flex-col lg:flex-row lg:items-center">
<div className="text-sm font-semibold text-gray-700 ltr:mr-1 rtl:ml-1">
{field.label || t(field.defaultLabel || "")}
</div>
<div className="flex items-center space-x-2">
<Badge variant="gray">{isRequired ? "Required" : "Optional"}</Badge>
{field.hidden ? <Badge variant="gray">Hidden</Badge> : null}
{Object.entries(groupedBySourceLabel).map(([sourceLabel, sources], key) => (
// We don't know how to pluralize `sourceLabel` because it can be anything
<Badge key={key} variant="blue">
{sources.length} {sources.length === 1 ? sourceLabel : `${sourceLabel}s`}
</Badge>
))}
</div>
</div>
<p className="max-w-[280px] break-words py-1 text-sm text-gray-500 sm:max-w-[500px]">
{fieldType.label}
</p>
</div>
{field.editable !== "user-readonly" && (
<div className="flex items-center space-x-2">
<Switch
disabled={field.editable === "system"}
tooltip={field.editable === "system" ? t("form_builder_system_field_cant_toggle") : ""}
checked={!field.hidden}
onCheckedChange={(checked) => {
update(index, { ...field, hidden: !checked });
}}
/>
<Button
color="secondary"
onClick={() => {
editField(index, field);
}}>
Edit
</Button>
<Button
color="minimal"
tooltip={
field.editable === "system" || field.editable === "system-but-optional"
? t("form_builder_system_field_cant_delete")
: ""
}
disabled={field.editable === "system" || field.editable === "system-but-optional"}
variant="icon"
onClick={() => {
removeField(index);
}}
StartIcon={FiTrash2}
/>
</div>
)}
</li>
);
})}
</ul>
<Button color="minimal" onClick={addField} className="mt-4" StartIcon={FiPlus}>
{addFieldLabel}
</Button>
</div>
<Dialog
open={fieldDialog.isOpen}
onOpenChange={(isOpen) =>
setFieldDialog({
isOpen,
fieldIndex: -1,
})
}>
<DialogContent>
<DialogHeader title={t("add_a_booking_question")} subtitle={t("form_builder_field_add_subtitle")} />
<div>
<Form
form={fieldForm}
handleSubmit={(data) => {
const isNewField = fieldDialog.fieldIndex == -1;
if (isNewField && fields.some((f) => f.name === data.name)) {
showToast(t("form_builder_field_already_exists"), "error");
return;
}
if (fieldDialog.fieldIndex !== -1) {
update(fieldDialog.fieldIndex, data);
} else {
const field: RhfFormField = {
...data,
sources: [
{
label: "User",
type: "user",
id: "user",
fieldRequired: data.required,
},
],
};
field.editable = field.editable || "user";
append(field);
}
setFieldDialog({
isOpen: false,
fieldIndex: -1,
});
}}>
<SelectField
required
isDisabled={
fieldForm.getValues("editable") === "system" ||
fieldForm.getValues("editable") === "system-but-optional"
}
onChange={(e) => {
const value = e?.value;
if (!value) {
return;
}
fieldForm.setValue("type", value);
}}
value={FieldTypesMap[fieldForm.getValues("type")]}
options={FieldTypes.filter((f) => !f.systemOnly)}
label="Input Type"
/>
<InputField
required
{...fieldForm.register("name")}
containerClassName="mt-6"
disabled={
fieldForm.getValues("editable") === "system" ||
fieldForm.getValues("editable") === "system-but-optional"
}
label="Name"
/>
<InputField
{...fieldForm.register("label")}
// System fields have a defaultLabel, so there a label is not required
required={!["system", "system-but-optional"].includes(fieldForm.getValues("editable") || "")}
placeholder={t(fieldForm.getValues("defaultLabel") || "")}
containerClassName="mt-6"
label="Label"
/>
{fieldType?.isTextType ? (
<InputField
{...fieldForm.register("placeholder")}
containerClassName="mt-6"
label="Placeholder"
placeholder={t(fieldForm.getValues("defaultPlaceholder") || "")}
/>
) : null}
{fieldType?.needsOptions ? (
<Controller
name="options"
render={({ field: { value, onChange } }) => {
return <OptionsField onChange={onChange} value={value} className="mt-6" />;
}}
/>
) : null}
<Controller
name="required"
control={fieldForm.control}
render={({ field: { value, onChange } }) => {
return (
<BooleanToggleGroupField
disabled={fieldForm.getValues("editable") === "system"}
value={value}
onValueChange={(val) => {
onChange(val);
}}
label="Required"
/>
);
}}
/>
<DialogFooter>
<DialogClose color="secondary">Cancel</DialogClose>
<Button type="submit">{isFieldEditMode ? t("save") : t("add")}</Button>
</DialogFooter>
</Form>
</div>
</DialogContent>
</Dialog>
</div>
);
};
// TODO: Add consistent `label` support to all the components and then remove the usage of WithLabel.
// Label should be handled by each Component itself.
const WithLabel = ({
field,
children,
readOnly,
}: {
field: Partial<RhfFormField>;
readOnly: boolean;
children: React.ReactNode;
}) => {
return (
<div>
{/* multiemail doesnt show label initially. It is shown on clicking CTA */}
{/* boolean type doesn't have a label overall, the radio has it's own label */}
{/* Component itself managing it's label should remove these checks */}
{field.type !== "boolean" && field.type !== "multiemail" && field.label && (
<div className="mb-2 flex items-center">
<Label className="!mb-0 flex items-center">{field.label}</Label>
<span className="ml-1 -mb-1 text-sm font-medium leading-none dark:text-white">
{!readOnly && field.required ? "*" : ""}
</span>
</div>
)}
{children}
</div>
);
};
type ValueProps =
| {
value: string[];
setValue: (value: string[]) => void;
}
| {
value: string;
setValue: (value: string) => void;
}
| {
value: {
value: string;
optionValue: string;
};
setValue: (value: { value: string; optionValue: string }) => void;
}
| {
value: boolean;
setValue: (value: boolean) => void;
};
export const ComponentForField = ({
field,
value,
setValue,
readOnly,
}: {
field: Omit<RhfFormField, "editable" | "label"> & {
// Label is optional because radioInput doesn't have a label
label?: string;
};
readOnly: boolean;
} & ValueProps) => {
const fieldType = field.type;
const componentConfig = Components[fieldType];
const isValueOfPropsType = (val: unknown, propsType: typeof componentConfig.propsType) => {
const propsTypeConditionMap = {
boolean: typeof val === "boolean",
multiselect: val instanceof Array && val.every((v) => typeof v === "string"),
objectiveWithInput: typeof val === "object" && val !== null ? "value" in val : false,
select: typeof val === "string",
text: typeof val === "string",
textList: val instanceof Array && val.every((v) => typeof v === "string"),
} as const;
if (!propsTypeConditionMap[propsType]) throw new Error(`Unknown propsType ${propsType}`);
return propsTypeConditionMap[propsType];
};
// If possible would have wanted `isValueOfPropsType` to narrow the type of `value` and `setValue` accordingly, but can't seem to do it.
// So, code following this uses type assertion to tell TypeScript that everything has been validated
if (value !== undefined && !isValueOfPropsType(value, componentConfig.propsType)) {
throw new Error(
`Value ${value} is not valid for type ${componentConfig.propsType} for field ${field.name}`
);
}
if (componentConfig.propsType === "text") {
return (
<WithLabel field={field} readOnly={readOnly}>
<componentConfig.factory
placeholder={field.placeholder}
label={field.label}
readOnly={readOnly}
name={field.name}
value={value as string}
setValue={setValue as (arg: typeof value) => void}
/>
</WithLabel>
);
}
if (componentConfig.propsType === "boolean") {
return (
<WithLabel field={field} readOnly={readOnly}>
<componentConfig.factory
label={field.label}
readOnly={readOnly}
value={value as boolean}
setValue={setValue as (arg: typeof value) => void}
placeholder={field.placeholder}
/>
</WithLabel>
);
}
if (componentConfig.propsType === "textList") {
return (
<WithLabel field={field} readOnly={readOnly}>
<componentConfig.factory
placeholder={field.placeholder}
label={field.label}
readOnly={readOnly}
value={value as string[]}
setValue={setValue as (arg: typeof value) => void}
/>
</WithLabel>
);
}
if (componentConfig.propsType === "select") {
if (!field.options) {
throw new Error("Field options is not defined");
}
return (
<WithLabel field={field} readOnly={readOnly}>
<componentConfig.factory
readOnly={readOnly}
value={value as string}
placeholder={field.placeholder}
setValue={setValue as (arg: typeof value) => void}
options={field.options.map((o) => ({ ...o, title: o.label }))}
/>
</WithLabel>
);
}
if (componentConfig.propsType === "multiselect") {
if (!field.options) {
throw new Error("Field options is not defined");
}
return (
<WithLabel field={field} readOnly={readOnly}>
<componentConfig.factory
placeholder={field.placeholder}
readOnly={readOnly}
value={value as string[]}
setValue={setValue as (arg: typeof value) => void}
options={field.options.map((o) => ({ ...o, title: o.label }))}
/>
</WithLabel>
);
}
if (componentConfig.propsType === "objectiveWithInput") {
if (!field.options) {
throw new Error("Field options is not defined");
}
if (!field.optionsInputs) {
throw new Error("Field optionsInputs is not defined");
}
return field.options.length ? (
<WithLabel field={field} readOnly={readOnly}>
<componentConfig.factory
placeholder={field.placeholder}
readOnly={readOnly}
name={field.name}
value={value as { value: string; optionValue: string }}
setValue={setValue as (arg: typeof value) => void}
optionsInputs={field.optionsInputs}
options={field.options}
/>
</WithLabel>
) : null;
}
throw new Error(`Field ${field.name} does not have a valid propsType`);
};
export const FormBuilderField = ({
field,
readOnly,
className,
}: {
field: RhfFormFields[number];
readOnly: boolean;
className: string;
}) => {
const { t } = useLocale();
const { control, formState } = useFormContext();
return (
<div
data-form-builder-field-name={field.name}
className={classNames(className, field.hidden ? "hidden" : "")}>
<Controller
control={control}
// Make it a variable
name={`responses.${field.name}`}
render={({ field: { value, onChange } }) => {
return (
<div>
<ComponentForField
field={field}
value={value}
readOnly={readOnly}
setValue={(val: unknown) => {
onChange(val);
}}
/>
<ErrorMessage
name="responses"
errors={formState.errors}
render={({ message }) => {
const name = message?.replace(/\{([^}]+)\}.*/, "$1");
// Use the message targeted for it.
if (name !== field.name) {
return null;
}
message = message.replace(/\{[^}]+\}(.*)/, "$1").trim();
if (field.hidden) {
console.error(`Error message for hidden field:${field.name} => ${message}`);
}
return (
<div
data-field-name={field.name}
className="mt-2 flex items-center text-sm text-red-700 ">
<FiInfo className="h-3 w-3 ltr:mr-2 rtl:ml-2" />
<p>{t(message)}</p>
</div>
);
}}
/>
</div>
);
}}
/>
</div>
);
};
@@ -0,0 +1,79 @@
import { z } from "zod";
const fieldTypeEnum = z.enum([
"name",
"text",
"textarea",
"number",
"email",
"phone",
"address",
"multiemail",
"select",
"multiselect",
"checkbox",
"radio",
"radioInput",
"boolean",
]);
export const EditableSchema = z.enum([
"system", // Can't be deleted, can't be hidden, name can't be edited, can't be marked optional
"system-but-optional", // Can't be deleted. Name can't be edited. But can be hidden or be marked optional
"user", // Fully editable
"user-readonly", // All fields are readOnly.
]);
const fieldSchema = z.object({
name: z.string(),
// TODO: We should make at least one of `defaultPlaceholder` and `placeholder` required. Do the same for label.
label: z.string().optional(),
placeholder: z.string().optional(),
/**
* Supports translation
*/
defaultLabel: z.string().optional(),
defaultPlaceholder: z.string().optional(),
type: fieldTypeEnum,
options: z.array(z.object({ label: z.string(), value: z.string() })).optional(),
optionsInputs: z
.record(
z.object({
// Support all types as needed
// Must be a subset of `fieldTypeEnum`.TODO: Enforce it in TypeScript
type: z.enum(["address", "phone", "text"]),
required: z.boolean().optional(),
placeholder: z.string().optional(),
})
)
.optional(),
required: z.boolean().default(false).optional(),
hidden: z.boolean().optional(),
editable: z
.enum([
"system", // Can't be deleted, can't be hidden, name can't be edited, can't be marked optional
"system-but-optional", // Can't be deleted. Name can't be edited. But can be hidden or be marked optional
"user", // Fully editable
"user-readonly", // All fields are readOnly.
])
.default("user")
.optional(),
sources: z
.array(
z.object({
// Unique ID for the `type`. If type is workflow, it's the workflow ID
id: z.string(),
type: z.union([z.literal("user"), z.literal("system"), z.string()]),
label: z.string(),
editUrl: z.string().optional(),
// Mark if a field is required by this source or not. This allows us to set `field.required` based on all the sources' fieldRequired value
fieldRequired: z.boolean().optional(),
})
)
.optional(),
});
export const fieldsSchema = z.array(fieldSchema);
+5
View File
@@ -0,0 +1,5 @@
// TODO: FormBuilder makes more sense in @calcom/ui but it has an additional thing that other components don't have
// It has zod schema associated with it and I currently can't import zod in there.
// Move it later there maybe? @sean
export { FormBuilder } from "./FormBuilder";
export { FormBuilderField } from "./FormBuilder";