fix: integer to text comparison in routing insights query (#25019)

* fix: integer to text comparison in routing insights query

Add explicit integer array cast to prevent PostgreSQL type mismatch error when comparing bookingUserId (integer) with user_id array values in getRoutedToPerPeriodData query

* add e2e tests

* refactor: remove LoadingInsight component and handle loading in ChartCard

- Enhanced ChartCard to render default loading UI when isPending is true
- Replaced all LoadingInsight usages with ChartCard that accepts isPending/isError props
- Removed LoadingInsight component and updated exports
- Updated 16 chart components to use the new pattern
- ChartCard now shows spinner and skeleton title during loading state

Co-Authored-By: [email protected] <[email protected]>

* fix: make children prop optional in ChartCard when isPending is true

Co-Authored-By: [email protected] <[email protected]>

* refactor: remove unused loadingState prop from ChartCard

- Remove loadingState prop and ChartLoadingState type export
- Simplify computedLoadingState to derive state only from isPending/isError
- No functional changes - loadingState was not being used by any components
- data-loading-state attribute behavior remains unchanged for E2E tests

Co-Authored-By: [email protected] <[email protected]>

* refactor: remove duplicate isPending early returns from chart components

- Update all 16 chart components to use single ChartCard return pattern
- Gate children rendering with !isPending && isSuccess && data checks
- Prevents data processing code from executing during loading state
- Improves code consistency and maintainability across all charts

Co-Authored-By: [email protected] <[email protected]>

* refactor: remove redundant !isPending check from chart conditionals

- Simplify conditional rendering to use just 'isSuccess && data' or 'isSuccess'
- In TanStack Query, isSuccess and isPending are mutually exclusive
- The !isPending check was redundant since isSuccess already implies !isPending
- Applied to all 16 chart components for consistency
- Components with safe defaults (data ?? []) use just 'isSuccess'
- Components requiring data check use 'isSuccess && data'

Co-Authored-By: [email protected] <[email protected]>

* revert the mistake

* apply feedback

* apply feedback

* fix e2e

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
Eunjae LeeandDevin AI authored and GitHub committed 2025-12-01 15:07:57 +01:00
1 parent 3c46c35b69
commit 6479adf14e
30 files changed
+794 -404

No files matched your search

+288
View File
@@ -0,0 +1,288 @@
import { expect } from "@playwright/test";
import { v4 as uuidv4 } from "uuid";
import { BookingStatus } from "@calcom/prisma/enums";
import { expectAllChartsToLoad, getAllChartIds } from "./lib/chart-helpers";
import { test } from "./lib/fixtures";
test.afterEach(({ users }) => users.deleteAll());
test.describe("Insights > Charts Loading", () => {
test.describe("Routing Insights", () => {
test("all charts should load successfully with data", async ({ page, users, routingForms, prisma }) => {
// Setup: Create routing form with complete data
const owner = await users.create(
{ name: "Chart Test Owner" },
{
hasTeam: true,
isUnpublished: true,
isOrg: true,
hasSubteam: true,
}
);
await owner.apiLogin();
const membership = await owner.getFirstTeamMembership();
// Create a routing form with fields
const formName = "Chart Loading Test Form";
const form = await routingForms.create({
name: formName,
userId: owner.id,
teamId: membership.teamId,
fields: [
{
type: "text",
label: "Name",
identifier: "name",
required: true,
},
{
type: "email",
label: "Email",
identifier: "email",
required: true,
},
{
type: "select",
label: "Department",
identifier: "department",
required: true,
options: [
{
id: uuidv4(),
label: "Sales",
},
{
id: uuidv4(),
label: "Support",
},
],
},
],
});
const fieldIds = (form.fields as Array<{ id: string }>).map((f) => f.id);
// Create users for routing
const user1 = await users.create({ name: "Sales User" });
const user2 = await users.create({ name: "Support User" });
// Add users to the team
await prisma.membership.createMany({
data: [
{
teamId: membership.teamId,
userId: user1.id,
role: "MEMBER",
accepted: true,
},
{
teamId: membership.teamId,
userId: user2.id,
role: "MEMBER",
accepted: true,
},
],
});
// Create bookings for both users
const booking1 = await prisma.booking.create({
data: {
uid: `booking-${uuidv4()}`,
title: "Sales Booking",
startTime: new Date(),
endTime: new Date(Date.now() + 60 * 60 * 1000),
userId: user1.id,
status: BookingStatus.ACCEPTED,
},
});
const booking2 = await prisma.booking.create({
data: {
uid: `booking-${uuidv4()}`,
title: "Support Booking",
startTime: new Date(),
endTime: new Date(Date.now() + 60 * 60 * 1000),
userId: user2.id,
status: BookingStatus.ACCEPTED,
},
});
// Create form responses with bookings
await prisma.app_RoutingForms_FormResponse.create({
data: {
formFillerId: "filler-1",
formId: form.id,
response: {
[fieldIds[0]]: { label: "Name", value: "John Doe" },
[fieldIds[1]]: { label: "Email", value: "[email protected]" },
[fieldIds[2]]: { label: "Department", value: "Sales" },
},
routedToBookingUid: booking1.uid,
},
});
await prisma.app_RoutingForms_FormResponse.create({
data: {
formFillerId: "filler-2",
formId: form.id,
response: {
[fieldIds[0]]: { label: "Name", value: "Jane Smith" },
[fieldIds[1]]: { label: "Email", value: "[email protected]" },
[fieldIds[2]]: { label: "Department", value: "Support" },
},
routedToBookingUid: booking2.uid,
},
});
// Create a response without booking (for "Failed Bookings" chart)
await prisma.app_RoutingForms_FormResponse.create({
data: {
formFillerId: "filler-3",
formId: form.id,
response: {
[fieldIds[0]]: { label: "Name", value: "Bob Wilson" },
[fieldIds[1]]: { label: "Email", value: "[email protected]" },
[fieldIds[2]]: { label: "Department", value: "Sales" },
},
routedToBookingUid: null,
},
});
// Navigate to insights routing page
await page.goto("/insights/routing");
await expect(page).toHaveURL(/\/insights\/routing/);
// Wait for the page to be fully loaded
await page.waitForLoadState("networkidle");
// Get all chart IDs before checking
const chartIds = await getAllChartIds(page);
console.log(`[Routing] Found ${chartIds.length} charts: ${chartIds.join(", ")}`);
// Assert all charts load successfully
await expectAllChartsToLoad(page, 20000); // 20 second timeout for all charts
// Verify specific expected charts are present and loaded
const expectedCharts = ["stats", "routing-funnel", "routed-to-per-period", "failed-bookings-by-field"];
for (const chartId of expectedCharts) {
const chart = page.locator(`[data-testid="chart-card"][data-chart-id="${chartId}"]`);
await expect(chart).toBeVisible();
await expect(chart).toHaveAttribute("data-loading-state", "loaded");
}
// Cleanup
await prisma.booking.delete({ where: { id: booking1.id } });
await prisma.booking.delete({ where: { id: booking2.id } });
});
});
test.describe("Bookings Insights", () => {
test("all charts should load successfully with booking data", async ({
page,
users,
bookings,
prisma,
}) => {
// Setup: Create users with team membership
const owner = await users.create({ name: "Chart Test Owner" });
const member = await users.create({ name: "Chart Test Member" });
// Create team and add both users
const team = await prisma.team.create({
data: {
name: "test-insights-bookings",
slug: `test-insights-bookings-${Date.now()}`,
},
});
await prisma.membership.createMany({
data: [
{
userId: owner.id,
teamId: team.id,
accepted: true,
role: "ADMIN",
},
{
userId: member.id,
teamId: team.id,
accepted: true,
role: "MEMBER",
},
],
});
await owner.apiLogin();
// Create some bookings for the user
const now = new Date();
const tomorrow = new Date(now);
tomorrow.setDate(tomorrow.getDate() + 1);
const dayAfterTomorrow = new Date(tomorrow);
dayAfterTomorrow.setDate(dayAfterTomorrow.getDate() + 1);
const threeDaysFromNow = new Date(dayAfterTomorrow);
threeDaysFromNow.setDate(threeDaysFromNow.getDate() + 1);
// Create bookings at different times to ensure unique idempotency keys
await bookings.create(owner.id, owner.username, owner.eventTypes[0].id, {
status: BookingStatus.ACCEPTED,
startTime: now,
endTime: tomorrow,
});
await bookings.create(owner.id, owner.username, owner.eventTypes[0].id, {
status: BookingStatus.ACCEPTED,
startTime: tomorrow,
endTime: dayAfterTomorrow,
});
await bookings.create(owner.id, owner.username, owner.eventTypes[0].id, {
status: BookingStatus.CANCELLED,
startTime: dayAfterTomorrow,
endTime: threeDaysFromNow,
});
// Navigate to insights bookings page
await page.goto("/insights");
await expect(page).toHaveURL(/\/insights/);
// Wait for the page to be fully loaded
await page.waitForLoadState("networkidle");
// Get all chart IDs before checking
const chartIds = await getAllChartIds(page);
console.log(`[Bookings] Found ${chartIds.length} charts: ${chartIds.join(", ")}`);
// Assert all charts load successfully
await expectAllChartsToLoad(page, 20000); // 20 second timeout for all charts
// Verify specific expected charts are present and loaded
const expectedCharts = [
"events",
"performance",
"event-trends",
"no-show-hosts-over-time",
"csat-over-time",
"bookings-by-hour",
"average-event-duration",
];
for (const chartId of expectedCharts) {
const chart = page.locator(`[data-testid="chart-card"][data-chart-id="${chartId}"]`);
// Chart should exist and be loaded
await expect(chart).toHaveCount(1);
await expect(chart).toHaveAttribute("data-loading-state", "loaded");
}
// Verify no charts are in error state
const errorCharts = page.locator('[data-testid="chart-card"][data-loading-state="error"]');
await expect(errorCharts).toHaveCount(0);
});
});
});
+1 -1
View File
@@ -272,7 +272,7 @@ test.describe("Insights", async () => {
for (const title of expectedChartTitles) {
const chartCard = page
.locator("[data-testid='panel-card'] h2")
.locator("[data-testid='chart-card'] h2")
.filter({ hasText: new RegExp(`^${title}$`) });
await expect(chartCard).toBeVisible();
}
+134
View File
@@ -0,0 +1,134 @@
import { expect, type Page } from "@playwright/test";
export type ChartLoadingState = "initial" | "loading" | "loaded" | "error";
export interface ChartLoadingResult {
chartId: string | null;
loadingState: ChartLoadingState;
success: boolean;
error?: string;
}
/**
* Wait for all chart cards on the page to reach "loaded" state
* @param page Playwright page object
* @param timeout Maximum time to wait for all charts (default: 15000ms)
* @returns Array of chart loading results
*/
export async function waitForAllChartsToLoad(page: Page, timeout = 15000): Promise<ChartLoadingResult[]> {
const startTime = Date.now();
const results: ChartLoadingResult[] = [];
// Wait for at least one chart card to be visible
await page.locator('[data-testid="chart-card"]').first().waitFor({ state: "visible", timeout });
// Get all chart cards
const chartCards = await page.locator('[data-testid="chart-card"]').all();
if (chartCards.length === 0) {
throw new Error("No chart cards found on the page");
}
// Wait for each chart to reach loaded state
for (let i = 0; i < chartCards.length; i++) {
const chart = chartCards[i];
const remainingTime = timeout - (Date.now() - startTime);
if (remainingTime <= 0) {
throw new Error(`Timeout waiting for charts to load after ${timeout}ms`);
}
const chartId = await chart.getAttribute("data-chart-id");
const result: ChartLoadingResult = {
chartId,
loadingState: "initial",
success: false,
};
try {
// Wait for this specific chart to reach loaded state
await expect(chart).toHaveAttribute("data-loading-state", "loaded", {
timeout: remainingTime,
});
result.loadingState = "loaded";
result.success = true;
} catch {
// Get the actual state if it failed
const actualState = await chart.getAttribute("data-loading-state");
result.loadingState = (actualState as ChartLoadingState) || "initial";
result.error = `Chart "${chartId}" failed to load. Current state: ${actualState}`;
result.success = false;
}
results.push(result);
}
return results;
}
/**
* Assert that all charts on the page have loaded successfully
* @param page Playwright page object
* @param timeout Maximum time to wait for all charts (default: 15000ms)
*/
export async function expectAllChartsToLoad(page: Page, timeout = 15000): Promise<void> {
const results = await waitForAllChartsToLoad(page, timeout);
const failedCharts = results.filter((r) => !r.success);
if (failedCharts.length > 0) {
const errorMessages = failedCharts.map((r) => r.error).join("\n");
throw new Error(`${failedCharts.length} chart(s) failed to load:\n${errorMessages}`);
}
// Additional check: ensure no charts are in error state
const errorCharts = page.locator('[data-testid="chart-card"][data-loading-state="error"]');
const errorCount = await errorCharts.count();
if (errorCount > 0) {
const errorChartIds = await Promise.all(
(await errorCharts.all()).map((chart) => chart.getAttribute("data-chart-id"))
);
throw new Error(`${errorCount} chart(s) are in error state: ${errorChartIds.join(", ")}`);
}
}
/**
* Get the loading state of a specific chart by its ID
* @param page Playwright page object
* @param chartId The chart ID (derived from title)
* @returns The loading state of the chart
*/
export async function getChartLoadingState(page: Page, chartId: string): Promise<ChartLoadingState | null> {
const chart = page.locator(`[data-testid="chart-card"][data-chart-id="${chartId}"]`);
const state = await chart.getAttribute("data-loading-state");
return state as ChartLoadingState | null;
}
/**
* Wait for a specific chart to reach loaded state
* @param page Playwright page object
* @param chartId The chart ID (derived from title)
* @param timeout Maximum time to wait (default: 10000ms)
*/
export async function waitForChartToLoad(page: Page, chartId: string, timeout = 10000): Promise<void> {
const chart = page.locator(`[data-testid="chart-card"][data-chart-id="${chartId}"]`);
await expect(chart).toHaveAttribute("data-loading-state", "loaded", { timeout });
}
/**
* Get all chart IDs on the page
* @param page Playwright page object
* @returns Array of chart IDs
*/
export async function getAllChartIds(page: Page): Promise<string[]> {
const chartCards = await page.locator('[data-testid="chart-card"]').all();
const chartIds = await Promise.all(
chartCards.map(async (chart) => {
const id = await chart.getAttribute("data-chart-id");
return id || "unknown";
})
);
return chartIds;
}