From 25e3e310458e5c42175264d8c41602417aad9de6 Mon Sep 17 00:00:00 2001 From: Leo Giovanetti Date: Fri, 4 Nov 2022 13:43:02 -0300 Subject: [PATCH] Improving recurring info in bookings (#5253) * Improving recurring info in bookings * Adding fixes to success page, it was invalid on custom tz * Remove dead code Co-authored-by: Alex van Andel --- .../components/booking/BookingListItem.tsx | 69 +++++++++++-------- apps/web/lib/parseDate.ts | 32 --------- apps/web/pages/bookings/[status].tsx | 21 +++--- apps/web/pages/success.tsx | 37 +++++----- packages/lib/date-fns/index.ts | 6 +- packages/prisma/seed.ts | 6 +- packages/trpc/server/routers/viewer.tsx | 47 ++++++++++++- 7 files changed, 122 insertions(+), 96 deletions(-) diff --git a/apps/web/components/booking/BookingListItem.tsx b/apps/web/components/booking/BookingListItem.tsx index 42412d19a2..80b0d56138 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 preferences const query = useMeQuery(); const user = query.data; - const { t, i18n } = useLocale(); + const { t } = useLocale(); const utils = trpc.useContext(); const router = useRouter(); const [rejectionReason, setRejectionReason] = useState(""); @@ -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")} )} -
- -
+ {recurringDates !== undefined && ( +
+ +
+ )} @@ -329,9 +324,11 @@ function BookingListItem(booking: BookingItemProps) { {t("pending_payment")} )} -
- -
+ {recurringDates !== undefined && ( +
+ +
+ )}
@@ -401,11 +398,16 @@ const RecurringBookingsTooltip = ({ booking, recurringDates }: RecurringBookings const { 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
( -

- {formatTime(booking.startTime, user?.timeFormat, user?.timeZone)} - {" - "} - {dayjs(aDate).format("D MMMM YYYY")} -

- ))}> + content={recurringDates.map((aDate, key) => { + const pastOrCancelled = + aDate < now || + booking.recurringInfo?.bookings[BookingStatus.CANCELLED] + .map((date) => date.toDateString()) + .includes(aDate.toDateString()); + return ( +

+ {formatTime(aDate, user?.timeFormat, user?.timeZone)} + {" - "} + {dayjs(aDate).format("D MMMM YYYY")} +

+ ); + })}>
diff --git a/apps/web/lib/parseDate.ts b/apps/web/lib/parseDate.ts index 56d67f25a8..3e2c44305a 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].tsx index 12e3251b2b..158502085f 100644 --- a/apps/web/pages/bookings/[status].tsx +++ b/apps/web/pages/bookings/[status].tsx @@ -95,14 +95,19 @@ export default function Bookings() { {query.data.pages.map((page, index) => ( - {page.bookings.filter(filterBookings).map((booking: BookingOutput) => ( - - ))} + {page.bookings.filter(filterBookings).map((booking: BookingOutput) => { + const recurringInfo = page.recurringInfo.find( + (info) => info.recurringEventId === booking.recurringEventId + ); + return ( + + ); + })} ))} diff --git a/apps/web/pages/success.tsx b/apps/web/pages/success.tsx index af6cef18bc..9a0bf0f740 100644 --- a/apps/web/pages/success.tsx +++ b/apps/web/pages/success.tsx @@ -15,6 +15,7 @@ import { getEventLocationValue, getSuccessPageLocationMessage } from "@calcom/ap import { 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({ )} {eventType.recurringEvent?.count && - recurringBookingsSorted.slice(0, 4).map((dateStr, idx) => ( + recurringBookingsSorted.slice(0, 4).map((dateStr: string, idx: number) => (
- {dayjs(dateStr).format("MMMM DD, YYYY")} + {dayjs.tz(dateStr, timeZone()).format("MMMM DD, YYYY")}
- {dayjs(dateStr).format("LT")} - {dayjs(dateStr).add(eventType.length, "m").format("LT")}{" "} - - ({localStorage.getItem("timeOption.preferredTimeZone") || dayjs.tz.guess()}) - + {formatTime(dateStr, is24h ? 24 : 12, timeZone())} -{" "} + {formatTime(dayjs(dateStr).add(eventType.length, "m"), is24h ? 24 : 12, timeZone())}{" "} + ({timeZone()})
))} {recurringBookingsSorted.length > 4 && ( @@ -679,14 +682,13 @@ export function RecurringBookings({ {eventType.recurringEvent?.count && - recurringBookingsSorted.slice(4).map((dateStr, idx) => ( + recurringBookingsSorted.slice(4).map((dateStr: string, idx: number) => (
- {dayjs(dateStr).format("MMMM DD, YYYY")} + {dayjs.tz(dateStr, timeZone()).format("MMMM DD, YYYY")}
- {dayjs(dateStr).format("LT")} - {dayjs(dateStr).add(eventType.length, "m").format("LT")}{" "} - - ({localStorage.getItem("timeOption.preferredTimeZone") || dayjs.tz.guess()}) - + {formatTime(dateStr, is24h ? 24 : 12, timeZone())} -{" "} + {formatTime(dayjs(dateStr).add(eventType.length, "m"), is24h ? 24 : 12, timeZone())}{" "} + ({timeZone()})
))}
@@ -698,12 +700,11 @@ export function RecurringBookings({ return ( <> - {date.format("MMMM DD, YYYY")} + {dayjs.tz(date, timeZone()).format("MMMM DD, YYYY")}
- {date.format("LT")} - {date.add(eventType.length, "m").format("LT")}{" "} - - ({localStorage.getItem("timeOption.preferredTimeZone") || dayjs.tz.guess()}) - + {formatTime(date, is24h ? 24 : 12, timeZone())} -{" "} + {formatTime(dayjs(date).add(eventType.length, "m"), is24h ? 24 : 12, timeZone())}{" "} + ({timeZone()}) ); } diff --git a/packages/lib/date-fns/index.ts b/packages/lib/date-fns/index.ts index af5f6450af..a565ba76db 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.ts index 4146e92d5d..59ec94a1f7 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.tsx index c8d08fc435..cf0fd61815 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,