refactor: FailedBookingsByField to use Insights Routing Service (#23259)
* refactor: FailedBookingsByField to use Insights Routing Service - Move getFailedBookingsByRoutingFormGroup logic to InsightsRoutingBaseService - Replace legacy getWhereForTeamOrAllTeams with getBaseConditions() - Add failedBookingsByFieldInputSchema with date filtering support - Update tRPC endpoint to use createInsightsRoutingService pattern - Update component to pass startDate/endDate parameters - Remove legacy method from routing-events.ts Follows same pattern as PR #23031 for RoutedToPerPeriod refactoring Co-Authored-By: [email protected] <[email protected]> * fix: use useInsightsRoutingParameters hook in FailedBookingsByField - Add missing import for useInsightsRoutingParameters - Update component to follow same pattern as PR #23031 - Add columnFilters support to failedBookingsByFieldInputSchema - Maintain routingFormId parameter from useInsightsParameters Co-Authored-By: [email protected] <[email protected]> * refactor: remove separate routingFormId parameter - Remove routingFormId parameter from getFailedBookingsByFieldData method - Update component to only use insightsRoutingParameters - Remove routingFormId from failedBookingsByFieldInputSchema - Let getBaseConditions handle all filtering including routing form filtering - Simplify tRPC endpoint to not pass separate routingFormId Co-Authored-By: [email protected] <[email protected]> * clean up * fix * refactor: use RoutingFormResponseDenormalized directly in getFailedBookingsByFieldData - Replace complex CTE approach with direct denormalized table query - Join with App_RoutingForms_Form to access field definitions from JSON - Use RoutingFormResponseField for response values - Filter failed bookings with bookingUid IS NULL - Maintain same data structure for UI compatibility - Follow existing service patterns for authorization and date filtering Co-Authored-By: [email protected] <[email protected]> * fixing failed bookings query * fix query * fix integration test --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
7145a2d640
commit
a494428334
5 files changed
+190
-286
No files matched your search
@@ -16,7 +16,7 @@ import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc";
|
||||
import { ToggleGroup } from "@calcom/ui/components/form";
|
||||
|
||||
import { useInsightsParameters } from "../../hooks/useInsightsParameters";
|
||||
import { useInsightsRoutingParameters } from "../../hooks/useInsightsRoutingParameters";
|
||||
import { ChartCard } from "../ChartCard";
|
||||
|
||||
// Custom Tooltip component
|
||||
@@ -131,13 +131,8 @@ function FormCard({ formName, fields }: FormCardProps) {
|
||||
|
||||
export function FailedBookingsByField() {
|
||||
const { t } = useLocale();
|
||||
const { userId, teamId, startDate, endDate, isAll, routingFormId } = useInsightsParameters();
|
||||
const { data } = trpc.viewer.insights.failedBookingsByField.useQuery({
|
||||
userId,
|
||||
teamId,
|
||||
isAll,
|
||||
routingFormId,
|
||||
});
|
||||
const insightsRoutingParams = useInsightsRoutingParameters();
|
||||
const { data } = trpc.viewer.insights.failedBookingsByField.useQuery(insightsRoutingParams);
|
||||
|
||||
if (!data || Object.entries(data).length === 0) return null;
|
||||
|
||||
|
||||
@@ -214,143 +214,6 @@ class RoutingEventsInsights {
|
||||
return fields;
|
||||
}
|
||||
|
||||
static async getFailedBookingsByRoutingFormGroup({
|
||||
userId,
|
||||
teamId,
|
||||
isAll,
|
||||
routingFormId,
|
||||
organizationId,
|
||||
}: RoutingFormInsightsTeamFilter) {
|
||||
const formsWhereCondition = await this.getWhereForTeamOrAllTeams({
|
||||
userId,
|
||||
teamId,
|
||||
isAll,
|
||||
organizationId,
|
||||
routingFormId,
|
||||
});
|
||||
|
||||
const teamConditions = [];
|
||||
|
||||
// @ts-expect-error it doesn't exist but TS isn't smart enough when it's a number or int filter
|
||||
if (formsWhereCondition.teamId?.in) {
|
||||
// @ts-expect-error it doesn't exist but TS isn't smart enough when it's a number or int filter
|
||||
teamConditions.push(`f."teamId" IN (${formsWhereCondition.teamId.in.join(",")})`);
|
||||
}
|
||||
// @ts-expect-error it doesn't exist but TS isn't smart enough when it's a number or int filter
|
||||
if (!formsWhereCondition.teamId?.in && userId) {
|
||||
teamConditions.push(`f."userId" = ${userId}`);
|
||||
}
|
||||
if (routingFormId) {
|
||||
teamConditions.push(`f.id = '${routingFormId}'`);
|
||||
}
|
||||
|
||||
const whereClause = teamConditions.length
|
||||
? Prisma.sql`AND ${Prisma.raw(teamConditions.join(" AND "))}`
|
||||
: Prisma.sql``;
|
||||
|
||||
// If you're at this point wondering what this does. This groups the responses by form and field and counts the number of responses for each option that don't have a booking.
|
||||
const result = await prisma.$queryRaw<
|
||||
{
|
||||
formId: string;
|
||||
formName: string;
|
||||
fieldId: string;
|
||||
fieldLabel: string;
|
||||
optionId: string;
|
||||
optionLabel: string;
|
||||
count: number;
|
||||
}[]
|
||||
>`
|
||||
WITH form_fields AS (
|
||||
SELECT
|
||||
f.id as form_id,
|
||||
f.name as form_name,
|
||||
field->>'id' as field_id,
|
||||
field->>'label' as field_label,
|
||||
opt->>'id' as option_id,
|
||||
opt->>'label' as option_label
|
||||
FROM "App_RoutingForms_Form" f,
|
||||
LATERAL jsonb_array_elements(f.fields) as field
|
||||
LEFT JOIN LATERAL jsonb_array_elements(field->'options') as opt ON true
|
||||
WHERE true
|
||||
${whereClause}
|
||||
),
|
||||
response_stats AS (
|
||||
SELECT
|
||||
r."formId",
|
||||
key as field_id,
|
||||
CASE
|
||||
WHEN jsonb_typeof(value->'value') = 'array' THEN
|
||||
v.value_item
|
||||
ELSE
|
||||
value->>'value'
|
||||
END as selected_option,
|
||||
COUNT(DISTINCT r.id) as response_count
|
||||
FROM "App_RoutingForms_FormResponse" r
|
||||
CROSS JOIN jsonb_each(r.response::jsonb) as fields(key, value)
|
||||
LEFT JOIN LATERAL jsonb_array_elements_text(
|
||||
CASE
|
||||
WHEN jsonb_typeof(value->'value') = 'array'
|
||||
THEN value->'value'
|
||||
ELSE NULL
|
||||
END
|
||||
) as v(value_item) ON true
|
||||
WHERE r."routedToBookingUid" IS NULL
|
||||
GROUP BY r."formId", key, selected_option
|
||||
)
|
||||
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`;
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
static async getRoutingFormHeaders({
|
||||
userId,
|
||||
teamId,
|
||||
|
||||
@@ -907,20 +907,14 @@ export const insightsRouter = router({
|
||||
return options;
|
||||
}),
|
||||
failedBookingsByField: userBelongsToTeamProcedure
|
||||
.input(
|
||||
z.object({
|
||||
userId: z.number().optional(),
|
||||
teamId: z.number().optional(),
|
||||
isAll: z.boolean(),
|
||||
routingFormId: z.string().optional(),
|
||||
})
|
||||
)
|
||||
.input(insightsRoutingServiceInputSchema)
|
||||
.query(async ({ ctx, input }) => {
|
||||
return await RoutingEventsInsights.getFailedBookingsByRoutingFormGroup({
|
||||
...input,
|
||||
userId: ctx.user.id,
|
||||
organizationId: ctx.user.organizationId ?? null,
|
||||
});
|
||||
const insightsRoutingService = createInsightsRoutingService(ctx, input);
|
||||
try {
|
||||
return await insightsRoutingService.getFailedBookingsByFieldData();
|
||||
} catch (e) {
|
||||
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
|
||||
}
|
||||
}),
|
||||
routingFormResponsesHeaders: userBelongsToTeamProcedure
|
||||
.input(
|
||||
|
||||
Reference in new issue
Block a user