From 07716474d3f1574a617c0f85856f776857326788 Mon Sep 17 00:00:00 2001 From: Vijay Date: Thu, 13 Mar 2025 12:54:20 +0530 Subject: [PATCH] feat: Fetch previous ooo records using DateRangeFilter (#19596) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * teamMates OOO is visible for teamMember * Update packages/features/settings/outOfOffice/CreateOrEditOutOfOfficeModal.tsx Co-authored-by: Omar López * nit * fixed tests, admin chk reqd for forMembers only * check reqd in case of teamOOO only * datefilter with default and improved search filter * fix preset options * fix ooo tests, due to default date filter * ensure ooo test's wont fail when run on different dates of the month, due to default filter * improvement: instead of 'Date to Year' safer is customRange * added test for non-admin team ooo * show disabled icons instead of notshowing * tests for dateRangeFilters * some more daterangefilter tests * nit * include only fetch prev records in this pr * nit * chore * chore * review comments * chore * update to fix tests * nit * nit * update pagination mode * removed unrelated changes * remove unrelated changes --------- Co-authored-by: Peer Richelsen Co-authored-by: Omar López --- .../my-account/out-of-office/page.tsx | 2 +- apps/web/playwright/out-of-office.e2e.ts | 159 +++++- .../outOfOffice/OutOfOfficeEntriesList.tsx | 522 ++++++++++-------- .../outOfOfficeEntriesList.handler.ts | 12 +- .../outOfOfficeEntriesList.schema.ts | 2 + 5 files changed, 448 insertions(+), 249 deletions(-) diff --git a/apps/web/app/(use-page-wrapper)/settings/(settings-layout)/my-account/out-of-office/page.tsx b/apps/web/app/(use-page-wrapper)/settings/(settings-layout)/my-account/out-of-office/page.tsx index a3599d4f54..78f9c1fd27 100644 --- a/apps/web/app/(use-page-wrapper)/settings/(settings-layout)/my-account/out-of-office/page.tsx +++ b/apps/web/app/(use-page-wrapper)/settings/(settings-layout)/my-account/out-of-office/page.tsx @@ -3,7 +3,7 @@ import { getTranslate } from "app/_utils"; import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader"; import CreateNewOutOfOfficeEntryButton from "@calcom/features/settings/outOfOffice/CreateNewOutOfOfficeEntryButton"; -import { OutOfOfficeEntriesList } from "@calcom/features/settings/outOfOffice/OutOfOfficeEntriesList"; +import OutOfOfficeEntriesList from "@calcom/features/settings/outOfOffice/OutOfOfficeEntriesList"; import { OutOfOfficeToggleGroup } from "@calcom/features/settings/outOfOffice/OutOfOfficeToggleGroup"; export const generateMetadata = async () => diff --git a/apps/web/playwright/out-of-office.e2e.ts b/apps/web/playwright/out-of-office.e2e.ts index b0a8a5fed6..daf7718797 100644 --- a/apps/web/playwright/out-of-office.e2e.ts +++ b/apps/web/playwright/out-of-office.e2e.ts @@ -646,6 +646,161 @@ test.describe("Out of office", () => { }); }); }); + + test.describe("Date range filters", () => { + test("Default date range filter set to `Last 7 Days`", async ({ page, users }) => { + const user = await users.create({ name: `userOne=${Date.now()}` }); + await user.apiLogin(); + await page.goto("/settings/my-account/out-of-office"); + await page.waitForLoadState("domcontentloaded"); + await page.locator('[data-testid="add-filter-button"]').click(); + await page.locator('[data-testid="add-filter-item-dateRange"]').click(); + await expect( + page + .locator('[data-testid="filter-popover-trigger-dateRange"] span', { hasText: "Last 7 Days" }) + .nth(0) + ).toBeVisible(); + }); + + test("Can choose date range presets", async ({ page, users }) => { + const user = await users.create({ name: `userOne=${Date.now()}` }); + await user.apiLogin(); + await page.goto("/settings/my-account/out-of-office"); + await page.waitForLoadState("domcontentloaded"); + await page.locator('[data-testid="add-filter-button"]').click(); + await page.locator('[data-testid="add-filter-item-dateRange"]').click(); + await page.locator('[data-testid="add-filter-button"]').click(); + await page.locator('[data-testid="filter-popover-trigger-dateRange"]').click(); + + await expect(page.locator('[data-testid="date-range-options-tdy"]')).toBeVisible(); //Today + await expect(page.locator('[data-testid="date-range-options-w"]')).toBeVisible(); //Last 7 Days + await expect(page.locator('[data-testid="date-range-options-t"]')).toBeVisible(); //Last 30 Days + await expect(page.locator('[data-testid="date-range-options-m"]')).toBeVisible(); //Month to Date + await expect(page.locator('[data-testid="date-range-options-y"]')).toBeVisible(); //Year to Date + await expect(page.locator('[data-testid="date-range-options-c"]')).toBeVisible(); //Custom + }); + + test("OOO records are fetched correctly w.r.t their end dates matching the date range filter selected.", async ({ + page, + users, + }) => { + const member1Name = `member-1-${Date.now()}`; + const member2Name = `member-2-${Date.now()}`; + const member3Name = `member-3-${Date.now()}`; + const teamMatesObj = [{ name: member1Name }, { name: member2Name }]; + const member3User = await users.create( + { name: member3Name }, + { + hasTeam: true, + teamRole: MembershipRole.MEMBER, + teammates: teamMatesObj, + } + ); + const member1User = users.get().find((user) => user.name === member1Name); + const member2User = users.get().find((user) => user.name === member2Name); + + //create OOO for member3, start:currentDate+2Days, end:currentDate+4days (future ooo) + await prisma.outOfOfficeEntry.create({ + data: { + start: dayjs().startOf("day").add(2, "days").toDate(), + end: dayjs().startOf("day").add(4, "days").toDate(), + uuid: uuidv4(), + user: { connect: { id: member3User?.id } }, + createdAt: new Date(), + reason: { + connect: { + id: 1, + }, + }, + }, + }); + + //create OOO for member3, start:currentDate-12Days, end:currentDate-10days (for Last 30 Days) + await prisma.outOfOfficeEntry.create({ + data: { + start: dayjs().startOf("day").subtract(12, "days").toDate(), + end: dayjs().startOf("day").subtract(10, "days").toDate(), + uuid: uuidv4(), + user: { connect: { id: member3User?.id } }, + toUser: { connect: { id: member1User?.id } }, + createdAt: new Date(), + reason: { + connect: { + id: 2, + }, + }, + }, + }); + + //create OOO for member3, start:currentDate-2Days, end:currentDate-4days (for Last 7 Days) + await prisma.outOfOfficeEntry.create({ + data: { + start: dayjs().startOf("day").subtract(4, "days").toDate(), + end: dayjs().startOf("day").subtract(2, "days").toDate(), + uuid: uuidv4(), + user: { connect: { id: member3User?.id } }, + toUser: { connect: { id: member2User?.id } }, + createdAt: new Date(), + reason: { + connect: { + id: 2, + }, + }, + }, + }); + + await member3User?.apiLogin(); + const entriesListRespPromise = page.waitForResponse( + (response) => response.url().includes("outOfOfficeEntriesList") && response.status() === 200 + ); + await page.goto("/settings/my-account/out-of-office"); + await page.waitForLoadState("domcontentloaded"); + await entriesListRespPromise; + + //By Default future OOO will be displayed + //1 OOO record should be visible for member3, end=currentDate+4days + expect(await page.locator('[data-testid^="table-redirect-"]').count()).toBe(1); + await expect(page.locator(`data-testid=table-redirect-n-a`).nth(0)).toBeVisible(); + + //Default filter 'Last 7 Days' when DateRange Filter is selected + await test.step("Default filter - 'Last 7 Days'", async () => { + await page.locator('[data-testid="add-filter-button"]').click(); + await page.locator('[data-testid="add-filter-item-dateRange"]').click(); + await page.locator('[data-testid="add-filter-button"]').click(); + const entriesListRespPromise = page.waitForResponse( + (response) => response.url().includes("outOfOfficeEntriesList") && response.status() === 200 + ); + await page.locator('[data-testid="add-filter-button"]').click(); + await entriesListRespPromise; + + //1 OOO record should be visible for member3, end=currentDate-4days + expect(await page.locator('[data-testid^="table-redirect-"]').count()).toBe(1); + await expect( + page.locator(`data-testid=table-redirect-${member2User?.username}`).nth(0) + ).toBeVisible(); + }); + + //Select 'Last 30 Days' + await test.step("select 'Last 30 Days'", async () => { + await page.locator('[data-testid="filter-popover-trigger-dateRange"]').click(); + const entriesListRespPromise = page.waitForResponse( + (response) => response.url().includes("outOfOfficeEntriesList") && response.status() === 200 + ); + await page.locator(`[data-testid="date-range-options-t"]`).click(); + await page.locator('[data-testid="filter-popover-trigger-dateRange"]').click(); + await entriesListRespPromise; + + //2 OOO records should be visible end=currentDate-4days, end=currentDate-12days + expect(await page.locator('[data-testid^="table-redirect-"]').count()).toBe(2); + await expect( + page.locator(`data-testid=table-redirect-${member2User?.username}`).nth(0) + ).toBeVisible(); + await expect( + page.locator(`data-testid=table-redirect-${member1User?.username}`).nth(0) + ).toBeVisible(); + }); + }); + }); }); async function saveAndWaitForResponse(page: Page, expectedStatusCode = 200) { @@ -671,11 +826,11 @@ async function selectDateAndCreateOOO( redirectToUserId?: number, expectedStatusCode = 200, forTeamMember = false, - month: "previous-month" | "next-month" = "next-month", + month: "previous" | "next" = "next", editMode = false ) { const t = await localize("en"); - await page.locator(`button[name="${month}"]`).click(); + await page.locator(`button[name="${month}-month"]`).click(); await page.locator(`button[name="day"]:text-is("${fromDate}")`).nth(0).click(); await page.locator(`button[name="day"]:text-is("${toDate}")`).nth(0).click(); editMode diff --git a/packages/features/settings/outOfOffice/OutOfOfficeEntriesList.tsx b/packages/features/settings/outOfOffice/OutOfOfficeEntriesList.tsx index 77d8e3cc40..075f316ce2 100644 --- a/packages/features/settings/outOfOffice/OutOfOfficeEntriesList.tsx +++ b/packages/features/settings/outOfOffice/OutOfOfficeEntriesList.tsx @@ -1,13 +1,26 @@ "use client"; import { keepPreviousData } from "@tanstack/react-query"; -import { getCoreRowModel, useReactTable, type ColumnDef } from "@tanstack/react-table"; +import { + createColumnHelper, + getCoreRowModel, + getFilteredRowModel, + useReactTable, +} from "@tanstack/react-table"; import { Trans } from "next-i18next"; -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { useFormState } from "react-hook-form"; import dayjs from "@calcom/dayjs"; -import { DataTable, DataTableToolbar } from "@calcom/features/data-table"; +import { + DataTableWrapper, + DataTableToolbar, + DataTableProvider, + ColumnFilterType, + useFilterValue, + ZDateRangeFilterValue, + DataTableFilters, +} from "@calcom/features/data-table"; import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl"; import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams"; import { useLocale } from "@calcom/lib/hooks/useLocale"; @@ -40,7 +53,15 @@ interface OutOfOfficeEntry { canEditAndDelete: boolean; } -export const OutOfOfficeEntriesList = () => { +export default function OutOfOfficeEntriesList() { + return ( + + + + ); +} + +function OutOfOfficeEntriesListContent() { const { t } = useLocale(); const tableContainerRef = useRef(null); const [searchTerm, setSearchTerm] = useState(""); @@ -56,12 +77,16 @@ export const OutOfOfficeEntriesList = () => { const searchParams = useCompatSearchParams(); const selectedTab = searchParams?.get("type") ?? OutOfOfficeTab.MINE; - const { data, isPending, fetchNextPage, isFetching, refetch } = + const endDateRange = useFilterValue("dateRange", ZDateRangeFilterValue)?.data; + + const { data, isPending, fetchNextPage, isFetching, refetch, hasNextPage } = trpc.viewer.outOfOfficeEntriesList.useInfiniteQuery( { limit: 10, fetchTeamMembersEntries: selectedTab === OutOfOfficeTab.TEAM, searchTerm, + endDateFilterStartRange: endDateRange?.startDate ?? undefined, + endDateFilterEndRange: endDateRange?.endDate ?? undefined, }, { getNextPageParam: (lastPage) => lastPage.nextCursor, @@ -79,214 +104,216 @@ export const OutOfOfficeEntriesList = () => { isPending || isFetching ? new Array(5).fill(null) : data?.pages?.flatMap((page) => page.rows) ?? [], [data, selectedTab, isPending, isFetching, searchTerm] ) as OutOfOfficeEntry[]; - const totalFetched = flatData.length; const memoColumns = useMemo(() => { - const columns: ColumnDef[] = []; - if (selectedTab === OutOfOfficeTab.TEAM) { - columns.push({ - id: "member", - header: `Member`, - size: 300, + const columnHelper = createColumnHelper(); + return [ + columnHelper.accessor((row) => row, { + id: "dateRange", + header: t("date_range"), + enableColumnFilter: true, + enableSorting: false, + cell: () => null, + filterFn: () => true, + meta: { + filter: { + type: ColumnFilterType.DATE_RANGE, + dateRangeOptions: { + range: "past", + }, + }, + }, + }), + ...(selectedTab === OutOfOfficeTab.TEAM + ? [ + columnHelper.display({ + id: "member", + header: `Member`, + size: 300, + cell: ({ row }) => { + if (!row.original || !row.original.user || isPending || isFetching) { + return ; + } + const { avatarUrl, username, email, name } = row.original.user; + const memberName = + name || + (() => { + const emailName = email.split("@")[0]; + return emailName.charAt(0).toUpperCase() + emailName.slice(1); + })(); + return ( +
+ +
+
+ {memberName} +
+
+ {email} +
+
+
+ ); + }, + }), + ] + : []), + columnHelper.display({ + id: "outOfOffice", + header: `${t("out_of_office")} (${totalRowCount})`, + size: selectedTab === OutOfOfficeTab.TEAM ? 370 : 660, cell: ({ row }) => { - if (!row.original || !row.original.user || isPending || isFetching) { - return ; - } - const { avatarUrl, username, email, name } = row.original.user; - const memberName = - name || - (() => { - const emailName = email.split("@")[0]; - return emailName.charAt(0).toUpperCase() + emailName.slice(1); - })(); + const item = row.original; return ( -
- -
+ <> + {row.original && !isPending && !isFetching ? (
- {memberName} + className="flex flex-row justify-between p-2" + data-testid={`table-redirect-${item.toUser?.username || "n-a"}`}> +
+
+ {item?.reason?.emoji || "🏝️"} +
+ +
+

+ {dayjs.utc(item.start).format("ll")} - {dayjs.utc(item.end).format("ll")} +

+

+ {item.toUser?.username ? ( + , + }} + /> + ) : ( + <>{t("ooo_not_forwarding")} + )} +

+ {item.notes && ( +

+ {t("notes")}: + + {item.notes} + +

+ )} +
+
-
- {email} -
-
-
+ ) : ( + + )} + ); }, - }); - } - columns.push({ - id: "outOfOffice", - header: `${t("out_of_office")} (${totalRowCount})`, - size: selectedTab === OutOfOfficeTab.TEAM ? 370 : 660, - cell: ({ row }) => { - const item = row.original; - return ( - <> - {row.original && !isPending && !isFetching ? ( -
-
-
- {item?.reason?.emoji || "🏝️"} -
- -
-

- {dayjs.utc(item.start).format("ll")} - {dayjs.utc(item.end).format("ll")} -

-

- {item.toUser?.username ? ( - , - }} - /> - ) : ( - <>{t("ooo_not_forwarding")} - )} -

- {item.notes && ( -

- {t("notes")}: - - {item.notes} - -

- )} -
+ }), + columnHelper.display({ + id: "actions", + size: 90, + cell: ({ row }) => { + const item = row.original; + return ( + <> + {row.original && !isPending && !isFetching ? ( +
+ +
-
- ) : ( - - )} - - ); - }, - }); - columns.push({ - id: "actions", - size: 90, - cell: ({ row }) => { - const item = row.original; - return ( - <> - {row.original && !isPending && !isFetching ? ( -
- -
- ) : ( - - )} - - ); - }, - }); - return columns; + ) : ( + + )} + + ); + }, + }), + ]; }, [selectedTab, isPending, isFetching]); - const fetchMoreOnBottomReached = useCallback( - (containerRefElement?: HTMLDivElement | null) => { - if (containerRefElement) { - const { scrollHeight, scrollTop, clientHeight } = containerRefElement; - if (scrollHeight - scrollTop - clientHeight < 100 && !isFetching && totalFetched < totalRowCount) { - fetchNextPage(); - } - if (isFetching) { - containerRefElement.classList.add("cursor-wait"); - } else { - containerRefElement.classList.remove("cursor-wait"); - } - } - }, - [fetchNextPage, isFetching, totalFetched, totalRowCount] - ); - const table = useReactTable({ data: flatData, columns: memoColumns, + initialState: { + columnVisibility: { + dateRange: false, + }, + }, enableRowSelection: false, - debugTable: true, manualPagination: true, getCoreRowModel: getCoreRowModel(), + getFilteredRowModel: getFilteredRowModel(), }); - useEffect(() => { - fetchMoreOnBottomReached(tableContainerRef.current); - }, [fetchMoreOnBottomReached]); - const deleteOutOfOfficeEntryMutation = trpc.viewer.outOfOfficeEntryDelete.useMutation({ onSuccess: () => { showToast(t("success_deleted_entry_out_of_office"), "success"); @@ -300,60 +327,67 @@ export const OutOfOfficeEntriesList = () => { return ( <> - {data === null || - (data?.pages?.length !== 0 && data?.pages[0].meta.totalRowCount === 0 && searchTerm === "") || - (data === undefined && !isPending) ? ( - } - customIcon={ -
-
-
-
-
-
-
-
-
-
- -
- z + setSearchTerm(value)} />} + ToolbarRight={ + <> + + + + + } + EmptyView={ + } + customIcon={ +
+
+
+
+
+
+
+
+
+
+ +
+ z +
-
- } + } + /> + } + /> + {openModal && ( + { + setOpenModal(false); + setCurrentlyEditingOutOfOfficeEntry(null); + }} + currentlyEditingOutOfOfficeEntry={currentlyEditingOutOfOfficeEntry} /> - ) : ( -
- fetchMoreOnBottomReached(e.target as HTMLDivElement)}> - - setSearchTerm(value)} /> - - - {openModal && ( - { - setOpenModal(false); - setCurrentlyEditingOutOfOfficeEntry(null); - }} - currentlyEditingOutOfOfficeEntry={currentlyEditingOutOfOfficeEntry} - /> - )} -
)} ); -}; +} diff --git a/packages/trpc/server/routers/loggedInViewer/outOfOfficeEntriesList.handler.ts b/packages/trpc/server/routers/loggedInViewer/outOfOfficeEntriesList.handler.ts index 00e1b3a57c..8689205ccb 100644 --- a/packages/trpc/server/routers/loggedInViewer/outOfOfficeEntriesList.handler.ts +++ b/packages/trpc/server/routers/loggedInViewer/outOfOfficeEntriesList.handler.ts @@ -16,7 +16,14 @@ type GetOptions = { export const outOfOfficeEntriesList = async ({ ctx, input }: GetOptions) => { const t = await getTranslation(ctx.user.locale, "common"); - const { cursor, limit, fetchTeamMembersEntries, searchTerm } = input; + const { + cursor, + limit, + fetchTeamMembersEntries, + searchTerm, + endDateFilterStartRange, + endDateFilterEndRange, + } = input; let fetchOOOEntriesForIds = [ctx.user.id]; let reportingUserIds = [0]; @@ -76,7 +83,8 @@ export const outOfOfficeEntriesList = async ({ ctx, input }: GetOptions) => { in: fetchOOOEntriesForIds, }, end: { - gte: new Date().toISOString(), + gte: endDateFilterStartRange ?? new Date().toISOString(), + lte: endDateFilterEndRange, }, ...(searchTerm ? { diff --git a/packages/trpc/server/routers/loggedInViewer/outOfOfficeEntriesList.schema.ts b/packages/trpc/server/routers/loggedInViewer/outOfOfficeEntriesList.schema.ts index 72b76b7e1f..f06bef177d 100644 --- a/packages/trpc/server/routers/loggedInViewer/outOfOfficeEntriesList.schema.ts +++ b/packages/trpc/server/routers/loggedInViewer/outOfOfficeEntriesList.schema.ts @@ -5,6 +5,8 @@ export const ZOutOfOfficeEntriesListSchema = z.object({ cursor: z.number().nullish(), fetchTeamMembersEntries: z.boolean().optional().default(false), searchTerm: z.string().optional(), + endDateFilterStartRange: z.string().optional(), + endDateFilterEndRange: z.string().optional(), }); export type TOutOfOfficeEntriesListSchema = z.infer;