feat: Future Limit - Toggle to exclude unavailable days (#14915)

* wip

* wip

* wip

* Add tests

* Update getSchedule.test.ts

* Update types.ts

* Self review fixes

* Update text

* PR feedback from Carina

* Use utcoffset for range as well

* Remove logging from the function that runs on every timeslot

* Add one more test

* Show x days instead of x+1 days for both ROLLING and ROLLING_WINDOW

* refactor tests

* Move bookingScenario imports to the top as they import prismock mock that has to be imported very early

* More reordering of imports

* Fix accidental min update at wrong place

* Handle legacy value of zero for periodDays

* Range fix

* Fix isDateOutOfBound not being checked properly during booking. Also added a test for the case

* Fix duplicate element, how the hell it reached there

* Use today plus x days for ROLLING periodType

* Add disabled for Checkbox as well

* Revert logger.ts

* Formatting

Signed-off-by: zomars <[email protected]>

* Fix ordering of imports that is causing tests failure

---------

Signed-off-by: zomars <[email protected]>
Co-authored-by: Alex van Andel <[email protected]>
Co-authored-by: Omar López <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-05-20 13:41:07 +01:00
1 parent b67d37fac7
commit 56022a1ba8
34 files changed
+1618 -428

No files matched your search

+219 -111
View File
@@ -3,7 +3,7 @@ import * as RadioGroup from "@radix-ui/react-radio-group";
import type { EventTypeSetupProps } from "pages/event-types/[type]";
import type { Key } from "react";
import React, { useEffect, useState } from "react";
import type { UseFormRegisterReturn } from "react-hook-form";
import type { UseFormRegisterReturn, UseFormReturn } from "react-hook-form";
import { Controller, useFormContext } from "react-hook-form";
import type { SingleValue } from "react-select";
@@ -11,15 +11,193 @@ import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hook
import { getDefinedBufferTimes } from "@calcom/features/eventtypes/lib/getDefinedBufferTimes";
import type { FormValues } from "@calcom/features/eventtypes/lib/types";
import { classNames } from "@calcom/lib";
import { ROLLING_WINDOW_PERIOD_MAX_DAYS_TO_CHECK } from "@calcom/lib/constants";
import type { DurationType } from "@calcom/lib/convertToNewDurationType";
import convertToNewDurationType from "@calcom/lib/convertToNewDurationType";
import findDurationType from "@calcom/lib/findDurationType";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { ascendingLimitKeys, intervalLimitKeyToUnit } from "@calcom/lib/intervalLimit";
import type { PeriodType } from "@calcom/prisma/enums";
import { PeriodType } from "@calcom/prisma/enums";
import type { IntervalLimit } from "@calcom/types/Calendar";
import { Button, DateRangePicker, InputField, Label, Select, SettingsToggle, TextField } from "@calcom/ui";
import CheckboxField from "@components/ui/form/CheckboxField";
type IPeriodType = (typeof PeriodType)[keyof typeof PeriodType];
/**
* We technically have a ROLLING_WINDOW future limit option that isn't shown as a Radio Option. Because UX is better by providing it as a toggle with ROLLING Limit radio option.
* Also, ROLLING_WINDOW reuses the same `periodDays` field and `periodCountCalendarDays` fields
*
* So we consider `periodType=ROLLING && rollingExcludeUnavailableDays=true` to be the ROLLING_WINDOW option
* We can't set `periodType=ROLLING_WINDOW` directly because it is not a valid Radio Option in UI
* So, here we can convert from periodType to uiValue any time.
*/
const getUiValueFromPeriodType = (periodType: PeriodType) => {
if (periodType === PeriodType.ROLLING_WINDOW) {
return {
value: PeriodType.ROLLING,
rollingExcludeUnavailableDays: true,
};
}
if (periodType === PeriodType.ROLLING) {
return {
value: PeriodType.ROLLING,
rollingExcludeUnavailableDays: false,
};
}
return {
value: periodType,
rollingExcludeUnavailableDays: null,
};
};
/**
* It compliments `getUiValueFromPeriodType`
*/
const getPeriodTypeFromUiValue = (uiValue: { value: PeriodType; rollingExcludeUnavailableDays: boolean }) => {
if (uiValue.value === PeriodType.ROLLING && uiValue.rollingExcludeUnavailableDays === true) {
return PeriodType.ROLLING_WINDOW;
}
return uiValue.value;
};
function RangeLimitRadioItem({
isDisabled,
formMethods,
radioValue,
}: {
radioValue: string;
isDisabled: boolean;
formMethods: UseFormReturn<FormValues>;
}) {
const { t } = useLocale();
return (
<div className={classNames("text-default mb-2 flex flex-wrap items-center text-sm")}>
{!isDisabled && (
<RadioGroup.Item
id={radioValue}
value={radioValue}
className="min-w-4 bg-default border-default flex h-4 w-4 cursor-pointer items-center rounded-full border focus:border-2 focus:outline-none ltr:mr-2 rtl:ml-2">
<RadioGroup.Indicator className="after:bg-inverted relative flex h-4 w-4 items-center justify-center after:block after:h-2 after:w-2 after:rounded-full" />
</RadioGroup.Item>
)}
<div>
<span>{t("within_date_range")}&nbsp;</span>
<div className="me-2 ms-2 inline-flex space-x-2 rtl:space-x-reverse">
<Controller
name="periodDates"
render={({ field: { onChange } }) => (
<DateRangePicker
dates={{
startDate: formMethods.getValues("periodDates").startDate,
endDate: formMethods.getValues("periodDates").endDate,
}}
disabled={isDisabled}
onDatesChange={({ startDate, endDate }) => {
onChange({
startDate,
endDate,
});
}}
/>
)}
/>
</div>
</div>
</div>
);
}
function RollingLimitRadioItem({
radioValue,
isDisabled,
formMethods,
onChange,
rollingExcludeUnavailableDays,
}: {
radioValue: IPeriodType;
isDisabled: boolean;
formMethods: UseFormReturn<FormValues>;
onChange: (opt: { value: number } | null) => void;
rollingExcludeUnavailableDays: boolean;
}) {
const { t } = useLocale();
const options = [
{ value: 0, label: t("business_days") },
{ value: 1, label: t("calendar_days") },
];
const getSelectedOption = () =>
options.find((opt) => opt.value === (formMethods.getValues("periodCountCalendarDays") === true ? 1 : 0));
const periodDaysWatch = formMethods.watch("periodDays");
return (
<div className={classNames("text-default mb-2 flex flex-wrap items-baseline text-sm")}>
{!isDisabled && (
<RadioGroup.Item
id={radioValue}
value={radioValue}
className="min-w-4 bg-default border-default flex h-4 w-4 cursor-pointer items-center rounded-full border focus:border-2 focus:outline-none ltr:mr-2 rtl:ml-2">
<RadioGroup.Indicator className="after:bg-inverted relative flex h-4 w-4 items-center justify-center after:block after:h-2 after:w-2 after:rounded-full" />
</RadioGroup.Item>
)}
<div>
<div className="flex items-center">
<TextField
labelSrOnly
type="number"
className="border-default my-0 block w-16 text-sm [appearance:textfield] ltr:mr-2 rtl:ml-2"
placeholder="30"
disabled={isDisabled}
min={0}
max={rollingExcludeUnavailableDays ? ROLLING_WINDOW_PERIOD_MAX_DAYS_TO_CHECK : undefined}
{...formMethods.register("periodDays", { valueAsNumber: true })}
/>
<Select
options={options}
isSearchable={false}
isDisabled={isDisabled}
onChange={onChange}
name="periodCoundCalendarDays"
value={getSelectedOption()}
defaultValue={getSelectedOption()}
/>
<span className="me-2 ms-2">&nbsp;{t("into_the_future")}</span>
</div>
<div className="py-2">
<CheckboxField
checked={!!rollingExcludeUnavailableDays}
disabled={isDisabled}
description={t("always_show_x_days", {
x: periodDaysWatch,
})}
onChange={(e) => {
const isChecked = e.target.checked;
formMethods.setValue(
"periodDays",
Math.min(periodDaysWatch, ROLLING_WINDOW_PERIOD_MAX_DAYS_TO_CHECK)
);
formMethods.setValue(
"periodType",
getPeriodTypeFromUiValue({
value: PeriodType.ROLLING,
rollingExcludeUnavailableDays: isChecked,
}),
{ shouldDirty: true }
);
}}
/>
</div>
</div>
</div>
);
}
const MinimumBookingNoticeInput = React.forwardRef<
HTMLInputElement,
Omit<UseFormRegisterReturn<"minimumBookingNotice">, "ref">
@@ -114,23 +292,6 @@ export const EventLimitsTab = ({ eventType }: Pick<EventTypeSetupProps, "eventTy
const { t, i18n } = useLocale();
const formMethods = useFormContext<FormValues>();
const PERIOD_TYPES = [
{
type: "ROLLING" as const,
suffix: t("into_the_future"),
},
{
type: "RANGE" as const,
prefix: t("within_date_range"),
},
{
type: "UNLIMITED" as const,
prefix: t("indefinitely_into_future"),
},
];
const watchPeriodType = formMethods.watch("periodType");
const { shouldLockIndicator, shouldLockDisableProps } = useLockedFieldsManager({
eventType,
translate: t,
@@ -143,11 +304,6 @@ export const EventLimitsTab = ({ eventType }: Pick<EventTypeSetupProps, "eventTy
const periodTypeLocked = shouldLockDisableProps("periodType");
const offsetStartLockedProps = shouldLockDisableProps("offsetStart");
const optionsPeriod = [
{ value: 0, label: t("business_days") },
{ value: 1, label: t("calendar_days") },
];
const [offsetToggle, setOffsetToggle] = useState(formMethods.getValues("offsetStart") > 0);
// Preview how the offset will affect start times
@@ -389,6 +545,10 @@ export const EventLimitsTab = ({ eventType }: Pick<EventTypeSetupProps, "eventTy
render={({ field: { onChange, value } }) => {
const isChecked = value && value !== "UNLIMITED";
const { value: watchPeriodTypeUiValue, rollingExcludeUnavailableDays } = getUiValueFromPeriodType(
formMethods.watch("periodType")
);
return (
<SettingsToggle
labelClassName="text-sm"
@@ -402,99 +562,47 @@ export const EventLimitsTab = ({ eventType }: Pick<EventTypeSetupProps, "eventTy
description={t("limit_future_bookings_description")}
{...periodTypeLocked}
checked={isChecked}
onCheckedChange={(bool) => {
if (bool && !formMethods.getValues("periodDays")) {
onCheckedChange={(isEnabled) => {
if (isEnabled && !formMethods.getValues("periodDays")) {
formMethods.setValue("periodDays", 30, { shouldDirty: true });
}
return onChange(bool ? "ROLLING" : "UNLIMITED");
return onChange(isEnabled ? PeriodType.ROLLING : PeriodType.UNLIMITED);
}}>
<div className="border-subtle rounded-b-lg border border-t-0 p-6">
<RadioGroup.Root
value={watchPeriodType}
onValueChange={(val) =>
formMethods.setValue("periodType", val as PeriodType, { shouldDirty: true })
}>
{PERIOD_TYPES.filter((opt) =>
periodTypeLocked.disabled ? watchPeriodType === opt.type : true
).map((period) => {
if (period.type === "UNLIMITED") return null;
return (
<div
className={classNames(
"text-default mb-2 flex flex-wrap items-center text-sm",
watchPeriodType === "UNLIMITED" && "pointer-events-none opacity-30"
)}
key={period.type}>
{!periodTypeLocked.disabled && (
<RadioGroup.Item
id={period.type}
value={period.type}
className="min-w-4 bg-default border-default flex h-4 w-4 cursor-pointer items-center rounded-full border focus:border-2 focus:outline-none ltr:mr-2 rtl:ml-2">
<RadioGroup.Indicator className="after:bg-inverted relative flex h-4 w-4 items-center justify-center after:block after:h-2 after:w-2 after:rounded-full" />
</RadioGroup.Item>
)}
{period.prefix ? <span>{period.prefix}&nbsp;</span> : null}
{period.type === "ROLLING" && (
<div className="flex items-center">
<TextField
labelSrOnly
type="number"
className="border-default my-0 block w-16 text-sm [appearance:textfield] ltr:mr-2 rtl:ml-2"
placeholder="30"
disabled={periodTypeLocked.disabled}
{...formMethods.register("periodDays", { valueAsNumber: true })}
/>
<Select
options={optionsPeriod}
isSearchable={false}
isDisabled={periodTypeLocked.disabled}
onChange={(opt) => {
formMethods.setValue(
"periodCountCalendarDays",
opt?.value === 1 ? true : false,
{ shouldDirty: true }
);
}}
name="periodCoundCalendarDays"
value={optionsPeriod.find((opt) => {
opt.value ===
(formMethods.getValues("periodCountCalendarDays") === true ? 1 : 0);
})}
defaultValue={optionsPeriod.find(
(opt) =>
opt.value ===
(formMethods.getValues("periodCountCalendarDays") === true ? 1 : 0)
)}
/>
</div>
)}
{period.type === "RANGE" && (
<div className="me-2 ms-2 inline-flex space-x-2 rtl:space-x-reverse">
<Controller
name="periodDates"
render={({ field: { onChange } }) => (
<DateRangePicker
dates={{
startDate: formMethods.getValues("periodDates").startDate,
endDate: formMethods.getValues("periodDates").endDate,
}}
disabled={periodTypeLocked.disabled}
onDatesChange={({ startDate, endDate }) => {
onChange({
startDate,
endDate,
});
}}
/>
)}
/>
</div>
)}
{period.suffix ? <span className="me-2 ms-2">&nbsp;{period.suffix}</span> : null}
</div>
value={watchPeriodTypeUiValue}
onValueChange={(val) => {
formMethods.setValue(
"periodType",
getPeriodTypeFromUiValue({
value: val as IPeriodType,
rollingExcludeUnavailableDays: formMethods.getValues("rollingExcludeUnavailableDays"),
}),
{
shouldDirty: true,
}
);
})}
}}>
{(periodTypeLocked.disabled ? watchPeriodTypeUiValue === PeriodType.ROLLING : true) && (
<RollingLimitRadioItem
rollingExcludeUnavailableDays={!!rollingExcludeUnavailableDays}
radioValue={PeriodType.ROLLING}
isDisabled={periodTypeLocked.disabled}
formMethods={formMethods}
onChange={(opt) => {
formMethods.setValue("periodCountCalendarDays", opt?.value === 1, {
shouldDirty: true,
});
}}
/>
)}
{(periodTypeLocked.disabled ? watchPeriodTypeUiValue === PeriodType.RANGE : true) && (
<RangeLimitRadioItem
radioValue={PeriodType.RANGE}
isDisabled={periodTypeLocked.disabled}
formMethods={formMethods}
/>
)}
</RadioGroup.Root>
</div>
</SettingsToggle>