feat: virtual queues tab in insights (#18260)

Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: sean-brydon <[email protected]>
Co-authored-by: sean-brydon <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: Omar López <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-12-23 19:16:38 +00:00
1 parent 5fe4e09975
commit cfb09a1b21
39 files changed
+538 -195

No files matched your search

@@ -3,6 +3,7 @@ import type z from "zod";
import { UserRepository } from "@calcom/lib/server/repository/user";
import prisma from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import { eventTypeAppMetadataOptionalSchema } from "@calcom/prisma/zod-utils";
import type { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import type { CredentialPayload } from "@calcom/types/Credential";
@@ -76,8 +77,7 @@ export const getAllCredentials = async (
}
// Only return CRM credentials that are enabled on the event type
const eventTypeAppMetadata = eventType?.metadata?.apps;
console.log(eventTypeAppMetadata);
const eventTypeAppMetadata = eventTypeAppMetadataOptionalSchema.parse(eventType?.metadata?.apps);
// Will be [credentialId]: { enabled: boolean }]
const eventTypeCrmCredentials: Record<number, { enabled: boolean }> = {};
@@ -24,7 +24,7 @@ import type { PrismaClient } from "@calcom/prisma";
import type { SchedulingType } from "@calcom/prisma/enums";
import { BookingStatus, WebhookTriggerEvents } from "@calcom/prisma/enums";
import type { PlatformClientParams } from "@calcom/prisma/zod-utils";
import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import { EventTypeMetaDataSchema, eventTypeAppMetadataOptionalSchema } from "@calcom/prisma/zod-utils";
import { getAllWorkflowsFromEventType } from "@calcom/trpc/server/routers/viewer/workflows/util";
import type { AdditionalInformation, CalendarEvent } from "@calcom/types/Calendar";
@@ -84,7 +84,8 @@ export async function handleConfirmation(args: {
} = args;
const eventType = booking.eventType;
const eventTypeMetadata = EventTypeMetaDataSchema.parse(eventType?.metadata || {});
const eventManager = new EventManager(user, eventTypeMetadata?.apps);
const apps = eventTypeAppMetadataOptionalSchema.parse(eventTypeMetadata?.apps);
const eventManager = new EventManager(user, apps);
const scheduleResult = await eventManager.create(evt);
const results = scheduleResult.results;
const metadata: AdditionalInformation = {};
@@ -68,6 +68,10 @@ import { WorkflowRepository } from "@calcom/lib/server/repository/workflow";
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
import prisma from "@calcom/prisma";
import { BookingStatus, SchedulingType, WebhookTriggerEvents } from "@calcom/prisma/enums";
import {
eventTypeAppMetadataOptionalSchema,
eventTypeMetaDataSchemaWithTypedApps,
} from "@calcom/prisma/zod-utils";
import type { PlatformClientParams } from "@calcom/prisma/zod-utils";
import { userMetadata as userMetadataSchema } from "@calcom/prisma/zod-utils";
import { getAllWorkflowsFromEventType } from "@calcom/trpc/server/routers/viewer/workflows/util";
@@ -421,7 +425,10 @@ async function handler(
const isTeamEventType =
!!eventType.schedulingType && ["COLLECTIVE", "ROUND_ROBIN"].includes(eventType.schedulingType);
const paymentAppData = getPaymentAppData(eventType);
const paymentAppData = getPaymentAppData({
...eventType,
metadata: eventTypeMetaDataSchemaWithTypedApps.parse(eventType.metadata),
});
loggerWithEventDetails.info(
`Booking eventType ${eventTypeId} started`,
safeStringify({
@@ -1051,7 +1058,13 @@ async function handler(
oAuthClientId: platformClientId,
};
const workflows = await getAllWorkflowsFromEventType(eventType, organizerUser.id);
const workflows = await getAllWorkflowsFromEventType(
{
...eventType,
metadata: eventTypeMetaDataSchemaWithTypedApps.parse(eventType.metadata),
},
organizerUser.id
);
if (isTeamEventType) {
evt.team = {
@@ -1275,8 +1288,9 @@ async function handler(
// After polling videoBusyTimes, credentials might have been changed due to refreshment, so query them again.
const credentials = await monitorCallbackAsync(refreshCredentials, allCredentials);
const apps = eventTypeAppMetadataOptionalSchema.parse(eventType?.metadata?.apps);
const eventManager = !isDryRun
? new EventManager({ ...organizerUser, credentials }, eventType?.metadata?.apps)
? new EventManager({ ...organizerUser, credentials }, apps)
: buildDryRunEventManager();
let videoCallUrl;
@@ -14,6 +14,7 @@ import { HttpError } from "@calcom/lib/http-error";
import { handlePayment } from "@calcom/lib/payment/handlePayment";
import prisma from "@calcom/prisma";
import { BookingStatus } from "@calcom/prisma/enums";
import { eventTypeAppMetadataOptionalSchema } from "@calcom/prisma/zod-utils";
import { findBookingQuery } from "../../handleNewBooking/findBookingQuery";
import type { IEventTypePaymentCredentialType } from "../../handleNewBooking/types";
@@ -147,7 +148,8 @@ const createNewSeat = async (
);
}
const credentials = await refreshCredentials(allCredentials);
const eventManager = new EventManager({ ...organizerUser, credentials }, eventType?.metadata?.apps);
const apps = eventTypeAppMetadataOptionalSchema.parse(eventType?.metadata?.apps);
const eventManager = new EventManager({ ...organizerUser, credentials }, apps);
await eventManager.updateCalendarAttendees(evt, seatedBooking);
const foundBooking = await findBookingQuery(seatedBooking.id);
@@ -14,7 +14,8 @@ import { bookingMinimalSelect, prisma } from "@calcom/prisma";
import { AppCategories, BookingStatus } from "@calcom/prisma/enums";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { EventTypeAppMetadataSchema, EventTypeMetadata } from "@calcom/prisma/zod-utils";
import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/prisma/zod-utils";
import { EventTypeMetaDataSchema, eventTypeAppMetadataOptionalSchema } from "@calcom/prisma/zod-utils";
import { userMetadata as userMetadataSchema } from "@calcom/prisma/zod-utils";
type App = {
@@ -151,9 +152,11 @@ const handleDeleteCredential = async ({
if (credential.app?.categories.includes(AppCategories.crm)) {
const metadata = EventTypeMetaDataSchema.parse(eventType.metadata);
const appSlugToDelete = credential.app?.slug;
const apps = eventTypeAppMetadataOptionalSchema.parse(metadata?.apps);
if (appSlugToDelete) {
const appMetadata = removeAppFromEventTypeMetadata(appSlugToDelete, metadata);
const appMetadata = removeAppFromEventTypeMetadata(appSlugToDelete, {
apps,
});
await prisma.$transaction(async () => {
await prisma.eventType.update({
@@ -179,7 +182,10 @@ const handleDeleteCredential = async ({
const metadata = EventTypeMetaDataSchema.parse(eventType.metadata);
const appSlug = credential.app?.slug;
if (appSlug) {
const appMetadata = removeAppFromEventTypeMetadata(appSlug, metadata);
const apps = eventTypeAppMetadataOptionalSchema.parse(metadata?.apps);
const appMetadata = removeAppFromEventTypeMetadata(appSlug, {
apps,
});
await prisma.$transaction(async () => {
await prisma.eventType.update({
@@ -358,7 +364,7 @@ const handleDeleteCredential = async ({
} else if (
appStoreMetadata[credential.app?.slug as keyof typeof appStoreMetadata]?.extendsFeature === "EventType"
) {
const metadata = EventTypeMetaDataSchema.parse(eventType.metadata);
const metadata = eventTypeMetaDataSchemaWithTypedApps.parse(eventType.metadata);
const appSlug = credential.app?.slug;
if (appSlug) {
await prisma.eventType.update({
@@ -456,7 +462,9 @@ const handleDeleteCredential = async ({
const removeAppFromEventTypeMetadata = (
appSlugToDelete: string,
eventTypeMetadata: z.infer<typeof EventTypeMetaDataSchema>
eventTypeMetadata: {
apps: z.infer<typeof eventTypeAppMetadataOptionalSchema>;
}
) => {
const appMetadata = eventTypeMetadata?.apps
? Object.entries(eventTypeMetadata.apps).reduce((filteredApps, [appName, appData]) => {
+3 -1
View File
@@ -17,6 +17,7 @@ import { handlePaymentSuccess } from "@calcom/lib/payment/handlePaymentSuccess";
import { safeStringify } from "@calcom/lib/safeStringify";
import { prisma } from "@calcom/prisma";
import { BookingStatus } from "@calcom/prisma/enums";
import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/prisma/zod-utils";
const log = logger.getSubLogger({ prefix: ["[paymentWebhook]"] });
@@ -72,7 +73,8 @@ const handleSetupSuccess = async (event: Stripe.Event) => {
},
});
if (!requiresConfirmation) {
const eventManager = new EventManager(user, eventType?.metadata?.apps);
const metadata = eventTypeMetaDataSchemaWithTypedApps.parse(eventType?.metadata);
const eventManager = new EventManager(user, metadata?.apps);
const scheduleResult = await eventManager.create(evt);
bookingData.references = { create: scheduleResult.referencesToCreate };
bookingData.status = BookingStatus.ACCEPTED;
@@ -11,6 +11,7 @@ import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
import type { baseEventTypeSelect } from "@calcom/prisma";
import { SchedulingType } from "@calcom/prisma/enums";
import type { EventTypeModel } from "@calcom/prisma/zod";
import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/prisma/zod-utils";
import { Badge } from "@calcom/ui";
export type EventTypeDescriptionProps = {
@@ -39,7 +40,10 @@ export const EventTypeDescription = ({
[eventType.recurringEvent]
);
const paymentAppData = getPaymentAppData(eventType);
const paymentAppData = getPaymentAppData({
...eventType,
metadata: eventTypeMetaDataSchemaWithTypedApps.parse(eventType.metadata),
});
return (
<>
@@ -1,5 +1,6 @@
import type { EventTypeSetupProps } from "@calcom/features/eventtypes/lib/types";
import getPaymentAppData from "@calcom/lib/getPaymentAppData";
import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/prisma/zod-utils";
import InstantEventController from "./InstantEventController";
@@ -7,7 +8,10 @@ export const EventInstantTab = ({
eventType,
isTeamEvent,
}: Pick<EventTypeSetupProps, "eventType"> & { isTeamEvent: boolean }) => {
const paymentAppData = getPaymentAppData(eventType);
const paymentAppData = getPaymentAppData({
...eventType,
metadata: eventTypeMetaDataSchemaWithTypedApps.parse(eventType.metadata),
});
const requirePayment = paymentAppData.price > 0;
@@ -1,4 +1,5 @@
import getPaymentAppData from "@calcom/lib/getPaymentAppData";
import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/prisma/zod-utils";
import type { RecurringEventControllerProps } from "./RecurringEventController";
import RecurringEventController from "./RecurringEventController";
@@ -6,7 +7,10 @@ import RecurringEventController from "./RecurringEventController";
export type EventRecurringTabProps = Omit<RecurringEventControllerProps, "paymentEnabled">;
export const EventRecurringTab = ({ eventType, customClassNames }: EventRecurringTabProps) => {
const paymentAppData = getPaymentAppData(eventType);
const paymentAppData = getPaymentAppData({
...eventType,
metadata: eventTypeMetaDataSchemaWithTypedApps.parse(eventType.metadata),
});
const requirePayment = paymentAppData.price > 0;
@@ -20,7 +20,7 @@ import type { Team } from "@calcom/prisma/client";
import type { BookerLayoutSettings } from "@calcom/prisma/zod-utils";
import {
BookerLayouts,
EventTypeMetaDataSchema,
eventTypeMetaDataSchemaWithTypedApps,
bookerLayoutOptions,
bookerLayouts as bookerLayoutsSchema,
customInputSchema,
@@ -368,7 +368,7 @@ export const getPublicEvent = async (
if (!event) return null;
const eventMetaData = EventTypeMetaDataSchema.parse(event.metadata || {});
const eventMetaData = eventTypeMetaDataSchemaWithTypedApps.parse(event.metadata || {});
const teamMetadata = teamMetadataSchema.parse(event.team?.metadata || {});
const usersAsHosts = event.hosts.map((host) => host.user);
@@ -517,7 +517,7 @@ function getProfileFromEvent(event: Event) {
const username = "username" in profile ? profile.username : team?.slug;
const weekStart = hosts?.[0]?.user?.weekStart || owner?.weekStart || "Monday";
const eventMetaData = EventTypeMetaDataSchema.parse(event.metadata || {});
const eventMetaData = eventTypeMetaDataSchemaWithTypedApps.parse(event.metadata || {});
const userMetaData = userMetadataSchema.parse(profile.metadata || {});
return {
+2 -2
View File
@@ -5,7 +5,7 @@ import type { ChildrenEventType } from "@calcom/features/eventtypes/components/C
import type { AttributesQueryValue } from "@calcom/lib/raqb/types";
import type { EventTypeTranslation } from "@calcom/prisma/client";
import type { PeriodType, SchedulingType } from "@calcom/prisma/enums";
import type { BookerLayoutSettings, EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import type { BookerLayoutSettings, eventTypeMetaDataSchemaWithTypedApps } from "@calcom/prisma/zod-utils";
import type { customInputSchema } from "@calcom/prisma/zod-utils";
import type { eventTypeBookingFields } from "@calcom/prisma/zod-utils";
import type { eventTypeColor } from "@calcom/prisma/zod-utils";
@@ -122,7 +122,7 @@ export type FormValues = {
beforeEventBuffer: number;
afterEventBuffer: number;
slotInterval: number | null;
metadata: z.infer<typeof EventTypeMetaDataSchema>;
metadata: z.infer<typeof eventTypeMetaDataSchemaWithTypedApps>;
destinationCalendar: {
integration: string;
externalId: string;
@@ -15,6 +15,7 @@ import { TRPCError } from "@trpc/server";
import { EventsInsights } from "./events";
import { RoutingEventsInsights } from "./routing-events";
import { VirtualQueuesInsights } from "./virtual-queues";
const UserBelongsToTeamInput = z.object({
teamId: z.coerce.number().optional().nullable(),
@@ -1796,4 +1797,15 @@ export const insightsRouter = router({
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
}
}),
getUserRelevantTeamRoutingForms: authedProcedure.query(async ({ ctx }) => {
try {
const routingForms = await VirtualQueuesInsights.getUserRelevantTeamRoutingForms({
userId: ctx.user.id,
});
return routingForms;
} catch (e) {
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
}
}),
});
@@ -0,0 +1,73 @@
import { readonlyPrisma as prisma } from "@calcom/prisma";
import { getSerializableForm } from "@calcom/routing-forms/lib/getSerializableForm";
class VirtualQueuesInsights {
static async getUserRelevantTeamRoutingForms({ userId }: { userId: number }) {
type JsonField = { [key: string]: any };
type RoutingFormType = {
id: string;
description: string | null;
position: number;
routes: JsonField | null;
createdAt: Date;
updatedAt: Date;
name: string;
fields: JsonField | null;
userId: number;
teamId: number | null;
disabled: boolean;
settings: JsonField | null;
};
const formsRedirectingToWeightedRR: RoutingFormType[] = await prisma.$queryRaw<RoutingFormType[]>`
WITH RECURSIVE json_array_elements_recursive AS (
SELECT f.id, f."teamId",
jsonb_array_elements(f.routes::jsonb) as route
FROM "App_RoutingForms_Form" f
WHERE f."teamId" IN (
SELECT "teamId"
FROM "Membership"
WHERE "userId" = ${userId}
)
)
SELECT DISTINCT f.*,
jsonb_build_object(
'parentId', t."parentId",
'parent', CASE WHEN p.id IS NOT NULL THEN jsonb_build_object('slug', p.slug) ELSE NULL END,
'metadata', t.metadata
) as team,
jsonb_build_object(
'id', u.id,
'username', u.username,
'movedToProfileId', u."movedToProfileId"
) as "user"
FROM "App_RoutingForms_Form" f
INNER JOIN json_array_elements_recursive r ON f.id = r.id
INNER JOIN "EventType" e ON (r.route->>'action')::jsonb->>'eventTypeId' = e.id::text
INNER JOIN "Team" t ON f."teamId" = t.id
LEFT JOIN "Team" p ON t."parentId" = p.id
INNER JOIN "users" u ON f."userId" = u.id
WHERE e."schedulingType" = 'roundRobin'
AND e."isRRWeightsEnabled" = true
AND EXISTS (
SELECT 1
FROM "Host" h
WHERE h."eventTypeId" = e.id
AND h."userId" = ${userId}
);
`;
// Convert the raw forms to serializable format
const serializableForms = await Promise.all(
formsRedirectingToWeightedRR.map(async (form) => {
const serializedForm = await getSerializableForm({ form });
return serializedForm;
})
);
return serializableForms;
}
}
export { VirtualQueuesInsights };
@@ -4,7 +4,7 @@ import type { eventTypeAppCardZod } from "@calcom/app-store/eventTypeAppCardZod"
import CrmManager from "@calcom/core/crmManager/crmManager";
import logger from "@calcom/lib/logger";
import prisma from "@calcom/prisma";
import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import { eventTypeAppMetadataOptionalSchema, EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import type { NoShowAttendees } from "../handleMarkNoShow";
import { noShowEnabledApps } from "./noShowEnabledApps";
@@ -38,7 +38,7 @@ export default async function handleSendingAttendeeNoShowDataToApps(
log.error(`Malformed event type metadata for bookingUid ${bookingUid}`);
return;
}
const eventTypeAppMetadata = eventTypeMetadataParse.data?.apps;
const eventTypeAppMetadata = eventTypeAppMetadataOptionalSchema.parse(eventTypeMetadataParse.data?.apps);
for (const slug in eventTypeAppMetadata) {
if (noShowEnabledApps.includes(slug)) {
@@ -116,6 +116,11 @@ const getNavigationItems = (orgBranding: OrganizationBranding): NavigationItemTy
href: "/insights/routing",
isCurrent: ({ pathname: path }) => path?.startsWith("/insights/routing") ?? false,
},
{
name: "router_position",
href: "/insights/virtual-queues",
isCurrent: ({ pathname: path }) => path?.startsWith("/insights/virtual-queues") ?? false,
},
],
},
];