fix: date range computation on /insights (#21436)
* fix: date range computation on /insights * remove log * error handling * update test cases * WIP * fix implementation * support weekStart * clean up * fix date range presets * clean up timeView * fix timeView * clean up * fix event trends * remove unused variables * fix flaky e2e tests * fix date range * update formatting logic
This commit is contained in:
1 parent
3131318b6a
commit
0a28b5825b
9 files changed
+1198
-372
No files matched your search
@@ -1,6 +1,10 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect } from "@playwright/test";
|
||||
|
||||
// Helper function to get text within a specific table column
|
||||
export const getByTableColumnText = (page: Page, columnId: string, text: string) =>
|
||||
page.locator(`[data-testid="data-table-td-${columnId}"]`).getByText(text);
|
||||
|
||||
/**
|
||||
* Add a filter from the filter dropdown
|
||||
*/
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
listSegments,
|
||||
clearFilters,
|
||||
openSegmentSubmenu,
|
||||
getByTableColumnText,
|
||||
} from "./filter-helpers";
|
||||
import { test } from "./lib/fixtures";
|
||||
|
||||
@@ -58,20 +59,20 @@ test.describe("Filter Segment Functionality", () => {
|
||||
await test.step("Can apply and save a role filter as a segment", async () => {
|
||||
await applySelectFilter(page, "role", "admin");
|
||||
|
||||
await expect(page.getByText(adminUser.email)).toBeVisible();
|
||||
await expect(page.getByText(memberUser.email)).toBeHidden();
|
||||
await expect(getByTableColumnText(page, "member", adminUser.email)).toBeVisible();
|
||||
await expect(getByTableColumnText(page, "member", memberUser.email)).toBeHidden();
|
||||
|
||||
await createFilterSegment(page, segmentName);
|
||||
|
||||
await clearFilters(page);
|
||||
|
||||
await expect(page.getByText(adminUser.email)).toBeVisible();
|
||||
await expect(page.getByText(memberUser.email)).toBeVisible();
|
||||
await expect(getByTableColumnText(page, "member", adminUser.email)).toBeVisible();
|
||||
await expect(getByTableColumnText(page, "member", memberUser.email)).toBeVisible();
|
||||
|
||||
await selectSegment(page, segmentName);
|
||||
|
||||
await expect(page.getByText(adminUser.email)).toBeVisible();
|
||||
await expect(page.getByText(memberUser.email)).toBeHidden();
|
||||
await expect(getByTableColumnText(page, "member", adminUser.email)).toBeVisible();
|
||||
await expect(getByTableColumnText(page, "member", memberUser.email)).toBeHidden();
|
||||
});
|
||||
|
||||
await test.step("Can delete a filter segment", async () => {
|
||||
@@ -119,8 +120,8 @@ test.describe("Filter Segment Functionality", () => {
|
||||
|
||||
await selectSegment(page, segmentName);
|
||||
|
||||
await expect(page.getByText(adminUser.email)).toBeVisible();
|
||||
await expect(page.getByText(memberUser.email)).toBeHidden();
|
||||
await expect(getByTableColumnText(page, "member", adminUser.email)).toBeVisible();
|
||||
await expect(getByTableColumnText(page, "member", memberUser.email)).toBeHidden();
|
||||
|
||||
await deleteSegment(page, segmentName);
|
||||
});
|
||||
@@ -167,8 +168,8 @@ test.describe("Filter Segment Functionality", () => {
|
||||
|
||||
await clearFilters(page);
|
||||
await selectSegment(page, segmentName);
|
||||
await expect(page.getByText(adminUser.email)).toBeVisible();
|
||||
await expect(page.getByText(memberUser.email)).toBeHidden();
|
||||
await expect(getByTableColumnText(page, "member", adminUser.email)).toBeVisible();
|
||||
await expect(getByTableColumnText(page, "member", memberUser.email)).toBeHidden();
|
||||
});
|
||||
|
||||
await test.step("Regular member can see but not modify team segments", async () => {
|
||||
@@ -193,8 +194,8 @@ test.describe("Filter Segment Functionality", () => {
|
||||
await expect(dataTable).toBeVisible();
|
||||
|
||||
await selectSegment(page, "Team Admin Filter");
|
||||
await expect(page.getByText(adminUser.email)).toBeVisible();
|
||||
await expect(page.getByText(memberUser.email)).toBeHidden();
|
||||
await expect(getByTableColumnText(page, "member", adminUser.email)).toBeVisible();
|
||||
await expect(getByTableColumnText(page, "member", memberUser.email)).toBeHidden();
|
||||
|
||||
await openSegmentSubmenu(page, segmentName);
|
||||
await expect(
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
applyTextFilter,
|
||||
applyNumberFilter,
|
||||
selectOptionValue,
|
||||
getByTableColumnText,
|
||||
} from "./filter-helpers";
|
||||
import { test } from "./lib/fixtures";
|
||||
|
||||
@@ -186,8 +187,8 @@ test.describe("Insights > Routing Filters", () => {
|
||||
|
||||
await applySelectFilter(page, "bookingUserId", user1Name);
|
||||
|
||||
await expect(page.getByText("John Doe")).toBeVisible();
|
||||
await expect(page.getByText("Jane Smith")).toBeHidden();
|
||||
await expect(getByTableColumnText(page, fieldId, "John Doe")).toBeVisible();
|
||||
await expect(getByTableColumnText(page, fieldId, "Jane Smith")).toBeHidden();
|
||||
|
||||
await prisma.booking.delete({ where: { id: booking1.id } });
|
||||
await prisma.booking.delete({ where: { id: booking2.id } });
|
||||
@@ -291,8 +292,8 @@ test.describe("Insights > Routing Filters", () => {
|
||||
await page.getByPlaceholder("Filter attendees by name or email").fill("John");
|
||||
await page.keyboard.press("Enter");
|
||||
|
||||
await expect(page.getByText("Response 1")).toBeVisible();
|
||||
await expect(page.getByText("Response 2")).toBeHidden();
|
||||
await expect(getByTableColumnText(page, fieldId, "Response 1")).toBeVisible();
|
||||
await expect(getByTableColumnText(page, fieldId, "Response 2")).toBeHidden();
|
||||
|
||||
await clearFilters(page);
|
||||
await addFilter(page, "bookingAttendees");
|
||||
@@ -300,8 +301,8 @@ test.describe("Insights > Routing Filters", () => {
|
||||
await page.getByPlaceholder("Filter attendees by name or email").fill("jane.smith@example");
|
||||
await page.keyboard.press("Enter");
|
||||
|
||||
await expect(page.getByText("Response 2")).toBeVisible();
|
||||
await expect(page.getByText("Response 1")).toBeHidden();
|
||||
await expect(getByTableColumnText(page, fieldId, "Response 2")).toBeVisible();
|
||||
await expect(getByTableColumnText(page, fieldId, "Response 1")).toBeHidden();
|
||||
|
||||
await clearFilters(page);
|
||||
await addFilter(page, "bookingAttendees");
|
||||
@@ -309,8 +310,8 @@ test.describe("Insights > Routing Filters", () => {
|
||||
await page.getByPlaceholder("Filter attendees by name or email").fill("JANE");
|
||||
await page.keyboard.press("Enter");
|
||||
|
||||
await expect(page.getByText("Response 2")).toBeVisible();
|
||||
await expect(page.getByText("Response 1")).toBeHidden();
|
||||
await expect(getByTableColumnText(page, fieldId, "Response 2")).toBeVisible();
|
||||
await expect(getByTableColumnText(page, fieldId, "Response 1")).toBeHidden();
|
||||
|
||||
await prisma.booking.delete({ where: { id: booking1.id } });
|
||||
await prisma.booking.delete({ where: { id: booking2.id } });
|
||||
@@ -392,26 +393,26 @@ test.describe("Insights > Routing Filters", () => {
|
||||
|
||||
await applyTextFilter(page, fieldId, "Contains", "test");
|
||||
|
||||
await expect(page.getByText("This is a test description")).toBeVisible();
|
||||
await expect(page.getByText("Another description for testing")).toBeVisible();
|
||||
await expect(getByTableColumnText(page, fieldId, "This is a test description")).toBeVisible();
|
||||
await expect(getByTableColumnText(page, fieldId, "Another description for testing")).toBeVisible();
|
||||
|
||||
await clearFilters(page);
|
||||
await applyTextFilter(page, fieldId, "Is", "This is a test description");
|
||||
|
||||
await expect(page.getByText("This is a test description")).toBeVisible();
|
||||
await expect(page.getByText("Another description for testing")).toBeHidden();
|
||||
await expect(getByTableColumnText(page, fieldId, "This is a test description")).toBeVisible();
|
||||
await expect(getByTableColumnText(page, fieldId, "Another description for testing")).toBeHidden();
|
||||
|
||||
await clearFilters(page);
|
||||
await applyTextFilter(page, fieldId, "Is empty");
|
||||
|
||||
await expect(page.getByText("This is a test description")).toBeHidden();
|
||||
await expect(page.getByText("Another description for testing")).toBeHidden();
|
||||
await expect(getByTableColumnText(page, fieldId, "This is a test description")).toBeHidden();
|
||||
await expect(getByTableColumnText(page, fieldId, "Another description for testing")).toBeHidden();
|
||||
|
||||
await clearFilters(page);
|
||||
await applyTextFilter(page, fieldId, "Contains", "TEST");
|
||||
|
||||
await expect(page.getByText("This is a test description")).toBeVisible();
|
||||
await expect(page.getByText("Another description for testing")).toBeVisible();
|
||||
await expect(getByTableColumnText(page, fieldId, "This is a test description")).toBeVisible();
|
||||
await expect(getByTableColumnText(page, fieldId, "Another description for testing")).toBeVisible();
|
||||
});
|
||||
|
||||
test("NUMBER field: should filter with different number operators", async ({
|
||||
@@ -489,26 +490,23 @@ test.describe("Insights > Routing Filters", () => {
|
||||
|
||||
await applyNumberFilter(page, fieldId, "=", 3);
|
||||
|
||||
const getByNumber = (number: number) =>
|
||||
page.locator(`[data-testid="data-table-td-${fieldId}"]`).getByText(String(number));
|
||||
|
||||
await expect(getByNumber(3)).toBeVisible();
|
||||
await expect(getByNumber(1)).toBeHidden();
|
||||
await expect(getByNumber(5)).toBeHidden();
|
||||
await expect(getByTableColumnText(page, fieldId, "3")).toBeVisible();
|
||||
await expect(getByTableColumnText(page, fieldId, "1")).toBeHidden();
|
||||
await expect(getByTableColumnText(page, fieldId, "5")).toBeHidden();
|
||||
|
||||
await clearFilters(page);
|
||||
await applyNumberFilter(page, fieldId, ">", 3);
|
||||
|
||||
await expect(getByNumber(5)).toBeVisible();
|
||||
await expect(getByNumber(1)).toBeHidden();
|
||||
await expect(getByNumber(3)).toBeHidden();
|
||||
await expect(getByTableColumnText(page, fieldId, "5")).toBeVisible();
|
||||
await expect(getByTableColumnText(page, fieldId, "1")).toBeHidden();
|
||||
await expect(getByTableColumnText(page, fieldId, "3")).toBeHidden();
|
||||
|
||||
await clearFilters(page);
|
||||
await applyNumberFilter(page, fieldId, "≤", 3);
|
||||
|
||||
await expect(getByNumber(1)).toBeVisible();
|
||||
await expect(getByNumber(3)).toBeVisible();
|
||||
await expect(getByNumber(5)).toBeHidden();
|
||||
await expect(getByTableColumnText(page, fieldId, "1")).toBeVisible();
|
||||
await expect(getByTableColumnText(page, fieldId, "3")).toBeVisible();
|
||||
await expect(getByTableColumnText(page, fieldId, "5")).toBeHidden();
|
||||
});
|
||||
|
||||
test("SINGLE_SELECT and MULTI_SELECT fields: should filter correctly", async ({
|
||||
@@ -620,19 +618,16 @@ test.describe("Insights > Routing Filters", () => {
|
||||
|
||||
await page.goto(`/insights/routing`);
|
||||
|
||||
const getByColumnValue = (columnId: string, value: string) =>
|
||||
page.locator(`[data-testid="data-table-td-${columnId}"]`).getByText(value);
|
||||
|
||||
await applySelectFilter(page, locationFieldId, "New York");
|
||||
await expect(getByColumnValue(locationFieldId, "New York")).toBeVisible();
|
||||
await expect(getByColumnValue(locationFieldId, "London")).toBeHidden();
|
||||
await expect(getByTableColumnText(page, locationFieldId, "New York")).toBeVisible();
|
||||
await expect(getByTableColumnText(page, locationFieldId, "London")).toBeHidden();
|
||||
|
||||
await clearFilters(page);
|
||||
await applySelectFilter(page, skillFieldId, "JavaScript");
|
||||
await applySelectFilter(page, skillFieldId, "TypeScript");
|
||||
await expect(getByColumnValue(skillFieldId, "JavaScript")).toBeVisible();
|
||||
await expect(getByColumnValue(skillFieldId, "TypeScript")).toBeVisible();
|
||||
await expect(getByColumnValue(skillFieldId, "React")).toBeHidden();
|
||||
await expect(getByTableColumnText(page, skillFieldId, "JavaScript")).toBeVisible();
|
||||
await expect(getByTableColumnText(page, skillFieldId, "TypeScript")).toBeVisible();
|
||||
await expect(getByTableColumnText(page, skillFieldId, "React")).toBeHidden();
|
||||
});
|
||||
|
||||
test("createdAt filter: should filter by date range", async ({ page, users, routingForms, prisma }) => {
|
||||
@@ -698,14 +693,14 @@ test.describe("Insights > Routing Filters", () => {
|
||||
await page.getByTestId("date-range-options-w").click(); // Last 7 Days
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
await expect(page.getByText("Recent Response")).toBeVisible();
|
||||
await expect(page.getByText("Old Response")).toBeHidden();
|
||||
await expect(getByTableColumnText(page, fieldId, "Recent Response")).toBeVisible();
|
||||
await expect(getByTableColumnText(page, fieldId, "Old Response")).toBeHidden();
|
||||
|
||||
await openFilter(page, "createdAt");
|
||||
await page.getByTestId("date-range-options-t").click(); // Last 30 Days
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
await expect(page.getByText("Recent Response")).toBeVisible();
|
||||
await expect(page.getByText("Old Response")).toBeVisible();
|
||||
await expect(getByTableColumnText(page, fieldId, "Recent Response")).toBeVisible();
|
||||
await expect(getByTableColumnText(page, fieldId, "Old Response")).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -28,7 +28,7 @@ export const PRESET_OPTIONS: PresetOption[] = [
|
||||
CUSTOM_PRESET,
|
||||
];
|
||||
|
||||
export const getDefaultStartDate = () => dayjs().subtract(1, "week").startOf("day");
|
||||
export const getDefaultStartDate = () => dayjs().subtract(6, "day").startOf("day");
|
||||
|
||||
export const getDefaultEndDate = () => dayjs().endOf("day");
|
||||
|
||||
@@ -46,11 +46,11 @@ export const getDateRangeFromPreset = (val: string | null) => {
|
||||
endDate = dayjs().endOf("day");
|
||||
break;
|
||||
case "w": // Last 7 days
|
||||
startDate = dayjs().subtract(1, "week").startOf("day");
|
||||
startDate = dayjs().subtract(6, "day").startOf("day");
|
||||
endDate = dayjs().endOf("day");
|
||||
break;
|
||||
case "t": // Last 30 days
|
||||
startDate = dayjs().subtract(30, "day").startOf("day");
|
||||
startDate = dayjs().subtract(29, "day").startOf("day");
|
||||
endDate = dayjs().endOf("day");
|
||||
break;
|
||||
case "m": // Month to Date
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Title } from "@tremor/react";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc";
|
||||
@@ -12,15 +11,7 @@ import { LoadingInsight } from "./LoadingInsights";
|
||||
|
||||
export const BookingStatusLineChart = () => {
|
||||
const { t } = useLocale();
|
||||
const { isAll, teamId, userId, startDate, endDate, dateRangePreset, eventTypeId } = useInsightsParameters();
|
||||
|
||||
const selectedTimeView = useMemo(() => {
|
||||
if (dateRangePreset === "tdy") return "day";
|
||||
else if (dateRangePreset === "w") return "week";
|
||||
else if (dateRangePreset === "m") return "month";
|
||||
else if (dateRangePreset === "y") return "year";
|
||||
else return "week";
|
||||
}, [dateRangePreset]);
|
||||
const { isAll, teamId, userId, startDate, endDate, eventTypeId } = useInsightsParameters();
|
||||
|
||||
const {
|
||||
data: eventsTimeLine,
|
||||
@@ -28,7 +19,6 @@ export const BookingStatusLineChart = () => {
|
||||
isPending,
|
||||
} = trpc.viewer.insights.eventsTimeline.useQuery(
|
||||
{
|
||||
timeView: selectedTimeView,
|
||||
startDate,
|
||||
endDate,
|
||||
teamId,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useMemo } from "react";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import {
|
||||
useFilterValue,
|
||||
useColumnFilters,
|
||||
@@ -28,14 +29,21 @@ export function useInsightsParameters() {
|
||||
const eventTypeId = useFilterValue("eventTypeId", ZSingleSelectFilterValue)?.data as number | undefined;
|
||||
const routingFormId = useFilterValue("formId", ZSingleSelectFilterValue)?.data as string | undefined;
|
||||
const createdAtRange = useFilterValue("createdAt", ZDateRangeFilterValue)?.data;
|
||||
const startDate = useMemo(
|
||||
() => preserveLocalTime(createdAtRange?.startDate ?? getDefaultStartDate().toISOString()),
|
||||
[createdAtRange?.startDate, preserveLocalTime]
|
||||
);
|
||||
const endDate = useMemo(
|
||||
() => preserveLocalTime(createdAtRange?.endDate ?? getDefaultEndDate().toISOString()),
|
||||
[createdAtRange?.endDate, preserveLocalTime]
|
||||
);
|
||||
// TODO for future: this preserving local time & startOf & endOf should be handled
|
||||
// from DateRangeFilter out of the box.
|
||||
// When we do it, we also need to remove those timezone handling logic from the backend side at the same time.
|
||||
const startDate = useMemo(() => {
|
||||
const timestamp = dayjs(createdAtRange?.startDate ?? getDefaultStartDate().toISOString())
|
||||
.startOf("day")
|
||||
.toISOString();
|
||||
return preserveLocalTime(timestamp);
|
||||
}, [createdAtRange?.startDate, preserveLocalTime]);
|
||||
const endDate = useMemo(() => {
|
||||
const timestamp = dayjs(createdAtRange?.endDate ?? getDefaultEndDate().toISOString())
|
||||
.endOf("day")
|
||||
.toISOString();
|
||||
return preserveLocalTime(timestamp);
|
||||
}, [createdAtRange?.endDate, preserveLocalTime]);
|
||||
|
||||
const dateRangePreset = useMemo<PresetOptionValue>(() => {
|
||||
return (createdAtRange?.preset as PresetOptionValue) ?? CUSTOM_PRESET_VALUE;
|
||||
|
||||
@@ -0,0 +1,849 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
|
||||
import { EventsInsights } from "../events";
|
||||
|
||||
describe("EventsInsights", () => {
|
||||
describe("getDateRanges", () => {
|
||||
describe("UTC timezone", () => {
|
||||
const timeZone = "UTC";
|
||||
|
||||
it("should handle daily ranges", () => {
|
||||
const startDate = "2025-05-01T00:00:00.000Z"; // Beginning of May 1st UTC
|
||||
const endDate = "2025-05-03T23:59:59.999Z"; // End of May 3rd UTC
|
||||
|
||||
const ranges = EventsInsights.getDateRanges({
|
||||
startDate,
|
||||
endDate,
|
||||
timeZone,
|
||||
timeView: "day",
|
||||
weekStart: "Sunday",
|
||||
});
|
||||
|
||||
if (!ranges) {
|
||||
throw new Error("Expected ranges to be defined");
|
||||
}
|
||||
|
||||
expect(ranges).toHaveLength(3);
|
||||
expect(ranges[0]).toEqual({
|
||||
startDate: "2025-05-01T00:00:00.000Z",
|
||||
endDate: "2025-05-01T23:59:59.999Z",
|
||||
formattedDate: "May 1",
|
||||
});
|
||||
expect(ranges[1]).toEqual({
|
||||
startDate: "2025-05-02T00:00:00.000Z",
|
||||
endDate: "2025-05-02T23:59:59.999Z",
|
||||
formattedDate: "2",
|
||||
});
|
||||
expect(ranges[2]).toEqual({
|
||||
startDate: "2025-05-03T00:00:00.000Z",
|
||||
endDate: "2025-05-03T23:59:59.999Z",
|
||||
formattedDate: "3",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle weekly ranges starting mid-week", () => {
|
||||
const startDate = "2025-05-01T00:00:00.000Z"; // Thursday
|
||||
const endDate = "2025-05-25T23:59:59.999Z";
|
||||
|
||||
const ranges = EventsInsights.getDateRanges({
|
||||
startDate,
|
||||
endDate,
|
||||
timeZone,
|
||||
timeView: "week",
|
||||
weekStart: "Sunday",
|
||||
});
|
||||
|
||||
if (!ranges) {
|
||||
throw new Error("Expected ranges to be defined");
|
||||
}
|
||||
|
||||
expect(ranges).toHaveLength(5);
|
||||
expect(ranges[0]).toEqual({
|
||||
startDate: "2025-05-01T00:00:00.000Z",
|
||||
endDate: "2025-05-03T23:59:59.999Z",
|
||||
formattedDate: "May 1 - 3",
|
||||
});
|
||||
expect(ranges[1]).toEqual({
|
||||
startDate: "2025-05-04T00:00:00.000Z",
|
||||
endDate: "2025-05-10T23:59:59.999Z",
|
||||
formattedDate: "May 4 - 10",
|
||||
});
|
||||
expect(ranges[2]).toEqual({
|
||||
startDate: "2025-05-11T00:00:00.000Z",
|
||||
endDate: "2025-05-17T23:59:59.999Z",
|
||||
formattedDate: "May 11 - 17",
|
||||
});
|
||||
expect(ranges[3]).toEqual({
|
||||
startDate: "2025-05-18T00:00:00.000Z",
|
||||
endDate: "2025-05-24T23:59:59.999Z",
|
||||
formattedDate: "May 18 - 24",
|
||||
});
|
||||
expect(ranges[4]).toEqual({
|
||||
startDate: "2025-05-25T00:00:00.000Z",
|
||||
endDate: "2025-05-25T23:59:59.999Z",
|
||||
formattedDate: "May 25 - 25",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle monthly ranges", () => {
|
||||
const startDate = "2025-05-15T00:00:00.000Z";
|
||||
const endDate = "2025-07-15T23:59:59.999Z";
|
||||
|
||||
const ranges = EventsInsights.getDateRanges({
|
||||
startDate,
|
||||
endDate,
|
||||
timeZone,
|
||||
timeView: "month",
|
||||
weekStart: "Sunday",
|
||||
});
|
||||
|
||||
if (!ranges) {
|
||||
throw new Error("Expected ranges to be defined");
|
||||
}
|
||||
|
||||
expect(ranges).toHaveLength(3);
|
||||
expect(ranges[0]).toEqual({
|
||||
startDate: "2025-05-15T00:00:00.000Z",
|
||||
endDate: "2025-05-31T23:59:59.999Z",
|
||||
formattedDate: "May",
|
||||
});
|
||||
expect(ranges[1]).toEqual({
|
||||
startDate: "2025-06-01T00:00:00.000Z",
|
||||
endDate: "2025-06-30T23:59:59.999Z",
|
||||
formattedDate: "Jun",
|
||||
});
|
||||
expect(ranges[2]).toEqual({
|
||||
startDate: "2025-07-01T00:00:00.000Z",
|
||||
endDate: "2025-07-15T23:59:59.999Z",
|
||||
formattedDate: "Jul",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle yearly ranges", () => {
|
||||
const startDate = "2025-06-15T00:00:00.000Z";
|
||||
const endDate = "2027-03-15T23:59:59.999Z";
|
||||
|
||||
const ranges = EventsInsights.getDateRanges({
|
||||
startDate,
|
||||
endDate,
|
||||
timeZone,
|
||||
timeView: "year",
|
||||
weekStart: "Sunday",
|
||||
});
|
||||
|
||||
if (!ranges) {
|
||||
throw new Error("Expected ranges to be defined");
|
||||
}
|
||||
|
||||
expect(ranges).toHaveLength(3);
|
||||
expect(ranges[0]).toEqual({
|
||||
startDate: "2025-06-15T00:00:00.000Z",
|
||||
endDate: "2025-12-31T23:59:59.999Z",
|
||||
formattedDate: "2025",
|
||||
});
|
||||
expect(ranges[1]).toEqual({
|
||||
startDate: "2026-01-01T00:00:00.000Z",
|
||||
endDate: "2026-12-31T23:59:59.999Z",
|
||||
formattedDate: "2026",
|
||||
});
|
||||
expect(ranges[2]).toEqual({
|
||||
startDate: "2027-01-01T00:00:00.000Z",
|
||||
endDate: "2027-03-15T23:59:59.999Z",
|
||||
formattedDate: "2027",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle same day ranges", () => {
|
||||
const startDate = "2025-05-01T00:00:00.000Z";
|
||||
const endDate = "2025-05-01T23:59:59.999Z";
|
||||
|
||||
const ranges = EventsInsights.getDateRanges({
|
||||
startDate,
|
||||
endDate,
|
||||
timeZone,
|
||||
timeView: "day",
|
||||
weekStart: "Sunday",
|
||||
});
|
||||
|
||||
if (!ranges) {
|
||||
throw new Error("Expected ranges to be defined");
|
||||
}
|
||||
|
||||
expect(ranges).toHaveLength(1);
|
||||
expect(ranges[0]).toEqual({
|
||||
startDate: "2025-05-01T00:00:00.000Z",
|
||||
endDate: "2025-05-01T23:59:59.999Z",
|
||||
formattedDate: "May 1",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Europe/Paris timezone", () => {
|
||||
const timeZone = "Europe/Paris";
|
||||
|
||||
it("should handle daily ranges across DST", () => {
|
||||
const startDate = "2025-03-29T23:00:00.000Z"; // March 30th 00:00 Paris time
|
||||
const endDate = "2025-03-31T21:59:59.999Z"; // March 31st 23:59:59 Paris time
|
||||
|
||||
const ranges = EventsInsights.getDateRanges({
|
||||
startDate,
|
||||
endDate,
|
||||
timeZone,
|
||||
timeView: "day",
|
||||
weekStart: "Sunday",
|
||||
});
|
||||
|
||||
if (!ranges) {
|
||||
throw new Error("Expected ranges to be defined");
|
||||
}
|
||||
|
||||
expect(ranges).toHaveLength(2);
|
||||
// DST begins on Sunday, March 30, 2025, at 3:00 AM local time
|
||||
expect(ranges[0]).toEqual({
|
||||
startDate: "2025-03-29T23:00:00.000Z", // March 30th 00:00 Paris time
|
||||
endDate: "2025-03-30T21:59:59.999Z", // March 30th 23:59:59 Paris time
|
||||
formattedDate: "Mar 30",
|
||||
});
|
||||
expect(new Date(ranges[0].endDate).getTime() - new Date(ranges[0].startDate).getTime()).toBeLessThan(
|
||||
23 * 60 * 60 * 1000
|
||||
); // 1 hour is skipped
|
||||
expect(ranges[1]).toEqual({
|
||||
startDate: "2025-03-30T22:00:00.000Z", // March 31st 00:00 Paris time
|
||||
endDate: "2025-03-31T21:59:59.999Z", // March 31st 23:59:59 Paris time
|
||||
formattedDate: "31",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle weekly ranges", () => {
|
||||
const startDate = "2025-05-15T22:00:00.000Z"; // May 16th 00:00 Paris time
|
||||
const endDate = "2025-05-29T21:59:59.999Z"; // May 29th 23:59:59 Paris time
|
||||
|
||||
const ranges = EventsInsights.getDateRanges({
|
||||
startDate,
|
||||
endDate,
|
||||
timeZone,
|
||||
timeView: "week",
|
||||
weekStart: "Sunday",
|
||||
});
|
||||
|
||||
if (!ranges) {
|
||||
throw new Error("Expected ranges to be defined");
|
||||
}
|
||||
|
||||
expect(ranges).toHaveLength(3);
|
||||
expect(ranges[0]).toEqual({
|
||||
startDate: "2025-05-15T22:00:00.000Z",
|
||||
endDate: "2025-05-17T21:59:59.999Z",
|
||||
formattedDate: "May 16 - 17",
|
||||
});
|
||||
expect(ranges[1]).toEqual({
|
||||
startDate: "2025-05-17T22:00:00.000Z",
|
||||
endDate: "2025-05-24T21:59:59.999Z",
|
||||
formattedDate: "May 18 - 24",
|
||||
});
|
||||
expect(ranges[2]).toEqual({
|
||||
startDate: "2025-05-24T22:00:00.000Z",
|
||||
endDate: "2025-05-29T21:59:59.999Z",
|
||||
formattedDate: "May 25 - 29",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle monthly ranges", () => {
|
||||
const startDate = "2025-05-31T22:00:00.000Z"; // June 1st 00:00 Paris time
|
||||
const endDate = "2025-07-31T21:59:59.999Z"; // July 31st 23:59:59 Paris time
|
||||
|
||||
const ranges = EventsInsights.getDateRanges({
|
||||
startDate,
|
||||
endDate,
|
||||
timeZone,
|
||||
timeView: "month",
|
||||
weekStart: "Sunday",
|
||||
});
|
||||
|
||||
if (!ranges) {
|
||||
throw new Error("Expected ranges to be defined");
|
||||
}
|
||||
|
||||
expect(ranges).toHaveLength(2);
|
||||
expect(ranges[0]).toEqual({
|
||||
startDate: "2025-05-31T22:00:00.000Z",
|
||||
endDate: "2025-06-30T21:59:59.999Z",
|
||||
formattedDate: "Jun",
|
||||
});
|
||||
expect(ranges[1]).toEqual({
|
||||
startDate: "2025-06-30T22:00:00.000Z",
|
||||
endDate: "2025-07-31T21:59:59.999Z",
|
||||
formattedDate: "Jul",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Asia/Seoul timezone", () => {
|
||||
const timeZone = "Asia/Seoul";
|
||||
|
||||
it("should handle daily ranges", () => {
|
||||
const startDate = "2025-05-14T15:00:00.000Z"; // May 15th 00:00 Seoul time
|
||||
const endDate = "2025-05-16T14:59:59.999Z"; // May 16th 23:59:59 Seoul time
|
||||
|
||||
const ranges = EventsInsights.getDateRanges({
|
||||
startDate,
|
||||
endDate,
|
||||
timeZone,
|
||||
timeView: "day",
|
||||
weekStart: "Sunday",
|
||||
});
|
||||
|
||||
if (!ranges) {
|
||||
throw new Error("Expected ranges to be defined");
|
||||
}
|
||||
|
||||
expect(ranges).toHaveLength(2);
|
||||
expect(ranges[0]).toEqual({
|
||||
startDate: "2025-05-14T15:00:00.000Z",
|
||||
endDate: "2025-05-15T14:59:59.999Z",
|
||||
formattedDate: "May 15",
|
||||
});
|
||||
expect(ranges[1]).toEqual({
|
||||
startDate: "2025-05-15T15:00:00.000Z",
|
||||
endDate: "2025-05-16T14:59:59.999Z",
|
||||
formattedDate: "16",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle weekly ranges", () => {
|
||||
const startDate = "2025-05-11T15:00:00.000Z"; // May 12th 00:00 Seoul time (Monday)
|
||||
const endDate = "2025-05-25T14:59:59.999Z"; // May 25th 23:59:59 Seoul time (Sunday)
|
||||
|
||||
const ranges = EventsInsights.getDateRanges({
|
||||
startDate,
|
||||
endDate,
|
||||
timeZone,
|
||||
timeView: "week",
|
||||
weekStart: "Sunday",
|
||||
});
|
||||
|
||||
if (!ranges) {
|
||||
throw new Error("Expected ranges to be defined");
|
||||
}
|
||||
|
||||
expect(ranges).toHaveLength(3);
|
||||
expect(ranges[0]).toEqual({
|
||||
startDate: "2025-05-11T15:00:00.000Z",
|
||||
endDate: "2025-05-17T14:59:59.999Z",
|
||||
formattedDate: "May 12 - 17",
|
||||
});
|
||||
expect(ranges[1]).toEqual({
|
||||
startDate: "2025-05-17T15:00:00.000Z",
|
||||
endDate: "2025-05-24T14:59:59.999Z",
|
||||
formattedDate: "May 18 - 24",
|
||||
});
|
||||
expect(ranges[2]).toEqual({
|
||||
startDate: "2025-05-24T15:00:00.000Z",
|
||||
endDate: "2025-05-25T14:59:59.999Z",
|
||||
formattedDate: "May 25 - 25",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle monthly ranges", () => {
|
||||
const startDate = "2025-04-30T15:00:00.000Z"; // May 1st 00:00 Seoul time
|
||||
const endDate = "2025-06-30T14:59:59.999Z"; // June 30th 23:59:59 Seoul time
|
||||
|
||||
const ranges = EventsInsights.getDateRanges({
|
||||
startDate,
|
||||
endDate,
|
||||
timeZone,
|
||||
timeView: "month",
|
||||
weekStart: "Sunday",
|
||||
});
|
||||
|
||||
if (!ranges) {
|
||||
throw new Error("Expected ranges to be defined");
|
||||
}
|
||||
|
||||
expect(ranges).toHaveLength(2);
|
||||
expect(ranges[0]).toEqual({
|
||||
startDate: "2025-04-30T15:00:00.000Z",
|
||||
endDate: "2025-05-31T14:59:59.999Z",
|
||||
formattedDate: "May",
|
||||
});
|
||||
expect(ranges[1]).toEqual({
|
||||
startDate: "2025-05-31T15:00:00.000Z",
|
||||
endDate: "2025-06-30T14:59:59.999Z",
|
||||
formattedDate: "Jun",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("should return empty array for invalid timeView", () => {
|
||||
const startDate = "2025-05-01T00:00:00.000Z";
|
||||
const endDate = "2025-05-03T23:59:59.999Z";
|
||||
const timeZone = "UTC";
|
||||
|
||||
const ranges = EventsInsights.getDateRanges({
|
||||
startDate,
|
||||
endDate,
|
||||
timeZone,
|
||||
weekStart: "Sunday",
|
||||
// @ts-expect-error - Testing invalid timeView value
|
||||
timeView: "invalid",
|
||||
});
|
||||
|
||||
if (!ranges) {
|
||||
throw new Error("Expected ranges to be defined");
|
||||
}
|
||||
|
||||
expect(ranges).toEqual([]);
|
||||
});
|
||||
|
||||
describe("Week start variations", () => {
|
||||
const timeZone = "UTC";
|
||||
|
||||
it("should handle weekly ranges with Monday start", () => {
|
||||
const startDate = "2025-05-01T00:00:00.000Z"; // Thursday
|
||||
const endDate = "2025-05-14T23:59:59.999Z"; // Wednesday
|
||||
|
||||
const ranges = EventsInsights.getDateRanges({
|
||||
startDate,
|
||||
endDate,
|
||||
timeZone,
|
||||
timeView: "week",
|
||||
weekStart: "Monday",
|
||||
});
|
||||
|
||||
if (!ranges) {
|
||||
throw new Error("Expected ranges to be defined");
|
||||
}
|
||||
|
||||
expect(ranges).toHaveLength(3);
|
||||
expect(ranges[0]).toEqual({
|
||||
startDate: "2025-05-01T00:00:00.000Z",
|
||||
endDate: "2025-05-04T23:59:59.999Z",
|
||||
formattedDate: "May 1 - 4",
|
||||
});
|
||||
expect(ranges[1]).toEqual({
|
||||
startDate: "2025-05-05T00:00:00.000Z",
|
||||
endDate: "2025-05-11T23:59:59.999Z",
|
||||
formattedDate: "May 5 - 11",
|
||||
});
|
||||
expect(ranges[2]).toEqual({
|
||||
startDate: "2025-05-12T00:00:00.000Z",
|
||||
endDate: "2025-05-14T23:59:59.999Z",
|
||||
formattedDate: "May 12 - 14",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle weekly ranges with Sunday start", () => {
|
||||
const startDate = "2025-05-01T00:00:00.000Z"; // Thursday
|
||||
const endDate = "2025-05-14T23:59:59.999Z"; // Wednesday
|
||||
|
||||
const ranges = EventsInsights.getDateRanges({
|
||||
startDate,
|
||||
endDate,
|
||||
timeZone,
|
||||
timeView: "week",
|
||||
weekStart: "Sunday",
|
||||
});
|
||||
|
||||
if (!ranges) {
|
||||
throw new Error("Expected ranges to be defined");
|
||||
}
|
||||
|
||||
expect(ranges).toHaveLength(3);
|
||||
expect(ranges[0]).toEqual({
|
||||
startDate: "2025-05-01T00:00:00.000Z",
|
||||
endDate: "2025-05-03T23:59:59.999Z",
|
||||
formattedDate: "May 1 - 3",
|
||||
});
|
||||
expect(ranges[1]).toEqual({
|
||||
startDate: "2025-05-04T00:00:00.000Z",
|
||||
endDate: "2025-05-10T23:59:59.999Z",
|
||||
formattedDate: "May 4 - 10",
|
||||
});
|
||||
expect(ranges[2]).toEqual({
|
||||
startDate: "2025-05-11T00:00:00.000Z",
|
||||
endDate: "2025-05-14T23:59:59.999Z",
|
||||
formattedDate: "May 11 - 14",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle weekly ranges with Saturday start", () => {
|
||||
const startDate = "2025-05-01T00:00:00.000Z"; // Thursday
|
||||
const endDate = "2025-05-14T23:59:59.999Z"; // Wednesday
|
||||
|
||||
const ranges = EventsInsights.getDateRanges({
|
||||
startDate,
|
||||
endDate,
|
||||
timeZone,
|
||||
timeView: "week",
|
||||
weekStart: "Saturday",
|
||||
});
|
||||
|
||||
if (!ranges) {
|
||||
throw new Error("Expected ranges to be defined");
|
||||
}
|
||||
|
||||
expect(ranges).toHaveLength(3);
|
||||
expect(ranges[0]).toEqual({
|
||||
startDate: "2025-05-01T00:00:00.000Z",
|
||||
endDate: "2025-05-02T23:59:59.999Z",
|
||||
formattedDate: "May 1 - 2",
|
||||
});
|
||||
expect(ranges[1]).toEqual({
|
||||
startDate: "2025-05-03T00:00:00.000Z",
|
||||
endDate: "2025-05-09T23:59:59.999Z",
|
||||
formattedDate: "May 3 - 9",
|
||||
});
|
||||
expect(ranges[2]).toEqual({
|
||||
startDate: "2025-05-10T00:00:00.000Z",
|
||||
endDate: "2025-05-14T23:59:59.999Z",
|
||||
formattedDate: "May 10 - 14",
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatPeriod", () => {
|
||||
describe("Day View", () => {
|
||||
describe("Beginning of data (wholeStart === start)", () => {
|
||||
it("should always show month for the first day when same year", () => {
|
||||
const result = EventsInsights.formatPeriod({
|
||||
start: dayjs("2024-01-15"),
|
||||
end: dayjs("2024-01-15"),
|
||||
timeView: "day",
|
||||
wholeStart: dayjs("2024-01-15"), // Same as start
|
||||
wholeEnd: dayjs("2024-01-20"),
|
||||
});
|
||||
expect(result).toBe("Jan 15");
|
||||
});
|
||||
|
||||
it("should always show month for the first day when different years", () => {
|
||||
const result = EventsInsights.formatPeriod({
|
||||
start: dayjs("2024-01-15"),
|
||||
end: dayjs("2024-01-15"),
|
||||
timeView: "day",
|
||||
wholeStart: dayjs("2024-01-15"), // Same as start
|
||||
wholeEnd: dayjs("2025-02-01"),
|
||||
});
|
||||
expect(result).toBe("Jan 15, 2024");
|
||||
});
|
||||
});
|
||||
|
||||
describe("First day of month (start.date() === 1)", () => {
|
||||
it("should show month for 1st day of month when same year", () => {
|
||||
const result = EventsInsights.formatPeriod({
|
||||
start: dayjs("2024-02-01"),
|
||||
end: dayjs("2024-02-01"),
|
||||
timeView: "day",
|
||||
wholeStart: dayjs("2024-01-15"),
|
||||
wholeEnd: dayjs("2024-02-10"),
|
||||
});
|
||||
expect(result).toBe("Feb 1");
|
||||
});
|
||||
|
||||
it("should show month for 1st day of month when different years", () => {
|
||||
const result = EventsInsights.formatPeriod({
|
||||
start: dayjs("2024-02-01"),
|
||||
end: dayjs("2024-02-01"),
|
||||
timeView: "day",
|
||||
wholeStart: dayjs("2023-12-15"),
|
||||
wholeEnd: dayjs("2024-03-01"),
|
||||
});
|
||||
expect(result).toBe("Feb 1, 2024");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Regular days (not first day, not 1st of month)", () => {
|
||||
it("should omit month for regular days when same year", () => {
|
||||
const result = EventsInsights.formatPeriod({
|
||||
start: dayjs("2024-01-16"),
|
||||
end: dayjs("2024-01-16"),
|
||||
timeView: "day",
|
||||
wholeStart: dayjs("2024-01-15"),
|
||||
wholeEnd: dayjs("2024-01-20"),
|
||||
});
|
||||
expect(result).toBe("16");
|
||||
});
|
||||
|
||||
it("should omit month but show year for regular days when different years", () => {
|
||||
const result = EventsInsights.formatPeriod({
|
||||
start: dayjs("2024-01-16"),
|
||||
end: dayjs("2024-01-16"),
|
||||
timeView: "day",
|
||||
wholeStart: dayjs("2023-12-15"),
|
||||
wholeEnd: dayjs("2024-02-01"),
|
||||
});
|
||||
expect(result).toBe("16, 2024");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Edge cases", () => {
|
||||
it("should show month when start is both beginning of data AND 1st of month", () => {
|
||||
const result = EventsInsights.formatPeriod({
|
||||
start: dayjs("2024-01-01"),
|
||||
end: dayjs("2024-01-01"),
|
||||
timeView: "day",
|
||||
wholeStart: dayjs("2024-01-01"), // Same as start AND 1st of month
|
||||
wholeEnd: dayjs("2024-01-05"),
|
||||
});
|
||||
expect(result).toBe("Jan 1");
|
||||
});
|
||||
|
||||
it("should show month for last day of month if it's 1st of month (edge case)", () => {
|
||||
// This tests the case where start.date() === 1 takes precedence
|
||||
const result = EventsInsights.formatPeriod({
|
||||
start: dayjs("2024-03-01"),
|
||||
end: dayjs("2024-03-01"),
|
||||
timeView: "day",
|
||||
wholeStart: dayjs("2024-02-28"),
|
||||
wholeEnd: dayjs("2024-03-05"),
|
||||
});
|
||||
expect(result).toBe("Mar 1");
|
||||
});
|
||||
|
||||
it("should omit month for end of month when not 1st and not beginning", () => {
|
||||
const result = EventsInsights.formatPeriod({
|
||||
start: dayjs("2024-01-31"),
|
||||
end: dayjs("2024-01-31"),
|
||||
timeView: "day",
|
||||
wholeStart: dayjs("2024-01-15"),
|
||||
wholeEnd: dayjs("2024-02-05"),
|
||||
});
|
||||
expect(result).toBe("31");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Real-world scenarios", () => {
|
||||
it("should format a range from Jan 15 to Jan 20 correctly", () => {
|
||||
// Simulating how getDateRanges would call formatPeriod for each day
|
||||
const wholeStart = dayjs("2024-01-15");
|
||||
const wholeEnd = dayjs("2024-01-20");
|
||||
|
||||
const results: string[] = [];
|
||||
for (let i = 0; i <= 5; i++) {
|
||||
const currentDay = wholeStart.add(i, "day");
|
||||
results.push(
|
||||
EventsInsights.formatPeriod({
|
||||
start: currentDay,
|
||||
end: currentDay,
|
||||
timeView: "day",
|
||||
wholeStart,
|
||||
wholeEnd,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
expect(results).toEqual(["Jan 15", "16", "17", "18", "19", "20"]);
|
||||
});
|
||||
|
||||
it("should format a range from Jan 30 to Feb 3 correctly", () => {
|
||||
// Simulating month transition
|
||||
const wholeStart = dayjs("2024-01-30");
|
||||
const wholeEnd = dayjs("2024-02-03");
|
||||
|
||||
const results: string[] = [];
|
||||
let currentDay = wholeStart;
|
||||
while (currentDay.isBefore(wholeEnd) || currentDay.isSame(wholeEnd)) {
|
||||
results.push(
|
||||
EventsInsights.formatPeriod({
|
||||
start: currentDay,
|
||||
end: currentDay,
|
||||
timeView: "day",
|
||||
wholeStart,
|
||||
wholeEnd,
|
||||
})
|
||||
);
|
||||
currentDay = currentDay.add(1, "day");
|
||||
}
|
||||
|
||||
expect(results).toEqual(["Jan 30", "31", "Feb 1", "2", "3"]);
|
||||
});
|
||||
|
||||
it("should format a range from Dec 30, 2023 to Jan 2, 2024 correctly", () => {
|
||||
// Simulating year transition with different years
|
||||
const wholeStart = dayjs("2023-12-30");
|
||||
const wholeEnd = dayjs("2024-01-02");
|
||||
|
||||
const results: string[] = [];
|
||||
let currentDay = wholeStart;
|
||||
while (currentDay.isBefore(wholeEnd) || currentDay.isSame(wholeEnd)) {
|
||||
results.push(
|
||||
EventsInsights.formatPeriod({
|
||||
start: currentDay,
|
||||
end: currentDay,
|
||||
timeView: "day",
|
||||
wholeStart,
|
||||
wholeEnd,
|
||||
})
|
||||
);
|
||||
currentDay = currentDay.add(1, "day");
|
||||
}
|
||||
|
||||
expect(results).toEqual(["Dec 30, 2023", "31, 2023", "Jan 1, 2024", "2, 2024"]);
|
||||
});
|
||||
|
||||
it("should format a single day range correctly", () => {
|
||||
const result = EventsInsights.formatPeriod({
|
||||
start: dayjs("2024-01-15"),
|
||||
end: dayjs("2024-01-15"),
|
||||
timeView: "day",
|
||||
wholeStart: dayjs("2024-01-15"),
|
||||
wholeEnd: dayjs("2024-01-15"),
|
||||
});
|
||||
|
||||
expect(result).toBe("Jan 15");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Week View", () => {
|
||||
describe("Same month", () => {
|
||||
it("should format dates without year when wholeStart and wholeEnd are same year", () => {
|
||||
const result = EventsInsights.formatPeriod({
|
||||
start: dayjs("2024-01-01"),
|
||||
end: dayjs("2024-01-07"),
|
||||
timeView: "week",
|
||||
wholeStart: dayjs("2024-01-01"),
|
||||
wholeEnd: dayjs("2024-12-31"),
|
||||
});
|
||||
expect(result).toBe("Jan 1 - 7");
|
||||
});
|
||||
|
||||
it("should format dates with year when wholeStart and wholeEnd are different years", () => {
|
||||
const result = EventsInsights.formatPeriod({
|
||||
start: dayjs("2024-01-01"),
|
||||
end: dayjs("2024-01-07"),
|
||||
timeView: "week",
|
||||
wholeStart: dayjs("2023-12-01"),
|
||||
wholeEnd: dayjs("2024-02-01"),
|
||||
});
|
||||
expect(result).toBe("Jan 1 - 7, 2024");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Different months", () => {
|
||||
it("should format dates without year when wholeStart and wholeEnd are same year", () => {
|
||||
const result = EventsInsights.formatPeriod({
|
||||
start: dayjs("2024-01-29"),
|
||||
end: dayjs("2024-02-04"),
|
||||
timeView: "week",
|
||||
wholeStart: dayjs("2024-01-01"),
|
||||
wholeEnd: dayjs("2024-12-31"),
|
||||
});
|
||||
expect(result).toBe("Jan 29 - Feb 4");
|
||||
});
|
||||
|
||||
it("should format dates with year when wholeStart and wholeEnd are different years", () => {
|
||||
const result = EventsInsights.formatPeriod({
|
||||
start: dayjs("2024-01-29"),
|
||||
end: dayjs("2024-02-04"),
|
||||
timeView: "week",
|
||||
wholeStart: dayjs("2023-12-01"),
|
||||
wholeEnd: dayjs("2024-03-01"),
|
||||
});
|
||||
expect(result).toBe("Jan 29 - Feb 4, 2024");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Different years", () => {
|
||||
it("should format dates with respective years when start and end span different years", () => {
|
||||
const result = EventsInsights.formatPeriod({
|
||||
start: dayjs("2023-12-31"),
|
||||
end: dayjs("2024-01-06"),
|
||||
timeView: "week",
|
||||
wholeStart: dayjs("2023-12-01"),
|
||||
wholeEnd: dayjs("2024-01-31"),
|
||||
});
|
||||
expect(result).toBe("Dec 31 , 2023 - Jan 6, 2024");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Month View", () => {
|
||||
it("should format month without year when wholeStart and wholeEnd are same year", () => {
|
||||
const result = EventsInsights.formatPeriod({
|
||||
start: dayjs("2024-01-01"),
|
||||
end: dayjs("2024-01-31"),
|
||||
timeView: "month",
|
||||
wholeStart: dayjs("2024-01-01"),
|
||||
wholeEnd: dayjs("2024-12-31"),
|
||||
});
|
||||
expect(result).toBe("Jan");
|
||||
});
|
||||
|
||||
it("should format month with year when wholeStart and wholeEnd are different years", () => {
|
||||
const result = EventsInsights.formatPeriod({
|
||||
start: dayjs("2024-01-01"),
|
||||
end: dayjs("2024-01-31"),
|
||||
timeView: "month",
|
||||
wholeStart: dayjs("2023-12-01"),
|
||||
wholeEnd: dayjs("2024-02-01"),
|
||||
});
|
||||
expect(result).toBe("Jan 2024");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Year View", () => {
|
||||
it("should format year regardless of wholeStart and wholeEnd values", () => {
|
||||
const resultWithSameYear = EventsInsights.formatPeriod({
|
||||
start: dayjs("2024-01-01"),
|
||||
end: dayjs("2024-12-31"),
|
||||
timeView: "year",
|
||||
wholeStart: dayjs("2024-01-01"),
|
||||
wholeEnd: dayjs("2024-12-31"),
|
||||
});
|
||||
expect(resultWithSameYear).toBe("2024");
|
||||
|
||||
const resultWithDifferentYears = EventsInsights.formatPeriod({
|
||||
start: dayjs("2024-01-01"),
|
||||
end: dayjs("2024-12-31"),
|
||||
timeView: "year",
|
||||
wholeStart: dayjs("2023-12-01"),
|
||||
wholeEnd: dayjs("2025-01-01"),
|
||||
});
|
||||
expect(resultWithDifferentYears).toBe("2024");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Invalid View", () => {
|
||||
it("should return empty string for invalid timeView", () => {
|
||||
const result = EventsInsights.formatPeriod({
|
||||
start: dayjs("2024-01-01"),
|
||||
end: dayjs("2024-01-01"),
|
||||
timeView: "invalid" as any,
|
||||
wholeStart: dayjs("2024-01-01"),
|
||||
wholeEnd: dayjs("2024-12-31"),
|
||||
});
|
||||
expect(result).toBe("");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("getTimeView", () => {
|
||||
it("should return year for ranges over 365 days", () => {
|
||||
const result = EventsInsights.getTimeView("2024-01-01T00:00:00.000Z", "2025-02-01T00:00:00.000Z");
|
||||
expect(result).toBe("year");
|
||||
});
|
||||
|
||||
it("should return month for ranges between 90 and 365 days", () => {
|
||||
const result = EventsInsights.getTimeView("2024-01-01T00:00:00.000Z", "2024-05-01T00:00:00.000Z");
|
||||
expect(result).toBe("month");
|
||||
});
|
||||
|
||||
it("should return week for ranges between 14 and 90 days", () => {
|
||||
const result = EventsInsights.getTimeView("2024-01-01T00:00:00.000Z", "2024-02-01T00:00:00.000Z");
|
||||
expect(result).toBe("week");
|
||||
});
|
||||
|
||||
it("should return day for ranges under 14 days", () => {
|
||||
const result = EventsInsights.getTimeView("2024-01-01T00:00:00.000Z", "2024-01-10T00:00:00.000Z");
|
||||
expect(result).toBe("day");
|
||||
});
|
||||
|
||||
it("should handle same day range", () => {
|
||||
const result = EventsInsights.getTimeView("2024-01-01T00:00:00.000Z", "2024-01-01T23:59:59.999Z");
|
||||
expect(result).toBe("day");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -61,21 +61,34 @@ function buildSqlCondition(condition: any): string {
|
||||
}
|
||||
}
|
||||
|
||||
export interface DateRange {
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
formattedDate: string;
|
||||
}
|
||||
|
||||
export interface GetDateRangesParams {
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
timeZone: string;
|
||||
timeView: "day" | "week" | "month" | "year";
|
||||
weekStart: "Sunday" | "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday" | "Saturday";
|
||||
}
|
||||
|
||||
class EventsInsights {
|
||||
static countGroupedByStatusForRanges = async (
|
||||
whereConditional: Prisma.BookingTimeStatusDenormalizedWhereInput,
|
||||
startDate: Dayjs,
|
||||
endDate: Dayjs,
|
||||
timeView: "week" | "month" | "year" | "day"
|
||||
dateRanges: DateRange[]
|
||||
): Promise<AggregateResult> => {
|
||||
// Determine the date truncation and date range based on timeView
|
||||
const formattedStartDate = dayjs(startDate).format("YYYY-MM-DD HH:mm:ss");
|
||||
const formattedEndDate = dayjs(endDate).format("YYYY-MM-DD HH:mm:ss");
|
||||
const whereClause = buildSqlCondition(whereConditional);
|
||||
|
||||
const data = await prisma.$queryRaw<
|
||||
{
|
||||
periodStart: Date;
|
||||
date: Date;
|
||||
bookingsCount: number;
|
||||
timeStatus: string;
|
||||
noShowHost: boolean;
|
||||
@@ -83,14 +96,14 @@ class EventsInsights {
|
||||
}[]
|
||||
>`
|
||||
SELECT
|
||||
"periodStart",
|
||||
DATE("createdAt") as "date",
|
||||
CAST(COUNT(*) AS INTEGER) AS "bookingsCount",
|
||||
CAST(COUNT(CASE WHEN "isNoShowGuest" = true THEN 1 END) AS INTEGER) AS "noShowGuests",
|
||||
"timeStatus",
|
||||
"noShowHost"
|
||||
FROM (
|
||||
SELECT
|
||||
DATE_TRUNC(${timeView}, "createdAt") AS "periodStart",
|
||||
"createdAt",
|
||||
"a"."noShow" AS "isNoShowGuest",
|
||||
"timeStatus",
|
||||
"noShowHost"
|
||||
@@ -101,41 +114,46 @@ class EventsInsights {
|
||||
WHERE
|
||||
"createdAt" BETWEEN ${formattedStartDate}::timestamp AND ${formattedEndDate}::timestamp
|
||||
AND ${Prisma.raw(whereClause)}
|
||||
) AS truncated_dates
|
||||
) AS bookings
|
||||
GROUP BY
|
||||
"periodStart",
|
||||
DATE("createdAt"),
|
||||
"timeStatus",
|
||||
"noShowHost"
|
||||
ORDER BY
|
||||
"periodStart";
|
||||
"date";
|
||||
`;
|
||||
|
||||
const aggregate: AggregateResult = {};
|
||||
data.forEach(({ periodStart, bookingsCount, timeStatus, noShowHost, noShowGuests }) => {
|
||||
const formattedDate = dayjs(periodStart).format("MMM D, YYYY");
|
||||
|
||||
if (dayjs(periodStart).isAfter(endDate)) {
|
||||
return;
|
||||
}
|
||||
// Initialize all date ranges with zero counts
|
||||
dateRanges.forEach(({ formattedDate }) => {
|
||||
aggregate[formattedDate] = {
|
||||
completed: 0,
|
||||
rescheduled: 0,
|
||||
cancelled: 0,
|
||||
noShowHost: 0,
|
||||
noShowGuests: 0,
|
||||
_all: 0,
|
||||
uncompleted: 0,
|
||||
};
|
||||
});
|
||||
|
||||
// Ensure the date entry exists in the aggregate object
|
||||
if (!aggregate[formattedDate]) {
|
||||
aggregate[formattedDate] = {
|
||||
completed: 0,
|
||||
rescheduled: 0,
|
||||
cancelled: 0,
|
||||
noShowHost: 0,
|
||||
_all: 0,
|
||||
uncompleted: 0,
|
||||
noShowGuests: 0,
|
||||
};
|
||||
}
|
||||
// Process the raw data
|
||||
data.forEach(({ date, bookingsCount, timeStatus, noShowHost, noShowGuests }) => {
|
||||
// Find which date range this date belongs to
|
||||
const dateRange = dateRanges.find((range) =>
|
||||
dayjs(date).isBetween(range.startDate, range.endDate, null, "[]")
|
||||
);
|
||||
|
||||
if (!dateRange) return;
|
||||
|
||||
const formattedDate = dateRange.formattedDate;
|
||||
const statusKey = timeStatus as keyof StatusAggregate;
|
||||
|
||||
// Add to the specific status count
|
||||
const statusKey = timeStatus as keyof StatusAggregate;
|
||||
aggregate[formattedDate][statusKey] += Number(bookingsCount);
|
||||
|
||||
// Always add to the total count (_all)
|
||||
// Add to the total count (_all)
|
||||
aggregate[formattedDate]["_all"] += Number(bookingsCount);
|
||||
|
||||
// Track no-show host counts separately
|
||||
@@ -147,41 +165,6 @@ class EventsInsights {
|
||||
aggregate[formattedDate]["noShowGuests"] += noShowGuests;
|
||||
});
|
||||
|
||||
// Generate a complete list of expected date labels based on the timeline
|
||||
let current = dayjs(startDate);
|
||||
const expectedDates: string[] = [];
|
||||
|
||||
while (current.isBefore(endDate) || current.isSame(endDate)) {
|
||||
const formattedDate = current.format("MMM D, YYYY");
|
||||
expectedDates.push(formattedDate);
|
||||
|
||||
// Increment based on the selected timeView
|
||||
if (timeView === "day") {
|
||||
current = current.add(1, "day");
|
||||
} else if (timeView === "week") {
|
||||
current = current.add(1, "week");
|
||||
} else if (timeView === "month") {
|
||||
current = current.add(1, "month");
|
||||
} else if (timeView === "year") {
|
||||
current = current.add(1, "year");
|
||||
}
|
||||
}
|
||||
|
||||
// Fill in any missing dates with zero counts
|
||||
expectedDates.forEach((label) => {
|
||||
if (!aggregate[label]) {
|
||||
aggregate[label] = {
|
||||
completed: 0,
|
||||
rescheduled: 0,
|
||||
cancelled: 0,
|
||||
noShowHost: 0,
|
||||
noShowGuests: 0,
|
||||
_all: 0,
|
||||
uncompleted: 0,
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
return aggregate;
|
||||
};
|
||||
|
||||
@@ -269,97 +252,19 @@ class EventsInsights {
|
||||
return csat;
|
||||
};
|
||||
|
||||
static getTimeLine = async (timeView: TimeViewType, startDate: Dayjs, endDate: Dayjs) => {
|
||||
let resultTimeLine: string[] = [];
|
||||
|
||||
if (timeView) {
|
||||
switch (timeView) {
|
||||
case "day":
|
||||
resultTimeLine = this.getDailyTimeline(startDate, endDate);
|
||||
break;
|
||||
case "week":
|
||||
resultTimeLine = this.getWeekTimeline(startDate, endDate);
|
||||
break;
|
||||
case "month":
|
||||
resultTimeLine = this.getMonthTimeline(startDate, endDate);
|
||||
break;
|
||||
case "year":
|
||||
resultTimeLine = this.getYearTimeline(startDate, endDate);
|
||||
break;
|
||||
default:
|
||||
resultTimeLine = this.getWeekTimeline(startDate, endDate);
|
||||
break;
|
||||
}
|
||||
static getTimeView = (startDate: string, endDate: string) => {
|
||||
const diff = dayjs(endDate).diff(dayjs(startDate), "day");
|
||||
if (diff > 365) {
|
||||
return "year";
|
||||
} else if (diff > 90) {
|
||||
return "month";
|
||||
} else if (diff > 30) {
|
||||
return "week";
|
||||
} else {
|
||||
return "day";
|
||||
}
|
||||
|
||||
return resultTimeLine;
|
||||
};
|
||||
|
||||
static getTimeView = (timeView: TimeViewType, startDate: Dayjs, endDate: Dayjs) => {
|
||||
let resultTimeView = timeView;
|
||||
|
||||
if (startDate.diff(endDate, "day") > 90) {
|
||||
resultTimeView = "month";
|
||||
} else if (startDate.diff(endDate, "day") > 365) {
|
||||
resultTimeView = "year";
|
||||
}
|
||||
|
||||
return resultTimeView;
|
||||
};
|
||||
|
||||
static getDailyTimeline(startDate: Dayjs, endDate: Dayjs): string[] {
|
||||
const now = dayjs();
|
||||
const endOfDay = now.endOf("day");
|
||||
let pivotDate = dayjs(startDate);
|
||||
const dates: string[] = [];
|
||||
while ((pivotDate.isBefore(endDate) || pivotDate.isSame(endDate)) && pivotDate.isBefore(endOfDay)) {
|
||||
dates.push(pivotDate.format("YYYY-MM-DD"));
|
||||
pivotDate = pivotDate.add(1, "day");
|
||||
}
|
||||
return dates;
|
||||
}
|
||||
|
||||
static getWeekTimeline(startDate: Dayjs, endDate: Dayjs): string[] {
|
||||
let pivotDate = dayjs(endDate);
|
||||
const dates: string[] = [];
|
||||
|
||||
// Add the endDate as the last date in the timeline
|
||||
dates.push(pivotDate.format("YYYY-MM-DD"));
|
||||
|
||||
// Move backwards in 6-day increments until reaching or passing the startDate
|
||||
while (pivotDate.isAfter(startDate)) {
|
||||
pivotDate = pivotDate.subtract(7, "day");
|
||||
if (pivotDate.isBefore(startDate)) {
|
||||
break;
|
||||
}
|
||||
dates.push(pivotDate.format("YYYY-MM-DD"));
|
||||
}
|
||||
|
||||
// Reverse the array to have the timeline in ascending order
|
||||
return dates.reverse();
|
||||
}
|
||||
|
||||
static getMonthTimeline(startDate: Dayjs, endDate: Dayjs) {
|
||||
let pivotDate = dayjs(startDate);
|
||||
const dates = [];
|
||||
while (pivotDate.isBefore(endDate)) {
|
||||
pivotDate = pivotDate.set("month", pivotDate.get("month") + 1);
|
||||
|
||||
dates.push(pivotDate.format("YYYY-MM-DD"));
|
||||
}
|
||||
return dates;
|
||||
}
|
||||
|
||||
static getYearTimeline(startDate: Dayjs, endDate: Dayjs) {
|
||||
const pivotDate = dayjs(startDate);
|
||||
const dates = [];
|
||||
while (pivotDate.isBefore(endDate)) {
|
||||
pivotDate.set("year", pivotDate.get("year") + 1);
|
||||
dates.push(pivotDate.format("YYYY-MM-DD"));
|
||||
}
|
||||
return dates;
|
||||
}
|
||||
|
||||
static getPercentage = (actualMetric: number, previousMetric: number) => {
|
||||
const differenceActualVsPrevious = actualMetric - previousMetric;
|
||||
if (differenceActualVsPrevious === 0) {
|
||||
@@ -374,6 +279,127 @@ class EventsInsights {
|
||||
return result;
|
||||
};
|
||||
|
||||
static getDateRanges({
|
||||
startDate: _startDate,
|
||||
endDate: _endDate,
|
||||
timeZone,
|
||||
timeView,
|
||||
weekStart,
|
||||
}: GetDateRangesParams): DateRange[] {
|
||||
if (!["day", "week", "month", "year"].includes(timeView)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const startDate = dayjs(_startDate).tz(timeZone);
|
||||
const endDate = dayjs(_endDate).tz(timeZone);
|
||||
const ranges: DateRange[] = [];
|
||||
let currentStartDate = startDate;
|
||||
|
||||
while (currentStartDate.isBefore(endDate)) {
|
||||
let currentEndDate = currentStartDate.endOf(timeView).tz(timeZone);
|
||||
|
||||
// Adjust week boundaries based on weekStart parameter
|
||||
if (timeView === "week") {
|
||||
const weekStartNum =
|
||||
{
|
||||
Sunday: 0,
|
||||
Monday: 1,
|
||||
Tuesday: 2,
|
||||
Wednesday: 3,
|
||||
Thursday: 4,
|
||||
Friday: 5,
|
||||
Saturday: 6,
|
||||
}[weekStart] ?? 0;
|
||||
|
||||
currentEndDate = currentEndDate.add(weekStartNum, "day");
|
||||
if (currentEndDate.subtract(7, "day").isAfter(currentStartDate)) {
|
||||
currentEndDate = currentEndDate.subtract(7, "day");
|
||||
}
|
||||
}
|
||||
|
||||
if (currentEndDate.isAfter(endDate)) {
|
||||
currentEndDate = endDate;
|
||||
ranges.push({
|
||||
startDate: currentStartDate.toISOString(),
|
||||
endDate: currentEndDate.toISOString(),
|
||||
formattedDate: this.formatPeriod({
|
||||
start: currentStartDate,
|
||||
end: currentEndDate,
|
||||
timeView,
|
||||
wholeStart: startDate,
|
||||
wholeEnd: endDate,
|
||||
}),
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
ranges.push({
|
||||
startDate: currentStartDate.toISOString(),
|
||||
endDate: currentEndDate.toISOString(),
|
||||
formattedDate: this.formatPeriod({
|
||||
start: currentStartDate,
|
||||
end: currentEndDate,
|
||||
timeView,
|
||||
wholeStart: startDate,
|
||||
wholeEnd: endDate,
|
||||
}),
|
||||
});
|
||||
|
||||
currentStartDate = currentEndDate.add(1, "day").startOf("day").tz(timeZone);
|
||||
}
|
||||
|
||||
return ranges;
|
||||
}
|
||||
|
||||
static formatPeriod({
|
||||
start,
|
||||
end,
|
||||
timeView,
|
||||
wholeStart,
|
||||
wholeEnd,
|
||||
}: {
|
||||
start: dayjs.Dayjs;
|
||||
end: dayjs.Dayjs;
|
||||
timeView: TimeViewType;
|
||||
wholeStart: dayjs.Dayjs;
|
||||
wholeEnd: dayjs.Dayjs;
|
||||
}): string {
|
||||
const omitYear = wholeStart.year() === wholeEnd.year();
|
||||
|
||||
switch (timeView) {
|
||||
case "day":
|
||||
const shouldShowMonth = wholeStart.isSame(start, "day") || start.date() === 1;
|
||||
|
||||
if (shouldShowMonth) {
|
||||
return omitYear ? start.format("MMM D") : start.format("MMM D, YYYY");
|
||||
} else {
|
||||
return omitYear ? start.format("D") : start.format("D, YYYY");
|
||||
}
|
||||
case "week":
|
||||
const startFormat = "MMM D";
|
||||
let endFormat = "MMM D";
|
||||
if (start.format("MMM") === end.format("MMM")) {
|
||||
endFormat = "D";
|
||||
}
|
||||
|
||||
if (start.format("YYYY") !== end.format("YYYY")) {
|
||||
return `${start.format(`${startFormat} , YYYY`)} - ${end.format(`${endFormat}, YYYY`)}`;
|
||||
}
|
||||
|
||||
if (omitYear) {
|
||||
return `${start.format(startFormat)} - ${end.format(endFormat)}`;
|
||||
} else {
|
||||
return `${start.format(startFormat)} - ${end.format(endFormat)}, ${end.format("YYYY")}`;
|
||||
}
|
||||
case "month":
|
||||
return omitYear ? start.format("MMM") : start.format("MMM YYYY");
|
||||
case "year":
|
||||
return start.format("YYYY");
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
static getCsvData = async (
|
||||
props: RawDataInput & {
|
||||
organizationId: number | null;
|
||||
|
||||
@@ -15,7 +15,7 @@ import { router } from "@calcom/trpc/server/trpc";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { EventsInsights } from "./events";
|
||||
import { EventsInsights, type GetDateRangesParams } from "./events";
|
||||
import { RoutingEventsInsights } from "./routing-events";
|
||||
import { VirtualQueuesInsights } from "./virtual-queues";
|
||||
|
||||
@@ -334,8 +334,8 @@ export const insightsRouter = router({
|
||||
const baseWhereCondition = {
|
||||
...whereConditional,
|
||||
createdAt: {
|
||||
gte: dayjs(startDate).startOf("day").toDate(),
|
||||
lte: dayjs(endDate).endOf("day").toDate(),
|
||||
gte: startDate,
|
||||
lte: endDate,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -447,120 +447,77 @@ export const insightsRouter = router({
|
||||
|
||||
return result;
|
||||
}),
|
||||
eventsTimeline: userBelongsToTeamProcedure
|
||||
.input(
|
||||
rawDataInputSchema.extend({
|
||||
timeView: z.enum(["week", "month", "year", "day"]),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const {
|
||||
teamId,
|
||||
eventTypeId,
|
||||
memberUserId,
|
||||
isAll,
|
||||
startDate: startDateString,
|
||||
endDate: endDateString,
|
||||
timeView: inputTimeView,
|
||||
userId: selfUserId,
|
||||
} = input;
|
||||
eventsTimeline: userBelongsToTeamProcedure.input(rawDataInputSchema).query(async ({ ctx, input }) => {
|
||||
const { teamId, eventTypeId, memberUserId, isAll, startDate, endDate, userId: selfUserId } = input;
|
||||
if (selfUserId && ctx.user?.id !== selfUserId) {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
|
||||
// Convert to UTC without shifting the time zone
|
||||
let startDate = dayjs.utc(startDateString).startOf("day");
|
||||
let endDate = dayjs.utc(endDateString).endOf("day");
|
||||
if (!teamId && !selfUserId) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (selfUserId && ctx.user?.id !== selfUserId) {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
const timeView = EventsInsights.getTimeView(startDate, endDate);
|
||||
const r = await buildBaseWhereCondition({
|
||||
teamId,
|
||||
eventTypeId: eventTypeId ?? undefined,
|
||||
memberUserId: memberUserId ?? undefined,
|
||||
userId: selfUserId ?? undefined,
|
||||
isAll: isAll ?? false,
|
||||
ctx: {
|
||||
userIsOwnerAdminOfParentTeam: ctx.user.isOwnerAdminOfParentTeam,
|
||||
userOrganizationId: ctx.user.organizationId,
|
||||
insightsDb: ctx.insightsDb,
|
||||
},
|
||||
});
|
||||
|
||||
const { whereCondition: whereConditional } = r;
|
||||
|
||||
const dateRanges = EventsInsights.getDateRanges({
|
||||
startDate,
|
||||
endDate,
|
||||
timeView,
|
||||
timeZone: ctx.user.timeZone,
|
||||
weekStart: ctx.user.weekStart as GetDateRangesParams["weekStart"],
|
||||
});
|
||||
if (!dateRanges.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Fetch counts grouped by status for the entire range
|
||||
const countsByStatus = await EventsInsights.countGroupedByStatusForRanges(
|
||||
whereConditional,
|
||||
dayjs(startDate),
|
||||
dayjs(endDate),
|
||||
dateRanges
|
||||
);
|
||||
|
||||
const result = dateRanges.map(({ formattedDate }) => {
|
||||
const EventData = {
|
||||
Month: formattedDate,
|
||||
Created: 0,
|
||||
Completed: 0,
|
||||
Rescheduled: 0,
|
||||
Cancelled: 0,
|
||||
"No-Show (Host)": 0,
|
||||
"No-Show (Guest)": 0,
|
||||
};
|
||||
|
||||
const countsForDateRange = countsByStatus[formattedDate];
|
||||
|
||||
if (countsForDateRange) {
|
||||
EventData["Created"] = countsForDateRange["_all"] || 0;
|
||||
EventData["Completed"] = countsForDateRange["completed"] || 0;
|
||||
EventData["Rescheduled"] = countsForDateRange["rescheduled"] || 0;
|
||||
EventData["Cancelled"] = countsForDateRange["cancelled"] || 0;
|
||||
EventData["No-Show (Host)"] = countsForDateRange["noShowHost"] || 0;
|
||||
EventData["No-Show (Guest)"] = countsForDateRange["noShowGuests"] || 0;
|
||||
}
|
||||
return EventData;
|
||||
});
|
||||
|
||||
if (!teamId && !selfUserId) {
|
||||
return [];
|
||||
}
|
||||
|
||||
let timeView = inputTimeView;
|
||||
|
||||
// Adjust the timeView if the range is less than 14 days
|
||||
if (timeView === "week" && endDate.diff(startDate, "day") < 14) {
|
||||
timeView = "day";
|
||||
}
|
||||
|
||||
// Align startDate to the Monday of the week if timeView is 'week'
|
||||
if (timeView === "week") {
|
||||
startDate = startDate.day(1); // Set startDate to Monday
|
||||
endDate = endDate.day(1).add(6, "day").endOf("day"); // Set endDate to Sunday of the same week
|
||||
}
|
||||
|
||||
const r = await buildBaseWhereCondition({
|
||||
teamId,
|
||||
eventTypeId: eventTypeId ?? undefined,
|
||||
memberUserId: memberUserId ?? undefined,
|
||||
userId: selfUserId ?? undefined,
|
||||
isAll: isAll ?? false,
|
||||
ctx: {
|
||||
userIsOwnerAdminOfParentTeam: ctx.user.isOwnerAdminOfParentTeam,
|
||||
userOrganizationId: ctx.user.organizationId,
|
||||
insightsDb: ctx.insightsDb,
|
||||
},
|
||||
});
|
||||
|
||||
const { whereCondition: whereConditional } = r;
|
||||
const timeline = await EventsInsights.getTimeLine(timeView, startDate, endDate);
|
||||
|
||||
if (!timeline) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const dateFormat: string = timeView === "year" ? "YYYY" : timeView === "month" ? "MMM YYYY" : "ll";
|
||||
|
||||
// Align date ranges consistently with weeks starting on Monday
|
||||
const dateRanges = timeline.map((date) => {
|
||||
let startOfRange = dayjs.utc(date).startOf(timeView);
|
||||
let endOfRange = dayjs.utc(date).endOf(timeView);
|
||||
|
||||
if (timeView === "week") {
|
||||
startOfRange = dayjs.utc(date).day(1); // Start at Monday in UTC
|
||||
endOfRange = startOfRange.add(6, "day").endOf("day"); // End at Sunday in UTC
|
||||
}
|
||||
|
||||
return {
|
||||
startDate: startOfRange.toISOString(),
|
||||
endDate: endOfRange.toISOString(),
|
||||
formattedDate: startOfRange.format(dateFormat), // Align formatted date for consistency
|
||||
};
|
||||
});
|
||||
// Fetch counts grouped by status for the entire range
|
||||
const countsByStatus = await EventsInsights.countGroupedByStatusForRanges(
|
||||
whereConditional,
|
||||
startDate,
|
||||
endDate,
|
||||
timeView
|
||||
);
|
||||
const result = dateRanges.map(({ formattedDate }) => {
|
||||
const EventData = {
|
||||
Month: formattedDate,
|
||||
Created: 0,
|
||||
Completed: 0,
|
||||
Rescheduled: 0,
|
||||
Cancelled: 0,
|
||||
"No-Show (Host)": 0,
|
||||
"No-Show (Guest)": 0,
|
||||
};
|
||||
|
||||
const countsForDateRange = countsByStatus[formattedDate];
|
||||
|
||||
if (countsForDateRange) {
|
||||
EventData["Created"] = countsForDateRange["_all"] || 0;
|
||||
EventData["Completed"] = countsForDateRange["completed"] || 0;
|
||||
EventData["Rescheduled"] = countsForDateRange["rescheduled"] || 0;
|
||||
EventData["Cancelled"] = countsForDateRange["cancelled"] || 0;
|
||||
EventData["No-Show (Host)"] = countsForDateRange["noShowHost"] || 0;
|
||||
EventData["No-Show (Guest)"] = countsForDateRange["noShowGuests"] || 0;
|
||||
}
|
||||
return EventData;
|
||||
});
|
||||
|
||||
return result;
|
||||
}),
|
||||
return result;
|
||||
}),
|
||||
popularEventTypes: userBelongsToTeamProcedure.input(rawDataInputSchema).query(async ({ ctx, input }) => {
|
||||
const { teamId, startDate, endDate, memberUserId, userId, isAll, eventTypeId } = input;
|
||||
|
||||
@@ -592,8 +549,8 @@ export const insightsRouter = router({
|
||||
bookingWhere = {
|
||||
...bookingWhere,
|
||||
createdAt: {
|
||||
gte: dayjs(startDate).toISOString(),
|
||||
lte: dayjs(endDate).toISOString(),
|
||||
gte: startDate,
|
||||
lte: endDate,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -691,15 +648,7 @@ export const insightsRouter = router({
|
||||
return result;
|
||||
}),
|
||||
averageEventDuration: userBelongsToTeamProcedure.input(rawDataInputSchema).query(async ({ ctx, input }) => {
|
||||
const {
|
||||
teamId,
|
||||
startDate: startDateString,
|
||||
endDate: endDateString,
|
||||
memberUserId,
|
||||
userId,
|
||||
eventTypeId,
|
||||
isAll,
|
||||
} = input;
|
||||
const { teamId, startDate, endDate, memberUserId, userId, eventTypeId, isAll } = input;
|
||||
|
||||
if (userId && ctx.user?.id !== userId) {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
@@ -709,9 +658,6 @@ export const insightsRouter = router({
|
||||
return [];
|
||||
}
|
||||
|
||||
const startDate = dayjs.utc(startDateString).startOf("day");
|
||||
const endDate = dayjs.utc(endDateString).endOf("day");
|
||||
|
||||
const { whereCondition: whereConditional } = await buildBaseWhereCondition({
|
||||
teamId,
|
||||
eventTypeId: eventTypeId ?? undefined,
|
||||
@@ -725,10 +671,16 @@ export const insightsRouter = router({
|
||||
},
|
||||
});
|
||||
|
||||
const timeView = EventsInsights.getTimeView("week", startDate, endDate);
|
||||
const timeLine = await EventsInsights.getTimeLine("week", startDate, endDate);
|
||||
const timeView = EventsInsights.getTimeView(startDate, endDate);
|
||||
const dateRanges = EventsInsights.getDateRanges({
|
||||
startDate,
|
||||
endDate,
|
||||
timeView,
|
||||
timeZone: ctx.user.timeZone,
|
||||
weekStart: ctx.user.weekStart as GetDateRangesParams["weekStart"],
|
||||
});
|
||||
|
||||
if (!timeLine) {
|
||||
if (!dateRanges.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -742,16 +694,17 @@ export const insightsRouter = router({
|
||||
where: {
|
||||
...whereConditional,
|
||||
createdAt: {
|
||||
gte: startDate.toDate(),
|
||||
lte: endDate.toDate(),
|
||||
gte: startDate,
|
||||
lte: endDate,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const resultMap = new Map<string, { totalDuration: number; count: number }>();
|
||||
|
||||
for (const date of timeLine) {
|
||||
resultMap.set(dayjs(date).startOf(startOfEndOf).format("ll"), { totalDuration: 0, count: 0 });
|
||||
// Initialize the map with all date ranges
|
||||
for (const range of dateRanges) {
|
||||
resultMap.set(dayjs(range.startDate).format("ll"), { totalDuration: 0, count: 0 });
|
||||
}
|
||||
|
||||
for (const booking of allBookings) {
|
||||
@@ -798,8 +751,8 @@ export const insightsRouter = router({
|
||||
bookingWhere = {
|
||||
...bookingWhere,
|
||||
createdAt: {
|
||||
gte: dayjs(startDate).startOf("day").toDate(),
|
||||
lte: dayjs(endDate).endOf("day").toDate(),
|
||||
gte: startDate,
|
||||
lte: endDate,
|
||||
},
|
||||
status: "CANCELLED",
|
||||
};
|
||||
@@ -881,8 +834,8 @@ export const insightsRouter = router({
|
||||
bookingWhere = {
|
||||
...bookingWhere,
|
||||
createdAt: {
|
||||
gte: dayjs(startDate).startOf("day").toDate(),
|
||||
lte: dayjs(endDate).endOf("day").toDate(),
|
||||
gte: startDate,
|
||||
lte: endDate,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -962,8 +915,8 @@ export const insightsRouter = router({
|
||||
bookingWhere = {
|
||||
...bookingWhere,
|
||||
createdAt: {
|
||||
gte: dayjs(startDate).startOf("day").toDate(),
|
||||
lte: dayjs(endDate).endOf("day").toDate(),
|
||||
gte: startDate,
|
||||
lte: endDate,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1217,8 +1170,8 @@ export const insightsRouter = router({
|
||||
bookingWhere = {
|
||||
...bookingWhere,
|
||||
createdAt: {
|
||||
gte: dayjs(startDate).startOf("day").toDate(),
|
||||
lte: dayjs(endDate).endOf("day").toDate(),
|
||||
gte: startDate,
|
||||
lte: endDate,
|
||||
},
|
||||
ratingFeedback: { not: null },
|
||||
};
|
||||
@@ -1333,8 +1286,8 @@ export const insightsRouter = router({
|
||||
bookingWhere = {
|
||||
...bookingWhere,
|
||||
createdAt: {
|
||||
gte: dayjs(startDate).startOf("day").toDate(),
|
||||
lte: dayjs(endDate).endOf("day").toDate(),
|
||||
gte: startDate,
|
||||
lte: endDate,
|
||||
},
|
||||
noShowHost: true,
|
||||
};
|
||||
@@ -1411,8 +1364,8 @@ export const insightsRouter = router({
|
||||
bookingWhere = {
|
||||
...bookingWhere,
|
||||
createdAt: {
|
||||
gte: dayjs(startDate).startOf("day").toDate(),
|
||||
lte: dayjs(endDate).endOf("day").toDate(),
|
||||
gte: startDate,
|
||||
lte: endDate,
|
||||
},
|
||||
rating: { not: null },
|
||||
};
|
||||
@@ -1489,8 +1442,8 @@ export const insightsRouter = router({
|
||||
bookingWhere = {
|
||||
...bookingWhere,
|
||||
createdAt: {
|
||||
gte: dayjs(startDate).startOf("day").toDate(),
|
||||
lte: dayjs(endDate).endOf("day").toDate(),
|
||||
gte: startDate,
|
||||
lte: endDate,
|
||||
},
|
||||
rating: { not: null },
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user