refactor: Cal.diy (#28903)

* feat: Cal.diy — community-driven MIT-licensed fork of Cal.com

This squashed commit contains all Cal.diy changes applied on top of calcom/cal.com main:

- Rebrand Cal.com to Cal.diy across the entire codebase
- Remove Enterprise Edition (EE) features, license checks, and AGPL restrictions
- Switch license from AGPL-3.0 to MIT
- Remove docs/ directory (migrated to Nextra at cal.diy)
- Remove dead code: org tests, EE tips, platform nav, premium username, SAML/SSO, etc.
- Clean up .env.example for self-hosted Cal.diy
- Update Docker image references to calcom/cal.diy
- Update README, CONTRIBUTING.md, and issue templates for Cal.diy community fork
- Add PR welcome bot for Cal.diy contributors
- Fix API v2 breaking changes oasdiff ignore entries
- Replace Blacksmith CI runners with default GitHub Actions

3893 files changed, 20789 insertions(+), 411020 deletions(-)

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

* refactor: remove org-specific /organizations/:orgId endpoints from API v2 atoms controllers (#1701)

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix: revert Cal.diy Inc to Cal.com, Inc. in license files, copyright notices, and package metadata (#1702)

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* rip out org related comments in api v2

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
Benny JooandDevin AI authored and GitHub committed 2026-04-15 09:52:36 -03:00
1 parent a17f28e9ab
commit ab21c7f805
4080 files changed
+14403 -404922

No files matched your search

+3 -2
View File
@@ -107,13 +107,14 @@ export default function BookingPageTagManager({
// Only support UpperCase,_and numbers in template variables. This prevents accidental replacement of other strings.
const regex = /\{([A-Z_\d]+)\}/g;
let matches;
const appDataRecord = eventTypeAppData as Record<string, unknown>;
while ((matches = regex.exec(val))) {
const variableName = matches[1];
if (eventTypeAppData[variableName]) {
if (appDataRecord[variableName]) {
// Replace if value is available. It can possible not be a template variable that just matches the regex.
val = val.replace(
new RegExp(`{${variableName}}`, "g"),
eventTypeAppData[variableName]
String(appDataRecord[variableName])
) as NonNullable<T>;
}
}
+3 -3
View File
@@ -10,7 +10,7 @@
1. Include installation instructions and links to the app's website.
2. For url use `<baseUrl>/api/integrations`, rather than `<Cal.com>/api/integrations`
2. For url use `<baseUrl>/api/integrations`, rather than `<Cal.diy>/api/integrations`
#### `config.json`
@@ -21,5 +21,5 @@
1. Add API documentation links in comments for files `api`, `lib` and `types`
2. Use [`AppDeclarativeHandler`](../types/AppHandler.d.ts) across all apps. Whatever isn't supported in it, support that.
3. README should be added in the respective app and can be linked in main README [like this](https://github.com/calcom/cal.com/pull/10429/files/155ac84537d12026f595551fe3542e810b029714#diff-b335630551682c19a781afebcf4d07bf978fb1f8ac04c6bf87428ed5106870f5R509)
4. Also, no env variables should be added by an app. They should be [added in `zod.ts`](https://github.com/calcom/cal.com/blob/main/packages/app-store/jitsivideo/zod.ts) and then they would be automatically available to be modified by the cal.com app admin. In local development you can open /settings/admin with the admin credentials (see [seed.ts](packages/prisma/seed.ts))
3. README should be added in the respective app and can be linked in main README [like this](https://github.com/calcom/cal.diy/pull/10429/files/155ac84537d12026f595551fe3542e810b029714#diff-b335630551682c19a781afebcf4d07bf978fb1f8ac04c6bf87428ed5106870f5R509)
4. Also, no env variables should be added by an app. They should be [added in `zod.ts`](https://github.com/calcom/cal.diy/blob/main/packages/app-store/jitsivideo/zod.ts) and then they would be automatically available to be modified by the cal.com app admin. In local development you can open /settings/admin with the admin credentials (see [seed.ts](packages/prisma/seed.ts))
-1
View File
@@ -7,7 +7,6 @@ import type { InstallAppButtonProps } from "./types";
export const InstallAppButton = (
props: {
teamsPlanRequired?: App["teamsPlanRequired"];
type: App["type"];
wrapperClassName?: string;
disableInstall?: boolean;
@@ -6,7 +6,7 @@ import useAddAppMutation from "../_utils/useAddAppMutation";
import { InstallAppButton } from "../InstallAppButton";
import type { AppCardApp } from "../types";
type AppData = Pick<AppCardApp, "type" | "variant" | "slug" | "teamsPlanRequired">;
type AppData = Pick<AppCardApp, "type" | "variant" | "slug">;
/**
* Use this component to allow installing an app from anywhere on the app.
@@ -45,7 +45,6 @@ export default function OmniInstallAppButton({
return (
<InstallAppButton
type={app.type}
teamsPlanRequired={app.teamsPlanRequired}
wrapperClassName={classNames("[@media(max-width:260px)]:w-full", className)}
render={({ useDefaultComponent, ...props }) => {
if (useDefaultComponent) {
@@ -1,72 +0,0 @@
import type { z } from "zod";
import type { EventTypeAppMetadataSchema } from "@calcom/app-store/zod-utils";
import CrmManager from "@calcom/features/crmManager/crmManager";
import logger from "@calcom/lib/logger";
import { prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
export async function getCRMContactOwnerForRRLeadSkip(
bookerEmail: string,
eventTypeMetadata: Prisma.JsonValue
): Promise<{
email: string | null;
recordType: string | null;
crmAppSlug: string | null;
recordId: string | null;
}> {
const nullReturnValue = { email: null, recordType: null, crmAppSlug: "", recordId: null };
const parsedEventTypeMetadata = EventTypeMetaDataSchema.safeParse(eventTypeMetadata);
if (!parsedEventTypeMetadata.success || !parsedEventTypeMetadata.data?.apps) return nullReturnValue;
const crm = await getCRMManagerWithRRLeadSkip(parsedEventTypeMetadata.data.apps);
if (!crm) return nullReturnValue;
const { crmManager, crmAppSlug } = crm;
const startTime = performance.now();
const contact = await crmManager.getContacts({ emails: bookerEmail, forRoundRobinSkip: true });
const endTime = performance.now();
logger.info(`Fetching from CRM took ${endTime - startTime}ms`);
if (!contact?.length || !contact[0].ownerEmail) return nullReturnValue;
return {
email: contact[0].ownerEmail ?? null,
recordType: contact[0].recordType ?? null,
crmAppSlug,
recordId: contact[0].id ?? null,
};
}
async function getCRMManagerWithRRLeadSkip(apps: z.infer<typeof EventTypeAppMetadataSchema>) {
let crmRoundRobinLeadSkip;
for (const appKey in apps) {
const app = apps[appKey as keyof typeof apps];
if (
app.enabled &&
typeof app.appCategories === "object" &&
app.appCategories.some((category: string) => category === "crm") &&
app.roundRobinLeadSkip
) {
crmRoundRobinLeadSkip = app;
break;
}
}
if (!crmRoundRobinLeadSkip) return;
const crmCredential = await prisma.credential.findUnique({
where: {
id: crmRoundRobinLeadSkip.credentialId,
},
include: {
user: {
select: {
email: true,
},
},
},
});
if (!crmCredential) return;
return {
crmManager: new CrmManager(crmCredential, crmRoundRobinLeadSkip),
crmAppSlug: crmCredential.appId,
};
}
@@ -0,0 +1,26 @@
/**
* Common shape for app metadata properties that may exist on any app.
*
* The generated appDataSchemas union includes {} (empty object) variants from apps
* with no custom schema (e.g. dailyvideo). This means when iterating over parsed app
* metadata, TypeScript cannot guarantee that common properties like `enabled`, `price`,
* or `currency` exist on all variants of the union.
*
* Use this interface to safely narrow app metadata values before accessing these
* common properties. Cast with `as CommonAppData` when you need to access shared
* fields across different app types.
*/
export interface CommonAppData {
enabled?: boolean;
price?: number;
currency?: string;
credentialId?: number;
appCategories?: string[];
paymentOption?: string;
TRACKING_ID?: string;
trackingId?: string;
trackingEvent?: string;
autoChargeNoShowFeeIfCancelled?: boolean;
autoChargeNoShowFeeTimeValue?: number;
autoChargeNoShowFeeTimeUnit?: string;
}
@@ -0,0 +1,19 @@
import { createHash } from "node:crypto";
import prisma from "@calcom/prisma";
import type { ApiKey } from "@calcom/prisma/client";
function hashAPIKey(apiKey: string): string {
return createHash("sha256").update(apiKey).digest("hex");
}
export async function findValidApiKey(apiKey: string, appId: string): Promise<ApiKey | null> {
const hashedKey = hashAPIKey(apiKey);
return prisma.apiKey.findFirst({
where: {
hashedKey,
appId,
OR: [{ expiresAt: null }, { expiresAt: { gte: new Date() } }],
},
});
}
+3 -40
View File
@@ -1,49 +1,12 @@
import type { eventTypeAppMetadataOptionalSchema } from "@calcom/app-store/zod-utils";
import type { z } from "zod";
import type { eventTypeAppMetadataOptionalSchema } from "@calcom/app-store/zod-utils";
import { getAppNameFromSlug } from "@calcom/features/booking-audit/lib/getAppNameFromSlug";
import { makeAppActor, makeAppActorUsingSlug } from "@calcom/features/booking-audit/lib/makeActor";
import type { Actor } from "@calcom/features/booking-audit/lib/dto/types";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
const log = logger.getSubLogger({ prefix: ["[getAppActor]"] });
/**
* Gets an actor object for an app, using the credentialId if available,
* otherwise falling back to the appSlug.
*
* @param params - The parameters for creating the actor
* @param params.appSlug - The slug of the app (e.g., "stripe", "paypal", "zoom")
* @param params.bookingId - The booking ID for logging purposes
* @param params.apps - The event type app metadata containing credentialIds
* @returns An Actor object representing the app
*/
export function getAppActor({
appSlug,
bookingId,
apps,
}: {
appSlug: string;
bookingId: number;
apps: z.infer<typeof eventTypeAppMetadataOptionalSchema>;
}): Actor {
let actor: Actor;
const appData = apps?.[appSlug as keyof typeof apps];
if (appData?.credentialId) {
actor = makeAppActor({ credentialId: appData.credentialId });
} else {
log.warn(
`Missing credentialId for app, using appSlug fallback`,
safeStringify({
bookingId,
appSlug,
})
);
actor = makeAppActorUsingSlug({
appSlug,
name: getAppNameFromSlug({ appSlug }),
});
}
return actor;
}): { type: string; identifier: string } {
return { type: "app", identifier: appSlug };
}
@@ -3,6 +3,8 @@ import type { z } from "zod";
import type { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/app-store/zod-utils";
import type { BookerEventForAppData } from "@calcom/features/bookings/types.server";
import type { CommonAppData } from "./commonAppDataType";
export type EventTypeApps = NonNullable<
NonNullable<z.infer<typeof eventTypeMetaDataSchemaWithTypedApps>>["apps"]
>;
@@ -12,20 +14,21 @@ export const getEventTypeAppData = <T extends EventTypeAppsList>(
eventType: BookerEventForAppData,
appId: T,
forcedGet?: boolean
): EventTypeApps[T] => {
): EventTypeApps[T] | null => {
const metadata = eventType.metadata;
const appMetadata = metadata?.apps && metadata.apps[appId];
if (appMetadata) {
const allowDataGet = forcedGet ? true : appMetadata.enabled;
const app = appMetadata as CommonAppData;
const allowDataGet = forcedGet ? true : app.enabled;
return allowDataGet
? {
...appMetadata,
// We should favor eventType's price and currency over appMetadata's price and currency
price: eventType.price || appMetadata.price || null,
currency: eventType.currency || appMetadata.currency || null,
price: eventType.price || app.price || null,
currency: eventType.currency || app.currency || null,
// trackingId is legacy way to store value for TRACKING_ID. So, we need to support both.
TRACKING_ID: appMetadata.TRACKING_ID || appMetadata.trackingId || null,
TRACKING_EVENT: appMetadata.trackingEvent || "Lead",
TRACKING_ID: app.TRACKING_ID || app.trackingId || null,
TRACKING_EVENT: app.trackingEvent || "Lead",
}
: null;
}
@@ -22,13 +22,14 @@ const checkForMultiplePaymentApps = (
let enabledPaymentApps = 0;
for (const appKey in metadata?.apps) {
const app = metadata?.apps[appKey as keyof typeof appDataSchemas];
if (!app) continue;
if ("appCategories" in app) {
if ("appCategories" in app && app.appCategories) {
const isPaymentApp = app.appCategories.includes("payment");
if (isPaymentApp && app.enabled) {
if (isPaymentApp && "enabled" in app && app.enabled) {
enabledPaymentApps++;
}
} else if ("price" in app && app.enabled) {
} else if ("price" in app && "enabled" in app && app.enabled) {
enabledPaymentApps++;
}
}
@@ -22,7 +22,17 @@ export function getPaymentAppData(
};
const metadataApps = eventType.metadata?.apps;
if (!metadataApps) {
return { enabled: false, price: 0, currency: "usd", appId: null };
return {
enabled: false,
price: 0,
currency: "usd",
appId: null,
paymentOption: "ON_BOOKING" as const,
credentialId: undefined,
refundPolicy: undefined,
refundDaysCount: undefined,
refundCountCalendarDays: undefined,
};
}
type appId = keyof typeof metadataApps;
// @TODO: a lot of unknowns types here can be improved later
@@ -38,7 +48,7 @@ export function getPaymentAppData(
price: number;
currency: string;
appId: EventTypeAppsList | null;
paymentOption: typeof paymentOptionEnum;
paymentOption: z.infer<typeof paymentOptionEnum>;
credentialId?: number;
refundPolicy?: string;
refundDaysCount?: number;
@@ -47,8 +57,16 @@ export function getPaymentAppData(
for (const appId of paymentAppIds) {
const appData = getEventTypeAppData(eventType, appId, forcedGet);
if (appData && paymentAppData === null) {
const data = appData as { enabled?: boolean; price?: number; currency?: string; paymentOption?: string; credentialId?: number; refundPolicy?: string; refundDaysCount?: number; refundCountCalendarDays?: boolean };
paymentAppData = {
...appData,
enabled: data.enabled ?? false,
price: data.price ?? 0,
currency: data.currency ?? "usd",
paymentOption: (data.paymentOption ?? "ON_BOOKING") as z.infer<typeof paymentOptionEnum>,
credentialId: data.credentialId,
refundPolicy: data.refundPolicy,
refundDaysCount: data.refundDaysCount,
refundCountCalendarDays: data.refundCountCalendarDays,
appId,
};
}
@@ -2,7 +2,7 @@
* @vitest-environment node
*/
import { BookingStatus, WebhookTriggerEvents, WorkflowTriggerEvents } from "@calcom/prisma/enums";
import { BookingStatus, WebhookTriggerEvents } from "@calcom/prisma/enums";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { handlePaymentSuccess } from "./handlePaymentSuccess";
@@ -10,15 +10,12 @@ import { handlePaymentSuccess } from "./handlePaymentSuccess";
vi.mock("@calcom/features/bookings/lib/payment/getBooking");
vi.mock("@calcom/features/webhooks/lib/getWebhooks");
vi.mock("@calcom/features/webhooks/lib/sendOrSchedulePayload");
vi.mock("@calcom/features/ee/workflows/lib/getAllWorkflowsFromEventType");
vi.mock("@calcom/features/ee/workflows/lib/service/WorkflowService");
vi.mock("@calcom/features/tasker");
vi.mock("@calcom/features/bookings/lib/getAllCredentialsForUsersOnEvent/getAllCredentials", () => ({
getAllCredentialsIncludeServiceAccountKey: vi.fn().mockResolvedValue([]),
}));
vi.mock("@calcom/features/users/repositories/UserRepository", () => ({
UserRepository: class {
constructor() {}
enrichUserWithItsProfile = vi.fn().mockResolvedValue({ profile: null });
},
}));
@@ -40,14 +37,10 @@ vi.mock("@calcom/prisma", async (importOriginal) => {
},
};
});
vi.mock("@calcom/lib/getOrgIdFromMemberOrTeamId");
vi.mock("@calcom/features/ee/organizations/lib/getBookerUrlServer");
vi.mock("@calcom/lib/getTeamIdFromEventType");
vi.mock("@calcom/lib/CalEventParser");
vi.mock("@calcom/features/ee/billing/credit-service");
vi.mock("@calcom/features/platform-oauth-client/platform-oauth-client.repository", () => ({
PlatformOAuthClientRepository: class {
constructor() {}
getByUserId = vi.fn().mockResolvedValue(null);
},
}));
@@ -65,12 +58,7 @@ vi.mock("@calcom/lib/logger", () => ({
})),
},
}));
vi.mock("@calcom/features/routing-forms/lib/findFieldValueByIdentifier", () => ({
findFieldValueByIdentifier: vi.fn(),
}));
vi.mock("@calcom/app-store/routing-forms/lib/findFieldValueByIdentifier", () => ({
findFieldValueByIdentifier: vi.fn(),
}));
// Routing forms feature removed - mocks no longer needed
vi.mock("@calcom/app-store/_utils/getCalendar", () => ({
getCalendar: vi.fn().mockReturnValue(null),
@@ -93,15 +81,9 @@ vi.mock("@calcom/features/calendars/lib/CalendarManager", () => ({
}));
import { getBooking } from "@calcom/features/bookings/lib/payment/getBooking";
import { CreditService } from "@calcom/features/ee/billing/credit-service";
import { getBookerBaseUrl } from "@calcom/features/ee/organizations/lib/getBookerUrlServer";
import { getAllWorkflowsFromEventType } from "@calcom/features/ee/workflows/lib/getAllWorkflowsFromEventType";
import { WorkflowService } from "@calcom/features/ee/workflows/lib/service/WorkflowService";
import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";
import { WebhookVersion } from "@calcom/features/webhooks/lib/interface/IWebhookRepository";
import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";
import { getVideoCallUrlFromCalEvent } from "@calcom/lib/CalEventParser";
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
import { getTeamIdFromEventType } from "@calcom/lib/getTeamIdFromEventType";
import type { TraceContext } from "@calcom/lib/tracing";
import prisma from "@calcom/prisma";
@@ -205,17 +187,6 @@ describe("handlePaymentSuccess", () => {
version: WebhookVersion.V_2021_10_20,
};
const mockWorkflow = {
id: 1,
name: "Test Workflow",
trigger: WorkflowTriggerEvents.BOOKING_PAID,
time: 24,
timeUnit: "HOUR" as const,
userId: 1,
teamId: null,
steps: [],
} as any;
beforeEach(() => {
vi.clearAllMocks();
@@ -237,16 +208,8 @@ describe("handlePaymentSuccess", () => {
vi.mocked(getWebhooks).mockResolvedValue([mockWebhookSubscriber]);
vi.mocked(sendPayload).mockResolvedValue({ ok: true, status: 200 });
// Mock workflow functions
vi.mocked(getAllWorkflowsFromEventType).mockResolvedValue([mockWorkflow]);
vi.mocked(WorkflowService.scheduleWorkflowsFilteredByTriggerEvent).mockResolvedValue(undefined);
// Mock utility functions
vi.mocked(getOrgIdFromMemberOrTeamId).mockResolvedValue(undefined);
vi.mocked(getBookerBaseUrl).mockResolvedValue("https://cal.com");
vi.mocked(getTeamIdFromEventType).mockResolvedValue(null);
vi.mocked(getVideoCallUrlFromCalEvent).mockReturnValue("");
vi.mocked(CreditService.prototype.hasAvailableCredits).mockResolvedValue(true);
});
it("should trigger BOOKING_PAID webhooks with correct payload", async () => {
@@ -265,7 +228,6 @@ describe("handlePaymentSuccess", () => {
eventTypeId: mockBooking.eventTypeId,
triggerEvent: WebhookTriggerEvents.BOOKING_PAID,
teamId: null,
orgId: undefined,
oAuthClientId: undefined,
});
@@ -292,39 +254,6 @@ describe("handlePaymentSuccess", () => {
);
});
it("should trigger BOOKING_PAID workflows with correct calendar event", async () => {
await expect(
handlePaymentSuccess({
paymentId: mockPaymentId,
appSlug: "stripe",
bookingId: mockBookingId,
traceContext: mockTraceContext,
})
).rejects.toThrow(); // Function throws HttpCode 200 at the end
// Verify workflows were fetched
expect(getAllWorkflowsFromEventType).toHaveBeenCalledWith(mockBooking.eventType, mockBooking.userId);
// Verify workflows were scheduled
expect(WorkflowService.scheduleWorkflowsFilteredByTriggerEvent).toHaveBeenCalledWith({
workflows: [mockWorkflow],
smsReminderNumber: null,
calendarEvent: expect.objectContaining({
type: mockEvt.type,
title: mockEvt.title,
startTime: mockEvt.startTime,
endTime: mockEvt.endTime,
eventType: expect.objectContaining({
slug: mockBooking.eventType.slug,
}),
bookerUrl: "https://cal.com",
}),
hideBranding: false,
triggers: [WorkflowTriggerEvents.BOOKING_PAID],
creditCheckFn: expect.any(Function),
});
});
it("should handle webhook errors gracefully without blocking", async () => {
const webhookError = new Error("Webhook failed");
vi.mocked(sendPayload).mockRejectedValueOnce(webhookError);
@@ -343,24 +272,6 @@ describe("handlePaymentSuccess", () => {
expect(sendPayload).toHaveBeenCalled();
});
it("should handle workflow errors gracefully without blocking", async () => {
const workflowError = new Error("Workflow failed");
vi.mocked(WorkflowService.scheduleWorkflowsFilteredByTriggerEvent).mockRejectedValueOnce(workflowError);
// Should not throw (workflow errors are caught)
await expect(
handlePaymentSuccess({
paymentId: mockPaymentId,
appSlug: "stripe",
bookingId: mockBookingId,
traceContext: mockTraceContext,
})
).rejects.toThrow(); // Throws HttpCode 200 at the end
// Verify workflow was still attempted
expect(WorkflowService.scheduleWorkflowsFilteredByTriggerEvent).toHaveBeenCalled();
});
it("should include payment metadata in webhook payload", async () => {
await expect(
handlePaymentSuccess({
@@ -1,24 +1,19 @@
import { eventTypeAppMetadataOptionalSchema } from "@calcom/app-store/zod-utils";
import { sendScheduledEmailsAndSMS } from "@calcom/emails/email-manager";
import EventManager, { placeholderCreatedEvent } from "@calcom/features/bookings/lib/EventManager";
import { doesBookingRequireConfirmation } from "@calcom/features/bookings/lib/doesBookingRequireConfirmation";
import EventManager, { placeholderCreatedEvent } from "@calcom/features/bookings/lib/EventManager";
import { getAllCredentialsIncludeServiceAccountKey } from "@calcom/features/bookings/lib/getAllCredentialsForUsersOnEvent/getAllCredentials";
import { handleBookingRequested } from "@calcom/features/bookings/lib/handleBookingRequested";
import { handleConfirmation } from "@calcom/features/bookings/lib/handleConfirmation";
import { getBooking } from "@calcom/features/bookings/lib/payment/getBooking";
import { CreditService } from "@calcom/features/ee/billing/credit-service";
import { getBookerBaseUrl } from "@calcom/features/ee/organizations/lib/getBookerUrlServer";
import { getAllWorkflowsFromEventType } from "@calcom/features/ee/workflows/lib/getAllWorkflowsFromEventType";
import { WorkflowService } from "@calcom/features/ee/workflows/lib/service/WorkflowService";
import { getPlatformParams } from "@calcom/features/platform-oauth-client/get-platform-params";
import { PlatformOAuthClientRepository } from "@calcom/features/platform-oauth-client/platform-oauth-client.repository";
import tasker from "@calcom/features/tasker";
import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";
import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";
import type { EventPayloadType, EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";
import { getVideoCallUrlFromCalEvent } from "@calcom/lib/CalEventParser";
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
import { getTeamIdFromEventType } from "@calcom/lib/getTeamIdFromEventType";
import tasker from "@calcom/features/tasker";
import { HttpError as HttpCode } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
@@ -26,11 +21,9 @@ import type { TraceContext } from "@calcom/lib/tracing";
import { distributedTracing } from "@calcom/lib/tracing/factory";
import prisma from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { BookingStatus, WebhookTriggerEvents, WorkflowTriggerEvents } from "@calcom/prisma/enums";
import { BookingStatus, WebhookTriggerEvents } from "@calcom/prisma/enums";
import type { EventTypeMetadata } from "@calcom/prisma/zod-utils";
import { getAppActor } from "../getAppActor";
const log = logger.getSubLogger({ prefix: ["[handlePaymentSuccess]"] });
export async function handlePaymentSuccess(params: {
@@ -46,9 +39,6 @@ export async function handlePaymentSuccess(params: {
});
log.debug(`handling payment success for bookingId ${bookingId}`);
const { booking, user: userWithCredentials, evt, eventType } = await getBooking(bookingId);
const apps = eventTypeAppMetadataOptionalSchema.parse(eventType?.metadata?.apps);
const actor = getAppActor({ appSlug, bookingId, apps });
try {
await tasker.cancelWithReference(booking.uid, "sendAwaitingPaymentEmail");
log.debug(`Cancelled scheduled awaiting payment email for booking ${bookingId}`);
@@ -133,13 +123,8 @@ export async function handlePaymentSuccess(params: {
});
const triggerForUser = !teamId || (teamId && booking.eventType?.parentId);
const userId = triggerForUser ? booking.userId : null;
const orgId = await getOrgIdFromMemberOrTeamId({ memberId: userId, teamId });
const bookerUrl = await getBookerBaseUrl(orgId ?? null);
try {
// Get workflows for BOOKING_PAID trigger
const workflows = await getAllWorkflowsFromEventType(booking.eventType, booking.userId);
const paymentExternalId = payment.externalId;
const paymentMetadata = {
@@ -160,9 +145,8 @@ export async function handlePaymentSuccess(params: {
length: booking.eventType?.length,
};
const { assignmentReason: _emailAssignmentReason, ...evtWithoutAssignmentReason } = evt;
const payload: EventPayloadType = {
...evtWithoutAssignmentReason,
...evt,
...eventTypeInfo,
bookingId,
eventTypeId: booking.eventType?.id,
@@ -179,7 +163,6 @@ export async function handlePaymentSuccess(params: {
eventTypeId: booking.eventTypeId,
triggerEvent: WebhookTriggerEvents.BOOKING_PAID,
teamId: booking.eventType?.teamId,
orgId,
oAuthClientId: platformClientParams?.platformClientId,
});
@@ -201,40 +184,6 @@ export async function handlePaymentSuccess(params: {
// Wait for webhook invocations to finish before returning
await Promise.all(bookingPaidSubscribers);
// Trigger BOOKING_PAID workflows
try {
const meetingUrl = getVideoCallUrlFromCalEvent(evt);
const calendarEventForWorkflow = {
...evt,
eventType: {
slug: booking.eventType?.slug || "",
schedulingType: booking.eventType?.schedulingType,
hosts:
booking.eventType?.hosts?.map((host) => ({
user: {
email: host.user.email,
destinationCalendar: host.user.destinationCalendar,
},
})) || [],
},
bookerUrl: bookerUrl,
metadata: meetingUrl ? { videoCallUrl: meetingUrl } : undefined,
};
const creditService = new CreditService();
await WorkflowService.scheduleWorkflowsFilteredByTriggerEvent({
workflows,
smsReminderNumber: booking.smsReminderNumber,
calendarEvent: calendarEventForWorkflow,
hideBranding: evt.hideBranding ?? false,
triggers: [WorkflowTriggerEvents.BOOKING_PAID],
creditCheckFn: creditService.hasAvailableCredits.bind(creditService),
});
} catch (error) {
log.error("Error while scheduling workflow reminders for booking paid", safeStringify(error));
}
} catch (error) {
log.error("Error while triggering BOOKING_PAID webhook", safeStringify(error));
}
@@ -250,15 +199,11 @@ export async function handlePaymentSuccess(params: {
paid: true,
platformClientParams,
traceContext: updatedTraceContext,
actionSource: "WEBHOOK",
impersonatedByUserUuid: null,
actor,
});
} else {
await handleBookingRequested({
evt,
booking,
oAuthClientId: platformClientParams?.platformClientId,
});
log.debug(`handling booking request for eventId ${eventType.id}`);
}
@@ -1,34 +0,0 @@
"use client";
/**
* Client-only RAQB utilities that require the react-awesome-query-builder runtime.
* These functions should only be imported in client-side React components.
*/
import type { JsonTree } from "react-awesome-query-builder";
import type { Config } from "react-awesome-query-builder";
import { Utils as QbUtils } from "react-awesome-query-builder";
export function buildEmptyQueryValue() {
return { id: QbUtils.uuid(), type: "group" as const };
}
export const buildStateFromQueryValue = ({
queryValue,
config,
}: {
/**
* Allow null as the queryValue as initially there could be no queryValue and without that we can't build the state and can't show the UI
*/
queryValue: JsonTree | null;
config: Config;
}) => {
const queryValueToUse = queryValue || buildEmptyQueryValue();
const immutableTree = QbUtils.checkTree(QbUtils.loadTree(queryValueToUse), config);
return {
state: {
tree: immutableTree,
config,
},
queryValue: QbUtils.getTree(immutableTree),
};
};
@@ -1,204 +0,0 @@
/**
* Server-safe RAQB utilities that don't require the react-awesome-query-builder runtime.
* These functions can be safely imported in server-side code (cron jobs, API routes, etc.)
* without pulling in the client-only RAQB library.
*/
import type { JsonGroup, JsonItem, JsonRule, JsonTree } from "react-awesome-query-builder";
import { getQueryBuilderConfigForAttributes } from "@calcom/app-store/routing-forms/lib/getQueryBuilderConfig";
import { resolveQueryValue } from "@calcom/app-store/routing-forms/lib/resolveQueryValue";
import type {
LocalRoute,
Attribute,
AttributeOptionValueWithType,
AttributeOptionValue,
} from "@calcom/app-store/routing-forms/types/types";
import type { dynamicFieldValueOperands } from "@calcom/lib/raqb/types";
import logger from "@calcom/lib/logger";
import { caseInsensitive } from "@calcom/lib/raqb/utils";
import { safeStringify } from "@calcom/lib/safeStringify";
import { AttributeType } from "@calcom/prisma/enums";
const log = logger.getSubLogger({ prefix: ["raqbUtils"] });
function ensureArray(value: string | string[]) {
return typeof value === "string" ? [value] : value;
}
export const raqbQueryValueUtils = {
isQueryValueARuleGroup: function isQueryValueARuleGroup(queryValue: JsonTree): queryValue is JsonGroup {
return queryValue.type === "group";
},
isARule: function isARule(rule: JsonItem): rule is JsonRule {
return rule.type === "rule";
},
getValueTypeFromAttributesQueryValueForRaqbField:
function getValueTypeFromAttributesQueryValueForRaqbField({
attributesQueryValue,
raqbFieldId,
}: {
attributesQueryValue: JsonTree;
raqbFieldId: string;
}) {
if (!raqbQueryValueUtils.isQueryValueARuleGroup(attributesQueryValue)) {
return null;
}
if (!attributesQueryValue.children1) {
return null;
}
let raqbFieldValueType = null;
Object.values(attributesQueryValue.children1).reduce((acc, rule) => {
if (!raqbQueryValueUtils.isARule(rule)) {
return acc;
}
const ruleProperties = rule?.properties;
if (!ruleProperties) {
return acc;
}
if (ruleProperties.field === raqbFieldId) {
raqbFieldValueType = ruleProperties.valueType?.[0];
}
return acc;
}, null);
return raqbFieldValueType;
},
isQueryValueEmpty: function isQueryValueEmpty(queryValue: JsonTree | null): queryValue is null {
if (!queryValue) {
return true;
}
return !queryValue.children1;
},
};
export function getValueOfAttributeOption(
attributeOptions:
| Pick<AttributeOptionValue, "isGroup" | "contains" | "value">
| Pick<AttributeOptionValue, "isGroup" | "contains" | "value">[]
) {
if (!(attributeOptions instanceof Array)) {
return transformAttributeOption(attributeOptions);
}
return attributeOptions
.map(transformAttributeOption)
.flat()
.filter((value, index, self) => self.indexOf(value) === index);
function transformAttributeOption(
attributeOption: Pick<AttributeOptionValue, "isGroup" | "contains" | "value">
) {
if (attributeOption.isGroup) {
const subOptions = attributeOption.contains.map((option) => option.value);
log.debug("A group option found. Using all its sub-options instead", safeStringify(subOptions));
return subOptions;
}
return attributeOption.value;
}
}
function getAttributesData({
attributesData,
}: {
attributesData: Record<string, AttributeOptionValueWithType>;
attributesQueryValue: NonNullable<LocalRoute["attributesQueryValue"]>;
}) {
return Object.entries(attributesData).reduce(
(acc, [attributeId, { type: attributeType, attributeOption }]) => {
const compatibleValueForAttributeAndFormFieldMatching = caseInsensitive(
getValueOfAttributeOption(attributeOption)
);
acc[attributeId] =
// multiselect attribute's value must be an array as all the operators multiselect_some_in, multiselect_all_in and their respective not operators expect an array
// If we add an operator that doesn't expect an array, we need to somehow make it operator based.
attributeType === AttributeType.MULTI_SELECT
? ensureArray(compatibleValueForAttributeAndFormFieldMatching)
: compatibleValueForAttributeAndFormFieldMatching;
return acc;
},
{} as Record<string, string | string[]>
);
}
/** Gets the attributes that were used to generate the chosen route and their values */
function getAttributesQueryValue({
attributesQueryValue,
attributes,
dynamicFieldValueOperands,
}: {
attributesQueryValue: LocalRoute["attributesQueryValue"] | null;
attributes: Attribute[];
dynamicFieldValueOperands?: dynamicFieldValueOperands;
}) {
if (!attributesQueryValue) {
return null;
}
const resolvedQueryValue = resolveQueryValue({
queryValue: attributesQueryValue,
attributes,
dynamicFieldValueOperands,
});
return resolvedQueryValue;
}
/**
* Returns attributesQueryBuilderConfig with the list of labels instead of list of ids.
*/
export function getAttributesQueryBuilderConfigHavingListofLabels({
dynamicFieldValueOperands,
attributes,
}: {
dynamicFieldValueOperands?: dynamicFieldValueOperands;
attributes: Attribute[];
}) {
const attributesQueryBuilderConfig = getQueryBuilderConfigForAttributes({
attributes,
dynamicOperandFields: dynamicFieldValueOperands?.fields,
});
const attributesQueryBuilderConfigFieldsWithCompatibleListValues = Object.fromEntries(
Object.entries(attributesQueryBuilderConfig.fields).map(([raqbFieldId, raqbField]) => {
const raqbFieldType = raqbField.type;
return [
raqbFieldId,
{
...raqbField,
type: raqbFieldType,
fieldSettings: {
...raqbField.fieldSettings,
listValues: raqbField.fieldSettings.listValues?.map((option) => {
return {
...option,
// Use the title(which is the attributeOption.value) as the value of the raqb field so that it can be compatible for matching with the form field value
value: caseInsensitive(option.title),
};
}),
},
},
];
})
);
const attributesQueryBuilderConfigWithCompatibleListValues = {
...attributesQueryBuilderConfig,
fields: attributesQueryBuilderConfigFieldsWithCompatibleListValues,
};
return attributesQueryBuilderConfigWithCompatibleListValues;
}
/**
* Utilities to establish compatibility between formFieldQueryValue and attributeQueryValue
*/
export const acrossQueryValueCompatiblity = {
getAttributesQueryBuilderConfigHavingListofLabels,
getAttributesQueryValue,
getAttributesData,
resolveQueryValue,
};
File diff suppressed because it is too large. Load diff
@@ -1,24 +0,0 @@
/**
* Barrel file that re-exports from both server and client modules for backward compatibility.
*
* IMPORTANT: This file imports from raqbUtils.client.ts which requires the react-awesome-query-builder runtime.
* For server-side code (cron jobs, API routes, etc.), import directly from raqbUtils.server.ts instead
* to avoid pulling in the client-only RAQB library.
*
* Server-side imports should use:
* import { acrossQueryValueCompatiblity, raqbQueryValueUtils } from "@calcom/app-store/_utils/raqb/raqbUtils.server";
*
* Client-side imports can use this file or import directly from raqbUtils.client.ts:
* import { buildStateFromQueryValue, buildEmptyQueryValue } from "@calcom/app-store/_utils/raqb/raqbUtils.client";
*/
// Re-export server-safe utilities
export {
raqbQueryValueUtils,
getValueOfAttributeOption,
getAttributesQueryBuilderConfigHavingListofLabels,
acrossQueryValueCompatiblity,
} from "./raqbUtils.server";
// Re-export client-only utilities (requires react-awesome-query-builder runtime)
export { buildEmptyQueryValue, buildStateFromQueryValue } from "./raqbUtils.client";
+1 -1
View File
@@ -9,7 +9,7 @@
"categories": ["payment"],
"publisher": "Alby",
"email": "[email protected]",
"description": "Your Bitcoin & Nostr companion for the web. Use Alby to charge Satoshi for your [Cal.com](https://cal.com) meetings.\r",
"description": "Your Bitcoin & Nostr companion for the web. Use Alby to charge Satoshi for your [Cal.diy](https://cal.com) meetings.\r",
"extendsFeature": "EventType",
"isTemplate": false,
"__createdUsingCli": true,
+1 -1
View File
@@ -15,5 +15,5 @@
"devDependencies": {
"@calcom/types": "workspace:*"
},
"description": "Your Bitcoin & Nostr companion for the web. Use Alby to charge Satoshi for your Cal.com meetings.\r"
"description": "Your Bitcoin & Nostr companion for the web. Use Alby to charge Satoshi for your Cal.diy meetings.\r"
}
@@ -11,7 +11,7 @@ export const metadata = {
categories: ["calendar"],
category: "calendar",
logo: "icon.svg",
publisher: "Cal.com",
publisher: "Cal.diy",
slug: "apple-calendar",
url: "https://cal.com/",
email: "[email protected]",
@@ -36,7 +36,6 @@ import { appKeysSchema as pipedrive_crm_zod_ts } from "./pipedrive-crm/zod";
import { appKeysSchema as plausible_zod_ts } from "./plausible/zod";
import { appKeysSchema as posthog_zod_ts } from "./posthog/zod";
import { appKeysSchema as qr_code_zod_ts } from "./qr_code/zod";
import { appKeysSchema as routing_forms_zod_ts } from "./routing-forms/zod";
import { appKeysSchema as salesforce_zod_ts } from "./salesforce/zod";
import { appKeysSchema as shimmervideo_zod_ts } from "./shimmervideo/zod";
import { appKeysSchema as stripepayment_zod_ts } from "./stripepayment/zod";
@@ -88,7 +87,6 @@ export const appKeysSchemas = {
plausible: plausible_zod_ts,
posthog: posthog_zod_ts,
qr_code: qr_code_zod_ts,
"routing-forms": routing_forms_zod_ts,
salesforce: salesforce_zod_ts,
shimmervideo: shimmervideo_zod_ts,
stripe: stripepayment_zod_ts,
@@ -79,7 +79,6 @@ import raycast_config_json from "./raycast/config.json";
import retell_ai_config_json from "./retell-ai/config.json";
import riverside_config_json from "./riverside/config.json";
import roam_config_json from "./roam/config.json";
import routing_forms_config_json from "./routing-forms/config.json";
import salesforce_config_json from "./salesforce/config.json";
import salesroom_config_json from "./salesroom/config.json";
import sendgrid_config_json from "./sendgrid/config.json";
@@ -192,7 +191,6 @@ export const appStoreMetadata = {
"retell-ai": retell_ai_config_json,
riverside: riverside_config_json,
roam: roam_config_json,
"routing-forms": routing_forms_config_json,
salesforce: salesforce_config_json,
salesroom: salesroom_config_json,
sendgrid: sendgrid_config_json,
@@ -36,7 +36,6 @@ import { appDataSchema as pipedrive_crm_zod_ts } from "./pipedrive-crm/zod";
import { appDataSchema as plausible_zod_ts } from "./plausible/zod";
import { appDataSchema as posthog_zod_ts } from "./posthog/zod";
import { appDataSchema as qr_code_zod_ts } from "./qr_code/zod";
import { appDataSchema as routing_forms_zod_ts } from "./routing-forms/zod";
import { appDataSchema as salesforce_zod_ts } from "./salesforce/zod";
import { appDataSchema as shimmervideo_zod_ts } from "./shimmervideo/zod";
import { appDataSchema as stripepayment_zod_ts } from "./stripepayment/zod";
@@ -88,7 +87,6 @@ export const appDataSchemas = {
plausible: plausible_zod_ts,
posthog: posthog_zod_ts,
qr_code: qr_code_zod_ts,
"routing-forms": routing_forms_zod_ts,
salesforce: salesforce_zod_ts,
shimmervideo: shimmervideo_zod_ts,
stripe: stripepayment_zod_ts,
@@ -58,7 +58,6 @@ export const apiHandlers = {
qr_code: import("./qr_code/api"),
riverside: import("./riverside/api"),
roam: import("./roam/api"),
"routing-forms": import("./routing-forms/api"),
salesforce: import("./salesforce/api"),
salesroom: import("./salesroom/api"),
sendgrid: import("./sendgrid/api"),
+1 -1
View File
@@ -11,7 +11,7 @@
],
"publisher": "Patrick Goeler von Ravensburg",
"email": "[email protected]",
"description": "You simply paste a [Cal.com](https://cal.com) link of someone, select a frequency and we will take care of the scheduling for you.\r\r",
"description": "You simply paste a [Cal.diy](https://cal.com) link of someone, select a frequency and we will take care of the scheduling for you.\r\r",
"isTemplate": false,
"__createdUsingCli": true,
"__template": "link-as-an-app",
@@ -90,7 +90,7 @@ class BasecampCalendarService implements Calendar {
hour12: true,
minute: "numeric",
});
const baseString = `<div>Event title: ${event.title}<br/>Date and time: ${date}, ${startTime} - ${endTime} ${timeZone}<br/>View on Cal.com: <a target="_blank" rel="noreferrer" class="autolinked" data-behavior="truncate" href="https://app.cal.com/booking/${event.uid}">https://app.cal.com/booking/${event.uid}</a> `;
const baseString = `<div>Event title: ${event.title}<br/>Date and time: ${date}, ${startTime} - ${endTime} ${timeZone}<br/>View on Cal.diy: <a target="_blank" rel="noreferrer" class="autolinked" data-behavior="truncate" href="https://app.cal.com/booking/${event.uid}">https://app.cal.com/booking/${event.uid}</a> `;
const guestString = `<br/>Guests: ${event.attendees.reduce((acc, attendee) => {
return `${acc}<br/><a target="_blank" rel="noreferrer" class="autolinked" data-behavior="truncate" href="mailto:${attendee.email}">${attendee.email}</a>`;
}, "")}`;
@@ -117,7 +117,7 @@ class BasecampCalendarService implements Calendar {
},
body: JSON.stringify({
description,
summary: `Cal.com: ${event.title}`,
summary: `Cal.diy: ${event.title}`,
starts_at: new Date(event.startTime).toISOString(),
ends_at: new Date(event.endTime).toISOString(),
}),
@@ -160,7 +160,7 @@ class BasecampCalendarService implements Calendar {
},
body: JSON.stringify({
description,
summary: `Cal.com: ${event.title}`,
summary: `Cal.diy: ${event.title}`,
starts_at: new Date(event.startTime).toISOString(),
ends_at: new Date(event.endTime).toISOString(),
}),
@@ -63,18 +63,18 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
data.invoiceId,
appConfig.type
);
if (!payment) throw new HttpCode({ statusCode: 404, message: "Cal.com: payment not found" });
if (!payment) throw new HttpCode({ statusCode: 404, message: "Cal.diy: payment not found" });
if (payment.success) return res.status(200).send({ message: "Payment already registered" });
const key = payment.booking?.user?.credentials?.[0].key;
if (!key) throw new HttpCode({ statusCode: 404, message: "Cal.com: credentials not found" });
if (!key) throw new HttpCode({ statusCode: 404, message: "Cal.diy: credentials not found" });
const parsedKey = btcpayCredentialKeysSchema.safeParse(key);
if (!parsedKey.success)
throw new HttpCode({ statusCode: 400, message: "Cal.com: Invalid BTCPay credentials" });
throw new HttpCode({ statusCode: 400, message: "Cal.diy: Invalid BTCPay credentials" });
const { webhookSecret, storeId } = parsedKey.data;
if (storeId !== data.storeId)
throw new HttpCode({ statusCode: 400, message: "Cal.com: Store ID mismatch" });
throw new HttpCode({ statusCode: 400, message: "Cal.diy: Store ID mismatch" });
const expectedSignature = signature.split("=")[1];
const computedSignature = verifyBTCPaySignature(rawBody, expectedSignature, webhookSecret);
@@ -16,6 +16,6 @@ Confirmed and verified list of all supported CalDAV integration calendar service
Every CalDav Provider is different and needs minor adjustments.
Follow our CalDav Roadmap here: <a class="text-blue-500" target="_blank" href="https://github.com/calcom/cal.com/issues/3457">https://github.com/calcom/cal.com/issues/3457</a>.
Follow our CalDav Roadmap here: <a class="text-blue-500" target="_blank" href="https://github.com/calcom/cal.diy/issues/3457">https://github.com/calcom/cal.diy/issues/3457</a>.
If your CalDav connection is not working, please try another Calendar provider (Google Mail or another CalDav).
@@ -11,7 +11,7 @@ export const metadata = {
category: "calendar",
categories: ["calendar"],
logo: "icon.svg",
publisher: "Cal.com",
publisher: "Cal.diy",
slug: "caldav-calendar",
url: "https://cal.com/",
email: "[email protected]",
+1 -1
View File
@@ -11,7 +11,7 @@ export const metadata = {
category: "calendar",
categories: ["calendar"],
logo: "icon.svg",
publisher: "Cal.com",
publisher: "Cal.diy",
slug: "caldav-calendar",
url: "https://cal.com/",
email: "[email protected]",
+1 -1
View File
@@ -11,7 +11,7 @@
],
"publisher": "Chatbase",
"email": "[email protected]",
"description": "Add [Cal.com](https://cal.com/) to your Chatbase AI Chatbot and accept bookings right inside chat.",
"description": "Add [Cal.diy](https://cal.com/) to your Chatbase AI Chatbot and accept bookings right inside chat.",
"isTemplate": false,
"__createdUsingCli": true,
"__template": "link-as-an-app",
+1 -1
View File
@@ -11,7 +11,7 @@
],
"publisher": "Chris Pacheco",
"email": "[email protected]",
"description": "Create, List and Interact with Your Cal.com links and connections easily.\r\r",
"description": "Create, List and Interact with Your Cal.diy links and connections easily.\r\r",
"isTemplate": false,
"__createdUsingCli": true,
"__template": "link-as-an-app",
@@ -29,7 +29,7 @@ const credentialSchema = z
const CALENDSO_ENCRYPTION_KEY = process.env.CALENDSO_ENCRYPTION_KEY || "";
// Cal.com Custom Activity Fields
// Cal.diy Custom Activity Fields
const calComCustomActivityFields: CloseComFieldOptions = [
// Field name, field type, required?, multiple values?
["Attendees", "contact", false, true],
@@ -55,7 +55,7 @@ const calComCustomActivityFields: CloseComFieldOptions = [
* Contact creation
* Every contact in Close.com need to belong to a Lead. When creating a contact in
* Close.com as part of this integration, a new generic Lead will be created in order
* to assign every contact created by this process, and it is named "From Cal.com"
* to assign every contact created by this process, and it is named "From Cal.diy"
*/
class CloseComCRMService implements CRM {
private integrationName = "";
@@ -7,6 +7,7 @@ import {
getCloseComLeadId,
getCustomActivityTypeInstanceData,
} from "@calcom/lib/CloseComeUtils";
import { APP_NAME } from "@calcom/lib/constants";
import type { CalendarEvent } from "@calcom/types/Calendar";
import { afterEach, expect, test, vi } from "vitest";
@@ -31,7 +32,7 @@ afterEach(() => {
test("check generic lead generator: already exists", async () => {
CloseCom.prototype.lead = {
list: () => ({
data: [{ name: "From Cal.com", id: "abc" }],
data: [{ name: `From ${APP_NAME}`, id: "abc" }],
}),
} as any;
@@ -138,7 +139,7 @@ test("retrieve custom fields for custom activity type: type exists, no field cre
CloseCom.prototype.customActivity = {
type: {
get: () => ({ data: [{ id: "typeX", name: "Cal.com Activity" }] }),
get: () => ({ data: [{ id: "typeX", name: `${APP_NAME} Activity` }] }),
},
} as any;
@@ -256,7 +257,7 @@ test("prepare data to create custom activity type instance: one attendees, with
CloseCom.prototype.lead = {
list: () => ({
data: [{ name: "From Cal.com", id: "abc" }],
data: [{ name: `From ${APP_NAME}`, id: "abc" }],
}),
} as any;
+1 -1
View File
@@ -11,7 +11,7 @@ export const metadata = {
url: "https://daily.co",
categories: ["conferencing"],
logo: "icon.svg",
publisher: "Cal.com",
publisher: "Cal.diy",
category: "conferencing",
slug: "daily-video",
title: "Cal Video",
@@ -1,626 +0,0 @@
import { organizationRepositoryMock } from "@calcom/features/ee/organizations/__mocks__/organizationMock";
import { setupAndTeardown } from "@calcom/testing/lib/bookingScenario/setupAndTeardown";
import { describe, it, expect, beforeEach, vi } from "vitest";
import { metadata as googleCalendarMetadata } from "@calcom/app-store/googlecalendar/_metadata";
import { metadata as googleMeetMetadata } from "@calcom/app-store/googlevideo/_metadata";
import type { ServiceAccountKey } from "@calcom/features/delegation-credentials/repositories/DelegationCredentialRepository";
import { DelegationCredentialRepository } from "@calcom/features/delegation-credentials/repositories/DelegationCredentialRepository";
import { SMSLockState, RRTimestampBasis } from "@calcom/prisma/enums";
import type { CredentialForCalendarService, CredentialPayload } from "@calcom/types/Credential";
import {
buildAllCredentials,
getDelegationCredentialOrRegularCredential,
enrichUsersWithDelegationCredentials,
enrichHostsWithDelegationCredentials,
enrichUserWithDelegationCredentialsIncludeServiceAccountKey,
enrichUserWithDelegationConferencingCredentialsWithoutOrgId,
getAllDelegationCredentialsForUserIncludeServiceAccountKey,
} from "./delegationCredential";
vi.mock("@calcom/prisma", () => ({
prisma: {},
}));
// Mock DelegationCredentialRepository
vi.mock("@calcom/features/delegation-credentials/repositories/DelegationCredentialRepository", () => ({
DelegationCredentialRepository: {
findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey: vi.fn(),
findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey: vi.fn(),
},
}));
const mockUser = {
email: "[email protected]",
id: 123,
};
const mockServiceAccountKey: ServiceAccountKey = {
client_email: "[email protected]",
client_id: "123456789",
private_key: "-----BEGIN PRIVATE KEY-----\nMIIE....\n-----END PRIVATE KEY-----\n",
};
const mockWorkspacePlatform = {
name: "Test Platform",
slug: "google",
};
const mockDelegationCredential = {
id: "delegationCredential-1",
enabled: true,
domain: "example.com",
organizationId: 1,
serviceAccountKey: mockServiceAccountKey,
workspacePlatform: mockWorkspacePlatform,
createdAt: new Date(),
updatedAt: new Date(),
lastEnabledAt: new Date(),
lastDisabledAt: null,
};
// Mock organization data
const mockOrganization = {
id: 1,
name: "Test Org",
metadata: {},
bio: null,
timeZone: "UTC",
weekStart: "Monday",
hideBranding: false,
theme: null,
timeFormat: null,
brandColor: null,
darkBrandColor: null,
createdAt: new Date(),
includeManagedEventsInLimits: false,
smsLockState: SMSLockState.LOCKED,
smsLockReviewedByAdmin: false,
slug: "test-org",
logoUrl: null,
bannerUrl: null,
isPrivate: false,
isOrganization: true,
isOrganizationVerified: true,
isOrganizationConfigured: true,
isOrganizationAdminReviewed: true,
orgAutoAcceptEmail: "example.com",
orgProfileRedirectsToVerifiedDomain: false,
allowSEOIndexing: true,
calVideoLogo: null,
appLogo: null,
appIconLogo: null,
hideBookATeamMember: false,
hideTeam: false,
hideCalendarNotes: false,
eventTypeMatchParentTeam: false,
lockEventTypeCreationForUsers: false,
parentId: null,
pendingPayment: false,
isPlatform: false,
createdByOAuthClientId: null,
bookingLimits: null,
hideTeamProfileLink: false,
rrResetInterval: null,
rrTimestampBasis: RRTimestampBasis.CREATED_AT,
autoOptInFeatures: false,
};
// Credential Builders
const buildDelegationCredential = (overrides = {}) => ({
type: "google_calendar",
appId: "google-calendar",
id: -1,
delegatedToId: mockDelegationCredential.id,
userId: mockUser.id,
user: { email: mockUser.email, name: null },
key: { access_token: "NOOP_UNUSED_DELEGATION_TOKEN" },
invalid: false,
teamId: null,
team: null,
// In-memory delegation credential has it set to null
delegationCredentialId: mockDelegationCredential.id,
delegatedTo: {
serviceAccountKey: mockServiceAccountKey,
},
encryptedKey: null,
...overrides,
});
const buildGoogleCalendarDelegationCredential = (overrides = {}) => ({
...buildDelegationCredential({
type: googleCalendarMetadata.type,
appId: googleCalendarMetadata.slug,
}),
...overrides,
});
const buildDelegationCredentialGoogleMeetCredential = (overrides = {}) => ({
...buildDelegationCredential({
type: googleMeetMetadata.type,
appId: googleMeetMetadata.slug,
}),
...overrides,
});
const buildRegularCredential = (overrides = {}): CredentialForCalendarService => ({
type: "google_calendar",
appId: "google-calendar",
id: 1,
userId: mockUser.id,
user: { email: mockUser.email },
key: JSON.stringify(mockServiceAccountKey),
invalid: false,
teamId: null,
delegatedToId: null,
delegatedTo: null,
// Regular credentials have it set to null always
delegationCredentialId: null,
encryptedKey: null,
...overrides,
});
const buildRegularGoogleCalendarCredential = (overrides = {}): CredentialPayload => ({
...buildRegularCredential({
appId: "google-calendar",
type: "google_calendar",
}),
...overrides,
});
const buildMockWorkspacePlatform = (overrides: Partial<typeof mockWorkspacePlatform> = {}) => ({
name: "Test Platform",
slug: "google",
...overrides,
});
const buildMockDelegationCredential = (overrides: Partial<typeof mockDelegationCredential> = {}) => ({
...mockDelegationCredential,
workspacePlatform: buildMockWorkspacePlatform(overrides.workspacePlatform || {}),
...overrides,
});
describe("getAllDelegationCredentialsForUserIncludeServiceAccountKey", () => {
setupAndTeardown();
beforeEach(() => {
vi.clearAllMocks();
organizationRepositoryMock.findByMemberEmail.mockResolvedValue(mockOrganization);
});
it("should return empty array when no DelegationCredential found", async () => {
vi.mocked(
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(null);
const result = await getAllDelegationCredentialsForUserIncludeServiceAccountKey({ user: mockUser });
expect(result).toEqual([]);
});
it("should return empty array when DelegationCredential is disabled", async () => {
vi.mocked(
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDelegationCredential({ enabled: false }));
const result = await getAllDelegationCredentialsForUserIncludeServiceAccountKey({ user: mockUser });
expect(result).toEqual([]);
});
it("should return credentials for enabled Google DelegationCredential", async () => {
vi.mocked(
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDelegationCredential());
const result = await getAllDelegationCredentialsForUserIncludeServiceAccountKey({ user: mockUser });
expect(result).toHaveLength(2);
expect(result).toEqual([
buildGoogleCalendarDelegationCredential(),
buildDelegationCredentialGoogleMeetCredential(),
]);
});
});
describe("buildAllCredentials", () => {
const mockDelegationCredentialGoogleCalendarCred = buildGoogleCalendarDelegationCredential();
const mockRegularGoogleCalendarCred = buildRegularGoogleCalendarCredential();
it("should combine DelegationCredential and regular credentials", () => {
const result = buildAllCredentials({
delegationCredentials: [mockDelegationCredentialGoogleCalendarCred],
existingCredentials: [mockRegularGoogleCalendarCred],
});
expect(result).toHaveLength(2);
expect(result).toContainEqual(mockDelegationCredentialGoogleCalendarCred);
expect(result).toContainEqual(mockRegularGoogleCalendarCred);
});
it("should deduplicate DelegationCredential credentials with same delegatedToId and appId", () => {
const duplicateDelegationCredential = buildGoogleCalendarDelegationCredential();
const result = buildAllCredentials({
delegationCredentials: [mockDelegationCredentialGoogleCalendarCred, duplicateDelegationCredential],
existingCredentials: [],
});
expect(result).toHaveLength(1);
expect(result[0]).toEqual(mockDelegationCredentialGoogleCalendarCred);
});
it("should keep DelegationCredential credentials with same delegatedToId but different appId", () => {
const differentAppDelegationCredential = buildDelegationCredentialGoogleMeetCredential();
const result = buildAllCredentials({
delegationCredentials: [mockDelegationCredentialGoogleCalendarCred, differentAppDelegationCredential],
existingCredentials: [],
});
expect(result).toHaveLength(2);
expect(result).toContainEqual(mockDelegationCredentialGoogleCalendarCred);
expect(result).toContainEqual(differentAppDelegationCredential);
});
it("should filter out DelegationCredential credentials from existingCredentials", () => {
const delegatedCalendarCredential = buildRegularGoogleCalendarCredential({ id: -2 });
const result = buildAllCredentials({
delegationCredentials: [mockDelegationCredentialGoogleCalendarCred],
existingCredentials: [mockRegularGoogleCalendarCred, delegatedCalendarCredential],
});
expect(result).toHaveLength(2);
expect(result).toContainEqual(mockDelegationCredentialGoogleCalendarCred);
expect(result).toContainEqual(mockRegularGoogleCalendarCred);
});
});
describe("getDelegationCredentialOrRegularCredential", () => {
const mockDelegationCredentialGoogleCalendarCred = buildGoogleCalendarDelegationCredential();
const mockRegularGoogleCalendarCred = buildRegularGoogleCalendarCredential();
const credentials = [mockDelegationCredentialGoogleCalendarCred, mockRegularGoogleCalendarCred];
it("should find Delegation credential by delegationCredentialId", () => {
const result = getDelegationCredentialOrRegularCredential({
credentials,
id: { credentialId: null, delegationCredentialId: mockDelegationCredential.id },
});
expect(result).toEqual(mockDelegationCredentialGoogleCalendarCred);
});
it("should find regular credential by credentialId", () => {
const result = getDelegationCredentialOrRegularCredential({
credentials,
id: { credentialId: mockRegularGoogleCalendarCred.id, delegationCredentialId: null },
});
expect(result).toEqual(mockRegularGoogleCalendarCred);
});
it("should return null when no matching credential found", () => {
const result = getDelegationCredentialOrRegularCredential({
credentials,
id: { credentialId: 999, delegationCredentialId: null },
});
expect(result).toBeNull();
});
it("should not match null to null for delegatedToId", () => {
const result = getDelegationCredentialOrRegularCredential({
credentials,
id: { credentialId: null, delegationCredentialId: null },
});
expect(result).toBeNull();
});
});
describe("enrichUsersWithDelegationCredentials", () => {
const mockUsers = [
{
...mockUser,
credentials: [buildRegularGoogleCalendarCredential()],
},
{
id: 456,
email: "[email protected]",
credentials: [buildRegularGoogleCalendarCredential({ id: 2 })],
},
];
beforeEach(() => {
vi.clearAllMocks();
});
it("should return users as is when orgId is null", async () => {
const result = await enrichUsersWithDelegationCredentials({
orgId: null,
users: mockUsers,
});
expect(result).toEqual(
mockUsers.map((user) => ({
...user,
credentials: user.credentials.map((cred) => ({
...cred,
delegatedTo: null,
delegatedToId: null,
})),
}))
);
});
it("should enrich users with DelegationCredential credentials when available", async () => {
vi.mocked(
DelegationCredentialRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDelegationCredential());
const result = await enrichUsersWithDelegationCredentials({
orgId: 1,
users: mockUsers,
});
expect(result).toHaveLength(2);
result.forEach((enrichedUser) => {
expect(enrichedUser.credentials).toHaveLength(3); // 1 regular + 2 DelegationCredential (calendar + meet)
expect(enrichedUser.credentials).toContainEqual(
expect.objectContaining({
type: googleCalendarMetadata.type,
appId: googleCalendarMetadata.slug,
})
);
expect(enrichedUser.credentials).toContainEqual(
expect.objectContaining({
type: googleMeetMetadata.type,
appId: googleMeetMetadata.slug,
})
);
});
});
it("should not add DelegationCredential credentials when DelegationCredential is disabled", async () => {
vi.mocked(
DelegationCredentialRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDelegationCredential({ enabled: false }));
const result = await enrichUsersWithDelegationCredentials({
orgId: 1,
users: mockUsers,
});
expect(result).toEqual(
mockUsers.map((user) => ({
...user,
credentials: user.credentials.map((cred) => ({
...cred,
delegatedTo: null,
delegatedToId: null,
})),
}))
);
});
it("should return empty array when users is empty", async () => {
const result = await enrichUsersWithDelegationCredentials({
orgId: 1,
users: [],
});
expect(result).toEqual([]);
});
});
describe("enrichHostsWithDelegationCredentials", () => {
const mockHosts = [
{
user: {
...mockUser,
credentials: [buildRegularGoogleCalendarCredential()],
},
metadata: { key: "value" },
},
{
user: {
id: 456,
email: "[email protected]",
credentials: [buildRegularGoogleCalendarCredential({ id: 2 })],
},
metadata: { key: "value2" },
},
];
beforeEach(() => {
vi.clearAllMocks();
});
it("should return hosts as is when orgId is null", async () => {
const result = await enrichHostsWithDelegationCredentials({
orgId: null,
hosts: mockHosts,
});
expect(result).toEqual(
mockHosts.map((host) => ({
...host,
user: {
...host.user,
credentials: host.user.credentials.map((cred) => ({
...cred,
delegatedTo: null,
delegatedToId: null,
})),
},
}))
);
});
it("should enrich hosts with DelegationCredential credentials when available", async () => {
vi.mocked(
DelegationCredentialRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDelegationCredential());
const result = await enrichHostsWithDelegationCredentials({
orgId: 1,
hosts: mockHosts,
});
expect(result).toHaveLength(2);
result.forEach((enrichedHost) => {
expect(enrichedHost.metadata).toBeDefined(); // Preserve non-user data
expect(enrichedHost.user.credentials).toHaveLength(3); // 1 regular + 2 DelegationCredential (calendar + meet)
expect(enrichedHost.user.credentials).toContainEqual(
expect.objectContaining({
type: googleCalendarMetadata.type,
appId: googleCalendarMetadata.slug,
})
);
expect(enrichedHost.user.credentials).toContainEqual(
expect.objectContaining({
type: googleMeetMetadata.type,
appId: googleMeetMetadata.slug,
})
);
});
});
it("should not add DelegationCredential credentials when DelegationCredential is disabled", async () => {
vi.mocked(
DelegationCredentialRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDelegationCredential({ enabled: false }));
const result = await enrichHostsWithDelegationCredentials({
orgId: 1,
hosts: mockHosts,
});
expect(result).toEqual(
mockHosts.map((host) => ({
...host,
user: {
...host.user,
credentials: host.user.credentials.map((cred) => ({
...cred,
delegatedTo: null,
delegatedToId: null,
})),
},
}))
);
});
it("should return empty array when hosts is empty", async () => {
const result = await enrichHostsWithDelegationCredentials({
orgId: 1,
hosts: [],
});
expect(result).toEqual([]);
});
});
describe("enrichUserWithDelegationCredentialsIncludeServiceAccountKey", () => {
const mockUserWithCredentials = {
...mockUser,
credentials: [buildRegularGoogleCalendarCredential()],
};
beforeEach(() => {
vi.clearAllMocks();
});
it("should enrich user with DelegationCredential credentials when available", async () => {
vi.mocked(
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDelegationCredential());
const result = await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
user: mockUserWithCredentials,
});
expect(result.credentials).toHaveLength(3); // 1 regular + 2 DelegationCredential (calendar + meet)
expect(result.credentials).toContainEqual(
expect.objectContaining({
type: googleCalendarMetadata.type,
appId: googleCalendarMetadata.slug,
})
);
expect(result.credentials).toContainEqual(
expect.objectContaining({
type: googleMeetMetadata.type,
appId: googleMeetMetadata.slug,
})
);
});
it("should not add DelegationCredential credentials when DelegationCredential is not found", async () => {
vi.mocked(
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(null);
const result = await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
user: mockUserWithCredentials,
});
expect(result).toEqual({
...mockUserWithCredentials,
credentials: mockUserWithCredentials.credentials.map((cred) => ({
...cred,
delegatedTo: null,
delegatedToId: null,
})),
});
});
it("should not add DelegationCredential credentials when DelegationCredential is disabled", async () => {
vi.mocked(
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDelegationCredential({ enabled: false }));
const result = await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
user: mockUserWithCredentials,
});
expect(result).toEqual({
...mockUserWithCredentials,
credentials: mockUserWithCredentials.credentials.map((cred) => ({
...cred,
delegatedTo: null,
delegatedToId: null,
})),
});
});
});
describe("enrichUserWithDelegationConferencingCredentialsWithoutOrgId", () => {
const mockUserWithCredentials = {
...mockUser,
credentials: [buildRegularGoogleCalendarCredential()],
};
beforeEach(() => {
vi.clearAllMocks();
});
it("should only return conferencing credentials", async () => {
vi.mocked(
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDelegationCredential());
const result = await enrichUserWithDelegationConferencingCredentialsWithoutOrgId({
user: mockUserWithCredentials,
});
expect(result.credentials).toHaveLength(1); // Only Google Meet
expect(result.credentials[0]).toEqual(
expect.objectContaining({
type: googleMeetMetadata.type,
appId: googleMeetMetadata.slug,
})
);
});
it("should return empty credentials array when no conferencing credentials found", async () => {
vi.mocked(
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(null);
const result = await enrichUserWithDelegationConferencingCredentialsWithoutOrgId({
user: mockUserWithCredentials,
});
expect(result.credentials).toEqual([]);
});
});
+60 -556
View File
@@ -1,470 +1,75 @@
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
import { metadata as googleCalendarMetadata } from "@calcom/app-store/googlecalendar/_metadata";
import { metadata as googleMeetMetadata } from "@calcom/app-store/googlevideo/_metadata";
import { metadata as office365CalendarMetaData } from "@calcom/app-store/office365calendar/_metadata";
import { metadata as office365VideoMetaData } from "@calcom/app-store/office365video/_metadata";
import { CredentialRepository } from "@calcom/features/credentials/repositories/CredentialRepository";
import type { ServiceAccountKey } from "@calcom/features/delegation-credentials/repositories/DelegationCredentialRepository";
import { DelegationCredentialRepository } from "@calcom/features/delegation-credentials/repositories/DelegationCredentialRepository";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import {
buildNonDelegationCredential,
buildNonDelegationCredentials,
isDelegationCredential,
} from "@calcom/lib/delegationCredential";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { prisma } from "@calcom/prisma";
import type { SelectedCalendar } from "@calcom/prisma/client";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { CredentialForCalendarService, CredentialPayload } from "@calcom/types/Credential";
const GOOGLE_WORKSPACE_SLUG = "google";
const OFFICE365_WORKSPACE_SLUG = "office365";
const WORKSPACE_PLATFORM_SLUGS = [GOOGLE_WORKSPACE_SLUG, OFFICE365_WORKSPACE_SLUG] as const;
type WORKSPACE_PLATFORM_SLUGS_TYPE = (typeof WORKSPACE_PLATFORM_SLUGS)[number];
const log = logger.getSubLogger({ prefix: ["app-store/delegationCredential"] });
interface DelegationCredential {
id: string;
workspacePlatform: {
slug: string;
};
serviceAccountKey: ServiceAccountKey | null;
}
interface DelegationCredentialWithSensitiveServiceAccountKey extends DelegationCredential {
serviceAccountKey: ServiceAccountKey;
}
interface User {
email: string;
id: number;
}
const isValidWorkspaceSlug = (slug: string) => {
return WORKSPACE_PLATFORM_SLUGS.includes(slug as unknown as WORKSPACE_PLATFORM_SLUGS_TYPE);
};
const getDelegationCredentialAppMetadata = (
slug: WORKSPACE_PLATFORM_SLUGS_TYPE,
isConferencing?: boolean
) => {
switch (slug) {
case GOOGLE_WORKSPACE_SLUG:
return isConferencing
? { type: googleMeetMetadata.type, appId: googleMeetMetadata.slug }
: { type: googleCalendarMetadata.type, appId: googleCalendarMetadata.slug };
case OFFICE365_WORKSPACE_SLUG:
return isConferencing
? { type: office365VideoMetaData.type, appId: office365VideoMetaData.slug }
: { type: office365CalendarMetaData.type, appId: office365CalendarMetaData.slug };
default:
throw new Error("App metadata does not exist");
}
};
const _isConferencingCredential = (credential: CredentialPayload) => {
return (
credential.type.endsWith("_video") ||
credential.type.endsWith("_conferencing") ||
credential.type.endsWith("_messaging")
);
};
const _buildCommonUserCredential = ({
delegationCredential,
user,
}: {
delegationCredential: DelegationCredential;
user: User;
}) => {
return {
id: -1,
delegatedToId: delegationCredential.id,
userId: user.id,
user: {
email: user.email,
name: null as string | null,
},
key: {
access_token: "NOOP_UNUSED_DELEGATION_TOKEN",
},
encryptedKey: null,
invalid: false,
teamId: null,
team: null,
delegationCredentialId: delegationCredential.id,
delegatedTo: delegationCredential.serviceAccountKey
? {
serviceAccountKey: delegationCredential.serviceAccountKey,
}
: null,
};
};
const _buildDelegatedCalendarCredential = ({
delegationCredential,
user,
}: {
delegationCredential: DelegationCredential;
user: User;
}) => {
log.debug(
"buildDelegationCredential",
safeStringify({
delegationCredential: {
id: delegationCredential.id,
},
user: {
id: user.id,
email: user.email,
},
})
);
// TODO: Build for other platforms as well
if (!isValidWorkspaceSlug(delegationCredential.workspacePlatform.slug)) {
log.warn(
`Only ${WORKSPACE_PLATFORM_SLUGS.toString()} Platforms are supported here, skipping ${
delegationCredential.workspacePlatform.slug
}`
);
return null;
}
return {
...getDelegationCredentialAppMetadata(
delegationCredential.workspacePlatform.slug as unknown as WORKSPACE_PLATFORM_SLUGS_TYPE,
false
),
..._buildCommonUserCredential({ delegationCredential, user }),
};
};
const _buildDelegatedCalendarCredentialWithServiceAccountKey = ({
delegationCredential,
user,
}: {
delegationCredential: DelegationCredentialWithSensitiveServiceAccountKey;
user: User;
}) => {
const credential = _buildDelegatedCalendarCredential({ delegationCredential, user });
if (!credential) {
return null;
}
return {
...credential,
delegatedTo: {
serviceAccountKey: delegationCredential.serviceAccountKey,
},
};
};
const _buildDelegatedConferencingCredential = ({
delegationCredential,
user,
}: {
delegationCredential: DelegationCredential;
user: User;
}) => {
// TODO: Build for other platforms as well
if (!isValidWorkspaceSlug(delegationCredential.workspacePlatform.slug)) {
log.warn(
`Only ${WORKSPACE_PLATFORM_SLUGS.toString()} Platforms are supported here, skipping ${
delegationCredential.workspacePlatform.slug
}`
);
return null;
}
return {
...getDelegationCredentialAppMetadata(
delegationCredential.workspacePlatform.slug as unknown as WORKSPACE_PLATFORM_SLUGS_TYPE,
true
),
..._buildCommonUserCredential({ delegationCredential, user }),
};
};
/**
* Gets calendar as well as conferencing credentials(stored in-memory) for the user from the corresponding enabled DelegationCredential.
*/
export async function getAllDelegationCredentialsForUserIncludeServiceAccountKey({
user,
}: {
user: { email: string; id: number };
}) {
log.debug("called with", safeStringify({ user }));
// We access the repository without checking for feature flag here.
// In case we need to disable the effects of DelegationCredential on credential we need to toggle DelegationCredential off from organization settings.
// We could think of the teamFeatures flag to just disable the UI. The actual effect of DelegationCredential on credentials is disabled by toggling DelegationCredential off from UI
const delegationCredential =
await DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey({
email: user.email,
});
if (!delegationCredential || !delegationCredential.enabled) {
return [];
}
const delegationCredentials = [
_buildDelegatedCalendarCredential({ delegationCredential, user }),
_buildDelegatedConferencingCredential({ delegationCredential, user }),
].filter((credential): credential is NonNullable<typeof credential> => credential !== null);
log.debug("Returned", safeStringify({ delegationCredentials }));
return delegationCredentials;
}
export async function getAllDelegationCredentialsForUser({ user }: { user: { email: string; id: number } }) {
const delegationCredentials = await getAllDelegationCredentialsForUserIncludeServiceAccountKey({
user,
});
return delegationCredentials.map(({ delegatedTo: _1, ...rest }) => {
return {
...rest,
};
});
}
export async function getAllDelegatedCalendarCredentialsForUser({
user,
}: {
user: { email: string; id: number };
}) {
const delegationCredentials = await getAllDelegationCredentialsForUserIncludeServiceAccountKey({
user,
});
const delegationCalendarCredentials = delegationCredentials.filter((credential) =>
credential.type.endsWith("_calendar")
);
return buildAllCredentials({
delegationCredentials: delegationCalendarCredentials,
existingCredentials: [],
});
}
async function _getDelegationCredentialsMapPerUser({
organizationId,
users,
}: {
organizationId: number | null;
users: User[];
}) {
const emptyMap = new Map<number, NonNullable<ReturnType<typeof _buildDelegatedCalendarCredential>>[]>();
if (!organizationId) {
return emptyMap;
}
// We assume that all users in an organization are from the same domain, so first one should be fine.
// TODO: There could be multiple domains in an organization(if an organization is migrating maybe from one to another or for some other reason) and we should actually consider all of them, maybe group by domain.
const userThatDeterminesDomain = users[0];
if (!userThatDeterminesDomain) {
return emptyMap;
}
const domain = userThatDeterminesDomain.email.split("@")[1];
log.debug("called with", safeStringify({ users }));
const delegationCredential =
await DelegationCredentialRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey(
{
organizationId,
domain,
}
);
if (!delegationCredential || !delegationCredential.enabled) {
return emptyMap;
}
const credentialsByUserId = new Map<
number,
NonNullable<ReturnType<typeof _buildDelegatedCalendarCredential>>[]
>();
for (const user of users) {
const delegationCredentials = [
_buildDelegatedCalendarCredential({ delegationCredential, user }),
_buildDelegatedConferencingCredential({ delegationCredential, user }),
].filter((credential): credential is NonNullable<typeof credential> => credential !== null);
log.debug(
"Returned for user",
safeStringify({
user,
delegationCredentialIds:
delegationCredentials?.map?.((delegationCredential) => delegationCredential?.delegatedToId) ?? [],
})
);
credentialsByUserId.set(user.id, delegationCredentials);
}
return credentialsByUserId;
}
export async function assertSuccessfullyConfiguredInWorkspace({
delegationCredential,
user,
}: {
delegationCredential: DelegationCredentialWithSensitiveServiceAccountKey;
user: User;
}): Promise<void> {
if (!isValidWorkspaceSlug(delegationCredential.workspacePlatform.slug)) {
const errorMessage = `Unsupported workspace platform: ${delegationCredential.workspacePlatform.slug}. Only ${WORKSPACE_PLATFORM_SLUGS.toString()} are supported.`;
log.warn(errorMessage);
throw new Error(errorMessage);
}
const credential = _buildDelegatedCalendarCredentialWithServiceAccountKey({
delegationCredential,
user,
});
const calendar = await getCalendar(credential, "none");
if (!calendar) {
throw new Error("Calendar App not found for the workspace platform");
}
await calendar.testDelegationCredentialSetup?.();
}
export async function getAllDelegationCredentialsForUserByAppType({
user,
appType,
}: {
user: User;
appType: string;
}) {
const delegationCredentials = await getAllDelegationCredentialsForUser({
user,
});
return delegationCredentials.filter((credential) => credential.type === appType);
}
export async function getAllDelegationCredentialsForUserByAppSlug({
user,
appSlug,
}: {
user: User;
appSlug: string;
}) {
const delegationCredentials = await getAllDelegationCredentialsForUserIncludeServiceAccountKey({
user,
});
const appDelegationCredentials = delegationCredentials.filter((credential) => credential.appId === appSlug);
return buildAllCredentials({
delegationCredentials: appDelegationCredentials,
existingCredentials: [],
});
}
type Host<TUser extends { id: number; email: string; credentials: CredentialPayload[] }> = {
user: TUser;
};
/**
* Prepares credentials for use by CalendarService and EventManager
* - Ensures no duplicate delegationCredentials caused by enrichment at possibly multiple places
*/
export async function getAllDelegationCredentialsForUserIncludeServiceAccountKey(_args: {
user: { email: string; id: number };
}) {
return [] as CredentialForCalendarService[];
}
export async function getAllDelegationCredentialsForUser(_args: { user: { email: string; id: number } }) {
return [] as CredentialForCalendarService[];
}
export async function getAllDelegatedCalendarCredentialsForUser(_args: {
user: { email: string; id: number };
}) {
return [] as CredentialForCalendarService[];
}
export async function assertSuccessfullyConfiguredInWorkspace(_args: {
delegationCredential: unknown;
user: unknown;
}): Promise<void> {
throw new Error("Delegation credentials are not available in the community edition");
}
export async function getAllDelegationCredentialsForUserByAppType(_args: {
user: { email: string; id: number };
appType: string;
}) {
return [] as CredentialForCalendarService[];
}
export async function getAllDelegationCredentialsForUserByAppSlug(_args: {
user: { email: string; id: number };
appSlug: string;
}) {
return [] as CredentialForCalendarService[];
}
export const buildAllCredentials = ({
delegationCredentials,
existingCredentials,
}: {
delegationCredentials: CredentialForCalendarService[];
existingCredentials: CredentialPayload[];
}) => {
const nonDelegationCredentials = existingCredentials.filter(
(cred) => !isDelegationCredential({ credentialId: cred.id })
);
const allCredentials: CredentialForCalendarService[] = [
...delegationCredentials,
...buildNonDelegationCredentials(nonDelegationCredentials),
];
const uniqueAllCredentials = allCredentials.reduce(
(acc, credential) => {
if (!credential.delegatedToId) {
// Regular credential go as is
acc.push(credential);
return acc;
}
const existingDelegationCredential = acc.find(
(c) => c.delegatedToId === credential.delegatedToId && c.appId === credential.appId
);
if (!existingDelegationCredential) {
acc.push(credential);
}
return acc;
},
[] as typeof allCredentials
);
return uniqueAllCredentials;
return existingCredentials as CredentialForCalendarService[];
};
export async function enrichUsersWithDelegationCredentials<
TUser extends { id: number; email: string; credentials: CredentialPayload[] },
>({ orgId, users }: { orgId: number | null; users: TUser[] }) {
const delegationCredentialsMap = await _getDelegationCredentialsMapPerUser({
organizationId: orgId,
users,
});
const enrichedUsers = users.map((user) => {
const { credentials, ...rest } = user;
const enrichedCredentials = buildAllCredentials({
delegationCredentials: delegationCredentialsMap.get(user.id) ?? [],
existingCredentials: credentials,
});
return {
...rest,
credentials: enrichedCredentials,
};
});
log.debug("enrichUsersWithDelegationCredentials", safeStringify({ enrichedUsers, orgId }));
return enrichedUsers;
>({ users }: { orgId: number | null; users: TUser[] }) {
return users;
}
export const enrichHostsWithDelegationCredentials = async <
THost extends Host<TUser>,
TUser extends { id: number; email: string; credentials: CredentialPayload[] },
>({
orgId,
hosts,
}: {
orgId: number | null;
hosts: THost[];
}) => {
const delegationCredentialsMap = await _getDelegationCredentialsMapPerUser({
organizationId: orgId,
users: hosts.map((host) => host.user),
});
const enrichedHosts = hosts.map((host) => {
const { credentials, ...restUser } = host.user;
return {
...host,
user: {
...restUser,
credentials: buildAllCredentials({
delegationCredentials: delegationCredentialsMap.get(restUser.id) ?? [],
existingCredentials: credentials,
}),
},
};
});
log.debug(
"enrichHostsWithDelegationCredentials",
safeStringify({
enrichedHosts: enrichedHosts.map((host) => {
return {
userId: host.user.id,
};
}),
orgId,
})
);
return enrichedHosts;
return hosts;
};
export const enrichUserWithDelegationCredentialsIncludeServiceAccountKey = async <
@@ -474,17 +79,7 @@ export const enrichUserWithDelegationCredentialsIncludeServiceAccountKey = async
}: {
user: TUser;
}) => {
const delegationCredentials = await getAllDelegationCredentialsForUserIncludeServiceAccountKey({
user,
});
const { credentials, ...restUser } = user;
return {
...restUser,
credentials: buildAllCredentials({
delegationCredentials: delegationCredentials,
existingCredentials: credentials,
}),
};
return user;
};
export const enrichUserWithDelegationCredentials = async <
@@ -494,35 +89,19 @@ export const enrichUserWithDelegationCredentials = async <
}: {
user: TUser;
}) => {
const { credentials, ...restUser } = await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
user,
});
return {
...restUser,
credentials: credentials.filter(_isConferencingCredential).map(({ delegatedTo: _1, ...rest }) => rest),
};
return user;
};
export async function enrichUserWithDelegationConferencingCredentialsWithoutOrgId<
TUser extends { id: number; email: string; credentials: CredentialPayload[] },
>({ user }: { user: TUser }) {
const { credentials, ...restUser } = await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
user,
});
return {
...restUser,
credentials: credentials.filter(_isConferencingCredential),
};
return user;
}
/**
* Either get Delegation credential from delegationCredentials or find regular credential from Credential table
*/
export async function getDelegationCredentialOrFindRegularCredential<
TDelegationCredential extends { delegatedToId?: string | null },
>({
id,
delegationCredentials,
}: {
id: {
credentialId: number | null | undefined;
@@ -530,18 +109,13 @@ export async function getDelegationCredentialOrFindRegularCredential<
};
delegationCredentials: TDelegationCredential[];
}) {
return id.delegationCredentialId
? delegationCredentials.find((cred) => cred.delegatedToId === id.delegationCredentialId)
: id.credentialId
? await CredentialRepository.findCredentialForCalendarServiceById({
id: id.credentialId,
})
: null;
return id.credentialId
? await CredentialRepository.findCredentialForCalendarServiceById({
id: id.credentialId,
})
: null;
}
/**
* Utility function to find a credential from a list of credentials, supporting both regular and DelegationCredential credentials
*/
export function getDelegationCredentialOrRegularCredential<
TCredential extends { delegatedToId?: string | null; id: number },
>({
@@ -553,10 +127,7 @@ export function getDelegationCredentialOrRegularCredential<
}) {
return (
credentials.find((cred) => {
// Ensure that we don't match null to null
if (cred.delegatedToId) {
return cred.delegatedToId === id.delegationCredentialId;
} else if (id.credentialId) {
if (id.credentialId) {
return cred.id === id.credentialId;
}
return false;
@@ -564,65 +135,27 @@ export function getDelegationCredentialOrRegularCredential<
);
}
export function getFirstDelegationConferencingCredential({
credentials,
}: {
export function getFirstDelegationConferencingCredential(_args: {
credentials: CredentialForCalendarService[];
}) {
return credentials.find((credential) => _isConferencingCredential(credential));
return undefined;
}
export function getFirstDelegationConferencingCredentialAppLocation({
credentials,
}: {
export function getFirstDelegationConferencingCredentialAppLocation(_args: {
credentials: CredentialForCalendarService[];
}) {
const delegatedConferencingCredential = getFirstDelegationConferencingCredential({ credentials });
if (delegatedConferencingCredential?.appId === googleMeetMetadata.slug) {
return googleMeetMetadata.appData?.location?.type ?? null;
}
if (delegatedConferencingCredential?.appId === office365VideoMetaData.slug) {
return office365VideoMetaData.appData?.location?.type ?? null;
}
return null;
}
export async function findUniqueDelegationCalendarCredential({
userId,
delegationCredentialId,
}: {
export async function findUniqueDelegationCalendarCredential(_args: {
userId: number;
delegationCredentialId: string;
}) {
const [delegationCredential, user] = await Promise.all([
DelegationCredentialRepository.findByIdIncludeSensitiveServiceAccountKey({ id: delegationCredentialId }),
new UserRepository(prisma).findById({ id: userId }),
]);
if (!delegationCredential) {
throw new Error("Delegation Credential not found");
}
if (!delegationCredential.enabled) {
return null;
}
if (!user) {
throw new Error("User not found");
}
const dwdCredential = _buildDelegatedCalendarCredential({
delegationCredential,
user,
});
return dwdCredential;
return null;
}
/**
* It includes in-memory DelegationCredential credentials as well.
*/
export async function getUsersCredentialsIncludeServiceAccountKey(user: Pick<User, "id" | "email">) {
const credentials = await prisma.credential.findMany({
export async function getUsersCredentialsIncludeServiceAccountKey(user: { id: number; email: string }) {
return prisma.credential.findMany({
where: {
userId: user.id,
},
@@ -631,48 +164,19 @@ export async function getUsersCredentialsIncludeServiceAccountKey(user: Pick<Use
id: "asc",
},
});
const { credentials: allCredentials } = await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
user: {
email: user.email,
id: user.id,
credentials,
},
});
return allCredentials;
}
export async function getUsersCredentials(user: User) {
const credentials = await getUsersCredentialsIncludeServiceAccountKey(user);
return credentials.map(({ delegatedTo: _1, ...rest }) => rest);
export async function getUsersCredentials(user: { id: number; email: string }) {
return getUsersCredentialsIncludeServiceAccountKey(user);
}
/**
* Find the credential for a selected calendar
* @param selectedCalendar
*/
export async function getCredentialForSelectedCalendar({
credentialId,
delegationCredentialId,
userId,
}: Partial<SelectedCalendar>) {
if (credentialId) {
const credentialRepository = new CredentialRepository(prisma);
const credential = await credentialRepository.findByIdWithDelegationCredential(credentialId);
if (credential?.delegationCredential?.id && credential.userId) {
return findUniqueDelegationCalendarCredential({
userId: credential.userId,
delegationCredentialId: credential.delegationCredential.id,
});
}
return credential ? buildNonDelegationCredential(credential) : undefined;
}
if (delegationCredentialId && userId) {
return findUniqueDelegationCalendarCredential({
userId,
delegationCredentialId,
});
return credential ?? undefined;
}
return undefined;
}
+1 -1
View File
@@ -7,7 +7,7 @@
"url": "https://meetings.dialpad.com/",
"variant": "conferencing",
"categories": ["conferencing"],
"publisher": "Cal.com",
"publisher": "Cal.diy",
"email": "[email protected]",
"appData": {
"location": {
+1 -1
View File
@@ -7,7 +7,7 @@
"url": "https://dub.co",
"variant": "analytics",
"categories": ["analytics"],
"publisher": "Cal.com",
"publisher": "Cal.diy",
"email": "[email protected]",
"description": "Dub is the modern link attribution platform for you to create short links, track conversion analytics, and run affiliate programs.",
"isTemplate": false,
@@ -116,7 +116,7 @@ class DubService implements AnalyticsService {
customerName: name,
customerEmail: email,
externalId: externalId ?? email,
eventName: eventName ?? "Cal.com lead",
eventName: eventName ?? "Cal.diy lead",
});
}
}
@@ -11,7 +11,7 @@ export const metadata = {
categories: ["calendar"],
label: "Exchange Calendar",
logo: "icon.svg",
publisher: "Cal.com",
publisher: "Cal.diy",
slug: "exchange2013-calendar",
url: "https://cal.com/",
email: "[email protected]",
@@ -11,7 +11,7 @@ export const metadata = {
categories: ["calendar"],
label: "Exchange Calendar",
logo: "icon.svg",
publisher: "Cal.com",
publisher: "Cal.diy",
slug: "exchange2016-calendar",
url: "https://cal.com/",
email: "[email protected]",
@@ -9,7 +9,7 @@
"url": "https://cal.com",
"variant": "calendar",
"categories": ["calendar"],
"publisher": "Cal.com",
"publisher": "Cal.diy",
"email": "[email protected]",
"description": "Fetch Microsoft Exchange calendars and availabilities using Exchange Web Services (EWS).",
"__createdUsingCli": true,
+3 -3
View File
@@ -16,9 +16,9 @@ Famulor.io is a no-code platform for building, testing, deploying, and monitorin
Build and test complex workflows in minutes using our visual builder, then deploy them via phone calls, web calls, or anywhere else. Handle millions of calls with scalable concurrent calling and support over 50 parallel conversations to reduce wait times.
## 🔗 Cal.com 1-Click Integration
## 🔗 Cal.diy 1-Click Integration
Connecting your Cal.com account is now faster and simpler than ever:
Connecting your Cal.diy account is now faster and simpler than ever:
- Use the new one-click connect button to instantly link your calendar
- Built-in troubleshooting tools help you identify and fix sync issues quickly
@@ -44,7 +44,7 @@ Support over 100 languages, including regional accents and cultural adaptations,
## Preset Functions
Easy-to-use functions like booking meetings at [Cal.com](https://cal.com), call transfer, voicemail detection, and more. Comprehensive call management with audio recordings, searchable transcripts, and detailed reports to monitor performance and campaign results.
Easy-to-use functions like booking meetings at [Cal.diy](https://cal.com), call transfer, voicemail detection, and more. Comprehensive call management with audio recordings, searchable transcripts, and detailed reports to monitor performance and campaign results.
## GDPR Compliant
@@ -7,12 +7,12 @@ const log = logger.getSubLogger({ prefix: [`[[FeishuTenantCredential]`] });
const msg = {
en_us: {
title: "Welcome to Cal.com!",
title: "Welcome to Cal.diy!",
content: [
[
{
tag: "text",
text: "Cal.com is an open source scheduling infrastructure.",
text: "Cal.diy is an open source scheduling infrastructure.",
},
],
[
+1 -1
View File
@@ -8,7 +8,7 @@ items:
{DESCRIPTION}
Introducing the official Cal.com component, now available in the Insert Panel under Forms.
Introducing the official Cal.diy component, now available in the Insert Panel under Forms.
Cal is a fully customizable scheduling software for individuals, businesses taking calls, and developers building scheduling platforms.
+1 -1
View File
@@ -11,7 +11,7 @@
],
"publisher": "Framer B.V.",
"email": "[email protected]",
"description": "Add Cal.com to Framer, the design tool for websites. Design freely, publish fast, and scale with CMS, SEO, analytics, and more.",
"description": "Add Cal.diy to Framer, the design tool for websites. Design freely, publish fast, and scale with CMS, SEO, analytics, and more.",
"isTemplate": false,
"__createdUsingCli": true,
"__template": "link-as-an-app",
+1 -1
View File
@@ -7,7 +7,7 @@ export const metadata = {
installed: true,
categories: ["other"],
logo: "icon.svg",
publisher: "Cal.com",
publisher: "Cal.diy",
slug: "giphy",
title: "Giphy",
type: "giphy_other",
@@ -13,7 +13,7 @@ export const metadata = {
category: "calendar",
categories: ["calendar"],
logo: "icon.svg",
publisher: "Cal.com",
publisher: "Cal.diy",
slug: "google-calendar",
url: "https://cal.com/",
email: "[email protected]",
@@ -454,7 +454,6 @@ describe("createEvent", () => {
eventTypeId: null,
credentialId: mockCredential.id,
delegationCredentialId: null,
domainWideDelegationCredentialId: null,
createdAt: new Date("2024-06-15T11:00:00Z"),
updatedAt: new Date("2024-06-15T11:00:00Z"),
customCalendarReminder: 10,
@@ -629,7 +628,6 @@ describe("createEvent", () => {
eventTypeId: null,
credentialId: mockCredential.id,
delegationCredentialId: null,
domainWideDelegationCredentialId: null,
createdAt: new Date("2024-06-15T11:00:00Z"),
updatedAt: new Date("2024-06-15T11:00:00Z"),
customCalendarReminder: 10,
@@ -713,7 +711,6 @@ describe("createEvent", () => {
eventTypeId: null,
credentialId: mockCredential.id,
delegationCredentialId: null,
domainWideDelegationCredentialId: null,
createdAt: new Date("2024-06-15T11:00:00Z"),
updatedAt: new Date("2024-06-15T11:00:00Z"),
customCalendarReminder: null,
@@ -780,7 +777,6 @@ describe("createEvent", () => {
eventTypeId: null,
credentialId: mockCredential.id,
delegationCredentialId: null,
domainWideDelegationCredentialId: null,
createdAt: new Date("2024-06-15T11:00:00Z"),
updatedAt: new Date("2024-06-15T11:00:00Z"),
customCalendarReminder: 0,
@@ -853,7 +849,6 @@ describe("createEvent", () => {
eventTypeId: null,
credentialId: mockCredential.id,
delegationCredentialId: null,
domainWideDelegationCredentialId: null,
createdAt: new Date("2024-06-15T11:00:00Z"),
updatedAt: new Date("2024-06-15T11:00:00Z"),
customCalendarReminder: null,
@@ -925,7 +920,6 @@ describe("updateEvent", () => {
eventTypeId: null,
credentialId: mockCredential.id,
delegationCredentialId: null,
domainWideDelegationCredentialId: null,
createdAt: new Date("2024-06-15T11:00:00Z"),
updatedAt: new Date("2024-06-15T11:00:00Z"),
customCalendarReminder: null,
@@ -996,7 +990,6 @@ describe("updateEvent", () => {
eventTypeId: null,
credentialId: mockCredential.id,
delegationCredentialId: null,
domainWideDelegationCredentialId: null,
createdAt: new Date("2024-06-15T11:00:00Z"),
updatedAt: new Date("2024-06-15T11:00:00Z"),
customCalendarReminder: null,
@@ -1058,7 +1051,6 @@ describe("updateEvent", () => {
eventTypeId: null,
credentialId: mockCredential.id,
delegationCredentialId: null,
domainWideDelegationCredentialId: null,
createdAt: new Date("2024-06-15T11:00:00Z"),
updatedAt: new Date("2024-06-15T11:00:00Z"),
customCalendarReminder: null,
@@ -10,7 +10,7 @@ import metadata from "../_metadata";
import { createGoogleCalendarServiceWithGoogleType } from "../lib/CalendarService";
/**
* Creates the booking on Cal.com and makes the GCal call to fetch the event.
* Creates the booking on Cal.diy and makes the GCal call to fetch the event.
* Ends on the booking success page
* @param page
*
+1 -1
View File
@@ -14,7 +14,7 @@ export const metadata = {
title: "Google Meet",
variant: "conferencing",
logo: "logo.webp",
publisher: "Cal.com",
publisher: "Cal.diy",
url: "https://cal.com/",
isGlobal: false,
email: "[email protected]",
+1 -1
View File
@@ -11,7 +11,7 @@
],
"publisher": "Greetmate Inc.",
"email": "[email protected]",
"description": "Connect [Cal.com](https://cal.com/) to [Greetmate.ai](https://www.greetmate.ai/) and enable appointment scheduling for your AI agents.",
"description": "Connect [Cal.diy](https://cal.com/) to [Greetmate.ai](https://www.greetmate.ai/) and enable appointment scheduling for your AI agents.",
"isTemplate": false,
"__createdUsingCli": true,
"__template": "link-as-an-app",
+10 -30
View File
@@ -1,33 +1,16 @@
The Cal.com Commercial License (EE) license (the “EE License”)
Copyright (c) 2020-present Cal.com, Inc
MIT License
With regard to the Cal.com Software:
Copyright (c) 2020-present Cal.com, Inc.
This software and associated documentation files (the "Software") may only be
used in production, if you (and any entity that you represent) have agreed to,
and are in compliance with, the Cal.com Subscription Terms available
at https://cal.com/terms (the “EE Terms”), or other agreements governing
the use of the Software, as mutually agreed by you and Cal.com, Inc ("Cal.com"),
and otherwise have a valid Cal.com Commercial License subscription ("EE Subscription")
for the correct number of hosts as defined in the EE Terms ("Hosts"). Subject to the foregoing sentence,
you are free to modify this Software and publish patches to the Software. You agree
that Cal.com and/or its licensors (as applicable) retain all right, title and interest in
and to all such modifications and/or patches, and all such modifications and/or
patches may only be used, copied, modified, displayed, distributed, or otherwise
exploited with a valid EE Subscription for the correct number of hosts.
Notwithstanding the foregoing, you may copy and modify the Software for development
and testing purposes, without requiring a subscription. You agree that Cal.com and/or
its licensors (as applicable) retain all right, title and interest in and to all such
modifications. You are not granted any other rights beyond what is expressly stated herein.
Subject to the foregoing, it is forbidden to copy, merge, publish, distribute, sublicense,
and/or sell the Software.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
This EE License applies only to the part of this Software that is not distributed under
the AGPLv3 license. Any part of this Software distributed under the MIT license or which
is served client-side as an image, font, cascading stylesheet (CSS), file which produces
or is compiled, arranged, augmented, or combined into client-side JavaScript, in whole or
in part, is copyrighted under the AGPLv3 license. The full text of this EE License shall
be included in all copies or substantial portions of the Software.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
@@ -37,6 +20,3 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
For all third party components incorporated into the Cal.com Software, those
components are licensed under the original license provided by the owner of the
applicable component.
+1 -1
View File
@@ -9,7 +9,7 @@
"categories": ["payment"],
"publisher": "HitPay",
"email": "[email protected]",
"description": "HitPay's Cal.com payment integration combines powerful scheduling with seamless local payment acceptance. Our online scheduling software integration is built for customers in APAC, supporting their favorite e-wallets and banking apps.",
"description": "HitPay's Cal.diy payment integration combines powerful scheduling with seamless local payment acceptance. Our online scheduling software integration is built for customers in APAC, supporting their favorite e-wallets and banking apps.",
"extendsFeature": "EventType",
"isTemplate": false,
"__createdUsingCli": true,
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://json.schemastore.org/package.json",
"private": true,
"license": "AGPLv3 (see LICENSE file)",
"license": "MIT",
"name": "@calcom/hitpay",
"version": "0.0.0",
"main": "./index.ts",
@@ -7,7 +7,7 @@
"url": "https://forwork.meta.com/de/en/horizon-workrooms/",
"variant": "conferencing",
"categories": ["conferencing"],
"publisher": "Cal.com, Inc",
"publisher": "Cal.diy, Inc",
"email": "[email protected]",
"appData": {
"location": {
+1 -1
View File
@@ -9,7 +9,7 @@ export const metadata = {
type: "hubspot_crm",
variant: "crm",
logo: "icon.svg",
publisher: "Cal.com",
publisher: "Cal.diy",
url: "https://hubspot.com/",
categories: ["crm"],
label: "HubSpot CRM",
@@ -553,7 +553,7 @@ describe("HubspotCalendarService", () => {
onBookingWriteToEventObjectFields: {
custom_source: {
fieldType: CrmFieldType.TEXT,
value: "Cal.com Booking",
value: "Cal.diy Booking",
whenToWrite: WhenToWrite.EVERY_BOOKING,
},
},
@@ -571,7 +571,7 @@ describe("HubspotCalendarService", () => {
await service.createEvent(event, contacts);
const createCall = mockHubspotClient.crm.objects.meetings.basicApi.create.mock.calls[0][0];
expect(createCall.properties.custom_source).toBe("Cal.com Booking");
expect(createCall.properties.custom_source).toBe("Cal.diy Booking");
});
it("should include custom text field with booking response placeholder", async () => {
@@ -9,7 +9,7 @@
"categories": ["calendar"],
"publisher": "Cal.com, Inc.",
"email": "[email protected]",
"description": "Import events from an ICS Feed into [Cal.com](https://cal.com).",
"description": "Import events from an ICS Feed into [Cal.diy](https://cal.com).",
"isTemplate": false,
"__createdUsingCli": true
}
@@ -17,5 +17,5 @@
"devDependencies": {
"@calcom/types": "workspace:*"
},
"description": "Import events from an ICS Feed into Cal.com."
"description": "Import events from an ICS Feed into Cal.diy."
}
+1 -1
View File
@@ -42,7 +42,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
<!DOCTYPE html>
<html>
<head>
<title>Cal.com</title>
<title>Cal.diy</title>
<meta charset="UTF-8" />
<script src="https://s3.amazonaws.com/intercom-sheets.com/messenger-sheet-library.latest.js"></script>
</head>
+1 -1
View File
@@ -9,7 +9,7 @@
"categories": ["automation"],
"publisher": "Valentin Chmara",
"email": "[email protected]",
"description": "Enhance your scheduling and appointment management experience with the Intercom Integration for [Cal.com](https://cal.com).",
"description": "Enhance your scheduling and appointment management experience with the Intercom Integration for [Cal.diy](https://cal.com).",
"isTemplate": false,
"__createdUsingCli": true,
"__template": "basic",
@@ -24,13 +24,13 @@ export async function handleLinkStep(req: NextApiRequest): Promise<NewCanvas | s
const input: InputComponent = {
type: "input",
id: "submit_booking_url",
label: "Enter your Cal.com link",
label: "Enter your Cal.diy link",
placeholder: "https://cal.com/valentinchmara/30min",
save_state: "unsaved",
action: {
type: "submit",
},
aria_label: "Enter your Cal.com link",
aria_label: "Enter your Cal.diy link",
};
const defaultCanvasData: NewCanvas = {
@@ -117,7 +117,7 @@ export async function handleLinkStep(req: NextApiRequest): Promise<NewCanvas | s
const text: TextComponent = {
type: "text",
text: "Or choose another Cal.com link:",
text: "Or choose another Cal.diy link:",
style: "muted",
align: "left",
};
+1 -1
View File
@@ -10,5 +10,5 @@
"devDependencies": {
"@calcom/types": "workspace:*"
},
"description": "Enhance your scheduling and appointment management experience with the Intercom Integration for Cal.com."
"description": "Enhance your scheduling and appointment management experience with the Intercom Integration for Cal.diy."
}
+1 -1
View File
@@ -9,7 +9,7 @@ export const metadata = {
variant: "conferencing",
categories: ["conferencing"],
logo: "icon.svg",
publisher: "Cal.com",
publisher: "Cal.diy",
url: "https://jitsi.org/",
slug: "jitsi",
title: "Jitsi Meet",
@@ -7,12 +7,12 @@ const log = logger.getSubLogger({ prefix: [`[[LarkTenantCredential]`] });
const msg = {
en_us: {
title: "Welcome to Cal.com!",
title: "Welcome to Cal.diy!",
content: [
[
{
tag: "text",
text: "Cal.com is an open source scheduling infrastructure.",
text: "Cal.diy is an open source scheduling infrastructure.",
},
],
[
+2 -2
View File
@@ -17,7 +17,7 @@ Follow-ups write themselves and next steps are captured instantly. Every meeting
## How It Works
1. Install Lyra from the Cal.com App Store
2. Sign in with your Lyra account to authorize Cal.com
1. Install Lyra from the Cal.diy App Store
2. Sign in with your Lyra account to authorize Cal.diy
3. Select Lyra as your conferencing option for event types
4. When bookings are made, Lyra meeting links are automatically generated
+1 -1
View File
@@ -63,7 +63,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
}
// Convert expires_in (seconds) to expiry_date (absolute ms timestamp)
// This follows Cal.com's universal OAuth token schema
// This follows Cal.diy's universal OAuth token schema
responseBody.expiry_date = Math.round(Date.now() + responseBody.expires_in * 1000);
delete responseBody.expires_in;
+1 -1
View File
@@ -7,4 +7,4 @@ items:
- 5.png
---
Workflow automation for everyone. Use the [Cal.com](https://cal.com) app in Make to automate your workflows when a booking is created, rescheduled, cancelled or when a meeting has ended. You can also get all your booking with the 'List Bookings' module.<br /><br />**After Installation:** Have you lost your API key? You can always generate a new key on the <a href="/apps/make/setup">**<ins>Make Setup Page</ins>**</a>
Workflow automation for everyone. Use the [Cal.diy](https://cal.com) app in Make to automate your workflows when a booking is created, rescheduled, cancelled or when a meeting has ended. You can also get all your booking with the 'List Bookings' module.<br /><br />**After Installation:** Have you lost your API key? You can always generate a new key on the <a href="/apps/make/setup">**<ins>Make Setup Page</ins>**</a>
+1 -1
View File
@@ -4,7 +4,7 @@
2. Go to `/admin/apps/automation` in Cal and set the `invite_link` for Make to `https://www.make.com/en/hq/app-invitation/6cb2772b61966508dd8f414ba3b44510` to use the app.
3. Create a [Make account](https://www.make.com/en/login), if you don't have one.
4. Go to `Scenarios` in the sidebar and click on **Create a new scenario**.
5. Search for `Cal.com` in the apps list and select from the list of triggers - Booking Created, Booking Deleted, Booking Rescheduled, Meeting Ended
5. Search for `Cal.diy` in the apps list and select from the list of triggers - Booking Created, Booking Deleted, Booking Rescheduled, Meeting Ended
6. To create a **connection** you will need your Cal deployment url and the app API Key generated above. You only need to create a **connection** once, all webhooks can use that connection.
7. Setup the webhook for the desired event in Make.
8. To delete a webhook, go to `Webhooks` in the left sidebar in Make, pick the webhook you want to delete and click **delete**.
@@ -1,9 +1,8 @@
import type { NextApiRequest, NextApiResponse } from "next";
import findValidApiKey from "@calcom/features/ee/api-keys/lib/findValidApiKey";
import { addSubscription } from "@calcom/features/webhooks/lib/scheduleTrigger";
import { defaultHandler } from "@calcom/lib/server/defaultHandler";
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
import type { NextApiRequest, NextApiResponse } from "next";
import { findValidApiKey } from "../../../_utils/findValidApiKey";
async function handler(req: NextApiRequest, res: NextApiResponse) {
const apiKey = req.query.apiKey as string;
@@ -1,10 +1,9 @@
import type { NextApiRequest, NextApiResponse } from "next";
import z from "zod";
import findValidApiKey from "@calcom/features/ee/api-keys/lib/findValidApiKey";
import { deleteSubscription } from "@calcom/features/webhooks/lib/scheduleTrigger";
import { defaultHandler } from "@calcom/lib/server/defaultHandler";
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
import type { NextApiRequest, NextApiResponse } from "next";
import z from "zod";
import { findValidApiKey } from "../../../_utils/findValidApiKey";
const querySchema = z.object({
apiKey: z.string(),
@@ -1,9 +1,8 @@
import type { NextApiRequest, NextApiResponse } from "next";
import findValidApiKey from "@calcom/features/ee/api-keys/lib/findValidApiKey";
import { listBookings } from "@calcom/features/webhooks/lib/scheduleTrigger";
import { defaultHandler } from "@calcom/lib/server/defaultHandler";
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
import type { NextApiRequest, NextApiResponse } from "next";
import { findValidApiKey } from "../../../_utils/findValidApiKey";
async function handler(req: NextApiRequest, res: NextApiResponse) {
const apiKey = req.query.apiKey as string;
@@ -1,7 +1,6 @@
import type { NextApiRequest, NextApiResponse } from "next";
import findValidApiKey from "@calcom/features/ee/api-keys/lib/findValidApiKey";
import prisma from "@calcom/prisma";
import type { NextApiRequest, NextApiResponse } from "next";
import { findValidApiKey } from "../../../_utils/findValidApiKey";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const apiKey = req.query.apiKey as string;
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "@calcom/make",
"version": "0.0.0",
"main": "./index.ts",
"description": "Workflow automation for everyone. Use the Cal.com Make app to trigger your workflows when a booking is created, rescheduled, or cancelled, or after a meeting ends.",
"description": "Workflow automation for everyone. Use the Cal.diy Make app to trigger your workflows when a booking is created, rescheduled, or cancelled, or after a meeting ends.",
"dependencies": {
"@calcom/lib": "workspace:*"
},
+2 -2
View File
@@ -5,7 +5,7 @@
3. On the upper right, click the profile icon and go to "Administration settings".
4. In the left panel under "Administration" click on "Security".
5. Scroll down until the end of the page to "OAuth 2.0 clients".
6. Under "Add client" give your client a name, e.g. "Cal.com".
7. Set the Redirection URI as `<Cal.com URL>/api/integrations/nextcloudtalk/callback` replacing [Cal.com](https://cal.com) URL with the URI at which your application runs.
6. Under "Add client" give your client a name, e.g. "Cal.diy".
7. Set the Redirection URI as `<Cal.diy URL>/api/integrations/nextcloudtalk/callback` replacing [Cal.diy](https://cal.com) URL with the URI at which your application runs.
8. Click "Add".
9. Copy the Client Identifier and Secret key and add these while enabling the app through Settings -> Admin -> Apps interface
+1 -1
View File
@@ -7,7 +7,7 @@
"url": "https://nextcloud.com/talk",
"variant": "conferencing",
"categories": ["conferencing"],
"publisher": "Cal.com",
"publisher": "Cal.diy",
"email": "[email protected]",
"appData": {
"location": {
@@ -10,7 +10,7 @@ export const metadata = {
category: "calendar",
categories: ["calendar"],
logo: "icon.svg",
publisher: "Cal.com",
publisher: "Cal.diy",
slug: "office365-calendar",
dirName: "office365calendar",
url: "https://cal.com/",
@@ -17,7 +17,7 @@ export const metadata = {
category: "conferencing",
categories: ["conferencing"],
logo: "icon.svg",
publisher: "Cal.com",
publisher: "Cal.diy",
slug: "msteams",
dirName: "office365video",
url: "https://www.microsoft.com/en-ca/microsoft-teams/group-chat-software",
@@ -4,7 +4,7 @@
"type": "office365_video",
"variant": "conferencing",
"logo": "icon.svg",
"publisher": "Cal.com",
"publisher": "Cal.diy",
"url": "https://www.microsoft.com/en-ca/microsoft-teams/group-chat-software",
"verified": true,
"rating": 4.3,
+2 -2
View File
@@ -6,9 +6,9 @@
"url": "https://paypal.com",
"variant": "payment",
"categories": ["payment"],
"publisher": "Cal.com",
"publisher": "Cal.diy",
"email": "[email protected]",
"description": "Paypal payment app by [Cal.com](https://cal.com)",
"description": "Paypal payment app by [Cal.diy](https://cal.com)",
"extendsFeature": "EventType",
"isTemplate": false,
"__createdUsingCli": true,
+1 -1
View File
@@ -10,5 +10,5 @@
"devDependencies": {
"@calcom/types": "workspace:*"
},
"description": "Paypal payment app by Cal.com"
"description": "Paypal payment app by Cal.diy"
}
+1 -1
View File
@@ -8,7 +8,7 @@
"variant": "crm",
"categories": ["crm"],
"extendsFeature": "EventType",
"publisher": "Cal.com",
"publisher": "Cal.diy",
"email": "[email protected]",
"description": "Founded in 2010, Pipedrive is an easy and effective sales CRM that drives small business growth.\r\rToday, Pipedrive is used by revenue teams at more than 100,000 companies worldwide. Pipedrive is headquartered in New York and has offices across Europe and the US.\r\rThe company is backed by majority holder Vista Equity Partners, Bessemer Venture Partners, Insight Partners, Atomico, and DTCP.\r\rLearn more at www.pipedrive.com.",
"isTemplate": false,
+1 -1
View File
@@ -6,4 +6,4 @@ items:
- 4.png
---
Quickly share your [Cal.com](https://cal.com) meeting links with Raycast. Requires [Raycast.com](https://www.raycast.com/) to be installed and the [Cal.com](https://cal.com) from the Raycast Store needs to be installed: https://www.raycast.com/cal/. You can create an API token in your Developer [Cal.com](https://cal.com) Settings, and then you can add the API Key by opening up the [Cal.com](https://cal.com) App in Raycast.
Quickly share your [Cal.diy](https://cal.com) meeting links with Raycast. Requires [Raycast.com](https://www.raycast.com/) to be installed and the [Cal.diy](https://cal.com) from the Raycast Store needs to be installed: https://www.raycast.com/cal/. You can create an API token in your Developer [Cal.diy](https://cal.com) Settings, and then you can add the API Key by opening up the [Cal.diy](https://cal.com) App in Raycast.
+1 -1
View File
@@ -11,7 +11,7 @@
],
"publisher": "Eric Luce",
"email": "[email protected]",
"description": "Quickly share your [Cal.com](https://cal.com) meeting links with Raycast",
"description": "Quickly share your [Cal.diy](https://cal.com) meeting links with Raycast",
"__createdUsingCli": true,
"isOAuth": false,
"externalLink": {
+1 -1
View File
@@ -17,7 +17,7 @@ Build and test complex workflows in a matter of minutes, then deploy them via ph
## Preset Functions
Ease of use functions like book a meeting at [Cal.com](https://cal.com), Call transfer, voicemail detection, etc...
Ease of use functions like book a meeting at [Cal.diy](https://cal.com), Call transfer, voicemail detection, etc...
## Humanlike Voice Experience
@@ -1,8 +0,0 @@
---
items:
- 1.jpg
- 2.jpg
- 3.jpg
---
It would allow a booker to connect with the right person or choose the right event, faster. It would work by taking inputs from the booker and using that data to route to the correct booker/event as configured by Cal user
@@ -1,34 +0,0 @@
# Routing Forms App
## Vocabulary
- RaqbField refers to the field in the context of React Awesome Query Builder(RAQB)
- See `getQueryBuilderConfig`
- Field refers to the field in the Routing Form
## Understanding the structure of queryValue(type JsonTree)
### AttributeQueryValue
- {
id: "Some-id-generated-and-used-internally-by-raqb"
type: "group",
children1: {
"Some-other-id-generated-and-used-internally-by-raqb": {
type: "rule",
properties: {
field: "ATTRIBUTE.id",
operator: "multiselect_equals", // One of many operators possible
value: ["AttributeOption.id"],
// This is the type of the attribute and the operator corresponds to it. The data provided to jsonLogic on which the logic(generated from RAQB config and this queryValue) is applied must also be as per the requirement of the operator.
valueType: ["multiselect"]
}
}
}
}
## How to run Tests
`yarn e2e:app-store` runs all Apps' tests. You can use `describe.only()` to run Routing Forms tests only.
Make sure that the app is running already with NEXT_PUBLIC_IS_E2E=1 so that the app is installable
-53
View File
@@ -1,53 +0,0 @@
## TODO - Routing
- [ ] Switching from Select to MultiSelect in attribute
- [ ] It immediately makes the Routing logic to not work. Fix it.
- [ ] It removes the selected option from Routing. Fix it.
- [ ] Warnings are needed with recommendation to create new attribute instead in unsupported scenarios. We need to test for more such changes to Attribute types.
- [ ] Test Seated events as routing targets.
- Improvements
- [ ] When choosing 'Value of Field' option in RAQB, show a warning somewhere if all options of the Form field aren't present in the attribute option.
- So, if Form Field is 'What is Company Size' with options Enterprise, Large, Medium, Small and Attribute for which Value of 'What is compnay size' has options Enterprise, Large, Medium. It would show a warning that 'Small' option is not present in the attribute.
- [ ] When logic can't be built(Short text maps to an attribute with given set of options but the short text value doesn't match any of the options), the team member matching route throws error but Test Preview still shows the previous value - It show should the error in there.
- [ ] When routing to a team that doesn't have the team members assigned that are chosen, we are unable to select those users. FIX it by ignoring the assigned members(except the fixed hosts) and just using the attributes matched team members.
- [ ] Fetch bookings on window focus but not when rerouting dialog is open. As soon as it is closed, we need to refetch again.
- [ ] Seated Events
- [ ] Disable routing for seated events. Disable only during creation.
- [ ] When rescheduling to a new event, the booking title remains same which will most probably not match the event-type title. This is the behaviour of reschedule. Should we use the new event-type title?
- [ ] What params should we forward to the booking page that we show after rerouting
- [ ] On completing the rerouting just show the new Routing status
- [ ] We need to disallow changing the email identifier field as during a reschedule user isn't allowed to change their email currently. Allowing to change that email response would mean that we support changing email during reschedule which might be disabled for some reasons unknown yet.
- [ ] What if there are changes to Form before rerouting but after initial routing.
- [ ] Not able to prefill rescheduleReason due to a bug in useInitialFormValues hook
- [ ] It is becoming a requirement to have BookingAttempt record to allow to store reroutingFormResponses as well as teamMemberIds in it. Other query params could also be stored later on when needed. It is important to reduce the payload of the query params due to routedTeamMemberIds and reroutingFormResponses
### Performance Tests and Improvements
- [ ] Test with ~1000 team members and ~100 attributes.
- [ ] getAttributes query optimization. It needs info from various tables(Attribute, AttributeOption, AttributeToUser, Membership)
- [ ] findTeamMembersMatchingAttributesQuery - Parallelize jsonLogic.apply across team members.
### Unit Tests
- [ ] evaluateRAQB
- [x] Basic Tests
- [ ] More Detailed Tests
- [ ] getAttributes
- [ ] Querying Logic Test
- [ ] getAvailableSlots
- [ ] should use routedTeamMemberIds in availability query
### Documentation / Tooltip
- [ ] Document well that the option label in Routing Form Field and Attribute Option label must be same to connect them.
- Due to the connection requirement b/w Attribute Option and Field Option, we use label(lowercased) to match attributes instead of attribute slug
- [ ] Fixed hosts of the event will be included through attribute routing as well. They aren't tested for attribute routing logic.
- [ ] When re-routed, the booking page doesn't allow rescheduling/cancellation to avoid any possible issues. We can open it up later.
- [ ] Booking with seats not supported yet. Need to figure out which seats should be re-routed or if re-routing makes sense for it even?
- [ ] Hashed link re-routing doesn't make sense with. With Routing you route to an event from form and it doesn't involve hashed link even if it is enabled
- [ ] User needs to ensure for now that the team event they redirect to has 'Assign all and future members of the team' checked.
### V2.0
- [ ] Fallback for when no team member matches the criteria.
- [x] Fallback will be attributes query builder that would match a different set of users. Though the booking will use the team members assigned to the event type, it might be better to be able to identify such a scenario and use a different set of users. It also makes it easy to identify when the fallback scenario happens.
- [ ] Mark if fallback was used by the router for a response.
- [ ] cal.routedTeamMembersIds query param - Could possible become a big payload and possibly break the URL limit. We could work on a short-lived row in a table that would hold that info and we pass the id of that row only in query param. handleNewBooking can then retrieve the routedTeamMembersIds from that short-lived row and delete the entry after successfully creating a booking.
- [ ] Better ability to test with contact owner from Routing Form Preview itself(if possible). Right now, we need to test the entire booking flow to verify that.
@@ -1,159 +0,0 @@
import { describe, it, vi, expect } from "vitest";
import {
FormFieldsBaseConfig,
AttributesBaseConfig,
} from "../components/react-awesome-query-builder/config/config";
vi.mock("../components/react-awesome-query-builder/widgets", () => ({
default: {},
}));
const assertCommonStructure = (config: any) => {
expect(config).toHaveProperty("conjunctions");
expect(config).toHaveProperty("operators");
expect(config).toHaveProperty("types");
expect(config).toHaveProperty("widgets");
expect(config).toHaveProperty("settings");
};
const assertCommonWidgetTypes = (config: any) => {
expect(config.widgets).toHaveProperty("text");
expect(config.widgets).toHaveProperty("textarea");
expect(config.widgets).toHaveProperty("number");
expect(config.widgets).toHaveProperty("multiselect");
expect(config.widgets).toHaveProperty("select");
expect(config.widgets).toHaveProperty("phone");
expect(config.widgets).toHaveProperty("email");
};
const assertSelectOperators = (config: any) => {
expect(config.operators).toHaveProperty("select_any_in");
expect(config.operators).toHaveProperty("select_not_any_in");
expect(config.operators).toHaveProperty("select_equals");
expect(config.operators).toHaveProperty("select_not_equals");
// Verify corresponding widgets for select operators
expect(config.types.select.widgets.multiselect.operators).toContain("select_any_in");
expect(config.types.select.widgets.multiselect.operators).toContain("select_not_any_in");
// Important to verify that select_equals and select_not_equals are not present in multiselect as that might cause multiselect widget operand to show up for these operators
expect(config.types.select.widgets.multiselect.operators).not.toContain("select_equals");
expect(config.types.select.widgets.multiselect.operators).not.toContain("select_not_equals");
expect(config.types.select.widgets.select.operators).toContain("select_equals");
expect(config.types.select.widgets.select.operators).toContain("select_not_equals");
// Important to verify that select_any_in and select_not_any_in are not present in select as that might cause select widget operand to show up for these operators
expect(config.types.select.widgets.select.operators).not.toContain("select_any_in");
expect(config.types.select.widgets.select.operators).not.toContain("select_not_any_in");
};
const assertMaxNesting = (config: any, value: number) => {
expect(config.settings.maxNesting).toBe(value);
};
describe("Query Builder Config", () => {
describe("FormFieldsBaseConfig", () => {
it("should have the correct structure", () => {
assertCommonStructure(FormFieldsBaseConfig);
});
it("should not support multiselect_some_in and multiselect_not_some_in - because they are not supported in Prisma for reporting(probably)", () => {
expect(FormFieldsBaseConfig.types.multiselect.widgets.multiselect.operators).not.toContain(
"multiselect_some_in"
);
expect(FormFieldsBaseConfig.types.multiselect.widgets.multiselect.operators).not.toContain(
"multiselect_not_some_in"
);
});
it("should support select_any_in, select_not_any_in, select_equals, select_not_equals - Verify both types.widgets and operators", () => {
assertSelectOperators(FormFieldsBaseConfig);
});
it("should have specific widget types", () => {
assertCommonWidgetTypes(FormFieldsBaseConfig);
});
it("should have maxNesting set to 1 in settings", () => {
assertMaxNesting(FormFieldsBaseConfig, 1);
});
});
describe("AttributesBaseConfig", () => {
it("should have the correct structure", () => {
assertCommonStructure(AttributesBaseConfig);
});
it("should support multiselect_some_in and multiselect_not_some_in operators for multiselect", () => {
expect(AttributesBaseConfig.types.multiselect.widgets.multiselect.operators).toContain(
"multiselect_some_in"
);
expect(AttributesBaseConfig.types.multiselect.widgets.multiselect.operators).toContain(
"multiselect_not_some_in"
);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const jsonLogic = AttributesBaseConfig.operators.multiselect_some_in.jsonLogic(
["A"],
"multiselect_some_in",
["A", "B"]
);
// Verifies that it is using some-in implementation
expect(jsonLogic).toEqual({
some: [["A"], { in: [{ var: "" }, ["A", "B"]] }],
});
});
it("should support select_any_in, select_not_any_in, select_equals, select_not_equals - Verify both types.widgets and operators", () => {
assertSelectOperators(AttributesBaseConfig);
});
it("should have specific widget types", () => {
assertCommonWidgetTypes(AttributesBaseConfig);
});
it("should have maxNesting set to 1 in settings", () => {
assertMaxNesting(AttributesBaseConfig, 1);
});
it("should provide jsonlogic for between operator", () => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const jsonLogic = AttributesBaseConfig.operators.between.jsonLogic(
{ var: "89ee81ae-953c-409b-aacc-700e1ce5ae20" },
"between",
["1", "5"]
);
// Verifies that it is using >= and <= in implementation and integer parsed
expect(jsonLogic).toEqual({
and: [
{ ">=": [{ var: "89ee81ae-953c-409b-aacc-700e1ce5ae20" }, 1] },
{ "<=": [{ var: "89ee81ae-953c-409b-aacc-700e1ce5ae20" }, 5] },
],
});
});
it("should provide jsonlogic for not_between operator", () => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const jsonLogic = AttributesBaseConfig.operators.not_between.jsonLogic(
{ var: "89ee81ae-953c-409b-aacc-700e1ce5ae20" },
"not_between",
["1", "5"]
);
// Verifies that it is using < and > in implementation and integer parsed
expect(jsonLogic).toEqual({
or: [
{ "<": [{ var: "89ee81ae-953c-409b-aacc-700e1ce5ae20" }, 1] },
{ ">": [{ var: "89ee81ae-953c-409b-aacc-700e1ce5ae20" }, 5] },
],
});
});
});
});
@@ -1,139 +0,0 @@
import { describe, it, expect } from "vitest";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { getAbsoluteEventTypeRedirectUrl } from "../getEventTypeRedirectUrl";
describe("getAbsoluteEventTypeRedirectUrl", () => {
const defaultForm = {
team: null,
nonOrgUsername: null,
nonOrgTeamslug: null,
userOrigin: "https://user.cal.com",
teamOrigin: "https://team.cal.com",
user: {
username: null,
},
};
const defaultParams = {
eventTypeRedirectUrl: "user/event",
form: defaultForm,
allURLSearchParams: new URLSearchParams(),
isEmbed: false,
};
it("should return WEBAPP_URL for non-migrated user", () => {
const result = getAbsoluteEventTypeRedirectUrl({
...defaultParams,
eventTypeRedirectUrl: "old-user/event",
form: {
...defaultForm,
nonOrgUsername: "old-user",
user: { username: "new-user" },
},
});
expect(result).toBe(`${WEBAPP_URL}/old-user/event?`);
});
it("should return user origin for migrated user", () => {
const result = getAbsoluteEventTypeRedirectUrl({
...defaultParams,
eventTypeRedirectUrl: "user/event",
form: {
...defaultForm,
nonOrgUsername: "user",
user: { username: "user" },
},
});
expect(result).toBe("https://user.cal.com/user/event?");
});
it("should return WEBAPP_URL for non-migrated team", () => {
const result = getAbsoluteEventTypeRedirectUrl({
...defaultParams,
eventTypeRedirectUrl: "team/team1/event",
form: { ...defaultForm, nonOrgTeamslug: "team1" },
});
expect(result).toBe(`${WEBAPP_URL}/team/team1/event?`);
});
it("should return team origin for migrated team", () => {
const result = getAbsoluteEventTypeRedirectUrl({
...defaultParams,
eventTypeRedirectUrl: "team/team1/event",
});
expect(result).toBe("https://team.cal.com/team/team1/event?");
});
it("should append URL search params", () => {
const result = getAbsoluteEventTypeRedirectUrl({
...defaultParams,
allURLSearchParams: new URLSearchParams("foo=bar&baz=qux"),
});
expect(result).toBe("https://user.cal.com/user/event?foo=bar&baz=qux");
});
it("should append /embed for embedded views", () => {
const result = getAbsoluteEventTypeRedirectUrl({
...defaultParams,
allURLSearchParams: new URLSearchParams("foo=bar&baz=qux"),
isEmbed: true,
});
expect(result).toBe("https://user.cal.com/user/event/embed?foo=bar&baz=qux");
});
it("should throw an error if invalid team event redirect URL is provided", () => {
expect(() =>
getAbsoluteEventTypeRedirectUrl({
...defaultParams,
eventTypeRedirectUrl: "team/",
})
).toThrow("eventTypeRedirectUrl must have username or teamSlug");
});
it("should use '&' separator when redirect URL already contains query parameters", () => {
const result = getAbsoluteEventTypeRedirectUrl({
...defaultParams,
eventTypeRedirectUrl: "user/event?existing=param",
allURLSearchParams: new URLSearchParams("foo=bar"),
});
expect(result).toBe("https://user.cal.com/user/event?existing=param&foo=bar");
});
it("should merge with '&' when redirect URL already contains multiple query parameters", () => {
const result = getAbsoluteEventTypeRedirectUrl({
...defaultParams,
eventTypeRedirectUrl: "user/event?existing1=param1&existing2=param2",
allURLSearchParams: new URLSearchParams("foo=bar"),
});
expect(result).toBe("https://user.cal.com/user/event?existing1=param1&existing2=param2&foo=bar");
});
it("should merge with '&' when no URL search params are present", () => {
const result = getAbsoluteEventTypeRedirectUrl({
...defaultParams,
eventTypeRedirectUrl: "user/event?existing=param",
allURLSearchParams: new URLSearchParams(),
});
expect(result).toBe("https://user.cal.com/user/event?existing=param&");
});
it("should merge when redirect URL ends with '/'", () => {
const result = getAbsoluteEventTypeRedirectUrl({
...defaultParams,
eventTypeRedirectUrl: "user/event/",
allURLSearchParams: new URLSearchParams("foo=bar"),
});
expect(result).toBe("https://user.cal.com/user/event/?foo=bar");
});
it("should be able to merge when redirect URL ends with '?'", () => {
const result = getAbsoluteEventTypeRedirectUrl({
...defaultParams,
eventTypeRedirectUrl: "user/event?",
allURLSearchParams: new URLSearchParams("foo=bar"),
});
expect(result).toBe("https://user.cal.com/user/event?&foo=bar");
});
});
@@ -1,159 +0,0 @@
import type { Settings } from "react-awesome-query-builder";
import { describe, it, vi, expect } from "vitest";
import {
ConfigFor,
withRaqbSettingsAndWidgets,
} from "../components/react-awesome-query-builder/config/uiConfig";
// Mock dependencies
vi.mock("../components/react-awesome-query-builder/widgets", () => ({
default: {
TextWidget: vi.fn(),
TextAreaWidget: vi.fn(),
MultiSelectWidget: vi.fn(),
SelectWidget: vi.fn(),
NumberWidget: vi.fn(),
FieldSelect: vi.fn(),
Conjs: vi.fn(),
Button: vi.fn(),
ButtonGroup: vi.fn(),
Provider: vi.fn(),
},
}));
describe("uiConfig", () => {
const mockConfig = {
widgets: {
text: {
type: "text",
},
textarea: {
type: "textarea",
},
number: {
type: "number",
},
multiselect: {
type: "multiselect",
},
select: {
type: "select",
},
phone: {
type: "phone",
},
email: {
type: "email",
},
},
settings: {} as Settings,
};
describe("withRaqbSettingsAndWidgets", () => {
it("should add factory functions to all widgets", () => {
const result = withRaqbSettingsAndWidgets({
config: mockConfig,
configFor: ConfigFor.FormFields,
});
// Verify each widget has a factory function
expect(result.widgets.text).toHaveProperty("factory");
expect(result.widgets.textarea).toHaveProperty("factory");
expect(result.widgets.number).toHaveProperty("factory");
expect(result.widgets.multiselect).toHaveProperty("factory");
expect(result.widgets.select).toHaveProperty("factory");
expect(result.widgets.phone).toHaveProperty("factory");
expect(result.widgets.email).toHaveProperty("factory");
});
it("should add render functions to settings", () => {
const result = withRaqbSettingsAndWidgets({
config: mockConfig,
configFor: ConfigFor.FormFields,
});
// Verify settings have all required render functions
expect(result.settings).toHaveProperty("renderField");
expect(result.settings).toHaveProperty("renderOperator");
expect(result.settings).toHaveProperty("renderFunc");
expect(result.settings).toHaveProperty("renderConjs");
expect(result.settings).toHaveProperty("renderButton");
expect(result.settings).toHaveProperty("renderButtonGroup");
expect(result.settings).toHaveProperty("renderProvider");
});
it("should preserve existing widget properties while adding factory", () => {
const configWithExistingProps = {
...mockConfig,
widgets: {
...mockConfig.widgets,
text: {
type: "text",
existingProp: "value",
},
},
};
const result = withRaqbSettingsAndWidgets({
config: configWithExistingProps,
configFor: ConfigFor.FormFields,
});
expect(result.widgets.text).toHaveProperty("existingProp", "value");
expect(result.widgets.text).toHaveProperty("factory");
});
it("should set correct placeholder for phone widget", () => {
const result = withRaqbSettingsAndWidgets({
config: mockConfig,
configFor: ConfigFor.FormFields,
});
expect(result.widgets.phone).toHaveProperty("valuePlaceholder", "Enter Phone Number");
});
it("should reuse same component fns for widgets - ensures remounting is not happening", () => {
const configWithExistingProps = {
...mockConfig,
};
const result = withRaqbSettingsAndWidgets({
config: configWithExistingProps,
configFor: ConfigFor.FormFields,
});
// @ts-expect-error - TODO: fix this
const textFactory = result.widgets.text.factory;
const result2 = withRaqbSettingsAndWidgets({
config: configWithExistingProps,
configFor: ConfigFor.FormFields,
});
// @ts-expect-error - TODO: fix this
// Using same reference
expect(result2.widgets.text.factory).toBe(textFactory);
});
it("should reuse same component fns for settings - ensures remounting is not happening", () => {
const configWithExistingProps = {
...mockConfig,
};
const result1 = withRaqbSettingsAndWidgets({
config: configWithExistingProps,
configFor: ConfigFor.FormFields,
});
const renderFieldOnFirstCallOfWithRaqbSettingsAndWidgets = result1.settings.renderField;
const result2 = withRaqbSettingsAndWidgets({
config: configWithExistingProps,
configFor: ConfigFor.FormFields,
});
expect(result2.settings.renderField).toBe(renderFieldOnFirstCallOfWithRaqbSettingsAndWidgets);
});
});
});
@@ -1,27 +0,0 @@
import prisma from "@calcom/prisma";
import type { AppDeclarativeHandler } from "@calcom/types/AppHandler";
import appConfig from "../config.json";
const handler: AppDeclarativeHandler = {
appType: appConfig.type,
variant: appConfig.variant,
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: async ({ user, appType, slug, teamId }) => {
return await prisma.credential.create({
data: {
type: appType,
key: {},
...(teamId ? { teamId } : { userId: user.id }),
appId: slug,
},
});
},
redirect: {
url: "/apps/routing-forms/forms",
},
};
export default handler;
@@ -1,2 +0,0 @@
export { default as add } from "./add";
export { default as responses } from "./responses/[formId]";
@@ -1,114 +0,0 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getSession } from "next-auth/react";
import {
entityPrismaWhereClause,
canEditEntity,
} from "@calcom/features/pbac/lib/entityPermissionUtils.server";
import { sanitizeValue } from "@calcom/lib/csvUtils";
import prisma from "@calcom/prisma";
import type { App_RoutingForms_Form } from "@calcom/prisma/client";
import { getSerializableForm } from "../../lib/getSerializableForm";
import { getHumanReadableFieldResponseValue } from "../../lib/responseData/getHumanReadableFieldResponseValue";
import type { FormResponse, SerializableForm } from "../../types/types";
type Fields = NonNullable<SerializableForm<App_RoutingForms_Form>["fields"]>;
async function* getResponses(formId: string, fields: Fields) {
let responses;
let skip = 0;
// Keep it small enough to be in Vercel limits of Serverless Function in terms of memory.
// To avoid limit in terms of execution time there is an RFC https://linear.app/calcom/issue/CAL-204/rfc-routing-form-improved-csv-exports
const take = 100;
while (
(responses = await prisma.app_RoutingForms_FormResponse.findMany({
where: {
formId,
},
take: take,
skip: skip,
})) &&
responses.length
) {
const csv: string[] = [];
responses.forEach((response) => {
const fieldResponses = response.response as FormResponse;
const csvCells: string[] = [];
fields.forEach((field) => {
const fieldResponse = fieldResponses[field.id];
const value = fieldResponse?.value || "";
const humanReadableResponseValue = getHumanReadableFieldResponseValue({ field, value });
const readableValues = Array.isArray(humanReadableResponseValue)
? humanReadableResponseValue
: [humanReadableResponseValue];
const serializedValue = readableValues.map((value) => sanitizeValue(value)).join(" | ");
csvCells.push(serializedValue);
});
csvCells.push(response.createdAt.toISOString());
csv.push(csvCells.join(","));
});
skip += take;
yield csv.join("\n");
}
return "";
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { args } = req.query;
if (!args) {
throw new Error("args must be set");
}
const formId = args[2];
if (!formId) {
throw new Error("formId must be provided");
}
const session = await getSession({ req });
if (!session) {
return res.status(401).json({ message: "Unauthorized" });
}
const { user } = session;
const form = await prisma.app_RoutingForms_Form.findFirst({
where: {
id: formId,
...entityPrismaWhereClause({ userId: user.id }),
},
});
if (!form) {
return res.status(404).json({ message: "Form not found or unauthorized" });
}
if (!(await canEditEntity(form, user.id))) {
return res.status(404).json({ message: "Form not found or unauthorized" });
}
const serializableForm = await getSerializableForm({ form, withDeletedFields: true });
res.setHeader("Content-Type", "text/csv; charset=UTF-8");
res.setHeader(
"Content-Disposition",
`attachment; filename="${serializableForm.name}-${serializableForm.id}.csv"`
);
res.setHeader("Transfer-Encoding", "chunked");
const headerFields = serializableForm.fields || [];
const csvIterator = getResponses(formId, headerFields);
// Make Header
res.write(
`${headerFields
.map((field) => `${field.label}${field.deleted ? "(Deleted)" : ""}`)
.concat(["Submission Time"])
.join(",")}\n`
);
for await (const partialCsv of csvIterator) {
res.write(partialCsv);
res.write("\n");
}
res.end();
}
@@ -1,14 +0,0 @@
import routingFormBookingFormHandler from "../salesforce/lib/routingFormBookingFormHandler";
import type { AttributeRoutingConfig } from "./types/types";
type AppBookingFormHandler = (
attendeeEmail: string,
attributeRoutingConfig: AttributeRoutingConfig,
eventTypeId: number
) => Promise<{ email: string | null; recordType: string | null; recordId: string | null }>;
const appBookingFormHandler: Record<string, AppBookingFormHandler> = {
salesforce: routingFormBookingFormHandler,
};
export default appBookingFormHandler;
@@ -1,5 +0,0 @@
import dynamic from "next/dynamic";
export const routingFormAppComponents = {
salesforce: dynamic(() => import("../salesforce/components/RoutingFormOptions")),
};
@@ -1,5 +0,0 @@
import { routingFormOptions as salesforce_routing_form_schema } from "../salesforce/zod";
export const routingFormAppDataSchemas = {
salesforce: salesforce_routing_form_schema,
};
@@ -1,29 +0,0 @@
import type { Route, AttributeRoutingConfig } from "../types/types";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function DynamicAppComponent<T extends Record<string, React.ComponentType<any>>>(props: {
componentMap: T;
slug: string;
appData: any;
route: Route;
setAttributeRoutingConfig: (id: string, attributeRoutingConfig: Partial<AttributeRoutingConfig>) => void;
wrapperClassName?: string;
}) {
const { componentMap, slug, wrapperClassName, appData, route, setAttributeRoutingConfig, ...rest } = props;
// There can be apps with no matching component
if (!componentMap[slug]) return null;
const Component = componentMap[slug];
return (
<div className={wrapperClassName || ""}>
<Component
appData={appData}
route={route}
setAttributeRoutingConfig={setAttributeRoutingConfig}
{...rest}
/>
</div>
);
}
Loaded 100 of 4080 files, more files were not shown because too many files have changed in this diff. Show more