Files
cal.diy/packages/features/insights/services/InsightsRoutingBaseService.ts
T
6923b97cd2 feat: upgrade Prisma to 6.16.0 with no-rust engine (#23816)
* feat: upgrade Prisma to 6.16.0 with no-rust engine

- Update Prisma packages to 6.16.0
- Add PostgreSQL adapter dependency
- Configure engineType: 'client' and provider: 'prisma-client' in schema
- Update Prisma client instantiation with PostgreSQL adapter
- Remove binaryTargets from generators (not needed with library engine)
- Fix schema view issue by removing @id decorator from BookingTimeStatusDenormalized
- Fix ESLint warning by removing non-null assertion

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* Web app running but types wrecked

* web app running but build and type issues

* Removed the connection pool

* Fixed zod type issue

* Fixed types in booking reference extension

* Fixed test issues

* Type checks passing it seems

* Using cjs as moduleFormat

* Fixing Prisma undefined

* fix: update prismock initialization for Prisma 6.16 compatibility

- Add @prisma/internals dependency for getDMMF()
- Restructure prismock initialization to use createPrismock() with DMMF
- Create Proxy that's returned from mock factory for proper spy support
- Fixes 89 failing unit tests with 'Cannot read properties of undefined (reading datamodel)' error
- Based on workaround from prismock issue #1482

All unit tests now pass (375 test files, 3323 tests passed)

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: cast serviceAccountKey to Prisma.InputJsonValue in bookingScenario.ts

- Apply type cast at lines 2493 and 2535
- Fixes type errors from Prisma 6.16 upgrade
- Follows established pattern from delegationCredential.ts
- Add eslint-disable for pre-existing any types
- Rename unused appStoreLookupKey parameter to satisfy lint
- All 3323 tests passing

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* chore: remove whitespace-only lines from bookingScenario.ts

- Remove blank lines where eslint-disable comments were replaced
- Cleanup from pre-commit hook formatting

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* Update is-prisma-available-check.ts

* fix: remove datasources config when using Prisma Driver Adapters

- Update customPrisma to create new adapter when datasources URL is provided
- Remove datasources config from API v2 Prisma services (already in adapter)
- Fixes 'Custom datasource configuration is not compatible with Prisma Driver Adapters' error

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: use Pool instances for PrismaPg adapters in index.ts

- Create Pool instance before passing to PrismaPg adapter
- Update customPrisma to create Pool for custom connection strings
- Matches working pattern from API v2 services
- Fixes 'Invalid `prisma.$queryRawUnsafe()` invocation' error

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* Not using queryRawUnsafe

* Trying anything at this point

* Make sure the DB is ready first

* Don't auto run migrations in CI mode

* Revert "Make sure the DB is ready first"

This reverts commit 2b20bd45c974f3d7e07d8b904bc7fcdae37cce03.

* Dynamic import of prisma

* Commenting where it seems to break

* Backwards compatability for API v2

* fix: add explicit type annotations for map callbacks in API v2

- Add type annotation for map parameter in memberships.repository.ts
- Add type annotation for map parameter in stripe.service.ts
- Fixes implicit 'any' type errors from stricter Prisma 6.16.0 type inference

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: add explicit type annotations for API v2 map callbacks

- users.repository.ts:292: add Profile & { user: User } type
- memberships.service.ts:19-20: add Membership type to filter callbacks

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: add explicit type annotation for attributeToUser in organizations-users.repository.ts

- organizations-users.repository.ts:63: add AttributeToUser with nested relations type

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: add explicit Membership type annotations in teams.repository.ts

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: use API v2 dedicated Prisma client to support adapter in PrismaClientOptions

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* Running API v2 build commands together so they all get the space size var

* Fixing Maximum call depth exceeded error

* fixed type issues

* Trying to make the seed more stable

* Revert "Trying to make the seed more stable"

This reverts commit 1fd4495e6af7acd7981cda7dedec3168979b0e9d.

* Fixed path to prisma client

* Fixed type check

* Fix eslint warnings

* fix: externalize @prisma/adapter-pg and pg in platform-libraries Vite config

- Add @prisma/adapter-pg and pg to external dependencies list
- Add corresponding globals for these packages
- Fix Prisma client aliases to point to packages/prisma/client instead of node_modules
- Add Node.js resolve conditions to prefer Node.js exports
- Keep commonjsOptions.include for proper CommonJS transformation
- Add eslint-disable for __dirname in Vite config file
- Remove problematic prettier/prettier eslint comment

This fixes the 'Extensions.defineExtension is unable to run in this browser environment' error when running yarn generate-swagger in apps/api/v2 after upgrading to Prisma v6.16 with the no-rust engine approach.

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: update Prisma imports in API v2 services to use package path

- Change imports from '../../../generated/prisma/client' to '@calcom/prisma/client'
- Fixes CI error: Cannot find module '../../../../../packages/prisma/generated/prisma/client.ts'
- Aligns with backwards compatibility re-export structure after Prisma v6.16 upgrade

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: remove .ts extension from Prisma client path mapping in tsconfig

- Remove file extension from @calcom/prisma/client path mapping
- Fixes runtime error: Cannot find module '../../../../../packages/prisma/generated/prisma/client.ts'
- TypeScript path mappings should not include file extensions per best practices
- Allows Node.js to correctly resolve to .js files at runtime

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: resolve Prisma 6.16.0 type incompatibilities in bookingScenario tests

- Changed InputPayment.data type from PaymentData to Prisma.InputJsonValue
- Changed createCredentials key parameter from JsonValue to InputJsonValue
- Removed unused PaymentData type definition
- Resolves type errors at lines 709 and 1088 without using 'as any' casts

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: remove non-existent Watchlist fields from test fixtures

- Remove createdById from isLockedOrBlocked.test.ts (lines 15, 20)
- Remove severity and createdById from _post.test.ts (line 110)
- These fields don't exist in Watchlist model schema after Prisma 6.16.0 upgrade
- Resolves TS2353 errors without using 'as any' casts

Relates to PR #23816

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: api v2 imports generated prisma and platform libraries

* fix: resolve type errors from Prisma 6.16 upgrade

- Add missing markdownToSafeHTML import in AppCard.tsx
- Fix organizationId null handling in fresh-booking.test.ts
- Remove non-existent createdById field from Watchlist test utils

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* Put back some external rollups

* Added back the resolve conditions

* Stop using Pool directly

* chore: remove prisma bookingReferenceExtension and update calls

* fix: organizations-admin-not-team-member-event-types.e2e-spec.ts

* chore: bring back POOL in api v2 prisma clients

* chore: remove Pool but await connect

* fixup! chore: remove Pool but await connect

* chore: bring back Pool on all clients

* chore: end pool manually

* chore: test with pool max 1

* chore: e2e test prisma max  pool of 1 connection

* chore: give more control over pool for prisma module with env

* remove pool from base prisma client

* chore: prisma client in libraries use pool

* Fixed types

* chore: log pool events and improve pooling

* Fixing some types and tests

* Changing the parsing of USE_POOL

* fix: ensure Prisma client is connected before seeding to prevent transaction errors

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* chore: adjust pools

* chore: add process.env.USE_POOL to libraries vite config

* fix: v1 _patch reference check bookingRef on the booking find

* fix: v1 get references deleted null for system admin

* test: add integration tests for bookingReference soft-delete behavior

- Add bookingReference.integration-test.ts to test repository methods
- Add handleDeleteCredential.integration-test.ts to test credential deletion cascade
- Add booking-references.integration-test.ts for API v1 integration tests
- All tests verify soft-delete behavior without using mocks
- Tests use real database operations to ensure soft-deleted records persist
- Cover scenarios: replacing references, credential deletion, querying with filters

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* refactor: convert booking-references test to actual API endpoint testing

- Modified _get.ts to export handler function for testing
- Refactored integration test to call API handler instead of directly testing Prisma
- Added timestamps to test data to avoid conflicts
- Tests now verify API layer correctly filters soft-deleted references
- All 4 tests passing

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: add explicit prisma.$connect() call to seed-insights script

With Prisma 6.16 and the PostgreSQL adapter, scripts need to explicitly call $connect() before running database operations to ensure the connection pool is properly initialized. This prevents 'Transaction already closed' errors.

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: add $connect() to main() execution in seed-insights

Both main() and createPerformanceData() entry points need explicit prisma.$connect() calls with the Prisma 6.16 PostgreSQL adapter.

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: always use connection pool for Prisma PostgreSQL adapter

Enable connection pooling by default for the Prisma adapter to prevent
transaction state issues during seed operations. Without a pool, each
operation creates a new connection which can lead to 'Transaction already
closed' errors during heavy database operations like seeding.

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* Revert "fix: always use connection pool for Prisma PostgreSQL adapter"

This reverts commit 6724bb08e42bc0a94846069de83b04db0aeb8e8b.

* fix: enable connection pool for db-seed in cache-db action

Set USE_POOL=true when running yarn db-seed to use connection pooling
with the Prisma PostgreSQL adapter. This prevents 'Transaction already
closed' errors during seeding by maintaining stable database connections.

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: add safety check for undefined ownerForEvent in seed script

Prevent 'Cannot read properties of undefined' error when orgMembersInDBWithProfileId
is empty. This can happen if organization members fail to create or when there's a
duplicate constraint violation causing early return.

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: v1 _patch reference check bookingRef

* fix: increase pool size and add timeout settings to prevent transaction errors

- Increase max connections from 5 to 10
- Add connectionTimeoutMillis: 30000 (30 seconds)
- Add statement_timeout: 60000 (60 seconds)

These settings help prevent 'Unknown transaction status' errors during
heavy database operations like seeding by giving transactions more time
to complete and allowing more concurrent connections.

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* Revert "fix: increase pool size and add timeout settings to prevent transaction errors"

This reverts commit 148264f1f1861dfb09a082937a3e2b49e78fc41a.

* fix: remove standalone execution in seed-app-store to prevent premature disconnect

The seed-app-store.ts file had a standalone main() call at the bottom
that would execute immediately when imported, including a prisma.$disconnect()
in its .finally() block.

This caused issues because:
1. seed.ts imports and calls mainAppStore()
2. The import triggers the standalone main() execution
3. This standalone execution disconnects prisma after completion
4. seed.ts then tries to call mainHugeEventTypesSeed() but prisma is disconnected
5. This leads to 'Unknown transaction status' errors

Fixed by removing the standalone execution since mainAppStore() is already
called programmatically from seed.ts which manages the connection lifecycle.

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: use require.main check to prevent premature disconnect when imported

Added require.main === module check so seed-app-store.ts:
- Runs standalone with proper connection management when executed directly
  via 'yarn seed-app-store' or 'ts-node seed-app-store.ts'
- Does NOT run standalone when imported as a module by seed.ts,
  preventing premature prisma disconnect

This fixes 'Unknown transaction status' errors while maintaining
backward compatibility for direct execution.

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: seed apps before creating users to prevent foreign key constraint violation

Reordered seeding operations to call mainAppStore() before main() because:
- main() creates users with credentials that reference apps via appId foreign key
- mainAppStore() seeds the App table with app records
- Apps must exist before credentials can reference them

This fixes the 'Foreign key constraint violated on Credential_appId_fkey' error
that occurred when creating credentials before the apps they reference existed.

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* Apply suggestion from @cubic-dev-ai[bot]

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* Removing functional changes of deleted: null

* Apply suggestion from @keithwillcode

* refactor: move seedAppData call to bottom of main() in seed.ts

Moved seedAppData() call from seed-app-store.ts to the bottom of main()
in seed.ts to ensure the 'pro' user is created before attempting to
create routing form data for them.

Changes:
- Exported seedAppData function from seed-app-store.ts
- Removed seedAppData() call from the main() export in seed-app-store.ts
- Added seedAppData() call at the bottom of main() in seed.ts
- Updated standalone execution in seed-app-store.ts to still call
  seedAppData() when run directly via 'yarn seed-app-store'

This ensures proper ordering: apps seeded → users created → routing
form data created for existing users.

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* refactor: move routing form seeding from seed-app-store.ts to seed.ts

Moved the routing form seeding logic (previously in seedAppData function)
from seed-app-store.ts to be inline at the bottom of main() in seed.ts.

This ensures the 'pro' user is created before attempting to create routing
form data for them.

Changes:
- Removed seedAppData function and seededForm export from seed-app-store.ts
- Removed import of seedAppData from seed.ts
- Added routing form seeding logic inline at bottom of main() in seed.ts

Seeding order: apps → users (including 'pro') → routing forms

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* fix: add deleted: null filter to bookingReference update operations

- Add deleted: null filter to API v1 PATCH endpoint to prevent updating soft-deleted booking references
- Add deleted: null filter to DailyVideo updateMeetingTokenIfExpired and setEnableRecordingUIAndUserIdForOrganizer
- Add comprehensive test coverage for PATCH endpoint soft-delete behavior
- Tests verify that soft-deleted booking references cannot be updated
- Tests verify that only active booking references can be updated successfully

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* revert: remove deleted: null filters to preserve existing functionality

Per @keithwillcode's feedback, reverting the soft-delete filtering changes to preserve existing functionality in this PR. This PR should focus only on the Prisma upgrade itself.

- Reverted API v1 PATCH endpoint change
- Reverted DailyVideo adapter changes (updateMeetingTokenIfExpired and setEnableRecordingUIAndUserIdForOrganizer)
- Removed test file that was added for soft-delete behavior testing

Addresses comments:
- https://github.com/calcom/cal.com/pull/23816#discussion_r2448854197
- https://github.com/calcom/cal.com/pull/23816#discussion_r2448860594
- https://github.com/calcom/cal.com/pull/23816#discussion_r2448860833

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* test: restore and update booking reference tests to match existing functionality

Updated tests to verify existing behavior where PATCH endpoint can update
booking references regardless of their deleted status. This matches the
current implementation after reverting the deleted: null filters.

Changes:
- Restored test file that was previously deleted
- Updated PATCH tests to expect successful updates of soft-deleted references
- Renamed test suite to 'Existing functionality' to clarify intent
- Tests now verify that the PATCH endpoint preserves existing behavior

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

* test: rename booking-references test to integration-test

The test requires a database connection and should run in the integration
test job, not the unit test job. Renamed from .test.ts to .integration-test.ts
to match the repository's testing conventions.

Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: cal.com <morgan@cal.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2025-10-21 20:02:03 +01:00

1073 lines
34 KiB
TypeScript

import { z } from "zod";
import dayjs from "@calcom/dayjs";
import { makeSqlCondition } from "@calcom/features/data-table/lib/server";
import type { FilterValue, TextFilterValue, TypedColumnFilter } from "@calcom/features/data-table/lib/types";
import type { ColumnFilterType } from "@calcom/features/data-table/lib/types";
import {
isMultiSelectFilterValue,
isTextFilterValue,
isNumberFilterValue,
isSingleSelectFilterValue,
} from "@calcom/features/data-table/lib/utils";
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
import type { DateRange } from "@calcom/features/insights/server/insightsDateUtils";
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
import type { PrismaClient } from "@calcom/prisma";
import { Prisma } from "@calcom/prisma/client";
import type { BookingStatus } from "@calcom/prisma/enums";
import { MembershipRole } from "@calcom/prisma/enums";
export const insightsRoutingServiceOptionsSchema = z.discriminatedUnion("scope", [
z.object({
scope: z.literal("user"),
userId: z.number(),
orgId: z.number().nullish().optional(),
}),
z.object({
scope: z.literal("org"),
userId: z.number(),
orgId: z.number(),
}),
z.object({
scope: z.literal("team"),
userId: z.number(),
orgId: z.number().nullish().optional(),
teamId: z.number(),
}),
]);
export type InsightsRoutingServicePublicOptions = {
scope: "user" | "org" | "team";
userId: number;
orgId: number | null | undefined;
teamId?: number;
};
export type InsightsRoutingServiceOptions = z.infer<typeof insightsRoutingServiceOptionsSchema>;
export type InsightsRoutingServiceFilterOptions = {
startDate: string;
endDate: string;
columnFilters?: TypedColumnFilter<ColumnFilterType>[];
};
export type InsightsRoutingTableItem = {
id: number;
uuid: string | null;
formId: string;
formName: string;
formTeamId: number | null;
formUserId: number;
bookingUid: string | null;
bookingId: number | null;
bookingStatus: BookingStatus | null;
bookingStatusOrder: number | null;
bookingCreatedAt: Date | null;
bookingUserId: number | null;
bookingUserName: string | null;
bookingUserEmail: string | null;
bookingUserAvatarUrl: string | null;
bookingAssignmentReason: string | null;
bookingStartTime: Date | null;
bookingEndTime: Date | null;
eventTypeId: number | null;
eventTypeParentId: number | null;
eventTypeSchedulingType: string | null;
createdAt: Date;
utm_source: string | null;
utm_medium: string | null;
utm_campaign: string | null;
utm_term: string | null;
utm_content: string | null;
bookingAttendees: Array<{
name: string;
timeZone: string;
email: string;
phoneNumber: string | null;
}>;
fields: Array<{
fieldId: string | null;
valueString: string | null;
valueNumber: number | null;
valueStringArray: string[] | null;
}>;
};
const NOTHING_CONDITION = Prisma.sql`1=0`;
// Define allowed column names for sorting to prevent SQL injection
const ALLOWED_SORT_COLUMNS = new Set([
"id",
"uuid",
"formId",
"formName",
"formTeamId",
"formUserId",
"bookingUid",
"bookingId",
"bookingStatus",
"bookingStatusOrder",
"bookingCreatedAt",
"bookingUserId",
"bookingUserName",
"bookingUserEmail",
"bookingUserAvatarUrl",
"bookingAssignmentReason",
"bookingStartTime",
"bookingEndTime",
"eventTypeId",
"eventTypeParentId",
"eventTypeSchedulingType",
"createdAt",
"utm_source",
"utm_medium",
"utm_campaign",
"utm_term",
"utm_content",
]);
type GetConditionsOptions = {
exclude?: {
createdAt?: boolean;
columnFilterIds?: string[];
};
};
export class InsightsRoutingBaseService {
private prisma: PrismaClient;
private options: InsightsRoutingServiceOptions | null;
private filters: InsightsRoutingServiceFilterOptions;
constructor({
prisma,
options,
filters,
}: {
prisma: PrismaClient;
options: InsightsRoutingServicePublicOptions;
filters: InsightsRoutingServiceFilterOptions;
}) {
this.prisma = prisma;
const validation = insightsRoutingServiceOptionsSchema.safeParse(options);
this.options = validation.success ? validation.data : null;
this.filters = filters;
}
/**
* Returns routing funnel data split by the given date ranges.
* @param dateRanges Array of { startDate, endDate, formattedDate }
*/
async getRoutingFunnelData(dateRanges: DateRange[]) {
if (!dateRanges.length) return [];
// Validate date formats
for (const range of dateRanges) {
if (isNaN(Date.parse(range.startDate)) || isNaN(Date.parse(range.endDate))) {
throw new Error(`Invalid date format in range: ${range.startDate} - ${range.endDate}`);
}
}
const baseConditions = await this.getBaseConditions();
// Build the CASE statements for each date range with proper date casting
const caseStatements = dateRanges
.map(
(dateRange) => Prisma.sql`
WHEN "createdAt" >= ${dateRange.startDate}::timestamp AND "createdAt" <= ${dateRange.endDate}::timestamp THEN ${dateRange.formattedDate}
`
)
.reduce((acc, curr) => Prisma.sql`${acc} ${curr}`);
// Single query to get all data grouped by date ranges using CTE
const query = Prisma.sql`
WITH date_ranged_data AS (
SELECT
CASE ${caseStatements}
ELSE NULL
END as "dateRange",
"bookingUid",
"bookingStatus"
FROM "RoutingFormResponseDenormalized" rfrd
WHERE ${baseConditions}
)
SELECT
"dateRange",
COUNT(*) as "totalSubmissions",
COUNT(CASE WHEN "bookingUid" IS NOT NULL THEN 1 END) as "successfulRoutings",
COUNT(CASE WHEN "bookingStatus" NOT IN ('cancelled', 'rejected') THEN 1 END) as "acceptedBookings"
FROM date_ranged_data
WHERE "dateRange" IS NOT NULL
GROUP BY "dateRange"
ORDER BY "dateRange"
`;
const results = await this.prisma.$queryRaw<
Array<{
dateRange: string | null;
totalSubmissions: bigint;
successfulRoutings: bigint;
acceptedBookings: bigint;
}>
>(query);
// Create a map of results by dateRange for easy lookup
const resultsMap = new Map(
results
.filter((row): row is typeof row & { dateRange: string } => row.dateRange !== null)
.map((row) => [
row.dateRange,
{
name: row.dateRange,
totalSubmissions: Number(row.totalSubmissions),
successfulRoutings: Number(row.successfulRoutings),
acceptedBookings: Number(row.acceptedBookings),
},
])
);
// Return all date ranges, filling with 0 values for missing data
return dateRanges.map((dateRange) => {
const existingData = resultsMap.get(dateRange.formattedDate);
const data = existingData || {
name: dateRange.formattedDate,
totalSubmissions: 0,
successfulRoutings: 0,
acceptedBookings: 0,
};
return {
...data,
formattedDateFull: dateRange.formattedDateFull,
};
});
}
/**
* Returns paginated table data for routing form responses.
* @param sorting Array of sorting objects with id and desc properties
* @param limit Number of records to return
* @param offset Number of records to skip
*/
async getTableData({
sorting,
limit,
offset,
}: {
sorting?: Array<{ id: string; desc: boolean }>;
limit: number;
offset: number;
}) {
const baseConditions = await this.getBaseConditions();
// Build ORDER BY clause
const orderByClause = this.buildOrderByClause(sorting);
// Get total count
const totalCountQuery = Prisma.sql`
SELECT COUNT(*) as count
FROM "RoutingFormResponseDenormalized" rfrd
WHERE ${baseConditions}
`;
const totalCountResult = await this.prisma.$queryRaw<Array<{ count: bigint }>>(totalCountQuery);
const totalCount = Number(totalCountResult[0]?.count || 0);
// Get paginated data with JSON aggregation for attendees and fields
const dataQuery = Prisma.sql`
SELECT
rfrd."id",
rfrd."uuid",
rfrd."formId",
rfrd."formName",
rfrd."formTeamId",
rfrd."formUserId",
rfrd."bookingUid",
rfrd."bookingId",
UPPER(rfrd."bookingStatus"::text) as "bookingStatus",
rfrd."bookingStatusOrder",
rfrd."bookingCreatedAt",
rfrd."bookingUserId",
rfrd."bookingUserName",
rfrd."bookingUserEmail",
rfrd."bookingUserAvatarUrl",
rfrd."bookingAssignmentReason",
rfrd."bookingStartTime",
rfrd."bookingEndTime",
rfrd."eventTypeId",
rfrd."eventTypeParentId",
rfrd."eventTypeSchedulingType",
rfrd."createdAt",
rfrd."utm_source",
rfrd."utm_medium",
rfrd."utm_campaign",
rfrd."utm_term",
rfrd."utm_content",
(
SELECT COALESCE(
json_agg(
json_build_object(
'name', a."name",
'timeZone', a."timeZone",
'email', a."email",
'phoneNumber', a."phoneNumber"
)
) FILTER (WHERE a."id" IS NOT NULL),
'[]'::json
)
FROM "Booking" b2
LEFT JOIN "Attendee" a ON a."bookingId" = b2."id"
WHERE b2."uid" = rfrd."bookingUid"
) as "bookingAttendees",
(
SELECT COALESCE(
json_agg(
json_build_object(
'fieldId', f."fieldId",
'valueString', f."valueString",
'valueNumber', f."valueNumber",
'valueStringArray', f."valueStringArray"
)
) FILTER (WHERE f."fieldId" IS NOT NULL),
'[]'::json
)
FROM "RoutingFormResponseField" f
WHERE f."responseId" = rfrd."id"
) as "fields"
FROM "RoutingFormResponseDenormalized" rfrd
WHERE ${baseConditions}
${orderByClause}
LIMIT ${limit}
OFFSET ${offset}
`;
const data = await this.prisma.$queryRaw<Array<InsightsRoutingTableItem>>(dataQuery);
return {
total: totalCount,
data,
};
}
async getRoutingFormStats() {
const baseConditions = await this.getBaseConditions();
// Check if bookingUid filter is applied - if so, return null as metrics don't provide value
const bookingUid = this.filters.columnFilters?.find((filter) => filter.id === "bookingUid");
if (bookingUid && isTextFilterValue(bookingUid.value) && bookingUid.value.data) {
// If bookingUid filter is applied, total count should be either 0 or 1.
// So this metrics doesn't provide any value.
return null;
}
// Get total count
const totalQuery = Prisma.sql`
SELECT COUNT(*) as count
FROM "RoutingFormResponseDenormalized" rfrd
WHERE ${baseConditions}
`;
const totalResult = await this.prisma.$queryRaw<Array<{ count: bigint }>>(totalQuery);
// Get total without booking count
const totalWithoutBookingQuery = Prisma.sql`
SELECT COUNT(*) as count
FROM "RoutingFormResponseDenormalized" rfrd
WHERE (${baseConditions}) AND ("bookingUid" IS NULL)
`;
const totalWithoutBookingResult = await this.prisma.$queryRaw<Array<{ count: bigint }>>(
totalWithoutBookingQuery
);
const total = Number(totalResult[0]?.count || 0);
const totalWithoutBooking = Number(totalWithoutBookingResult[0]?.count || 0);
return {
total,
totalWithoutBooking,
totalWithBooking: total - totalWithoutBooking,
};
}
private buildOrderByClause(sorting?: Array<{ id: string; desc: boolean }>): Prisma.Sql {
if (!sorting || sorting.length === 0) {
return Prisma.sql`ORDER BY "createdAt" DESC`;
}
const orderByParts = sorting
.filter((sort) => ALLOWED_SORT_COLUMNS.has(sort.id))
.map((sort) => {
const direction = sort.desc ? Prisma.sql`DESC` : Prisma.sql`ASC`;
return Prisma.sql`"${Prisma.raw(sort.id)}" ${direction}`;
});
if (orderByParts.length === 0) {
return Prisma.sql`ORDER BY "createdAt" DESC`;
}
return Prisma.sql`ORDER BY ${orderByParts.reduce((acc, part, index) => {
if (index === 0) return part;
return Prisma.sql`${acc}, ${part}`;
})}`;
}
/**
* Returns routed to per period data with pagination support.
* @param period The period type (day, week, month)
* @param limit Optional limit for results
* @param searchQuery Optional search query for user names/emails
*/
async getRoutedToPerPeriodData({
period,
limit,
searchQuery,
}: {
period: "perDay" | "perWeek" | "perMonth";
limit?: number;
searchQuery?: string;
}) {
const dayJsPeriodMap = {
perDay: "day",
perWeek: "week",
perMonth: "month",
} as const;
const dayjsPeriod = dayJsPeriodMap[period];
const startDate = dayjs(this.filters.startDate).startOf(dayjsPeriod).toDate();
const endDate = dayjs(this.filters.endDate).endOf(dayjsPeriod).toDate();
const baseConditions = await this.getBaseConditions({ exclude: { createdAt: true } });
// Build search condition
const searchCondition = searchQuery
? Prisma.sql`("bookingUserName" ILIKE ${`%${searchQuery}%`} OR "bookingUserEmail" ILIKE ${`%${searchQuery}%`})`
: Prisma.sql`1 = 1`;
// Get users who have been routed to during the period
const usersQuerySql = Prisma.sql`
SELECT DISTINCT ON ("bookingUserId")
"bookingUserId" as id,
"bookingUserName" as name,
"bookingUserEmail" as email,
"bookingUserAvatarUrl" as "avatarUrl"
FROM "RoutingFormResponseDenormalized" rfrd
WHERE "bookingUid" IS NOT NULL
AND "bookingUserId" IS NOT NULL
AND "createdAt" >= ${startDate}
AND "createdAt" <= ${endDate}
AND ${baseConditions}
AND ${searchCondition}
ORDER BY "bookingUserId", "createdAt" DESC
${limit ? Prisma.sql`LIMIT ${limit}` : Prisma.empty}
`;
const usersQuery = await this.prisma.$queryRaw<
Array<{
id: number;
name: string | null;
email: string | null;
avatarUrl: string | null;
}>
>(usersQuerySql);
const users = usersQuery;
// Return early if no users found
if (users.length === 0) {
return {
users: {
data: [],
nextCursor: undefined,
},
periodStats: {
data: [],
nextCursor: undefined,
},
};
}
// Get periods with pagination
const periodStatsQuery = Prisma.sql`
WITH RECURSIVE date_range AS (
SELECT date_trunc(${dayjsPeriod}, ${startDate}::timestamp) as date
UNION ALL
SELECT date + (CASE
WHEN ${dayjsPeriod} = 'day' THEN interval '1 day'
WHEN ${dayjsPeriod} = 'week' THEN interval '1 week'
WHEN ${dayjsPeriod} = 'month' THEN interval '1 month'
END)
FROM date_range
WHERE date + (CASE
WHEN ${dayjsPeriod} = 'day' THEN interval '1 day'
WHEN ${dayjsPeriod} = 'week' THEN interval '1 week'
WHEN ${dayjsPeriod} = 'month' THEN interval '1 month'
END) <= date_trunc(${dayjsPeriod}, ${endDate}::timestamp)
),
all_users AS (
SELECT unnest(ARRAY[${Prisma.join(users.map((u) => u.id))}]) as user_id
),
paginated_periods AS (
SELECT date as period_start
FROM date_range
ORDER BY date ASC
${limit ? Prisma.sql`LIMIT ${limit}` : Prisma.empty}
), date_user_combinations AS (
SELECT
period_start,
user_id as "userId"
FROM paginated_periods
CROSS JOIN all_users
),
booking_counts AS (
SELECT
"bookingUserId",
date_trunc(${dayjsPeriod}, "createdAt") as period_start,
COUNT(DISTINCT "bookingId")::integer as total
FROM "RoutingFormResponseDenormalized" rfrd
WHERE "bookingUserId" IN (SELECT user_id FROM all_users)
AND "createdAt" >= (SELECT MIN(period_start) FROM paginated_periods)
AND "createdAt" < (
(SELECT MAX(period_start) FROM paginated_periods)
+ (CASE
WHEN ${dayjsPeriod} = 'day' THEN interval '1 day'
WHEN ${dayjsPeriod} = 'week' THEN interval '1 week'
WHEN ${dayjsPeriod} = 'month' THEN interval '1 month'
END)
)
AND ${baseConditions}
GROUP BY 1, 2
)
SELECT
c."userId",
c.period_start,
COALESCE(b.total, 0)::integer as total
FROM date_user_combinations c
LEFT JOIN booking_counts b ON
b."bookingUserId" = c."userId" AND
b.period_start = c.period_start
ORDER BY c.period_start ASC, c."userId" ASC
`;
const periodStats = await this.prisma.$queryRaw<
Array<{
userId: number;
period_start: Date;
total: number;
}>
>(periodStatsQuery);
// Get statistics for the entire period for comparison
const statsQuerySql = Prisma.sql`
SELECT
"bookingUserId" as "userId",
COUNT(DISTINCT "bookingId")::integer as total_bookings
FROM "RoutingFormResponseDenormalized" rfrd
WHERE "bookingUid" IS NOT NULL
AND "createdAt" >= ${startDate}
AND "createdAt" <= ${endDate}
AND ${baseConditions}
GROUP BY "bookingUserId"
ORDER BY total_bookings ASC
`;
const statsQuery = await this.prisma.$queryRaw<
Array<{
userId: number;
total_bookings: number;
}>
>(statsQuerySql);
// Calculate average and median
const average =
statsQuery.reduce((sum, stat) => sum + Number(stat.total_bookings), 0) / statsQuery.length || 0;
const median = statsQuery[Math.floor(statsQuery.length / 2)]?.total_bookings || 0;
// Create a map of user performance indicators
const userPerformance = statsQuery.reduce((acc, stat) => {
acc[stat.userId] = {
total: stat.total_bookings,
performance:
stat.total_bookings > average
? "above_average"
: stat.total_bookings === median
? "median"
: stat.total_bookings < average
? "below_average"
: "at_average",
};
return acc;
}, {} as Record<number, { total: number; performance: "above_average" | "at_average" | "below_average" | "median" }>);
return {
users: {
data: users.map((user) => ({
...user,
performance: userPerformance[user.id]?.performance || "no_data",
totalBookings: userPerformance[user.id]?.total || 0,
})),
},
periodStats: {
data: periodStats,
},
};
}
/**
* Get routed to per period data for CSV export
* @param period The period type (day, week, month)
* @param searchQuery Optional search query for user names/emails
*/
async getRoutedToPerPeriodCsvData({
period,
searchQuery,
}: {
period: "perDay" | "perWeek" | "perMonth";
searchQuery?: string;
}) {
// Call the main method without limit to get all data
const data = await this.getRoutedToPerPeriodData({
period,
searchQuery,
// No limit = get all data
});
// Transform to CSV format
const userStatsMap = new Map<number, Record<string, number>>();
data.periodStats.data.forEach((stat) => {
const userId = stat.userId;
if (!userStatsMap.has(userId)) {
userStatsMap.set(userId, {});
}
const userStat = userStatsMap.get(userId);
if (userStat) {
userStat[stat.period_start.toISOString()] = stat.total;
}
});
return data.users.data.map((user) => {
const stats = userStatsMap.get(user.id) || {};
const periodData = Object.entries(stats).reduce(
(acc, [periodStart, total]) => ({
...acc,
[`Responses ${dayjs(periodStart).format("YYYY-MM-DD")}`]: total.toString(),
}),
{} as Record<string, string>
);
return {
"User ID": user.id.toString(),
Name: user.name || "",
Email: user.email || "",
"Total Bookings": user.totalBookings.toString(),
Performance: user.performance,
...periodData,
};
});
}
async getBaseConditions(conditionsOptions?: GetConditionsOptions): Promise<Prisma.Sql> {
const authConditions = await this.getAuthorizationConditions();
const filterConditions = await this.getFilterConditions(conditionsOptions);
if (authConditions && filterConditions) {
return Prisma.sql`((${authConditions}) AND (${filterConditions}))`;
} else if (authConditions) {
return Prisma.sql`(${authConditions})`;
} else if (filterConditions) {
return Prisma.sql`(${filterConditions})`;
} else {
return NOTHING_CONDITION;
}
}
async getFilterConditions(conditionsOptions?: GetConditionsOptions): Promise<Prisma.Sql | null> {
const conditions: Prisma.Sql[] = [];
const exclude = (conditionsOptions || {}).exclude || {};
// Date range filtering
if (!exclude.createdAt) {
conditions.push(
Prisma.sql`rfrd."createdAt" >= ${this.filters.startDate}::timestamp AND rfrd."createdAt" <= ${this.filters.endDate}::timestamp`
);
}
const columnFilters = (this.filters.columnFilters || []).filter(
(filter) => !(exclude.columnFilterIds || []).includes(filter.id)
);
// Extract specific filters from columnFilters
// Convert columnFilters array to object for easier access
const filtersMap =
columnFilters.reduce((acc, filter) => {
acc[filter.id] = filter;
return acc;
}, {} as Record<string, TypedColumnFilter<ColumnFilterType>>) || {};
// Extract booking status order filter
const bookingStatusOrder = filtersMap["bookingStatusOrder"];
if (bookingStatusOrder && isMultiSelectFilterValue(bookingStatusOrder.value)) {
const statusCondition = makeSqlCondition(bookingStatusOrder.value);
if (statusCondition) {
conditions.push(Prisma.sql`rfrd."bookingStatusOrder" ${statusCondition}`);
}
}
// Extract booking assignment reason filter
const bookingAssignmentReason = filtersMap["bookingAssignmentReason"];
if (bookingAssignmentReason && isTextFilterValue(bookingAssignmentReason.value)) {
const reasonCondition = makeSqlCondition(bookingAssignmentReason.value);
if (reasonCondition) {
conditions.push(Prisma.sql`rfrd."bookingAssignmentReason" ${reasonCondition}`);
}
}
// Extract booking UID filter
const bookingUid = filtersMap["bookingUid"];
if (bookingUid && isTextFilterValue(bookingUid.value)) {
const uidCondition = makeSqlCondition(bookingUid.value);
if (uidCondition) {
conditions.push(Prisma.sql`rfrd."bookingUid" ${uidCondition}`);
}
}
// Extract attendee name filter
const attendeeName = filtersMap["attendeeName"];
if (attendeeName && isTextFilterValue(attendeeName.value)) {
const nameCondition = this.buildAttendeeSqlCondition(attendeeName.value, "name");
if (nameCondition) {
conditions.push(nameCondition);
}
}
// Extract attendee email filter
const attendeeEmail = filtersMap["attendeeEmail"];
if (attendeeEmail && isTextFilterValue(attendeeEmail.value)) {
const emailCondition = this.buildAttendeeSqlCondition(attendeeEmail.value, "email");
if (emailCondition) {
conditions.push(emailCondition);
}
}
// Extract attendee phone filter
const attendeePhone = filtersMap["attendeePhone"];
if (attendeePhone && isTextFilterValue(attendeePhone.value)) {
const phoneCondition = this.buildAttendeeSqlCondition(attendeePhone.value, "phone");
if (phoneCondition) {
conditions.push(phoneCondition);
}
}
// Extract member user IDs filter (multi-select)
const memberUserIds = filtersMap["bookingUserId"];
if (memberUserIds && isMultiSelectFilterValue(memberUserIds.value)) {
conditions.push(Prisma.sql`rfrd."bookingUserId" = ANY(${memberUserIds.value.data})`);
}
// Extract form ID filter (single-select)
const formId = filtersMap["formId"];
if (formId && isSingleSelectFilterValue(formId.value)) {
const formIdCondition = makeSqlCondition(formId.value);
if (formIdCondition) {
conditions.push(Prisma.sql`rfrd."formId" ${formIdCondition}`);
}
}
const fieldIdSchema = z.string().uuid();
const fieldFilters = (columnFilters || []).filter((filter) => fieldIdSchema.safeParse(filter.id).success);
if (fieldFilters.length > 0) {
const fieldConditions = fieldFilters
.map((fieldFilter) => this.buildFormFieldSqlCondition(fieldFilter.id, fieldFilter.value))
.filter((condition): condition is Prisma.Sql => condition !== null);
if (fieldConditions.length > 0) {
// Join multiple field conditions with AND
const joinedConditions = fieldConditions.reduce((acc, condition, index) => {
if (index === 0) return condition;
return Prisma.sql`(${acc}) AND (${condition})`;
});
conditions.push(joinedConditions);
}
}
if (conditions.length === 0) {
return null;
}
// Join all conditions with AND
return conditions.reduce((acc, condition, index) => {
if (index === 0) return condition;
return Prisma.sql`(${acc}) AND (${condition})`;
});
}
async getAuthorizationConditions(): Promise<Prisma.Sql> {
if (!this.options) {
return NOTHING_CONDITION;
}
const scope = this.options.scope;
const targetId =
scope === "org" ? this.options.orgId : scope === "team" ? this.options.teamId : undefined;
if (targetId && scope !== "user") {
const isOwnerOrAdmin = await this.isOwnerOrAdmin(this.options.userId, targetId);
if (!isOwnerOrAdmin) {
return NOTHING_CONDITION;
}
}
if (scope === "user") {
return Prisma.sql`rfrd."formUserId" = ${this.options.userId} AND rfrd."formTeamId" IS NULL`;
} else if (scope === "org") {
return await this.buildOrgAuthorizationCondition(this.options);
} else if (scope === "team") {
return await this.buildTeamAuthorizationCondition(this.options);
} else {
return NOTHING_CONDITION;
}
}
private async buildOrgAuthorizationCondition(
options: Extract<InsightsRoutingServiceOptions, { scope: "org" }>
): Promise<Prisma.Sql> {
// Get all teams from the organization
const teamRepo = new TeamRepository(this.prisma);
const teamsFromOrg = await teamRepo.findAllByParentId({
parentId: options.orgId,
select: { id: true },
});
const teamIds = [options.orgId, ...teamsFromOrg.map((t) => t.id)];
return Prisma.sql`(rfrd."formTeamId" = ANY(${teamIds})) OR (rfrd."formUserId" = ${options.userId} AND rfrd."formTeamId" IS NULL)`;
}
private async buildTeamAuthorizationCondition(
options: Extract<InsightsRoutingServiceOptions, { scope: "team" }>
): Promise<Prisma.Sql> {
const teamRepo = new TeamRepository(this.prisma);
if (options.orgId) {
// team under org
const childTeamOfOrg = await teamRepo.findByIdAndParentId({
id: options.teamId,
parentId: options.orgId,
select: { id: true },
});
if (!childTeamOfOrg) {
// teamId and its orgId does not match
return NOTHING_CONDITION;
}
} else {
// standalone team
const team = await teamRepo.findById({
id: options.teamId,
});
if (team?.parentId) {
// a team without orgId is not supposed to have parentId
return NOTHING_CONDITION;
}
}
return Prisma.sql`rfrd."formTeamId" = ${options.teamId}`;
}
private async isOwnerOrAdmin(userId: number, targetId: number): Promise<boolean> {
const permissionCheckService = new PermissionCheckService();
return await permissionCheckService.checkPermission({
userId,
teamId: targetId,
permission: "insights.read",
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
});
}
private buildFormFieldSqlCondition(fieldId: string, filterValue: FilterValue): Prisma.Sql | null {
if (isMultiSelectFilterValue(filterValue)) {
// For multi-select fields, check if the field contains any of the selected values
return Prisma.sql`EXISTS (
SELECT 1 FROM "RoutingFormResponseField" rrf
WHERE rrf."responseId" = rfrd."id"
AND rrf."fieldId" = ${fieldId}
AND rrf."valueStringArray" @> ${filterValue.data.map(String)}
)`;
} else if (isSingleSelectFilterValue(filterValue)) {
return Prisma.sql`EXISTS (
SELECT 1 FROM "RoutingFormResponseField" rrf
WHERE rrf."responseId" = rfrd."id"
AND rrf."fieldId" = ${fieldId}
AND rrf."valueString" = ${filterValue.data}
)`;
} else if (isTextFilterValue(filterValue)) {
const condition = makeSqlCondition(filterValue);
if (!condition) {
return null;
}
return Prisma.sql`EXISTS (
SELECT 1 FROM "RoutingFormResponseField" rrf
WHERE rrf."responseId" = rfrd."id"
AND rrf."fieldId" = ${fieldId}
AND rrf."valueString" ${condition}
)`;
} else if (isNumberFilterValue(filterValue)) {
const condition = makeSqlCondition(filterValue);
if (!condition) {
return null;
}
return Prisma.sql`EXISTS (
SELECT 1 FROM "RoutingFormResponseField" rrf
WHERE rrf."responseId" = rfrd."id"
AND rrf."fieldId" = ${fieldId}
AND rrf."valueNumber" ${condition}
)`;
} else {
return null;
}
}
private buildAttendeeSqlCondition(
filterValue: TextFilterValue,
attendeeColumn: "name" | "email" | "phone"
): Prisma.Sql | null {
if (!isTextFilterValue(filterValue)) {
return null;
}
const textCondition = makeSqlCondition(filterValue);
if (!textCondition) {
return null;
}
// Use switch-case to avoid Prisma.raw for column names
let columnCondition: Prisma.Sql;
switch (attendeeColumn) {
case "name":
columnCondition = Prisma.sql`a.name ${textCondition}`;
break;
case "email":
columnCondition = Prisma.sql`a.email ${textCondition}`;
break;
case "phone":
columnCondition = Prisma.sql`a."phoneNumber" ${textCondition}`;
break;
default:
return null;
}
return Prisma.sql`EXISTS (
SELECT 1 FROM "Booking" b
INNER JOIN "Attendee" a ON a."bookingId" = b."id"
WHERE b."uid" = rfrd."bookingUid"
AND ${columnCondition}
)`;
}
async getFailedBookingsByFieldData(): Promise<
Record<string, Record<string, { optionId: string; count: number; optionLabel: string }[]>>
> {
const baseConditions = await this.getBaseConditions();
// Get failed bookings (responses without a successful booking) grouped by form, field, and option
const query = Prisma.sql`
WITH form_fields AS (
SELECT DISTINCT
rfrd."formId" as form_id,
rfrd."formName" as form_name,
field->>'id' as field_id,
field->>'label' as field_label,
opt->>'id' as option_id,
opt->>'label' as option_label
FROM "RoutingFormResponseDenormalized" rfrd
JOIN "App_RoutingForms_Form" f ON rfrd."formId" = f.id,
LATERAL jsonb_array_elements(f.fields) as field
LEFT JOIN LATERAL jsonb_array_elements(field->'options') as opt ON true
WHERE
${baseConditions}
),
response_stats AS (
SELECT
rfrd."formId",
f."fieldId" as field_id,
COALESCE(arr.value, f."valueString", f."valueNumber"::text) as selected_option,
COUNT(DISTINCT rfrd.id) as response_count
FROM "RoutingFormResponseDenormalized" rfrd
JOIN "RoutingFormResponseField" f ON rfrd.id = f."responseId"
LEFT JOIN LATERAL unnest(f."valueStringArray") as arr(value) ON f."valueStringArray" != '{}'
WHERE ${baseConditions}
AND rfrd."bookingUid" IS NULL
AND COALESCE(arr.value, f."valueString", f."valueNumber"::text) IS NOT NULL
GROUP BY rfrd."formId", f."fieldId", COALESCE(arr.value, f."valueString", f."valueNumber"::text)
)
SELECT
ff.form_id as "formId",
ff.form_name as "formName",
ff.field_id as "fieldId",
ff.field_label as "fieldLabel",
ff.option_id as "optionId",
ff.option_label as "optionLabel",
COALESCE(rs.response_count, 0)::integer as count
FROM form_fields ff
LEFT JOIN response_stats rs ON
rs."formId" = ff.form_id AND
rs.field_id = ff.field_id AND
rs.selected_option = ff.option_id
WHERE ff.option_id IS NOT NULL
ORDER BY count DESC
`;
const result = await this.prisma.$queryRaw<
{
formId: string;
formName: string;
fieldId: string;
fieldLabel: string;
optionId: string;
optionLabel: string;
count: number;
}[]
>(query);
// First group by form and field
const groupedByFormAndField = result.reduce((acc, curr) => {
const formKey = curr.formName;
acc[formKey] = acc[formKey] || {};
const labelKey = curr.fieldLabel;
acc[formKey][labelKey] = acc[formKey][labelKey] || [];
acc[formKey][labelKey].push({
optionId: curr.optionId,
count: curr.count,
optionLabel: curr.optionLabel,
});
return acc;
}, {} as Record<string, Record<string, { optionId: string; count: number; optionLabel: string }[]>>);
// NOTE: totalCount represents the sum of all response counts across all fields and options for a form
// For example, if a form has 2 fields with 2 options each:
// Field1: Option1 (5 responses), Option2 (3 responses)
// Field2: Option1 (2 responses), Option2 (4 responses)
// Then totalCount = 5 + 3 + 2 + 4 = 14 total responses
const sortedEntries = Object.entries(groupedByFormAndField)
.map(([formName, fields]) => ({
formName,
fields,
totalCount: Object.values(fields)
.flat()
.reduce((sum, item) => sum + item.count, 0),
}))
.sort((a, b) => b.totalCount - a.totalCount);
// Convert back to original format
const sortedGroupedByFormAndField = sortedEntries.reduce((acc, { formName, fields }) => {
acc[formName] = fields;
return acc;
}, {} as Record<string, Record<string, { optionId: string; count: number; optionLabel: string }[]>>);
return sortedGroupedByFormAndField;
}
}