Feature/date overrides (#5991)

* Initial incomplete (but mostly functional) push of date override functions

* Fixed date shifting on load

* Bring back minDate (automatically disable all dates before current date)

* Fix type error

* Supply working hours to render available dates

* Converted to SSR

* moving defaultValues to the backend

* Improv. as filter can be achieved within the reduce

Co-authored-by: Omar López <[email protected]>

* Double inversion -> single, as it is an early return

* uniq() exit - not needed anymore

* Typefixes

* It's overriding dates :D

* Fixed duplication DateOverrides in list

* Implemented changing the month

* Make dateOverrides an optional param

* Fixed test (which requires dateOverrides due to auto-typing)

* Prevent a full update on set as default from list view

* Added some extra keys to keep ts happy

* Only allow a single date override per date

* Disallow editing excludedDates to the same date

* Bring back duplicate key ?.?

Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: zomars <[email protected]>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2022-12-14 17:30:55 +00:00
1 parent 8fd5d6b5b5
commit 2f2b72dd54
20 files changed
+707 -202

No files matched your search

-4
View File
@@ -1,4 +0,0 @@
# Availability related code will live here
- [ ] Maybe migrate `getBusyTimes` here
- [ ] Maybe migrate `getUserAvailability` here (or into `users` feature)
@@ -195,6 +195,7 @@ const getEventTypesFromDB = async (eventTypeId: number) => {
},
availability: {
select: {
date: true,
startTime: true,
endTime: true,
days: true,
@@ -67,7 +67,7 @@ export default function MemberChangeRoleModal(props: {
}
return (
<Dialog open={props.isOpen} onOpenChange={props.onExit}>
<DialogContent type="creation" size="md">
<DialogContent type="creation">
<>
<div className="mb-4 sm:flex sm:items-start">
<div className="text-center sm:text-left">
@@ -33,7 +33,7 @@ export default function TeamAvailabilityModal(props: Props) {
return (
<LicenseRequired>
<>
<div className="grid h-[400px] w-[36.7rem] grid-cols-2 space-x-11 rtl:space-x-reverse">
<div className="grid h-[400px] grid-cols-2 space-x-11 rtl:space-x-reverse">
<div className="col-span-1">
<div className="flex">
<Avatar
@@ -0,0 +1,189 @@
import { useState, useEffect, useMemo } from "react";
import { useForm } from "react-hook-form";
import dayjs, { Dayjs } from "@calcom/dayjs";
import { daysInMonth, yyyymmdd } from "@calcom/lib/date-fns";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { WorkingHours } from "@calcom/types/schedule";
import {
Dialog,
DialogContent,
DialogTrigger,
DialogHeader,
DialogClose,
Switch,
DatePicker,
Form,
Button,
} from "@calcom/ui";
import { DayRanges, TimeRange } from "./Schedule";
const ALL_DAY_RANGE = {
start: new Date(dayjs.utc().hour(0).minute(0).second(0).format()),
end: new Date(dayjs.utc().hour(0).minute(0).second(0).format()),
};
// eslint-disable-next-line @typescript-eslint/no-empty-function
const noop = () => {};
const DateOverrideForm = ({
value,
workingHours,
excludedDates,
onChange,
onClose = noop,
}: {
workingHours?: WorkingHours[];
onChange: (newValue: TimeRange[]) => void;
excludedDates: string[];
value?: TimeRange[];
onClose?: () => void;
}) => {
const [browsingDate, setBrowsingDate] = useState<Dayjs>();
const { t, i18n, isLocaleReady } = useLocale();
const [datesUnavailable, setDatesUnavailable] = useState(
value &&
value[0].start.getHours() === 0 &&
value[0].start.getMinutes() === 0 &&
value[0].end.getHours() === 0 &&
value[0].end.getMinutes() === 0
);
const [date, setDate] = useState<Dayjs | null>(value ? dayjs(value[0].start) : null);
const includedDates = useMemo(
() =>
workingHours
? workingHours.reduce((dates, workingHour) => {
for (let dNum = 1; dNum <= daysInMonth(browsingDate || dayjs()); dNum++) {
const d = browsingDate ? browsingDate.date(dNum) : dayjs.utc().date(dNum);
if (workingHour.days.includes(d.day())) {
dates.push(yyyymmdd(d));
}
}
return dates;
}, [] as string[])
: [],
// eslint-disable-next-line react-hooks/exhaustive-deps
[browsingDate]
);
const form = useForm<{ range: TimeRange[] }>();
const { reset } = form;
useEffect(() => {
if (value) {
reset({
range: value.map((range) => ({
start: new Date(
dayjs.utc().hour(range.start.getUTCHours()).minute(range.start.getUTCMinutes()).second(0).format()
),
end: new Date(
dayjs.utc().hour(range.end.getUTCHours()).minute(range.end.getUTCMinutes()).second(0).format()
),
})),
});
return;
}
const dayRanges = (workingHours || []).reduce((dayRanges, workingHour) => {
if (date && workingHour.days.includes(date.day())) {
dayRanges.push({
start: dayjs.utc().startOf("day").add(workingHour.startTime, "minute").toDate(),
end: dayjs.utc().startOf("day").add(workingHour.endTime, "minute").toDate(),
});
}
return dayRanges;
}, [] as TimeRange[]);
reset({
range: dayRanges,
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [date, value]);
return (
<Form
form={form}
handleSubmit={(values) => {
if (!date) return;
onChange(
(datesUnavailable ? [ALL_DAY_RANGE] : values.range).map((item) => ({
start: date.hour(item.start.getHours()).minute(item.start.getMinutes()).toDate(),
end: date.hour(item.end.getHours()).minute(item.end.getMinutes()).toDate(),
}))
);
onClose();
}}
className="flex space-x-4">
<div className="w-1/2 border-r pr-6">
<DialogHeader title={t("date_overrides_dialog_title")} />
<DatePicker
includedDates={includedDates}
excludedDates={excludedDates}
weekStart={0}
selected={date}
onChange={(day) => setDate(day)}
onMonthChange={(newMonth) => {
setBrowsingDate(newMonth);
}}
browsingDate={browsingDate}
locale={isLocaleReady ? i18n.language : "en"}
/>
</div>
{date && (
<div className="relative flex w-1/2 flex-col pl-2">
<div className="mb-4 flex-grow space-y-4">
<p className="text-medium text-sm">{t("date_overrides_dialog_which_hours")}</p>
<div>
{datesUnavailable ? (
<p className="rounded border p-2 text-sm text-neutral-500">
{t("date_overrides_unavailable")}
</p>
) : (
<DayRanges name="range" />
)}
</div>
<Switch
label={t("date_overrides_mark_all_day_unavailable_one")}
checked={datesUnavailable}
onCheckedChange={setDatesUnavailable}
/>
</div>
<div className="flex flex-row-reverse">
<Button className="ml-2" color="primary" type="submit" disabled={!date}>
{value ? t("date_overrides_update_btn") : t("date_overrides_add_btn")}
</Button>
<DialogClose onClick={onClose} />
</div>
</div>
)}
</Form>
);
};
const DateOverrideInputDialog = ({
Trigger,
excludedDates = [],
...passThroughProps
}: {
workingHours: WorkingHours[];
excludedDates?: string[];
Trigger: React.ReactNode;
onChange: (newValue: TimeRange[]) => void;
value?: TimeRange[];
}) => {
const [open, setOpen] = useState(false);
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>{Trigger}</DialogTrigger>
<DialogContent size="md">
<DateOverrideForm
excludedDates={excludedDates}
{...passThroughProps}
onClose={() => setOpen(false)}
/>
</DialogContent>
</Dialog>
);
};
export default DateOverrideInputDialog;
@@ -0,0 +1,100 @@
import { UseFieldArrayRemove } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { TimeRange, WorkingHours } from "@calcom/types/schedule";
import { Button, DialogTrigger, Icon, Tooltip } from "@calcom/ui";
import DateOverrideInputDialog from "./DateOverrideInputDialog";
const DateOverrideList = ({
items,
remove,
update,
workingHours,
excludedDates = [],
}: {
remove: UseFieldArrayRemove;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
update: any;
items: { ranges: TimeRange[]; id: string }[];
workingHours: WorkingHours[];
excludedDates?: string[];
}) => {
const { t, i18n } = useLocale();
if (!items.length) {
return <></>;
}
const timeSpan = ({ start, end }: TimeRange) => {
return (
new Intl.DateTimeFormat(i18n.language, { hour: "numeric", minute: "numeric", hour12: true }).format(
new Date(start.toISOString().slice(0, -1))
) +
" - " +
new Intl.DateTimeFormat(i18n.language, { hour: "numeric", minute: "numeric", hour12: true }).format(
new Date(end.toISOString().slice(0, -1))
)
);
};
return (
<ul className="rounded border border-gray-200">
{items.map((item, index) => (
<li key={item.id} className="flex justify-between border-b px-5 py-4 last:border-b-0">
<div>
<h3 className="text-sm text-gray-900">
{new Intl.DateTimeFormat("en-GB", {
weekday: "short",
month: "long",
day: "numeric",
}).format(item.ranges[0].start)}
</h3>
{item.ranges[0].end.getUTCHours() === 0 && item.ranges[0].end.getUTCMinutes() === 0 ? (
<p className="text-xs text-neutral-500">{t("unavailable")}</p>
) : (
item.ranges.map((range, i) => (
<p key={i} className="text-xs text-neutral-500">
{timeSpan(range)}
</p>
))
)}
</div>
<div className="space-x-2">
<DateOverrideInputDialog
excludedDates={excludedDates}
workingHours={workingHours}
value={item.ranges}
onChange={(ranges) => {
update(index, {
ranges,
});
}}
Trigger={
<DialogTrigger asChild>
<Button
tooltip={t("edit")}
className="text-gray-700"
color="minimal"
size="icon"
StartIcon={Icon.FiEdit2}
/>
</DialogTrigger>
}
/>
<Tooltip content="Delete">
<Button
className="text-gray-700"
color="destructive"
size="icon"
StartIcon={Icon.FiTrash2}
onClick={() => remove(index)}
/>
</Tooltip>
</div>
</li>
))}
</ul>
);
};
export default DateOverrideList;
@@ -30,6 +30,8 @@ import {
Switch,
} from "@calcom/ui";
export type { TimeRange };
export type FieldPathByValue<TFieldValues extends FieldValues, TValue> = {
[Key in FieldPath<TFieldValues>]: FieldPathValue<TFieldValues, Key> extends TValue ? Key : never;
}[FieldPath<TFieldValues>];
@@ -40,7 +42,7 @@ const ScheduleDay = <TFieldValues extends FieldValues>({
control,
CopyButton,
}: {
name: string;
name: ArrayPath<TFieldValues>;
weekday: string;
control: Control<TFieldValues>;
CopyButton: JSX.Element;
@@ -60,7 +62,7 @@ const ScheduleDay = <TFieldValues extends FieldValues>({
defaultChecked={watchDayRange && watchDayRange.length > 0}
checked={watchDayRange && !!watchDayRange.length}
onCheckedChange={(isChecked) => {
setValue(name, isChecked ? [DEFAULT_DAY_RANGE] : []);
setValue(name, (isChecked ? [DEFAULT_DAY_RANGE] : []) as TFieldValues[typeof name]);
}}
/>
</div>
@@ -142,7 +144,7 @@ const Schedule = <
{/* First iterate for each day */}
{weekdayNames(i18n.language, weekStart, "long").map((weekday, num) => {
const weekdayIndex = (num + weekStart) % 7;
const dayRangeName = `${name}.${weekdayIndex}`;
const dayRangeName = `${name}.${weekdayIndex}` as ArrayPath<TFieldValues>;
return (
<ScheduleDay
name={dayRangeName}
@@ -157,18 +159,18 @@ const Schedule = <
);
};
const DayRanges = <TFieldValues extends FieldValues>({
export const DayRanges = <TFieldValues extends FieldValues>({
name,
control,
}: {
name: string;
control: Control<TFieldValues>;
name: ArrayPath<TFieldValues>;
control?: Control<TFieldValues>;
}) => {
const { t } = useLocale();
const { remove, fields, append } = useFieldArray({
control,
name: name as unknown as ArrayPath<TFieldValues>,
name,
});
return (
@@ -224,7 +226,7 @@ const RemoveTimeButton = ({
const TimeRangeField = ({ className, value, onChange }: { className?: string } & ControllerRenderProps) => {
// this is a controlled component anyway given it uses LazySelect, so keep it RHF agnostic.
return (
<div className={classNames("mr-1 sm:mx-1", className)}>
<div className={className}>
<LazySelect
className="inline-block h-9 w-[100px]"
value={value.start}
@@ -30,15 +30,7 @@ export function ScheduleListItem({
timeZone?: string;
hour12?: boolean;
};
updateDefault: ({
scheduleId,
isDefault,
schedule,
}: {
scheduleId: number;
isDefault: boolean;
schedule: Schedule;
}) => void;
updateDefault: ({ scheduleId, isDefault }: { scheduleId: number; isDefault: boolean }) => void;
}) {
const { t, i18n } = useLocale();
@@ -59,15 +51,17 @@ export function ScheduleListItem({
)}
</div>
<p className="mt-1 text-xs text-neutral-500">
{schedule.availability.map((availability: Availability) => (
<Fragment key={availability.id}>
{availabilityAsString(availability, {
locale: i18n.language,
hour12: displayOptions?.hour12,
})}
<br />
</Fragment>
))}
{schedule.availability
.filter((availability) => !!availability.days.length)
.map((availability) => (
<Fragment key={availability.id}>
{availabilityAsString(availability, {
locale: i18n.language,
hour12: displayOptions?.hour12,
})}
<br />
</Fragment>
))}
{schedule.timeZone && schedule.timeZone !== displayOptions?.timeZone && (
<p className="my-1 flex items-center first-letter:text-xs">
<Icon.FiGlobe />
@@ -95,7 +89,6 @@ export function ScheduleListItem({
updateDefault({
scheduleId: schedule.id,
isDefault: true,
schedule: data.availability,
});
}}>
{t("set_as_default")}
@@ -1,3 +1,5 @@
export { NewScheduleButton } from "./NewScheduleButton";
export { default as Schedule } from "./Schedule";
export { ScheduleListItem } from "./ScheduleListItem";
export { default as DateOverrideInputDialog } from "./DateOverrideInputDialog";
export { default as Schedule } from "./Schedule";
export { default as DateOverrideList } from "./DateOverrideList";