refactor: circular deps between app store and lib [5] (#23936)
* getBulkEventTypes * 2 eventtypes related utils to features * locationsResolver * checkForEmptyAssignment * mv defaultEvents to features * update imports * PrismaAppRepository * mv currencyConversions from appstore to lib * useAppsData * videoClient * analytics files * fix * mv * prettier * use named import
This commit is contained in:
1 parent
dfdda8a5b8
commit
76332a759b
75 files changed
+182
-192
No files matched your search
@@ -0,0 +1,58 @@
|
||||
import { useFormContext } from "react-hook-form";
|
||||
|
||||
import type { GetAppData, SetAppData } from "@calcom/app-store/EventTypeAppContext";
|
||||
import type { EventTypeAppsList } from "@calcom/app-store/utils";
|
||||
import type { FormValues } from "@calcom/features/eventtypes/lib/types";
|
||||
|
||||
const useAppsData = () => {
|
||||
const formMethods = useFormContext<FormValues>();
|
||||
const allAppsData = formMethods.watch("metadata")?.apps || {};
|
||||
|
||||
const setAllAppsData = (_allAppsData: typeof allAppsData) => {
|
||||
formMethods.setValue(
|
||||
"metadata",
|
||||
{
|
||||
...formMethods.getValues("metadata"),
|
||||
apps: _allAppsData,
|
||||
},
|
||||
{ shouldDirty: true }
|
||||
);
|
||||
};
|
||||
|
||||
const getAppDataGetter = (appId: EventTypeAppsList): GetAppData => {
|
||||
return function (key) {
|
||||
const appData = allAppsData[appId as keyof typeof allAppsData] || {};
|
||||
if (key) {
|
||||
return appData[key as keyof typeof appData];
|
||||
}
|
||||
return appData;
|
||||
};
|
||||
};
|
||||
|
||||
const eventTypeFormMetadata = formMethods.getValues("metadata");
|
||||
|
||||
const getAppDataSetter = (
|
||||
appId: EventTypeAppsList,
|
||||
appCategories: string[],
|
||||
credentialId?: number
|
||||
): SetAppData => {
|
||||
return function (key, value) {
|
||||
// Always get latest data available in Form because consequent calls to setData would update the Form but not allAppsData(it would update during next render)
|
||||
const allAppsDataFromForm = formMethods.getValues("metadata")?.apps || {};
|
||||
const appData = allAppsDataFromForm[appId];
|
||||
setAllAppsData({
|
||||
...allAppsDataFromForm,
|
||||
[appId]: {
|
||||
...appData,
|
||||
[key]: value,
|
||||
credentialId,
|
||||
appCategories,
|
||||
},
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
return { getAppDataGetter, getAppDataSetter, eventTypeFormMetadata };
|
||||
};
|
||||
|
||||
export default useAppsData;
|
||||
@@ -0,0 +1,26 @@
|
||||
import { appStoreMetadata } from "@calcom/app-store/appStoreMetaData";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
|
||||
export class PrismaAppRepository {
|
||||
static async seedApp(dirName: string, keys?: any) {
|
||||
const appMetadata = appStoreMetadata[dirName as keyof typeof appStoreMetadata];
|
||||
|
||||
if (!appMetadata) {
|
||||
throw new Error(`App ${dirName} not found`);
|
||||
}
|
||||
|
||||
await prisma.app.create({
|
||||
data: {
|
||||
slug: appMetadata.slug,
|
||||
categories: appMetadata.categories,
|
||||
dirName: dirName,
|
||||
keys,
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findAppStore() {
|
||||
return await prisma.app.findMany({ select: { slug: true } });
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import dynamic from "next/dynamic";
|
||||
|
||||
import { formatPrice } from "@calcom/lib/price";
|
||||
import { formatPrice } from "@calcom/lib/currencyConversions";
|
||||
|
||||
import type { EventPrice } from "../../types";
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ import type {
|
||||
import { createEvent, updateEvent, deleteEvent } from "@calcom/features/calendars/lib/CalendarManager";
|
||||
import CrmManager from "@calcom/lib/crmManager/crmManager";
|
||||
import { isDelegationCredential } from "@calcom/lib/delegationCredential/clientAndServer";
|
||||
import { createMeeting, updateMeeting, deleteMeeting } from "@calcom/lib/videoClient";
|
||||
import { createMeeting, updateMeeting, deleteMeeting } from "@calcom/app-store/videoClient";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["EventManager"] });
|
||||
const CALENDSO_ENCRYPTION_KEY = process.env.CALENDSO_ENCRYPTION_KEY || "";
|
||||
|
||||
@@ -3,6 +3,7 @@ import short, { uuid } from "short-uuid";
|
||||
import { v5 as uuidv5 } from "uuid";
|
||||
|
||||
import processExternalId from "@calcom/app-store/_utils/calendars/processExternalId";
|
||||
import { getPaymentAppData } from "@calcom/app-store/_utils/payments/getPaymentAppData";
|
||||
import { metadata as GoogleMeetMetadata } from "@calcom/app-store/googlevideo/_metadata";
|
||||
import {
|
||||
getLocationValueForDB,
|
||||
@@ -16,6 +17,7 @@ import dayjs from "@calcom/dayjs";
|
||||
import { scheduleMandatoryReminder } from "@calcom/ee/workflows/lib/reminders/scheduleMandatoryReminder";
|
||||
import getICalUID from "@calcom/emails/lib/getICalUID";
|
||||
import { CalendarEventBuilder } from "@calcom/features/CalendarEventBuilder";
|
||||
import EventManager, { placeholderCreatedEvent } from "@calcom/features/bookings/lib/EventManager";
|
||||
import type { BookingDataSchemaGetter } from "@calcom/features/bookings/lib/dto/types";
|
||||
import type { CreateRegularBookingData, CreateBookingMeta } from "@calcom/features/bookings/lib/dto/types";
|
||||
import type { CheckBookingAndDurationLimitsService } from "@calcom/features/bookings/lib/handleNewBooking/checkBookingAndDurationLimits";
|
||||
@@ -24,9 +26,11 @@ import { handleWebhookTrigger } from "@calcom/features/bookings/lib/handleWebhoo
|
||||
import { isEventTypeLoggingEnabled } from "@calcom/features/bookings/lib/isEventTypeLoggingEnabled";
|
||||
import type { CacheService } from "@calcom/features/calendar-cache/lib/getShouldServeCache";
|
||||
import AssignmentReasonRecorder from "@calcom/features/ee/round-robin/assignmentReason/AssignmentReasonRecorder";
|
||||
import { getUsernameList } from "@calcom/features/eventtypes/lib/defaultEvents";
|
||||
import { getEventName, updateHostInEventName } from "@calcom/features/eventtypes/lib/eventNaming";
|
||||
import type { FeaturesRepository } from "@calcom/features/flags/features.repository";
|
||||
import { getFullName } from "@calcom/features/form-builder/utils";
|
||||
import { handleAnalyticsEvents } from "@calcom/features/tasker/tasks/analytics/handleAnalyticsEvents";
|
||||
import { UsersRepository } from "@calcom/features/users/users.repository";
|
||||
import type { GetSubscriberOptions } from "@calcom/features/webhooks/lib/getWebhooks";
|
||||
import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";
|
||||
@@ -36,12 +40,9 @@ import {
|
||||
scheduleTrigger,
|
||||
} from "@calcom/features/webhooks/lib/scheduleTrigger";
|
||||
import { getVideoCallUrlFromCalEvent } from "@calcom/lib/CalEventParser";
|
||||
import EventManager, { placeholderCreatedEvent } from "@calcom/features/bookings/lib/EventManager";
|
||||
import { handleAnalyticsEvents } from "@calcom/lib/analyticsManager/handleAnalyticsEvents";
|
||||
import { groupHostsByGroupId } from "@calcom/lib/bookings/hostGroupUtils";
|
||||
import { shouldIgnoreContactOwner } from "@calcom/lib/bookings/routing/utils";
|
||||
import { DEFAULT_GROUP_ID } from "@calcom/lib/constants";
|
||||
import { getUsernameList } from "@calcom/lib/defaultEvents";
|
||||
import {
|
||||
enrichHostsWithDelegationCredentials,
|
||||
getFirstDelegationConferencingCredentialAppLocation,
|
||||
@@ -54,7 +55,6 @@ import { getErrorFromUnknown } from "@calcom/lib/errors";
|
||||
import { extractBaseEmail } from "@calcom/lib/extract-base-email";
|
||||
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
|
||||
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
|
||||
import { getPaymentAppData } from "@calcom/app-store/_utils/payments/getPaymentAppData";
|
||||
import { getTeamIdFromEventType } from "@calcom/lib/getTeamIdFromEventType";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import type { CheckBookingLimitsService } from "@calcom/lib/intervalLimits/server/checkBookingLimits";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getDefaultEvent } from "@calcom/lib/defaultEvents";
|
||||
import { getDefaultEvent } from "@calcom/features/eventtypes/lib/defaultEvents";
|
||||
import { withReporting } from "@calcom/lib/sentryWrapper";
|
||||
|
||||
import { getBookingFieldsWithSystemFields } from "../getBookingFields";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { LocationObject } from "@calcom/app-store/locations";
|
||||
import { workflowSelect } from "@calcom/ee/workflows/lib/getAllWorkflows";
|
||||
import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/getBookingFields";
|
||||
import type { DefaultEvent } from "@calcom/lib/defaultEvents";
|
||||
import type { DefaultEvent } from "@calcom/features/eventtypes/lib/defaultEvents";
|
||||
import { ErrorCode } from "@calcom/lib/errorCodes";
|
||||
import { parseRecurringEvent } from "@calcom/lib/isRecurringEvent";
|
||||
import { withSelectedCalendars } from "@calcom/lib/server/repository/user";
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { PaymentServiceMap } from "@calcom/app-store/payment.services.generated";
|
||||
import type { EventTypeAppsList } from "@calcom/app-store/utils";
|
||||
import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/app-store/zod-utils";
|
||||
import type { AppCategories, Prisma, EventType } from "@calcom/prisma/client";
|
||||
import { convertToSmallestCurrencyUnit } from "@calcom/app-store/_utils/payments/currencyConversions";
|
||||
import type { Fields } from "@calcom/features/bookings/lib/getBookingFields";
|
||||
import { fieldTypesConfigMap } from "@calcom/features/form-builder/fieldTypes";
|
||||
import { convertToSmallestCurrencyUnit } from "@calcom/lib/currencyConversions";
|
||||
import type { AppCategories, Prisma, EventType } from "@calcom/prisma/client";
|
||||
import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
import type { IAbstractPaymentService } from "@calcom/types/PaymentService";
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { WorkflowRepository } from "@calcom/lib/server/repository/workflow";
|
||||
import { updateMeeting } from "@calcom/lib/videoClient";
|
||||
import { updateMeeting } from "@calcom/app-store/videoClient";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
|
||||
import { bookingCancelAttendeeSeatSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
|
||||
import { getAllDelegationCredentialsForUserIncludeServiceAccountKey } from "@calcom/lib/delegationCredential/server";
|
||||
import { getDelegationCredentialOrFindRegularCredential } from "@calcom/lib/delegationCredential/server";
|
||||
import { deleteMeeting } from "@calcom/lib/videoClient";
|
||||
import { deleteMeeting } from "@calcom/app-store/videoClient";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { Attendee } from "@calcom/prisma/client";
|
||||
import { BookingStatus } from "@calcom/prisma/enums";
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
|
||||
import { describe, test, expect, beforeEach } from "vitest";
|
||||
|
||||
import { PrismaAppRepository } from "@calcom/lib/server/repository/PrismaAppRepository";
|
||||
import { PrismaAppRepository } from "@calcom/features/apps/repository/PrismaAppRepository";
|
||||
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
|
||||
import { DestinationCalendarRepository } from "@calcom/lib/server/repository/destinationCalendar";
|
||||
import { EventTypeRepository } from "@calcom/lib/server/repository/eventTypeRepository";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { getEventTypeResponse } from "@calcom/features/bookings/lib/handleNewBooking/getEventTypesFromDB";
|
||||
import { scheduleEmailReminder } from "@calcom/features/ee/workflows/lib/reminders/emailReminderManager";
|
||||
import type { Workflow } from "@calcom/features/ee/workflows/lib/types";
|
||||
import type { getDefaultEvent } from "@calcom/lib/defaultEvents";
|
||||
import type { getDefaultEvent } from "@calcom/features/eventtypes/lib/defaultEvents";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { withReporting } from "@calcom/lib/sentryWrapper";
|
||||
import { WorkflowTriggerEvents, TimeUnit, WorkflowActions, WorkflowTemplates } from "@calcom/prisma/enums";
|
||||
|
||||
@@ -4,10 +4,10 @@ import { useFormContext } from "react-hook-form";
|
||||
import { EventTypeAppCard } from "@calcom/app-store/_components/EventTypeAppCardInterface";
|
||||
import type { EventTypeAppCardComponentProps } from "@calcom/app-store/types";
|
||||
import type { EventTypeAppsList } from "@calcom/app-store/utils";
|
||||
import useAppsData from "@calcom/features/apps/hooks/useAppsData";
|
||||
import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hooks/useLockedFieldsManager";
|
||||
import type { FormValues, EventTypeSetupProps } from "@calcom/features/eventtypes/lib/types";
|
||||
import ServerTrans from "@calcom/lib/components/ServerTrans";
|
||||
import useAppsData from "@calcom/lib/hooks/useAppsData";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Alert } from "@calcom/ui/components/alert";
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { checkForEmptyAssignment } from "./checkForEmptyAssignment";
|
||||
|
||||
describe("Tests to Check if Event Types have empty Assignment", () => {
|
||||
it("should return true if managed event type has no assigned users", () => {
|
||||
expect(
|
||||
checkForEmptyAssignment({
|
||||
assignedUsers: [],
|
||||
assignAllTeamMembers: false,
|
||||
hosts: [
|
||||
{
|
||||
userId: 101,
|
||||
isFixed: false,
|
||||
priority: 2,
|
||||
weight: 100,
|
||||
scheduleId: null,
|
||||
user: { timeZone: "America/New_York" },
|
||||
},
|
||||
],
|
||||
isManagedEventType: true,
|
||||
})
|
||||
).toBe(true);
|
||||
});
|
||||
it("should return true if non-managed event type has no hosts assigned", () => {
|
||||
expect(
|
||||
checkForEmptyAssignment({
|
||||
assignedUsers: [
|
||||
{
|
||||
created: true,
|
||||
owner: {
|
||||
id: 101,
|
||||
avatar: "avatar.svg",
|
||||
email: "[email protected]",
|
||||
membership: "OWNER",
|
||||
name: "First user",
|
||||
username: "firstuser",
|
||||
profile: {
|
||||
username: "firstuser",
|
||||
upId: "usr-101",
|
||||
id: null,
|
||||
organization: null,
|
||||
organizationId: null,
|
||||
},
|
||||
avatarUrl: null,
|
||||
nonProfileUsername: null,
|
||||
},
|
||||
slug: "managedevent",
|
||||
hidden: false,
|
||||
},
|
||||
],
|
||||
assignAllTeamMembers: false,
|
||||
hosts: [],
|
||||
isManagedEventType: false,
|
||||
})
|
||||
).toBe(true);
|
||||
});
|
||||
it("should return false if assignAllTeamMembers is selected", () => {
|
||||
expect(
|
||||
checkForEmptyAssignment({
|
||||
assignedUsers: [],
|
||||
assignAllTeamMembers: true,
|
||||
hosts: [],
|
||||
isManagedEventType: false,
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
it("should return false if non-managed event type has hosts assigned", () => {
|
||||
expect(
|
||||
checkForEmptyAssignment({
|
||||
assignedUsers: [],
|
||||
assignAllTeamMembers: false,
|
||||
hosts: [
|
||||
{
|
||||
userId: 101,
|
||||
isFixed: false,
|
||||
priority: 2,
|
||||
weight: 100,
|
||||
scheduleId: null,
|
||||
user: { timeZone: "America/New_York" },
|
||||
},
|
||||
],
|
||||
isManagedEventType: false,
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
it("should return false if managed event type has assigned users", () => {
|
||||
expect(
|
||||
checkForEmptyAssignment({
|
||||
assignedUsers: [
|
||||
{
|
||||
created: true,
|
||||
owner: {
|
||||
id: 101,
|
||||
avatar: "avatar.svg",
|
||||
email: "[email protected]",
|
||||
membership: "OWNER",
|
||||
name: "First user",
|
||||
username: "firstuser",
|
||||
profile: {
|
||||
username: "firstuser",
|
||||
upId: "usr-101",
|
||||
id: null,
|
||||
organization: null,
|
||||
organizationId: null,
|
||||
},
|
||||
avatarUrl: null,
|
||||
nonProfileUsername: null,
|
||||
},
|
||||
slug: "managedevent",
|
||||
hidden: false,
|
||||
},
|
||||
],
|
||||
assignAllTeamMembers: false,
|
||||
hosts: [
|
||||
{
|
||||
userId: 101,
|
||||
isFixed: false,
|
||||
priority: 2,
|
||||
weight: 100,
|
||||
scheduleId: null,
|
||||
user: { timeZone: "America/New_York" },
|
||||
},
|
||||
],
|
||||
isManagedEventType: true,
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { EventTypeAssignedUsers, EventTypeHosts } from "../components/EventType";
|
||||
|
||||
// This function checks if EventType requires assignment.
|
||||
// returns true: if EventType requires assignment but there is no assignment yet done by the user.
|
||||
// returns false: for all other scenarios.
|
||||
export function checkForEmptyAssignment({
|
||||
assignedUsers,
|
||||
hosts,
|
||||
isManagedEventType,
|
||||
assignAllTeamMembers,
|
||||
}: {
|
||||
assignedUsers: EventTypeAssignedUsers;
|
||||
hosts: EventTypeHosts;
|
||||
isManagedEventType: boolean;
|
||||
assignAllTeamMembers: boolean;
|
||||
}): boolean {
|
||||
// If Team-events have assignAllTeamMembers checked, return false as assignment is complete.
|
||||
if (assignAllTeamMembers) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// For managed eventtype check if assigned users are empty.
|
||||
// For non-managed eventtype check if hosts are empty.
|
||||
if (isManagedEventType ? assignedUsers.length === 0 : hosts.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
import { DailyLocationType } from "@calcom/app-store/constants";
|
||||
import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/app-store/zod-utils";
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
import type { Prisma, SelectedCalendar } from "@calcom/prisma/client";
|
||||
import { PeriodType, SchedulingType } from "@calcom/prisma/enums";
|
||||
import type { userSelect } from "@calcom/prisma/selects";
|
||||
import type { CustomInputSchema } from "@calcom/prisma/zod-utils";
|
||||
import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
|
||||
import type { CredentialPayload } from "@calcom/types/Credential";
|
||||
|
||||
type User = Omit<Prisma.UserGetPayload<{ select: typeof userSelect }>, "selectedCalendars"> & {
|
||||
allSelectedCalendars: SelectedCalendar[];
|
||||
userLevelSelectedCalendars: SelectedCalendar[];
|
||||
};
|
||||
|
||||
type UsernameSlugLinkProps = {
|
||||
users: {
|
||||
id?: number;
|
||||
username: string | null;
|
||||
email?: string;
|
||||
name?: string | null;
|
||||
bio?: string | null;
|
||||
avatar?: string | null;
|
||||
theme?: string | null;
|
||||
away?: boolean;
|
||||
verified?: boolean | null;
|
||||
allowDynamicBooking?: boolean | null;
|
||||
}[];
|
||||
slug: string;
|
||||
};
|
||||
|
||||
const user: User & { credentials: CredentialPayload[] } = {
|
||||
metadata: null,
|
||||
theme: null,
|
||||
credentials: [],
|
||||
username: "john.doe",
|
||||
timeZone: "",
|
||||
bufferTime: 0,
|
||||
availability: [],
|
||||
id: 0,
|
||||
startTime: 0,
|
||||
endTime: 0,
|
||||
allSelectedCalendars: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
schedules: [],
|
||||
defaultScheduleId: null,
|
||||
locale: "en",
|
||||
email: "[email protected]",
|
||||
name: "John doe",
|
||||
destinationCalendar: null,
|
||||
hideBranding: true,
|
||||
brandColor: "#797979",
|
||||
darkBrandColor: "#efefef",
|
||||
allowDynamicBooking: true,
|
||||
timeFormat: 12,
|
||||
travelSchedules: [],
|
||||
locked: false,
|
||||
isPlatformManaged: false,
|
||||
};
|
||||
|
||||
const customInputs: CustomInputSchema[] = [];
|
||||
|
||||
const commons = {
|
||||
isDynamic: true,
|
||||
periodCountCalendarDays: true,
|
||||
periodStartDate: null,
|
||||
periodEndDate: null,
|
||||
beforeEventBuffer: 0,
|
||||
afterEventBuffer: 0,
|
||||
periodType: PeriodType.UNLIMITED,
|
||||
periodDays: null,
|
||||
slotInterval: null,
|
||||
offsetStart: 0,
|
||||
locations: [{ type: DailyLocationType }],
|
||||
customInputs,
|
||||
disableGuests: true,
|
||||
minimumBookingNotice: 120,
|
||||
schedule: null,
|
||||
timeZone: null,
|
||||
successRedirectUrl: "",
|
||||
forwardParamsSuccessRedirect: true,
|
||||
teamId: null,
|
||||
scheduleId: null,
|
||||
availability: [],
|
||||
price: 0,
|
||||
currency: "usd",
|
||||
schedulingType: SchedulingType.COLLECTIVE,
|
||||
seatsPerTimeSlot: null,
|
||||
seatsShowAttendees: null,
|
||||
seatsShowAvailabilityCount: null,
|
||||
disableCancelling: false,
|
||||
disableRescheduling: false,
|
||||
onlyShowFirstAvailableSlot: false,
|
||||
allowReschedulingPastBookings: false,
|
||||
allowReschedulingCancelledBookings: false,
|
||||
hideOrganizerEmail: false,
|
||||
showOptimizedSlots: false,
|
||||
id: 0,
|
||||
hideCalendarNotes: false,
|
||||
hideCalendarEventDetails: false,
|
||||
recurringEvent: null,
|
||||
destinationCalendar: null,
|
||||
team: null,
|
||||
lockTimeZoneToggleOnBookingPage: false,
|
||||
lockedTimeZone: null,
|
||||
requiresConfirmation: false,
|
||||
requiresConfirmationForFreeEmail: false,
|
||||
requiresBookerEmailVerification: false,
|
||||
bookingLimits: null,
|
||||
maxActiveBookingsPerBooker: null,
|
||||
maxActiveBookingPerBookerOfferReschedule: false,
|
||||
durationLimits: null,
|
||||
hidden: false,
|
||||
userId: 0,
|
||||
parentId: null,
|
||||
parent: null,
|
||||
owner: null,
|
||||
workflows: [],
|
||||
users: [user],
|
||||
hosts: [],
|
||||
subsetOfHosts: [],
|
||||
metadata: EventTypeMetaDataSchema.parse({}),
|
||||
bookingFields: [],
|
||||
assignAllTeamMembers: false,
|
||||
assignRRMembersUsingSegment: false,
|
||||
rrSegmentQueryValue: null,
|
||||
isRRWeightsEnabled: false,
|
||||
rescheduleWithSameRoundRobinHost: false,
|
||||
useEventTypeDestinationCalendarEmail: false,
|
||||
secondaryEmailId: null,
|
||||
secondaryEmail: null,
|
||||
autoTranslateDescriptionEnabled: false,
|
||||
fieldTranslations: [],
|
||||
maxLeadThreshold: null,
|
||||
includeNoShowInRRCalculation: false,
|
||||
useEventLevelSelectedCalendars: false,
|
||||
rrResetInterval: null,
|
||||
rrTimestampBasis: null,
|
||||
interfaceLanguage: null,
|
||||
customReplyToEmail: null,
|
||||
restrictionScheduleId: null,
|
||||
useBookerTimezone: false,
|
||||
profileId: null,
|
||||
requiresConfirmationWillBlockSlot: false,
|
||||
canSendCalVideoTranscriptionEmails: false,
|
||||
instantMeetingExpiryTimeOffsetInSeconds: 0,
|
||||
instantMeetingScheduleId: null,
|
||||
instantMeetingParameters: [],
|
||||
eventTypeColor: null,
|
||||
hostGroups: [],
|
||||
bookingRequiresAuthentication: false,
|
||||
};
|
||||
|
||||
export const dynamicEvent = {
|
||||
length: 30,
|
||||
slug: "dynamic",
|
||||
title: "Group Meeting",
|
||||
eventName: "Group Meeting",
|
||||
description: "Join us for a meeting with multiple people",
|
||||
descriptionAsSafeHTML: "",
|
||||
position: 0,
|
||||
...commons,
|
||||
metadata: eventTypeMetaDataSchemaWithTypedApps.parse({ multipleDuration: [15, 30, 45, 60, 90] }),
|
||||
};
|
||||
|
||||
export const defaultEvents = [dynamicEvent];
|
||||
|
||||
export const getDynamicEventDescription = (dynamicUsernames: string[], slug: string): string => {
|
||||
return `Book a ${slug} min event with ${dynamicUsernames.join(", ")}`;
|
||||
};
|
||||
|
||||
export const getDynamicEventName = (dynamicNames: string[], slug: string): string => {
|
||||
const lastUser = dynamicNames.pop();
|
||||
return `Dynamic Collective ${slug} min event with ${dynamicNames.join(", ")} & ${lastUser}`;
|
||||
};
|
||||
|
||||
export const getDefaultEvent = (slug: string) => {
|
||||
const event = defaultEvents.find((obj) => {
|
||||
return obj.slug === slug;
|
||||
});
|
||||
return event || dynamicEvent;
|
||||
};
|
||||
|
||||
export const getGroupName = (usernameList: string[]): string => {
|
||||
return usernameList.join(", ");
|
||||
};
|
||||
|
||||
export const getUsernameSlugLink = ({ users, slug }: UsernameSlugLinkProps): string => {
|
||||
let slugLink = ``;
|
||||
if (users.length > 1) {
|
||||
const combinedUsername = users.map((user) => user.username).join("+");
|
||||
slugLink = `/${combinedUsername}/${slug}`;
|
||||
} else {
|
||||
slugLink = `/${users[0].username}/${slug}`;
|
||||
}
|
||||
return slugLink;
|
||||
};
|
||||
|
||||
const arrayCast = (value: unknown | unknown[]) => {
|
||||
return Array.isArray(value) ? value : value ? [value] : [];
|
||||
};
|
||||
|
||||
export const getUsernameList = (users: string | string[] | undefined): string[] => {
|
||||
// Multiple users can come in case of a team round-robin booking and in that case dynamic link won't be a user.
|
||||
// So, even though this code handles even if individual user is dynamic link, that isn't a possibility right now.
|
||||
users = arrayCast(users);
|
||||
const allUsers = users
|
||||
.map((user) => user.replace(/( |%20|%2b)/gi, "+").split("+"))
|
||||
.flat()
|
||||
.filter(Boolean);
|
||||
return Array.prototype.concat(...allUsers.map((userSlug) => slugify(userSlug)));
|
||||
};
|
||||
|
||||
export default defaultEvents;
|
||||
|
||||
export type DefaultEvent = Awaited<ReturnType<typeof getDefaultEvent>>;
|
||||
@@ -0,0 +1,359 @@
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { orderBy } from "lodash";
|
||||
|
||||
import { hasFilter } from "@calcom/features/filters/lib/hasFilter";
|
||||
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
|
||||
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
|
||||
import { getBookerBaseUrlSync } from "@calcom/lib/getBookerUrl/client";
|
||||
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { EventTypeRepository } from "@calcom/lib/server/repository/eventTypeRepository";
|
||||
import { MembershipRepository } from "@calcom/lib/server/repository/membership";
|
||||
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { MembershipRole, SchedulingType } from "@calcom/prisma/enums";
|
||||
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
import { eventTypeMetaDataSchemaWithUntypedApps } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["viewer.eventTypes.getByViewer"] });
|
||||
|
||||
type User = {
|
||||
id: number;
|
||||
profile: {
|
||||
upId: string;
|
||||
};
|
||||
};
|
||||
|
||||
type Filters = {
|
||||
teamIds?: number[];
|
||||
upIds?: string[];
|
||||
schedulingTypes?: SchedulingType[];
|
||||
};
|
||||
|
||||
export type EventTypesByViewer = Awaited<ReturnType<typeof getEventTypesByViewer>>;
|
||||
|
||||
export const getEventTypesByViewer = async (user: User, filters?: Filters, forRoutingForms?: boolean) => {
|
||||
const userProfile = user.profile;
|
||||
const profile = await ProfileRepository.findByUpId(userProfile.upId);
|
||||
const parentOrgHasLockedEventTypes =
|
||||
profile?.organization?.organizationSettings?.lockEventTypeCreationForUsers;
|
||||
const isFilterSet = filters && hasFilter(filters);
|
||||
const isUpIdInFilter = filters?.upIds?.includes(userProfile.upId);
|
||||
|
||||
let shouldListUserEvents = !isFilterSet || isUpIdInFilter;
|
||||
// FIX: Handles the case when an upId != lightProfile - pretend like there is no filter.
|
||||
// Results in {"eventTypeGroups":[],"profiles":[]} - this crashes all dependencies.
|
||||
if (isFilterSet && filters?.upIds && !isUpIdInFilter) {
|
||||
shouldListUserEvents = true;
|
||||
}
|
||||
const eventTypeRepo = new EventTypeRepository(prisma);
|
||||
const [profileMemberships, profileEventTypes] = await Promise.all([
|
||||
MembershipRepository.findAllByUpIdIncludeTeamWithMembersAndEventTypes(
|
||||
{
|
||||
upId: userProfile.upId,
|
||||
},
|
||||
{
|
||||
where: {
|
||||
accepted: true,
|
||||
},
|
||||
}
|
||||
),
|
||||
shouldListUserEvents
|
||||
? eventTypeRepo.findAllByUpId(
|
||||
{
|
||||
upId: userProfile.upId,
|
||||
userId: user.id,
|
||||
},
|
||||
{
|
||||
where: {
|
||||
teamId: null,
|
||||
},
|
||||
orderBy: [
|
||||
{
|
||||
position: "desc",
|
||||
},
|
||||
{
|
||||
id: "asc",
|
||||
},
|
||||
],
|
||||
}
|
||||
)
|
||||
: [],
|
||||
]);
|
||||
|
||||
if (!profile) {
|
||||
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
|
||||
}
|
||||
|
||||
const memberships = profileMemberships.map((membership) => ({
|
||||
...membership,
|
||||
team: {
|
||||
...membership.team,
|
||||
metadata: teamMetadataSchema.parse(membership.team.metadata),
|
||||
},
|
||||
}));
|
||||
|
||||
log.debug(
|
||||
safeStringify({
|
||||
profileMemberships,
|
||||
profileEventTypes,
|
||||
})
|
||||
);
|
||||
|
||||
type UserEventTypes = (typeof profileEventTypes)[number];
|
||||
|
||||
const mapEventType = async (eventType: UserEventTypes) => {
|
||||
const userRepo = new UserRepository(prisma);
|
||||
return {
|
||||
...eventType,
|
||||
safeDescription: eventType?.description ? markdownToSafeHTML(eventType.description) : undefined,
|
||||
users: await Promise.all(
|
||||
(!!eventType?.hosts?.length ? eventType?.hosts.map((host) => host.user) : eventType.users).map(
|
||||
async (u) =>
|
||||
await userRepo.enrichUserWithItsProfile({
|
||||
user: u,
|
||||
})
|
||||
)
|
||||
),
|
||||
metadata: eventType.metadata ? eventTypeMetaDataSchemaWithUntypedApps.parse(eventType.metadata) : null,
|
||||
children: await Promise.all(
|
||||
(eventType.children || []).map(async (c) => ({
|
||||
...c,
|
||||
users: await Promise.all(
|
||||
c.users.map(
|
||||
async (u) =>
|
||||
await userRepo.enrichUserWithItsProfile({
|
||||
user: u,
|
||||
})
|
||||
)
|
||||
),
|
||||
}))
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
const userEventTypes = (await Promise.all(profileEventTypes.map(mapEventType))).filter((eventType) => {
|
||||
const isAChildEvent = eventType.parentId;
|
||||
if (!isAChildEvent) {
|
||||
return true;
|
||||
}
|
||||
// A child event only has one user
|
||||
const childEventAssignee = eventType.users[0];
|
||||
if (!childEventAssignee || childEventAssignee.id != user.id) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
type EventTypeGroup = {
|
||||
teamId?: number | null;
|
||||
parentId?: number | null;
|
||||
bookerUrl: string;
|
||||
membershipRole?: MembershipRole | null;
|
||||
profile: {
|
||||
slug: (typeof profile)["username"] | null;
|
||||
name: (typeof profile)["name"];
|
||||
image: string;
|
||||
eventTypesLockedByOrg?: boolean;
|
||||
};
|
||||
metadata: {
|
||||
membershipCount: number;
|
||||
readOnly: boolean;
|
||||
};
|
||||
eventTypes: typeof userEventTypes;
|
||||
};
|
||||
|
||||
let eventTypeGroups: EventTypeGroup[] = [];
|
||||
|
||||
const unmanagedEventTypes = userEventTypes.filter(
|
||||
(evType) => evType.schedulingType !== SchedulingType.MANAGED
|
||||
);
|
||||
|
||||
log.debug(safeStringify({ profileMemberships, profileEventTypes, profile }));
|
||||
|
||||
log.debug(
|
||||
"Filter Settings",
|
||||
safeStringify({
|
||||
isFilterSet,
|
||||
isProfileIdInFilter: isUpIdInFilter,
|
||||
})
|
||||
);
|
||||
|
||||
if (shouldListUserEvents) {
|
||||
const bookerUrl = await getBookerBaseUrl(profile.organizationId ?? null);
|
||||
eventTypeGroups.push({
|
||||
teamId: null,
|
||||
bookerUrl,
|
||||
membershipRole: null,
|
||||
profile: {
|
||||
slug: profile.username,
|
||||
name: profile.name,
|
||||
image: getUserAvatarUrl({
|
||||
avatarUrl: profile.avatarUrl,
|
||||
}),
|
||||
eventTypesLockedByOrg: parentOrgHasLockedEventTypes,
|
||||
},
|
||||
eventTypes: orderBy(unmanagedEventTypes, ["position", "id"], ["desc", "asc"]),
|
||||
metadata: {
|
||||
membershipCount: 1,
|
||||
readOnly: false,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const teamMemberships = profileMemberships.map((membership) => ({
|
||||
teamId: membership.team.id,
|
||||
membershipRole: membership.role,
|
||||
}));
|
||||
|
||||
const filterByTeamIds = async (eventType: Awaited<ReturnType<typeof mapEventType>>) => {
|
||||
if (!filters || !hasFilter(filters)) {
|
||||
return true;
|
||||
}
|
||||
return filters?.teamIds?.includes(eventType?.teamId || 0) ?? false;
|
||||
};
|
||||
const filterBySchedulingTypes = (evType: Awaited<ReturnType<typeof mapEventType>>) => {
|
||||
if (!filters || !hasFilter(filters) || !filters.schedulingTypes) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!evType.schedulingType) return false;
|
||||
|
||||
return filters.schedulingTypes.includes(evType.schedulingType);
|
||||
};
|
||||
|
||||
eventTypeGroups = ([] as EventTypeGroup[]).concat(
|
||||
eventTypeGroups,
|
||||
await Promise.all(
|
||||
memberships
|
||||
.filter((mmship) => {
|
||||
if (mmship.team.isOrganization) {
|
||||
return false;
|
||||
} else {
|
||||
if (!filters || !hasFilter(filters)) {
|
||||
return true;
|
||||
}
|
||||
return filters?.teamIds?.includes(mmship?.team?.id || 0) ?? false;
|
||||
}
|
||||
})
|
||||
.map(async (membership) => {
|
||||
const orgMembership = teamMemberships.find(
|
||||
(teamM) => teamM.teamId === membership.team.parentId
|
||||
)?.membershipRole;
|
||||
|
||||
const team = {
|
||||
...membership.team,
|
||||
metadata: teamMetadataSchema.parse(membership.team.metadata),
|
||||
};
|
||||
|
||||
let slug;
|
||||
|
||||
if (forRoutingForms) {
|
||||
// For Routing form we want to ensure that after migration of team to an org, the URL remains same for the team
|
||||
// Once we solve this https://github.com/calcom/cal.com/issues/12399, we can remove this conditional change in slug
|
||||
slug = `team/${team.slug}`;
|
||||
} else {
|
||||
// In an Org, a team can be accessed without /team prefix as well as with /team prefix
|
||||
slug = team.slug ? (!team.parentId ? `team/${team.slug}` : `${team.slug}`) : null;
|
||||
}
|
||||
|
||||
const eventTypes = await Promise.all(team.eventTypes.map(mapEventType));
|
||||
const teamParentMetadata = team.parent ? teamMetadataSchema.parse(team.parent.metadata) : null;
|
||||
return {
|
||||
teamId: team.id,
|
||||
parentId: team.parentId,
|
||||
bookerUrl: getBookerBaseUrlSync(team.parent?.slug ?? teamParentMetadata?.requestedSlug ?? null),
|
||||
membershipRole:
|
||||
orgMembership && compareMembership(orgMembership, membership.role)
|
||||
? orgMembership
|
||||
: membership.role,
|
||||
profile: {
|
||||
image: team.parent
|
||||
? getPlaceholderAvatar(team.parent.logoUrl, team.parent.name)
|
||||
: getPlaceholderAvatar(team.logoUrl, team.name),
|
||||
name: team.name,
|
||||
slug,
|
||||
},
|
||||
metadata: {
|
||||
membershipCount: team.members.length,
|
||||
readOnly:
|
||||
membership.role ===
|
||||
(team.parentId
|
||||
? orgMembership && compareMembership(orgMembership, membership.role)
|
||||
? orgMembership
|
||||
: MembershipRole.MEMBER
|
||||
: MembershipRole.MEMBER),
|
||||
},
|
||||
eventTypes: eventTypes
|
||||
.filter(filterByTeamIds)
|
||||
.filter((evType) => {
|
||||
const res = evType.userId === null || evType.userId === user.id;
|
||||
return res;
|
||||
})
|
||||
.filter((evType) =>
|
||||
membership.role === MembershipRole.MEMBER
|
||||
? evType.schedulingType !== SchedulingType.MANAGED
|
||||
: true
|
||||
)
|
||||
.filter(filterBySchedulingTypes),
|
||||
};
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
const denormalizedPayload = {
|
||||
eventTypeGroups,
|
||||
// so we can show a dropdown when the user has teams
|
||||
profiles: eventTypeGroups.map((group) => ({
|
||||
...group.profile,
|
||||
...group.metadata,
|
||||
teamId: group.teamId,
|
||||
membershipRole: group.membershipRole,
|
||||
})),
|
||||
};
|
||||
|
||||
return normalizePayload(denormalizedPayload);
|
||||
|
||||
/**
|
||||
* Reduces the size of payload
|
||||
*/
|
||||
function normalizePayload(payload: typeof denormalizedPayload) {
|
||||
const allUsersAcrossAllEventTypes = new Map<
|
||||
number,
|
||||
EventTypeGroup["eventTypes"][number]["users"][number]
|
||||
>();
|
||||
const eventTypeGroups = payload.eventTypeGroups.map((group) => {
|
||||
return {
|
||||
...group,
|
||||
eventTypes: group.eventTypes.map((eventType) => {
|
||||
const { users, ...rest } = eventType;
|
||||
return {
|
||||
...rest,
|
||||
// Send userIds per event and keep the actual users object outside
|
||||
userIds: users.map((user) => {
|
||||
allUsersAcrossAllEventTypes.set(user.id, user);
|
||||
return user.id;
|
||||
}),
|
||||
};
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
...payload,
|
||||
allUsersAcrossAllEventTypes,
|
||||
eventTypeGroups,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
export function compareMembership(mship1: MembershipRole, mship2: MembershipRole) {
|
||||
const mshipToNumber = (mship: MembershipRole) =>
|
||||
Object.keys(MembershipRole).findIndex((mmship) => mmship === mship);
|
||||
return mshipToNumber(mship1) > mshipToNumber(mship2);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import type { baseEventTypeSelect } from "@calcom/prisma/selects";
|
||||
import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["getEventTypesPublic"] });
|
||||
|
||||
export type EventTypesPublic = Awaited<ReturnType<typeof getEventTypesPublic>>;
|
||||
|
||||
export async function getEventTypesPublic(userId: number) {
|
||||
const eventTypesWithHidden = await getEventTypesWithHiddenFromDB(userId);
|
||||
|
||||
const eventTypesRaw = eventTypesWithHidden.filter((evt) => !evt.hidden);
|
||||
|
||||
return eventTypesRaw.map((eventType) => ({
|
||||
...eventType,
|
||||
metadata: EventTypeMetaDataSchema.parse(eventType.metadata || {}),
|
||||
descriptionAsSafeHTML: markdownToSafeHTML(eventType.description),
|
||||
}));
|
||||
}
|
||||
|
||||
type BaseEventType = Prisma.EventTypeGetPayload<{
|
||||
select: typeof baseEventTypeSelect;
|
||||
}>;
|
||||
|
||||
type RawEventType = BaseEventType & {
|
||||
metadata: Record<string, any> | null;
|
||||
};
|
||||
|
||||
const getEventTypesWithHiddenFromDB = async (userId: number) => {
|
||||
const eventTypes = await prisma.$queryRaw<RawEventType[]>`
|
||||
SELECT data."id", data."title", data."description", data."length", data."schedulingType"::text,
|
||||
data."recurringEvent", data."slug", data."hidden", data."price", data."currency",
|
||||
data."lockTimeZoneToggleOnBookingPage", data."lockedTimeZone", data."requiresConfirmation", data."requiresBookerEmailVerification",
|
||||
data."metadata", data."canSendCalVideoTranscriptionEmails"
|
||||
FROM (
|
||||
SELECT "EventType"."id", "EventType"."title", "EventType"."description",
|
||||
"EventType"."position", "EventType"."length", "EventType"."schedulingType"::text,
|
||||
"EventType"."recurringEvent", "EventType"."slug", "EventType"."hidden",
|
||||
"EventType"."price", "EventType"."currency",
|
||||
"EventType"."lockTimeZoneToggleOnBookingPage", "EventType"."lockedTimeZone", "EventType"."requiresConfirmation",
|
||||
"EventType"."requiresBookerEmailVerification", "EventType"."metadata",
|
||||
"EventType"."canSendCalVideoTranscriptionEmails", "EventType"."seatsPerTimeSlot"
|
||||
FROM "EventType"
|
||||
WHERE "EventType"."teamId" IS NULL AND "EventType"."userId" = ${userId}
|
||||
UNION
|
||||
SELECT "EventType"."id", "EventType"."title", "EventType"."description",
|
||||
"EventType"."position", "EventType"."length", "EventType"."schedulingType"::text,
|
||||
"EventType"."recurringEvent", "EventType"."slug", "EventType"."hidden",
|
||||
"EventType"."price", "EventType"."currency",
|
||||
"EventType"."lockTimeZoneToggleOnBookingPage", "EventType"."lockedTimeZone", "EventType"."requiresConfirmation",
|
||||
"EventType"."requiresBookerEmailVerification", "EventType"."metadata",
|
||||
"EventType"."canSendCalVideoTranscriptionEmails", "EventType"."seatsPerTimeSlot"
|
||||
FROM "EventType"
|
||||
WHERE "EventType"."teamId" IS NULL
|
||||
AND "EventType"."userId" IS NOT NULL
|
||||
AND "EventType"."id" IN (
|
||||
SELECT "uet1"."A" FROM "_user_eventtype" AS "uet1"
|
||||
INNER JOIN "users" AS "u1" ON "u1"."id" = "uet1"."B"
|
||||
WHERE "u1"."id" = ${userId} AND "uet1"."A" IS NOT NULL
|
||||
)
|
||||
) data
|
||||
ORDER BY data."position" DESC, data."id" ASC`;
|
||||
|
||||
// map and filter metadata, exclude eventType entirely when faulty metadata is found.
|
||||
// report error to exception so we don't lose the error.
|
||||
return eventTypes.reduce<typeof eventTypes>((eventTypes, eventType) => {
|
||||
const parsedMetadata = EventTypeMetaDataSchema.safeParse(eventType.metadata);
|
||||
if (!parsedMetadata.success) {
|
||||
log.error(parsedMetadata.error);
|
||||
return eventTypes;
|
||||
}
|
||||
eventTypes.push({
|
||||
...eventType,
|
||||
metadata: parsedMetadata.data,
|
||||
});
|
||||
return eventTypes;
|
||||
}, []);
|
||||
};
|
||||
@@ -7,7 +7,7 @@ import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/
|
||||
import { getSlugOrRequestedSlug } from "@calcom/features/ee/organizations/lib/orgDomains";
|
||||
import { getOrgOrTeamAvatar } from "@calcom/lib/defaultAvatarImage";
|
||||
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
|
||||
import { getDefaultEvent, getUsernameList } from "@calcom/lib/defaultEvents";
|
||||
import { getDefaultEvent, getUsernameList } from "@calcom/features/eventtypes/lib/defaultEvents";
|
||||
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
|
||||
import { getBookerBaseUrlSync } from "@calcom/lib/getBookerUrl/client";
|
||||
import { isRecurringEvent, parseRecurringEvent } from "@calcom/lib/isRecurringEvent";
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { EventLocationType } from "@calcom/app-store/locations";
|
||||
import type { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/app-store/zod-utils";
|
||||
import type { ChildrenEventType } from "@calcom/features/eventtypes/components/ChildrenEventTypeSelect";
|
||||
import type { IntervalLimit } from "@calcom/lib/intervalLimits/intervalLimitSchema";
|
||||
import type { EventLocationType } from "@calcom/app-store/locations";
|
||||
import type { AttributesQueryValue } from "@calcom/lib/raqb/types";
|
||||
import type { EventTypeTranslation } from "@calcom/prisma/client";
|
||||
import { type PeriodType, SchedulingType } from "@calcom/prisma/enums";
|
||||
|
||||
@@ -4,9 +4,10 @@ import type { SubmitHandler, UseFormReturn } from "react-hook-form";
|
||||
import { Controller, useFieldArray, useForm, useFormContext } from "react-hook-form";
|
||||
import type { z } from "zod";
|
||||
import { ZodError } from "zod";
|
||||
|
||||
import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
|
||||
import { getCurrencySymbol } from "@calcom/app-store/_utils/payments/currencyConversions";
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { getCurrencySymbol } from "@calcom/lib/currencyConversions";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { md } from "@calcom/lib/markdownIt";
|
||||
import { markdownToSafeHTMLClient } from "@calcom/lib/markdownToSafeHTMLClient";
|
||||
|
||||
@@ -20,7 +20,7 @@ vi.mock("@calcom/features/notifications/sendNotification", () => ({
|
||||
sendNotification: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/lib/videoClient", () => ({
|
||||
vi.mock("@calcom/app-store/videoClient", () => ({
|
||||
createInstantMeetingWithCalVideo: vi.fn().mockResolvedValue({
|
||||
type: "daily_video",
|
||||
id: "MOCK_INSTANT_MEETING_ID",
|
||||
|
||||
@@ -22,7 +22,7 @@ import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
|
||||
import { isPrismaObjOrUndefined } from "@calcom/lib/isPrismaObj";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { createInstantMeetingWithCalVideo } from "@calcom/lib/videoClient";
|
||||
import { createInstantMeetingWithCalVideo } from "@calcom/app-store/videoClient";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { Prisma } from "@calcom/prisma/client";
|
||||
import { BookingStatus, WebhookTriggerEvents } from "@calcom/prisma/enums";
|
||||
|
||||
@@ -6,7 +6,7 @@ import { isBookingDryRun } from "@calcom/features/bookings/Booker/utils/isBookin
|
||||
import { useTimesForSchedule } from "@calcom/features/schedules/lib/use-schedule/useTimesForSchedule";
|
||||
import { getRoutedTeamMemberIdsFromSearchParams } from "@calcom/lib/bookings/getRoutedTeamMemberIdsFromSearchParams";
|
||||
import { PUBLIC_QUERY_AVAILABLE_SLOTS_INTERVAL_SECONDS } from "@calcom/lib/constants";
|
||||
import { getUsernameList } from "@calcom/lib/defaultEvents";
|
||||
import { getUsernameList } from "@calcom/features/eventtypes/lib/defaultEvents";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
import { useApiV2AvailableSlots } from "./useApiV2AvailableSlots";
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { getAnalyticsService } from "@calcom/app-store/_utils/getAnalytics";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import type { AnalyticsService, SendEventProps } from "@calcom/types/AnalyticsService";
|
||||
import type { CredentialPayload } from "@calcom/types/Credential";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["AnalyticsManager"] });
|
||||
export default class AnalyticsManager {
|
||||
analyticsService: AnalyticsService | null | undefined = null;
|
||||
credential: CredentialPayload;
|
||||
|
||||
constructor(credential: CredentialPayload) {
|
||||
this.credential = credential;
|
||||
}
|
||||
|
||||
private async getAnalyticsService(credential: CredentialPayload) {
|
||||
if (this.analyticsService) return this.analyticsService;
|
||||
const analyticsService = await getAnalyticsService({ credential });
|
||||
this.analyticsService = analyticsService;
|
||||
|
||||
if (!this.analyticsService) {
|
||||
log.error("Analytics service initialization failed");
|
||||
}
|
||||
|
||||
return analyticsService;
|
||||
}
|
||||
|
||||
public async sendEvent(props: SendEventProps) {
|
||||
const analyticsService = await this.getAnalyticsService(this.credential);
|
||||
if (!analyticsService) return;
|
||||
|
||||
return await analyticsService.sendEvent(props);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { CredentialForCalendarService } from "@calcom/types/Credential";
|
||||
|
||||
import { tasker } from "../../../tasker";
|
||||
|
||||
interface HandleAnalyticsEventsProps {
|
||||
credentials: CredentialForCalendarService[];
|
||||
rawBookingData: Record<string, any>;
|
||||
bookingInfo: {
|
||||
email: string;
|
||||
name: string;
|
||||
eventName: string;
|
||||
};
|
||||
isTeamEventType: boolean;
|
||||
}
|
||||
|
||||
export const handleAnalyticsEvents = async ({
|
||||
credentials,
|
||||
rawBookingData,
|
||||
bookingInfo,
|
||||
isTeamEventType,
|
||||
}: HandleAnalyticsEventsProps) => {
|
||||
const { dub_id } = await rawBookingData;
|
||||
|
||||
if (!dub_id || typeof dub_id !== "string") return;
|
||||
|
||||
const dubCredential = credentials.find((cred) => {
|
||||
if (cred.appId !== "dub") return false;
|
||||
if (isTeamEventType && !cred.teamId) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
if (!dubCredential) return;
|
||||
|
||||
try {
|
||||
await tasker.create("sendAnalyticsEvent", {
|
||||
credentialId: dubCredential.id,
|
||||
info: {
|
||||
id: dub_id,
|
||||
...bookingInfo,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("Error sending dub lead: ", err);
|
||||
}
|
||||
};
|
||||
@@ -1,8 +1,8 @@
|
||||
import AnalyticsManager from "@calcom/lib/analyticsManager/analyticsManager";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
|
||||
|
||||
import AnalyticsManager from "./analyticsManager";
|
||||
import { sendAnalyticsEventSchema } from "./schema";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: [`[[tasker] sendAnalyticsEvent]`] });
|
||||
|
||||
Reference in new issue
Block a user