Scheduling infrastructure for absolutely everyone.
Improving recurring info in bookings (#5253)
Leo Giovanetti25e3e310458e
diff --git a/apps/web/components/booking/BookingListItem.tsx b/apps/web/components/booking/BookingListItem.tsxindex 42412d19a2c..80b0d561382 100644--- a/apps/web/components/booking/BookingListItem.tsx+++ b/apps/web/components/booking/BookingListItem.tsx@@ -19,7 +19,6 @@ import Tooltip from "@calcom/ui/v2/core/Tooltip";import showToast from "@calcom/ui/v2/core/notifications";import useMeQuery from "@lib/hooks/useMeQuery";-import { extractRecurringDates } from "@lib/parseDate";import { EditLocationDialog } from "@components/dialog/EditLocationDialog";import { RescheduleDialog } from "@components/dialog/RescheduleDialog";@@ -31,14 +30,14 @@ type BookingItem = inferQueryOutput<"viewer.bookings">["bookings"][number];type BookingItemProps = BookingItem & {listingStatus: BookingListingStatus;- recurringBookings: inferQueryOutput<"viewer.bookings">["recurringInfo"];+ recurringInfo: inferQueryOutput<"viewer.bookings">["recurringInfo"][number] | undefined;};function BookingListItem(booking: BookingItemProps) {// Get user so we can determine 12/24 hour format preferencesconst query = useMeQuery();const user = query.data;- const { t, i18n } = useLocale();+ const { t } = useLocale();const utils = trpc.useContext();const router = useRouter();const [rejectionReason, setRejectionReason] = useState<string>("");@@ -176,17 +175,11 @@ function BookingListItem(booking: BookingItemProps) {setLocationMutation.mutate({ bookingId: booking.id, newLocation });};- const [, recurringDates] = useMemo(() => {- if (- booking.recurringBookings !== undefined &&- booking.eventType.recurringEvent?.freq !== undefined &&- booking.recurringEventId- ) {- return extractRecurringDates(booking, user?.timeZone, i18n);- }- return [[], []];- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [user?.timeZone, i18n.language, booking.recurringBookings]);+ // Getting accepted recurring dates to show+ const recurringDates = booking.recurringInfo?.bookings[BookingStatus.ACCEPTED]+ .concat(booking.recurringInfo?.bookings[BookingStatus.CANCELLED])+ .concat(booking.recurringInfo?.bookings[BookingStatus.PENDING])+ .sort((date1: Date, date2: Date) => date1.getTime() - date2.getTime());const location = booking.location || "";@@ -291,9 +284,11 @@ function BookingListItem(booking: BookingItemProps) {{t("pending_payment")}</Badge>)}- <div className="mt-2 text-sm text-gray-400">- <RecurringBookingsTooltip booking={booking} recurringDates={recurringDates} />- </div>+ {recurringDates !== undefined && (+ <div className="mt-2 text-sm text-gray-400">+ <RecurringBookingsTooltip booking={booking} recurringDates={recurringDates} />+ </div>+ )}</div></td><td className={"w-full px-4" + (isRejected ? " line-through" : "")} onClick={onClickTableData}>@@ -329,9 +324,11 @@ function BookingListItem(booking: BookingItemProps) {{t("pending_payment")}</Badge>)}- <div className="text-sm text-gray-400 sm:hidden">- <RecurringBookingsTooltip booking={booking} recurringDates={recurringDates} />- </div>+ {recurringDates !== undefined && (+ <div className="text-sm text-gray-400 sm:hidden">+ <RecurringBookingsTooltip booking={booking} recurringDates={recurringDates} />+ </div>+ )}</div><div className="cursor-pointer py-4">@@ -401,11 +398,16 @@ const RecurringBookingsTooltip = ({ booking, recurringDates }: RecurringBookingsconst { t } = useLocale();const now = new Date();const recurringCount = recurringDates.filter((date) => {- return date >= now;+ return (+ date >= now &&+ !booking.recurringInfo?.bookings[BookingStatus.CANCELLED]+ .map((date) => date.toDateString())+ .includes(date.toDateString())+ );}).length;return (- (booking.recurringBookings &&+ (booking.recurringInfo &&booking.eventType?.recurringEvent?.freq &&(booking.listingStatus === "recurring" ||booking.listingStatus === "unconfirmed" ||@@ -413,13 +415,20 @@ const RecurringBookingsTooltip = ({ booking, recurringDates }: RecurringBookings<div className="underline decoration-gray-400 decoration-dashed underline-offset-2"><div className="flex"><Tooltip- content={recurringDates.map((aDate, key) => (- <p key={key} className={classNames(recurringDates[key] < now && "line-through")}>- {formatTime(booking.startTime, user?.timeFormat, user?.timeZone)}- {" - "}- {dayjs(aDate).format("D MMMM YYYY")}- </p>- ))}>+ content={recurringDates.map((aDate, key) => {+ const pastOrCancelled =+ aDate < now ||+ booking.recurringInfo?.bookings[BookingStatus.CANCELLED]+ .map((date) => date.toDateString())+ .includes(aDate.toDateString());+ return (+ <p key={key} className={classNames(pastOrCancelled && "line-through")}>+ {formatTime(aDate, user?.timeFormat, user?.timeZone)}+ {" - "}+ {dayjs(aDate).format("D MMMM YYYY")}+ </p>+ );+ })}><div className="text-gray-600 dark:text-white"><Icon.FiRefreshCcwstrokeWidth="3"@@ -433,7 +442,7 @@ const RecurringBookingsTooltip = ({ booking, recurringDates }: RecurringBookings: getEveryFreqFor({t,recurringEvent: booking.eventType.recurringEvent,- recurringCount,+ recurringCount: booking.recurringInfo.count,})}</p></div>diff --git a/apps/web/lib/parseDate.ts b/apps/web/lib/parseDate.tsindex 56d67f25a89..3e2c44305a8 100644--- a/apps/web/lib/parseDate.ts+++ b/apps/web/lib/parseDate.ts@@ -55,35 +55,3 @@ export const parseRecurringDates = (return [dateStrings, times.map((t) => t.toDate())];};--export const extractRecurringDates = (- booking: inferQueryOutput<"viewer.bookings">["bookings"][number] & {- eventType: { recurringEvent: RecurringEvent | null };- recurringEventId: string | null;- recurringBookings: inferQueryOutput<"viewer.bookings">["recurringInfo"];- },- timeZone: string | undefined,- i18n: I18n-): [string[], Date[]] => {- // eslint-disable-next-line @typescript-eslint/no-unused-vars- const { count = 0, ...rest } =- booking.eventType.recurringEvent !== null ? booking.eventType.recurringEvent : {};- const recurringInfo = booking.recurringBookings.find(- (val) => val.recurringEventId === booking.recurringEventId- );- if (!recurringInfo) {- // something went wrong, fail here before RRule.- return [[], []];- }- const allDates = new RRule({- ...rest,- count: recurringInfo?._count.recurringEventId,- dtstart: recurringInfo?._min.startTime,- }).all();-- const utcOffset = dayjs(recurringInfo?._min.startTime).tz(timeZone).utcOffset();- const dateStrings = allDates.map((r) => {- return processDate(dayjs.utc(r).utcOffset(utcOffset), i18n);- });- return [dateStrings, allDates];-};diff --git a/apps/web/pages/bookings/[status].tsx b/apps/web/pages/bookings/[status].tsxindex 12e3251b2b9..158502085fb 100644--- a/apps/web/pages/bookings/[status].tsx+++ b/apps/web/pages/bookings/[status].tsx@@ -95,14 +95,19 @@ export default function Bookings() {<tbody className="divide-y divide-gray-200 bg-white" data-testid="bookings">{query.data.pages.map((page, index) => (<Fragment key={index}>- {page.bookings.filter(filterBookings).map((booking: BookingOutput) => (- <BookingListItem- key={booking.id}- listingStatus={status}- recurringBookings={page.recurringInfo}- {...booking}- />- ))}+ {page.bookings.filter(filterBookings).map((booking: BookingOutput) => {+ const recurringInfo = page.recurringInfo.find(+ (info) => info.recurringEventId === booking.recurringEventId+ );+ return (+ <BookingListItem+ key={booking.id}+ listingStatus={status}+ recurringInfo={recurringInfo}+ {...booking}+ />+ );+ })}</Fragment>))}</tbody>diff --git a/apps/web/pages/success.tsx b/apps/web/pages/success.tsxindex af6cef18bc2..9a0bf0f7402 100644--- a/apps/web/pages/success.tsx+++ b/apps/web/pages/success.tsx@@ -15,6 +15,7 @@ import { getEventLocationValue, getSuccessPageLocationMessage } from "@calcom/apimport { getEventTypeAppData } from "@calcom/app-store/utils";import { getEventName } from "@calcom/core/event";import dayjs from "@calcom/dayjs";+import { ConfigType } from "@calcom/dayjs";import {sdkActionManager,useEmbedNonStylesConfig,@@ -23,6 +24,7 @@ import {} from "@calcom/embed-core/embed-iframe";import { parseRecurringEvent } from "@calcom/lib";import CustomBranding from "@calcom/lib/CustomBranding";+import { formatTime } from "@calcom/lib/date-fns";import { getDefaultEvent } from "@calcom/lib/defaultEvents";import { useLocale } from "@calcom/lib/hooks/useLocale";import useTheme from "@calcom/lib/hooks/useTheme";@@ -37,6 +39,7 @@ import { Icon } from "@calcom/ui/Icon";import { EmailInput } from "@calcom/ui/form/fields";import { asStringOrThrow } from "@lib/asStringOrNull";+import { timeZone } from "@lib/clock";import { inferSSRProps } from "@lib/types/inferSSRProps";import CancelBooking from "@components/booking/CancelBooking";@@ -638,13 +641,14 @@ export function RecurringBookings({eventType,recurringBookings,date,+ is24h,listingStatus,}: RecurringBookingsProps) {const [moreEventsVisible, setMoreEventsVisible] = useState(false);const { t } = useLocale();const recurringBookingsSorted = recurringBookings- ? recurringBookings.sort((a, b) => (dayjs(a).isAfter(dayjs(b)) ? 1 : -1))+ ? recurringBookings.sort((a: ConfigType, b: ConfigType) => (dayjs(a).isAfter(dayjs(b)) ? 1 : -1)): null;if (recurringBookingsSorted && listingStatus === "recurring") {@@ -660,14 +664,13 @@ export function RecurringBookings({</span>)}{eventType.recurringEvent?.count &&- recurringBookingsSorted.slice(0, 4).map((dateStr, idx) => (+ recurringBookingsSorted.slice(0, 4).map((dateStr: string, idx: number) => (<div key={idx} className="mb-2">- {dayjs(dateStr).format("MMMM DD, YYYY")}+ {dayjs.tz(dateStr, timeZone()).format("MMMM DD, YYYY")}<br />- {dayjs(dateStr).format("LT")} - {dayjs(dateStr).add(eventType.length, "m").format("LT")}{" "}- <span className="text-bookinglight">- ({localStorage.getItem("timeOption.preferredTimeZone") || dayjs.tz.guess()})- </span>+ {formatTime(dateStr, is24h ? 24 : 12, timeZone())} -{" "}+ {formatTime(dayjs(dateStr).add(eventType.length, "m"), is24h ? 24 : 12, timeZone())}{" "}+ <span className="text-bookinglight">({timeZone()})</span></div>))}{recurringBookingsSorted.length > 4 && (@@ -679,14 +682,13 @@ export function RecurringBookings({</CollapsibleTrigger><CollapsibleContent>{eventType.recurringEvent?.count &&- recurringBookingsSorted.slice(4).map((dateStr, idx) => (+ recurringBookingsSorted.slice(4).map((dateStr: string, idx: number) => (<div key={idx} className="mb-2">- {dayjs(dateStr).format("MMMM DD, YYYY")}+ {dayjs.tz(dateStr, timeZone()).format("MMMM DD, YYYY")}<br />- {dayjs(dateStr).format("LT")} - {dayjs(dateStr).add(eventType.length, "m").format("LT")}{" "}- <span className="text-bookinglight">- ({localStorage.getItem("timeOption.preferredTimeZone") || dayjs.tz.guess()})- </span>+ {formatTime(dateStr, is24h ? 24 : 12, timeZone())} -{" "}+ {formatTime(dayjs(dateStr).add(eventType.length, "m"), is24h ? 24 : 12, timeZone())}{" "}+ <span className="text-bookinglight">({timeZone()})</span></div>))}</CollapsibleContent>@@ -698,12 +700,11 @@ export function RecurringBookings({return (<>- {date.format("MMMM DD, YYYY")}+ {dayjs.tz(date, timeZone()).format("MMMM DD, YYYY")}<br />- {date.format("LT")} - {date.add(eventType.length, "m").format("LT")}{" "}- <span className="text-bookinglight">- ({localStorage.getItem("timeOption.preferredTimeZone") || dayjs.tz.guess()})- </span>+ {formatTime(date, is24h ? 24 : 12, timeZone())} -{" "}+ {formatTime(dayjs(date).add(eventType.length, "m"), is24h ? 24 : 12, timeZone())}{" "}+ <span className="text-bookinglight">({timeZone()})</span></>);}diff --git a/packages/lib/date-fns/index.ts b/packages/lib/date-fns/index.tsindex af5f6450af2..a565ba76db3 100644--- a/packages/lib/date-fns/index.ts+++ b/packages/lib/date-fns/index.ts@@ -15,12 +15,14 @@ export const formatTime = (date: string | Date | Dayjs,timeFormat?: number | null,timeZone?: string | null-) =>- timeZone+) => {+ // console.log(timeZone, date);+ return timeZone? dayjs(date).tz(timeZone).format(timeFormat === 12 ? "h:mma" : "HH:mm"): dayjs(date).format(timeFormat === 12 ? "h:mma" : "HH:mm");+};/*** Sorts two timezones by their offset from GMT.diff --git a/packages/prisma/seed.ts b/packages/prisma/seed.tsindex 4146e92d5d1..59ec94a1f71 100644--- a/packages/prisma/seed.ts+++ b/packages/prisma/seed.ts@@ -347,7 +347,7 @@ async function main() {title: "Seeded Yoga class",description: "seeded",recurringEventId: Buffer.from("seeded-yoga-class").toString("base64"),- startTime: dayjs().subtract(4, "day").toDate(),+ startTime: dayjs().subtract(4, "day").add(1, "week").toDate(),endTime: dayjs().subtract(4, "day").add(1, "week").add(30, "minutes").toDate(),status: BookingStatus.ACCEPTED,},@@ -356,7 +356,7 @@ async function main() {title: "Seeded Yoga class",description: "seeded",recurringEventId: Buffer.from("seeded-yoga-class").toString("base64"),- startTime: dayjs().subtract(4, "day").toDate(),+ startTime: dayjs().subtract(4, "day").add(2, "week").toDate(),endTime: dayjs().subtract(4, "day").add(2, "week").add(30, "minutes").toDate(),status: BookingStatus.ACCEPTED,},@@ -365,7 +365,7 @@ async function main() {title: "Seeded Yoga class",description: "seeded",recurringEventId: Buffer.from("seeded-yoga-class").toString("base64"),- startTime: dayjs().subtract(4, "day").toDate(),+ startTime: dayjs().subtract(4, "day").add(3, "week").toDate(),endTime: dayjs().subtract(4, "day").add(3, "week").add(30, "minutes").toDate(),status: BookingStatus.ACCEPTED,},diff --git a/packages/trpc/server/routers/viewer.tsx b/packages/trpc/server/routers/viewer.tsxindex c8d08fc435f..cf0fd618150 100644--- a/packages/trpc/server/routers/viewer.tsx+++ b/packages/trpc/server/routers/viewer.tsx@@ -612,7 +612,7 @@ const loggedInViewerRouter = createProtectedRouter()skip,});- const recurringInfo = await prisma.booking.groupBy({+ const recurringInfoBasic = await prisma.booking.groupBy({by: ["recurringEventId"],_min: {startTime: true,@@ -624,13 +624,54 @@ const loggedInViewerRouter = createProtectedRouter()recurringEventId: {not: { equals: null },},- status: {- notIn: [BookingStatus.CANCELLED],+ userId: user.id,+ },+ });++ const recurringInfoExtended = await prisma.booking.groupBy({+ by: ["recurringEventId", "status", "startTime"],+ _min: {+ startTime: true,+ },+ where: {+ recurringEventId: {+ not: { equals: null },},userId: user.id,},});+ const recurringInfo = recurringInfoBasic.map(+ (+ info: typeof recurringInfoBasic[number]+ ): {+ recurringEventId: string | null;+ count: number;+ firstDate: Date | null;+ bookings: {+ [key: string]: Date[];+ };+ } => {+ const bookings = recurringInfoExtended+ .filter((ext) => ext.recurringEventId === info.recurringEventId)+ .reduce(+ (prev, curr) => {+ prev[curr.status].push(curr.startTime);+ return prev;+ },+ { ACCEPTED: [], CANCELLED: [], REJECTED: [], PENDING: [] } as {+ [key in BookingStatus]: Date[];+ }+ );+ return {+ recurringEventId: info.recurringEventId,+ count: info._count.recurringEventId,+ firstDate: info._min.startTime,+ bookings,+ };+ }+ );+const bookings = bookingsQuery.map((booking) => {return {...booking,