feat: travel schedules to schedule timezone changes (#14512)
* add Travel Schedule modal * UI to list schedules * set shouldDirty * add backend to add new travelSchedule * implement deleting a schedule * check if schedule is overlapping * WIP * fix finding overlapping travel schedule * only use travelSchedule when default availability is used * adjust date overrides to timezone schedule * first version of changeTimeZone cron job * fix tests by adding travelSchedules * fixes for cron job api call * improve unit tests * add migration * fix type error * fix collective-scheduling test * clean up cron job * code clean up * code clean up * show timezone from travel schedule for date override * add date override tests * show tz on date override only in default schedule * fix deleting old schedules * minor fixes in cron api handler * code clean up * code clean up from feedback * fix asia/kalkota comment * fix dark mode * fix start and end date conversion to utc * add first unit test for travel schedules * Fix modal render issue * show timezone city wtihout _ * fix dark more for datepicker * reset values after closing dialog * remove session from middleware * exit loop early once schedule is found * fix type error * add getTravelSchedules handler * clean up DatePicker * fix type error * code clean up * code clean up * add indexes * use deleteMany * fix icons --------- Co-authored-by: CarinaWolli <[email protected]> Co-authored-by: Alex van Andel <[email protected]> Co-authored-by: Joe Au-Yeung <[email protected]>
This commit is contained in:
26 files changed
+873
-33
No files matched your search
@@ -0,0 +1,160 @@
|
||||
import type { FormValues } from "@pages/settings/my-account/general";
|
||||
import { useState } from "react";
|
||||
import type { UseFormSetValue } from "react-hook-form";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { useTimePreferences } from "@calcom/features/bookings/lib/timePreferences";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogClose,
|
||||
Button,
|
||||
Label,
|
||||
DateRangePicker,
|
||||
TimezoneSelect,
|
||||
SettingsToggle,
|
||||
DatePicker,
|
||||
} from "@calcom/ui";
|
||||
|
||||
interface TravelScheduleModalProps {
|
||||
open: boolean;
|
||||
onOpenChange: () => void;
|
||||
setValue: UseFormSetValue<FormValues>;
|
||||
existingSchedules: FormValues["travelSchedules"];
|
||||
}
|
||||
|
||||
const TravelScheduleModal = ({
|
||||
open,
|
||||
onOpenChange,
|
||||
setValue,
|
||||
existingSchedules,
|
||||
}: TravelScheduleModalProps) => {
|
||||
const { t } = useLocale();
|
||||
const { timezone: preferredTimezone } = useTimePreferences();
|
||||
|
||||
const [startDate, setStartDate] = useState<Date>(new Date());
|
||||
const [endDate, setEndDate] = useState<Date | undefined>(new Date());
|
||||
|
||||
const [selectedTimeZone, setSelectedTimeZone] = useState(preferredTimezone);
|
||||
const [isNoEndDate, setIsNoEndDate] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
|
||||
const isOverlapping = (newSchedule: { startDate: Date; endDate?: Date }) => {
|
||||
const newStart = dayjs(newSchedule.startDate);
|
||||
const newEnd = newSchedule.endDate ? dayjs(newSchedule.endDate) : null;
|
||||
|
||||
for (const schedule of existingSchedules) {
|
||||
const start = dayjs(schedule.startDate);
|
||||
const end = schedule.endDate ? dayjs(schedule.endDate) : null;
|
||||
|
||||
if (!newEnd) {
|
||||
// if the start date is after or on the existing schedule's start date and before the existing schedule's end date (if it has one)
|
||||
if (newStart.isSame(start) || newStart.isAfter(start)) {
|
||||
if (!end || newStart.isSame(end) || newStart.isBefore(end)) return true;
|
||||
}
|
||||
} else {
|
||||
// For schedules with an end date, check for any overlap
|
||||
if (newStart.isSame(end) || newStart.isBefore(end) || end === null) {
|
||||
if (newEnd.isSame(start) || newEnd.isAfter(start)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const resetValues = () => {
|
||||
setStartDate(new Date());
|
||||
setEndDate(new Date());
|
||||
setSelectedTimeZone(preferredTimezone);
|
||||
setIsNoEndDate(false);
|
||||
};
|
||||
|
||||
const createNewSchedule = () => {
|
||||
const newSchedule = {
|
||||
startDate,
|
||||
endDate,
|
||||
timeZone: selectedTimeZone,
|
||||
};
|
||||
|
||||
if (!isOverlapping(newSchedule)) {
|
||||
setValue("travelSchedules", existingSchedules.concat(newSchedule), { shouldDirty: true });
|
||||
onOpenChange();
|
||||
resetValues();
|
||||
} else {
|
||||
setErrorMessage(t("overlaps_with_existing_schedule"));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent
|
||||
title={t("travel_schedule")}
|
||||
description={t("travel_schedule_description")}
|
||||
type="creation">
|
||||
<div>
|
||||
{!isNoEndDate ? (
|
||||
<>
|
||||
<Label className="mt-2">{t("time_range")}</Label>
|
||||
<DateRangePicker
|
||||
startDate={startDate}
|
||||
endDate={endDate ?? startDate}
|
||||
onDatesChange={({ startDate: newStartDate, endDate: newEndDate }) => {
|
||||
setStartDate(newStartDate);
|
||||
setEndDate(newEndDate);
|
||||
setErrorMessage("");
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Label className="mt-2">{t("date")}</Label>
|
||||
<DatePicker
|
||||
minDate={new Date()}
|
||||
date={startDate}
|
||||
className="w-56"
|
||||
onDatesChange={(newDate) => {
|
||||
setStartDate(newDate);
|
||||
setErrorMessage("");
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<div className="text-error mt-1 text-sm">{errorMessage}</div>
|
||||
<div className="mt-3">
|
||||
<SettingsToggle
|
||||
labelClassName="mt-1 font-normal"
|
||||
title={t("schedule_tz_without_end_date")}
|
||||
checked={isNoEndDate}
|
||||
onCheckedChange={(e) => {
|
||||
setEndDate(!e ? startDate : undefined);
|
||||
setIsNoEndDate(e);
|
||||
setErrorMessage("");
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<Label className="mt-6">{t("timezone")}</Label>
|
||||
<TimezoneSelect
|
||||
id="timeZone"
|
||||
value={selectedTimeZone}
|
||||
onChange={({ value }) => setSelectedTimeZone(value)}
|
||||
className="mb-11 mt-2 w-full rounded-md text-sm"
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter showDivider className="relative">
|
||||
<DialogClose />
|
||||
<Button
|
||||
onClick={() => {
|
||||
createNewSchedule();
|
||||
}}>
|
||||
{t("add")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default TravelScheduleModal;
|
||||
@@ -16,3 +16,12 @@ export type WorkingHours = {
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
};
|
||||
|
||||
export type TravelSchedule = {
|
||||
id: number;
|
||||
timeZone: string;
|
||||
userId: number;
|
||||
startDate: Date;
|
||||
endDate: Date | null;
|
||||
prevTimeZone: string | null;
|
||||
};
|
||||
@@ -0,0 +1,173 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { getDefaultScheduleId } from "@calcom/trpc/server/routers/viewer/availability/util";
|
||||
|
||||
const travelScheduleSelect = {
|
||||
id: true,
|
||||
startDate: true,
|
||||
endDate: true,
|
||||
timeZone: true,
|
||||
prevTimeZone: true,
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
timeZone: true,
|
||||
defaultScheduleId: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const apiKey = req.headers.authorization || req.query.apiKey;
|
||||
if (process.env.CRON_API_KEY !== apiKey) {
|
||||
res.status(401).json({ message: "Not authenticated" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method !== "POST") {
|
||||
res.status(405).json({ message: "Invalid method" });
|
||||
return;
|
||||
}
|
||||
|
||||
let timeZonesChanged = 0;
|
||||
|
||||
const setNewTimeZone = async (timeZone: string, user: { id: number; defaultScheduleId: number | null }) => {
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
data: {
|
||||
timeZone: timeZone,
|
||||
},
|
||||
});
|
||||
|
||||
const defaultScheduleId = await getDefaultScheduleId(user.id, prisma);
|
||||
|
||||
if (!user.defaultScheduleId) {
|
||||
// set default schedule if not already set
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
data: {
|
||||
defaultScheduleId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
await prisma.schedule.updateMany({
|
||||
where: {
|
||||
id: defaultScheduleId,
|
||||
},
|
||||
data: {
|
||||
timeZone: timeZone,
|
||||
},
|
||||
});
|
||||
timeZonesChanged++;
|
||||
};
|
||||
|
||||
/* travelSchedules should be deleted automatically when timezone is set back to original tz,
|
||||
but we do this in case there cron job didn't run for some reason
|
||||
*/
|
||||
const schedulesToDelete = await prisma.travelSchedule.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{
|
||||
startDate: {
|
||||
lt: dayjs.utc().subtract(2, "day").toDate(),
|
||||
},
|
||||
endDate: null,
|
||||
},
|
||||
{
|
||||
endDate: {
|
||||
lt: dayjs.utc().subtract(2, "day").toDate(),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
select: travelScheduleSelect,
|
||||
});
|
||||
|
||||
for (const travelSchedule of schedulesToDelete) {
|
||||
if (travelSchedule.prevTimeZone) {
|
||||
await setNewTimeZone(travelSchedule.prevTimeZone, travelSchedule.user);
|
||||
}
|
||||
await prisma.travelSchedule.delete({
|
||||
where: {
|
||||
id: travelSchedule.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const travelSchedulesCloseToCurrentDate = await prisma.travelSchedule.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{
|
||||
startDate: {
|
||||
gte: dayjs.utc().subtract(1, "day").toDate(),
|
||||
lte: dayjs.utc().add(1, "day").toDate(),
|
||||
},
|
||||
},
|
||||
{
|
||||
endDate: {
|
||||
gte: dayjs.utc().subtract(1, "day").toDate(),
|
||||
lte: dayjs.utc().add(1, "day").toDate(),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
select: travelScheduleSelect,
|
||||
});
|
||||
|
||||
const travelScheduleIdsToDelete = [];
|
||||
|
||||
for (const travelSchedule of travelSchedulesCloseToCurrentDate) {
|
||||
const userTz = travelSchedule.user.timeZone;
|
||||
const offset = dayjs().tz(userTz).utcOffset();
|
||||
|
||||
// midnight of user's time zone in utc time
|
||||
const startDateUTC = dayjs(travelSchedule.startDate).subtract(offset, "minute");
|
||||
// 23:59 of user's time zone in utc time
|
||||
const endDateUTC = dayjs(travelSchedule.endDate).subtract(offset, "minute");
|
||||
if (
|
||||
!dayjs.utc().isBefore(startDateUTC) &&
|
||||
dayjs.utc().isBefore(endDateUTC) &&
|
||||
!travelSchedule.prevTimeZone
|
||||
) {
|
||||
// if travel schedule has started and prevTimeZone is not yet set, we need to change time zone
|
||||
await setNewTimeZone(travelSchedule.timeZone, travelSchedule.user);
|
||||
|
||||
if (!travelSchedule.endDate) {
|
||||
travelScheduleIdsToDelete.push(travelSchedule.id);
|
||||
} else {
|
||||
await prisma.travelSchedule.update({
|
||||
where: {
|
||||
id: travelSchedule.id,
|
||||
},
|
||||
data: {
|
||||
prevTimeZone: travelSchedule.user.timeZone,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
if (!dayjs.utc().isBefore(endDateUTC)) {
|
||||
if (travelSchedule.prevTimeZone) {
|
||||
// travel schedule ended, change back to original timezone
|
||||
await setNewTimeZone(travelSchedule.prevTimeZone, travelSchedule.user);
|
||||
}
|
||||
travelScheduleIdsToDelete.push(travelSchedule.id);
|
||||
}
|
||||
}
|
||||
|
||||
await prisma.travelSchedule.deleteMany({
|
||||
where: {
|
||||
id: {
|
||||
in: travelScheduleIdsToDelete,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
res.status(200).json({ timeZonesChanged });
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import { Controller, useForm } from "react-hook-form";
|
||||
|
||||
import SectionBottomActions from "@calcom/features/settings/SectionBottomActions";
|
||||
import { getLayout } from "@calcom/features/settings/layouts/SettingsLayout";
|
||||
import { classNames } from "@calcom/lib";
|
||||
import { formatLocalizedDateTime } from "@calcom/lib/date-fns";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { localeOptions } from "@calcom/lib/i18n";
|
||||
import { nameOfDay } from "@calcom/lib/weekday";
|
||||
@@ -26,6 +28,29 @@ import {
|
||||
} from "@calcom/ui";
|
||||
|
||||
import PageWrapper from "@components/PageWrapper";
|
||||
import TravelScheduleModal from "@components/settings/TravelScheduleModal";
|
||||
|
||||
export type FormValues = {
|
||||
locale: {
|
||||
value: string;
|
||||
label: string;
|
||||
};
|
||||
timeZone: string;
|
||||
timeFormat: {
|
||||
value: number;
|
||||
label: string | number;
|
||||
};
|
||||
weekStart: {
|
||||
value: string;
|
||||
label: string;
|
||||
};
|
||||
travelSchedules: {
|
||||
id?: number;
|
||||
startDate: Date;
|
||||
endDate?: Date;
|
||||
timeZone: string;
|
||||
}[];
|
||||
};
|
||||
|
||||
const SkeletonLoader = ({ title, description }: { title: string; description: string }) => {
|
||||
return (
|
||||
@@ -46,24 +71,34 @@ const SkeletonLoader = ({ title, description }: { title: string; description: st
|
||||
interface GeneralViewProps {
|
||||
localeProp: string;
|
||||
user: RouterOutputs["viewer"]["me"];
|
||||
travelSchedules: RouterOutputs["viewer"]["getTravelSchedules"];
|
||||
}
|
||||
|
||||
const GeneralQueryView = () => {
|
||||
const { t } = useLocale();
|
||||
|
||||
const { data: user, isPending } = trpc.viewer.me.useQuery();
|
||||
if (isPending) return <SkeletonLoader title={t("general")} description={t("general_description")} />;
|
||||
|
||||
const { data: travelSchedules, isPending: isPendingTravelSchedules } =
|
||||
trpc.viewer.getTravelSchedules.useQuery();
|
||||
|
||||
if (isPending || isPendingTravelSchedules)
|
||||
return <SkeletonLoader title={t("general")} description={t("general_description")} />;
|
||||
if (!user) {
|
||||
throw new Error(t("something_went_wrong"));
|
||||
}
|
||||
return <GeneralView user={user} localeProp={user.locale} />;
|
||||
return <GeneralView user={user} travelSchedules={travelSchedules || []} localeProp={user.locale} />;
|
||||
};
|
||||
|
||||
const GeneralView = ({ localeProp, user }: GeneralViewProps) => {
|
||||
const utils = trpc.useUtils();
|
||||
const { t } = useLocale();
|
||||
const GeneralView = ({ localeProp, user, travelSchedules }: GeneralViewProps) => {
|
||||
const utils = trpc.useContext();
|
||||
const {
|
||||
t,
|
||||
i18n: { language },
|
||||
} = useLocale();
|
||||
const { update } = useSession();
|
||||
const [isUpdateBtnLoading, setIsUpdateBtnLoading] = useState<boolean>(false);
|
||||
const [isTZScheduleOpen, setIsTZScheduleOpen] = useState<boolean>(false);
|
||||
|
||||
const mutation = trpc.viewer.updateProfile.useMutation({
|
||||
onSuccess: async (res) => {
|
||||
@@ -100,7 +135,7 @@ const GeneralView = ({ localeProp, user }: GeneralViewProps) => {
|
||||
{ value: "Saturday", label: nameOfDay(localeProp, 6) },
|
||||
];
|
||||
|
||||
const formMethods = useForm({
|
||||
const formMethods = useForm<FormValues>({
|
||||
defaultValues: {
|
||||
locale: {
|
||||
value: localeProp || "",
|
||||
@@ -115,6 +150,15 @@ const GeneralView = ({ localeProp, user }: GeneralViewProps) => {
|
||||
value: user.weekStart,
|
||||
label: nameOfDay(localeProp, user.weekStart === "Sunday" ? 0 : 1),
|
||||
},
|
||||
travelSchedules:
|
||||
travelSchedules.map((schedule) => {
|
||||
return {
|
||||
id: schedule.id,
|
||||
startDate: schedule.startDate,
|
||||
endDate: schedule.endDate ?? undefined,
|
||||
timeZone: schedule.timeZone,
|
||||
};
|
||||
}) || [],
|
||||
},
|
||||
});
|
||||
const {
|
||||
@@ -132,6 +176,8 @@ const GeneralView = ({ localeProp, user }: GeneralViewProps) => {
|
||||
!!user.receiveMonthlyDigestEmail
|
||||
);
|
||||
|
||||
const watchedTzSchedules = formMethods.watch("travelSchedules");
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Form
|
||||
@@ -181,6 +227,64 @@ const GeneralView = ({ localeProp, user }: GeneralViewProps) => {
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
{!watchedTzSchedules.length ? (
|
||||
<Button color="minimal" className="mt-2" onClick={() => setIsTZScheduleOpen(true)}>
|
||||
{t("schedule_timezone_change")}
|
||||
</Button>
|
||||
) : (
|
||||
<div className="bg-muted border-subtle mt-2 rounded-md border p-4">
|
||||
<Label>{t("travel_schedule")}</Label>
|
||||
<div className="dark:bg-darkgray-100 border-subtle mt-4 rounded-md border bg-white text-sm">
|
||||
{watchedTzSchedules.map((schedule, index) => {
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
"flex items-center p-4",
|
||||
index !== 0 ? "border-subtle border-t" : ""
|
||||
)}
|
||||
key={index}>
|
||||
<div>
|
||||
<div className="text-emphasis font-semibold">{`${formatLocalizedDateTime(
|
||||
schedule.startDate,
|
||||
{ day: "numeric", month: "long" },
|
||||
language
|
||||
)} ${
|
||||
schedule.endDate
|
||||
? `- ${formatLocalizedDateTime(
|
||||
schedule.endDate,
|
||||
{ day: "numeric", month: "long" },
|
||||
language
|
||||
)}`
|
||||
: ``
|
||||
}`}</div>
|
||||
<div className="text-subtle">{schedule.timeZone.replace(/_/g, " ")}</div>
|
||||
</div>
|
||||
<Button
|
||||
color="secondary"
|
||||
className="ml-auto"
|
||||
variant="icon"
|
||||
StartIcon="trash-2"
|
||||
onClick={() => {
|
||||
const updatedSchedules = watchedTzSchedules.filter(
|
||||
(s, filterIndex) => filterIndex !== index
|
||||
);
|
||||
formMethods.setValue("travelSchedules", updatedSchedules, { shouldDirty: true });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<Button
|
||||
StartIcon="plus"
|
||||
color="secondary"
|
||||
className="mt-4"
|
||||
onClick={() => setIsTZScheduleOpen(true)}>
|
||||
{t("add")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Controller
|
||||
name="timeFormat"
|
||||
control={formMethods.control}
|
||||
@@ -267,6 +371,12 @@ const GeneralView = ({ localeProp, user }: GeneralViewProps) => {
|
||||
}}
|
||||
switchContainerClassName="mt-6"
|
||||
/>
|
||||
<TravelScheduleModal
|
||||
open={isTZScheduleOpen}
|
||||
onOpenChange={() => setIsTZScheduleOpen(false)}
|
||||
setValue={formMethods.setValue}
|
||||
existingSchedules={formMethods.getValues("travelSchedules") ?? []}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -2318,6 +2318,11 @@
|
||||
"field_identifiers_as_variables": "Use field identifiers as variables for your custom event redirect",
|
||||
"field_identifiers_as_variables_with_example": "Use field identifiers as variables for your custom event redirect (e.g. {{variable}})",
|
||||
"account_already_linked": "Account is already linked",
|
||||
"travel_schedule": "Travel Schedule",
|
||||
"travel_schedule_description": "Plan your trip ahead to keep your existing schedule in a different timezone and prevent being booked at midnight.",
|
||||
"schedule_timezone_change": "Schedule timezone change",
|
||||
"date": "Date",
|
||||
"overlaps_with_existing_schedule": "This overlaps with an existing schedule. Please select a different date.",
|
||||
|
||||
"email_team_invite|subject|added_to_org": "{{user}} added you to the organization {{team}} on {{appName}}",
|
||||
"email_team_invite|subject|invited_to_org": "{{user}} invited you to join the organization {{team}} on {{appName}}",
|
||||
@@ -2354,6 +2359,7 @@
|
||||
"confirm_email": "Confirm your email",
|
||||
"confirm_email_description": "We sent an email to <strong>{{email}}</strong>. Click the link in the email to verify this address.",
|
||||
"send_event_details_to": "Send event details to",
|
||||
"schedule_tz_without_end_date": "Schedule timezone without end date",
|
||||
"select_members": "Select members",
|
||||
"lock_event_types_modal_header": "What should we do with your member's existing event types?",
|
||||
"org_delete_event_types_org_admin": "All of your members individual event types (except managed ones) will be permanently deleted. They will not be able to create new ones",
|
||||
|
||||
Reference in new issue
Block a user